xref: /openbmc/qemu/hw/usb/dev-mtp.c (revision 89aa165e)
1 /*
2  * Media Transfer Protocol implementation, backed by host filesystem.
3  *
4  * Copyright Red Hat, Inc 2014
5  *
6  * Author:
7  *   Gerd Hoffmann <kraxel@redhat.com>
8  *
9  * This code is licensed under the GPL v2 or later.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qemu-common.h"
14 #include "qapi/error.h"
15 #include "qemu/error-report.h"
16 #include <wchar.h>
17 #include <dirent.h>
18 
19 #include <sys/statvfs.h>
20 
21 
22 #include "qemu/iov.h"
23 #include "qemu/module.h"
24 #include "qemu/filemonitor.h"
25 #include "trace.h"
26 #include "hw/qdev-properties.h"
27 #include "hw/usb.h"
28 #include "migration/vmstate.h"
29 #include "desc.h"
30 #include "qemu/units.h"
31 
32 /* ----------------------------------------------------------------------- */
33 
34 enum mtp_container_type {
35     TYPE_COMMAND  = 1,
36     TYPE_DATA     = 2,
37     TYPE_RESPONSE = 3,
38     TYPE_EVENT    = 4,
39 };
40 
41 /* MTP write stage, for internal use only */
42 enum mtp_write_status {
43     WRITE_START    = 1,
44     WRITE_CONTINUE = 2,
45     WRITE_END      = 3,
46 };
47 
48 enum mtp_code {
49     /* command codes */
50     CMD_GET_DEVICE_INFO            = 0x1001,
51     CMD_OPEN_SESSION               = 0x1002,
52     CMD_CLOSE_SESSION              = 0x1003,
53     CMD_GET_STORAGE_IDS            = 0x1004,
54     CMD_GET_STORAGE_INFO           = 0x1005,
55     CMD_GET_NUM_OBJECTS            = 0x1006,
56     CMD_GET_OBJECT_HANDLES         = 0x1007,
57     CMD_GET_OBJECT_INFO            = 0x1008,
58     CMD_GET_OBJECT                 = 0x1009,
59     CMD_DELETE_OBJECT              = 0x100b,
60     CMD_SEND_OBJECT_INFO           = 0x100c,
61     CMD_SEND_OBJECT                = 0x100d,
62     CMD_GET_PARTIAL_OBJECT         = 0x101b,
63     CMD_GET_OBJECT_PROPS_SUPPORTED = 0x9801,
64     CMD_GET_OBJECT_PROP_DESC       = 0x9802,
65     CMD_GET_OBJECT_PROP_VALUE      = 0x9803,
66 
67     /* response codes */
68     RES_OK                         = 0x2001,
69     RES_GENERAL_ERROR              = 0x2002,
70     RES_SESSION_NOT_OPEN           = 0x2003,
71     RES_INVALID_TRANSACTION_ID     = 0x2004,
72     RES_OPERATION_NOT_SUPPORTED    = 0x2005,
73     RES_PARAMETER_NOT_SUPPORTED    = 0x2006,
74     RES_INCOMPLETE_TRANSFER        = 0x2007,
75     RES_INVALID_STORAGE_ID         = 0x2008,
76     RES_INVALID_OBJECT_HANDLE      = 0x2009,
77     RES_INVALID_OBJECT_FORMAT_CODE = 0x200b,
78     RES_STORE_FULL                 = 0x200c,
79     RES_STORE_READ_ONLY            = 0x200e,
80     RES_PARTIAL_DELETE             = 0x2012,
81     RES_STORE_NOT_AVAILABLE        = 0x2013,
82     RES_SPEC_BY_FORMAT_UNSUPPORTED = 0x2014,
83     RES_INVALID_OBJECTINFO         = 0x2015,
84     RES_DESTINATION_UNSUPPORTED    = 0x2020,
85     RES_INVALID_PARENT_OBJECT      = 0x201a,
86     RES_INVALID_PARAMETER          = 0x201d,
87     RES_SESSION_ALREADY_OPEN       = 0x201e,
88     RES_INVALID_OBJECT_PROP_CODE   = 0xA801,
89 
90     /* format codes */
91     FMT_UNDEFINED_OBJECT           = 0x3000,
92     FMT_ASSOCIATION                = 0x3001,
93 
94     /* event codes */
95     EVT_CANCEL_TRANSACTION         = 0x4001,
96     EVT_OBJ_ADDED                  = 0x4002,
97     EVT_OBJ_REMOVED                = 0x4003,
98     EVT_OBJ_INFO_CHANGED           = 0x4007,
99 
100     /* object properties */
101     PROP_STORAGE_ID                = 0xDC01,
102     PROP_OBJECT_FORMAT             = 0xDC02,
103     PROP_OBJECT_COMPRESSED_SIZE    = 0xDC04,
104     PROP_PARENT_OBJECT             = 0xDC0B,
105     PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER = 0xDC41,
106     PROP_NAME                      = 0xDC44,
107 };
108 
109 enum mtp_data_type {
110     DATA_TYPE_UINT16  = 0x0004,
111     DATA_TYPE_UINT32  = 0x0006,
112     DATA_TYPE_UINT64  = 0x0008,
113     DATA_TYPE_UINT128 = 0x000a,
114     DATA_TYPE_STRING  = 0xffff,
115 };
116 
117 typedef struct {
118     uint32_t length;
119     uint16_t type;
120     uint16_t code;
121     uint32_t trans;
122 } QEMU_PACKED mtp_container;
123 
124 /* ----------------------------------------------------------------------- */
125 
126 typedef struct MTPState MTPState;
127 typedef struct MTPControl MTPControl;
128 typedef struct MTPData MTPData;
129 typedef struct MTPObject MTPObject;
130 
131 enum {
132     EP_DATA_IN = 1,
133     EP_DATA_OUT,
134     EP_EVENT,
135 };
136 
137 typedef struct MTPMonEntry MTPMonEntry;
138 
139 struct MTPMonEntry {
140     uint32_t event;
141     uint32_t handle;
142 
143     QTAILQ_ENTRY(MTPMonEntry) next;
144 };
145 
146 struct MTPControl {
147     uint16_t     code;
148     uint32_t     trans;
149     int          argc;
150     uint32_t     argv[5];
151 };
152 
153 struct MTPData {
154     uint16_t     code;
155     uint32_t     trans;
156     uint64_t     offset;
157     uint64_t     length;
158     uint64_t     alloc;
159     uint8_t      *data;
160     bool         first;
161     /* Used for >4G file sizes */
162     bool         pending;
163     int          fd;
164     uint8_t      write_status;
165     /* Internal pointer per every MTP_WRITE_BUF_SZ */
166     uint64_t     data_offset;
167 };
168 
169 struct MTPObject {
170     uint32_t     handle;
171     uint16_t     format;
172     char         *name;
173     char         *path;
174     struct stat  stat;
175     /* file monitor watch id */
176     int64_t      watchid;
177     MTPObject    *parent;
178     uint32_t     nchildren;
179     QLIST_HEAD(, MTPObject) children;
180     QLIST_ENTRY(MTPObject) list;
181     bool         have_children;
182     QTAILQ_ENTRY(MTPObject) next;
183 };
184 
185 struct MTPState {
186     USBDevice    dev;
187     char         *root;
188     char         *desc;
189     uint32_t     flags;
190 
191     MTPData      *data_in;
192     MTPData      *data_out;
193     MTPControl   *result;
194     uint32_t     session;
195     uint32_t     next_handle;
196     bool         readonly;
197 
198     QTAILQ_HEAD(, MTPObject) objects;
199     QFileMonitor *file_monitor;
200     QTAILQ_HEAD(, MTPMonEntry) events;
201     /* Responder is expecting a write operation */
202     bool write_pending;
203     struct {
204         uint32_t parent_handle;
205         uint16_t format;
206         uint32_t size;
207         char *filename;
208     } dataset;
209 };
210 
211 /*
212  * ObjectInfo dataset received from initiator
213  * Fields we don't care about are ignored
214  */
215 typedef struct {
216     uint32_t storage_id; /*unused*/
217     uint16_t format;
218     uint16_t protection_status; /*unused*/
219     uint32_t size;
220     uint16_t thumb_format; /*unused*/
221     uint32_t thumb_comp_sz; /*unused*/
222     uint32_t thumb_pix_width; /*unused*/
223     uint32_t thumb_pix_height; /*unused*/
224     uint32_t image_pix_width; /*unused*/
225     uint32_t image_pix_height; /*unused*/
226     uint32_t image_bit_depth; /*unused*/
227     uint32_t parent; /*unused*/
228     uint16_t assoc_type;
229     uint32_t assoc_desc;
230     uint32_t seq_no; /*unused*/
231     uint8_t length; /*part of filename field*/
232     uint8_t filename[0]; /* UTF-16 encoded */
233     char date_created[0]; /*unused*/
234     char date_modified[0]; /*unused*/
235     char keywords[0]; /*unused*/
236     /* string and other data follows */
237 } QEMU_PACKED ObjectInfo;
238 
239 #define TYPE_USB_MTP "usb-mtp"
240 #define USB_MTP(obj) OBJECT_CHECK(MTPState, (obj), TYPE_USB_MTP)
241 
242 #define QEMU_STORAGE_ID 0x00010001
243 
244 #define MTP_FLAG_WRITABLE 0
245 
246 #define FLAG_SET(_mtp, _flag)  ((_mtp)->flags & (1 << (_flag)))
247 
248 /* ----------------------------------------------------------------------- */
249 
250 #define MTP_MANUFACTURER  "QEMU"
251 #define MTP_PRODUCT       "QEMU filesharing"
252 #define MTP_WRITE_BUF_SZ  (512 * KiB)
253 
254 enum {
255     STR_MANUFACTURER = 1,
256     STR_PRODUCT,
257     STR_SERIALNUMBER,
258     STR_MTP,
259     STR_CONFIG_FULL,
260     STR_CONFIG_HIGH,
261     STR_CONFIG_SUPER,
262 };
263 
264 static const USBDescStrings desc_strings = {
265     [STR_MANUFACTURER] = MTP_MANUFACTURER,
266     [STR_PRODUCT]      = MTP_PRODUCT,
267     [STR_SERIALNUMBER] = "34617",
268     [STR_MTP]          = "MTP",
269     [STR_CONFIG_FULL]  = "Full speed config (usb 1.1)",
270     [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
271     [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
272 };
273 
274 static const USBDescIface desc_iface_full = {
275     .bInterfaceNumber              = 0,
276     .bNumEndpoints                 = 3,
277     .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
278     .bInterfaceSubClass            = 0x01,
279     .bInterfaceProtocol            = 0x01,
280     .iInterface                    = STR_MTP,
281     .eps = (USBDescEndpoint[]) {
282         {
283             .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
284             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
285             .wMaxPacketSize        = 64,
286         },{
287             .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
288             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
289             .wMaxPacketSize        = 64,
290         },{
291             .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
292             .bmAttributes          = USB_ENDPOINT_XFER_INT,
293             .wMaxPacketSize        = 64,
294             .bInterval             = 0x0a,
295         },
296     }
297 };
298 
299 static const USBDescDevice desc_device_full = {
300     .bcdUSB                        = 0x0200,
301     .bMaxPacketSize0               = 8,
302     .bNumConfigurations            = 1,
303     .confs = (USBDescConfig[]) {
304         {
305             .bNumInterfaces        = 1,
306             .bConfigurationValue   = 1,
307             .iConfiguration        = STR_CONFIG_FULL,
308             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
309             .bMaxPower             = 2,
310             .nif = 1,
311             .ifs = &desc_iface_full,
312         },
313     },
314 };
315 
316 static const USBDescIface desc_iface_high = {
317     .bInterfaceNumber              = 0,
318     .bNumEndpoints                 = 3,
319     .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
320     .bInterfaceSubClass            = 0x01,
321     .bInterfaceProtocol            = 0x01,
322     .iInterface                    = STR_MTP,
323     .eps = (USBDescEndpoint[]) {
324         {
325             .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
326             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
327             .wMaxPacketSize        = 512,
328         },{
329             .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
330             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
331             .wMaxPacketSize        = 512,
332         },{
333             .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
334             .bmAttributes          = USB_ENDPOINT_XFER_INT,
335             .wMaxPacketSize        = 64,
336             .bInterval             = 0x0a,
337         },
338     }
339 };
340 
341 static const USBDescDevice desc_device_high = {
342     .bcdUSB                        = 0x0200,
343     .bMaxPacketSize0               = 64,
344     .bNumConfigurations            = 1,
345     .confs = (USBDescConfig[]) {
346         {
347             .bNumInterfaces        = 1,
348             .bConfigurationValue   = 1,
349             .iConfiguration        = STR_CONFIG_HIGH,
350             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
351             .bMaxPower             = 2,
352             .nif = 1,
353             .ifs = &desc_iface_high,
354         },
355     },
356 };
357 
358 static const USBDescMSOS desc_msos = {
359     .CompatibleID = "MTP",
360     .SelectiveSuspendEnabled = true,
361 };
362 
363 static const USBDesc desc = {
364     .id = {
365         .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
366         .idProduct         = 0x0004,
367         .bcdDevice         = 0,
368         .iManufacturer     = STR_MANUFACTURER,
369         .iProduct          = STR_PRODUCT,
370         .iSerialNumber     = STR_SERIALNUMBER,
371     },
372     .full  = &desc_device_full,
373     .high  = &desc_device_high,
374     .str   = desc_strings,
375     .msos  = &desc_msos,
376 };
377 
378 /* ----------------------------------------------------------------------- */
379 
380 static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle,
381                                        MTPObject *parent, const char *name)
382 {
383     MTPObject *o = g_new0(MTPObject, 1);
384 
385     if (name[0] == '.') {
386         goto ignore;
387     }
388 
389     o->watchid = -1;
390     o->handle = handle;
391     o->parent = parent;
392     o->name = g_strdup(name);
393     if (parent == NULL) {
394         o->path = g_strdup(name);
395     } else {
396         o->path = g_strdup_printf("%s/%s", parent->path, name);
397     }
398 
399     if (lstat(o->path, &o->stat) != 0) {
400         goto ignore;
401     }
402     if (S_ISREG(o->stat.st_mode)) {
403         o->format = FMT_UNDEFINED_OBJECT;
404     } else if (S_ISDIR(o->stat.st_mode)) {
405         o->format = FMT_ASSOCIATION;
406     } else {
407         goto ignore;
408     }
409 
410     if (access(o->path, R_OK) != 0) {
411         goto ignore;
412     }
413 
414     trace_usb_mtp_object_alloc(s->dev.addr, o->handle, o->path);
415 
416     QTAILQ_INSERT_TAIL(&s->objects, o, next);
417     return o;
418 
419 ignore:
420     g_free(o->name);
421     g_free(o->path);
422     g_free(o);
423     return NULL;
424 }
425 
426 static void usb_mtp_object_free(MTPState *s, MTPObject *o)
427 {
428     MTPObject *iter;
429 
430     if (!o) {
431         return;
432     }
433 
434     trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path);
435 
436     if (o->watchid != -1 && s->file_monitor) {
437         qemu_file_monitor_remove_watch(s->file_monitor, o->path, o->watchid);
438     }
439 
440     QTAILQ_REMOVE(&s->objects, o, next);
441     if (o->parent) {
442         QLIST_REMOVE(o, list);
443         o->parent->nchildren--;
444     }
445 
446     while (!QLIST_EMPTY(&o->children)) {
447         iter = QLIST_FIRST(&o->children);
448         usb_mtp_object_free(s, iter);
449     }
450     g_free(o->name);
451     g_free(o->path);
452     g_free(o);
453 }
454 
455 static MTPObject *usb_mtp_object_lookup(MTPState *s, uint32_t handle)
456 {
457     MTPObject *o;
458 
459     QTAILQ_FOREACH(o, &s->objects, next) {
460         if (o->handle == handle) {
461             return o;
462         }
463     }
464     return NULL;
465 }
466 
467 static MTPObject *usb_mtp_add_child(MTPState *s, MTPObject *o,
468                                     const char *name)
469 {
470     MTPObject *child =
471         usb_mtp_object_alloc(s, s->next_handle++, o, name);
472 
473     if (child) {
474         trace_usb_mtp_add_child(s->dev.addr, child->handle, child->path);
475         QLIST_INSERT_HEAD(&o->children, child, list);
476         o->nchildren++;
477 
478         if (child->format == FMT_ASSOCIATION) {
479             QLIST_INIT(&child->children);
480         }
481     }
482 
483     return child;
484 }
485 
486 static MTPObject *usb_mtp_object_lookup_name(MTPObject *parent,
487                                              const char *name, int len)
488 {
489     MTPObject *iter;
490 
491     if (len == -1) {
492         len = strlen(name);
493     }
494 
495     QLIST_FOREACH(iter, &parent->children, list) {
496         if (strncmp(iter->name, name, len) == 0) {
497             return iter;
498         }
499     }
500 
501     return NULL;
502 }
503 
504 static MTPObject *usb_mtp_object_lookup_id(MTPState *s, int64_t id)
505 {
506     MTPObject *iter;
507 
508     QTAILQ_FOREACH(iter, &s->objects, next) {
509         if (iter->watchid == id) {
510             return iter;
511         }
512     }
513 
514     return NULL;
515 }
516 
517 static void file_monitor_event(int64_t id,
518                                QFileMonitorEvent ev,
519                                const char *name,
520                                void *opaque)
521 {
522     MTPState *s = opaque;
523     MTPObject *parent = usb_mtp_object_lookup_id(s, id);
524     MTPMonEntry *entry = NULL;
525     MTPObject *o;
526 
527     if (!parent) {
528         return;
529     }
530 
531     switch (ev) {
532     case QFILE_MONITOR_EVENT_CREATED:
533         if (usb_mtp_object_lookup_name(parent, name, -1)) {
534             /* Duplicate create event */
535             return;
536         }
537         entry = g_new0(MTPMonEntry, 1);
538         entry->handle = s->next_handle;
539         entry->event = EVT_OBJ_ADDED;
540         o = usb_mtp_add_child(s, parent, name);
541         if (!o) {
542             g_free(entry);
543             return;
544         }
545         trace_usb_mtp_file_monitor_event(s->dev.addr, name, "Obj Added");
546         break;
547 
548     case QFILE_MONITOR_EVENT_DELETED:
549         /*
550          * The kernel issues a IN_IGNORED event
551          * when a dir containing a watchpoint is
552          * deleted, so we don't have to delete the
553          * watchpoint
554          */
555         o = usb_mtp_object_lookup_name(parent, name, -1);
556         if (!o) {
557             return;
558         }
559         entry = g_new0(MTPMonEntry, 1);
560         entry->handle = o->handle;
561         entry->event = EVT_OBJ_REMOVED;
562         trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, "Obj Deleted");
563         usb_mtp_object_free(s, o);
564         break;
565 
566     case QFILE_MONITOR_EVENT_MODIFIED:
567         o = usb_mtp_object_lookup_name(parent, name, -1);
568         if (!o) {
569             return;
570         }
571         entry = g_new0(MTPMonEntry, 1);
572         entry->handle = o->handle;
573         entry->event = EVT_OBJ_INFO_CHANGED;
574         trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, "Obj Modified");
575         break;
576 
577     case QFILE_MONITOR_EVENT_IGNORED:
578         trace_usb_mtp_file_monitor_event(s->dev.addr, parent->path,
579                                     "Obj parent dir ignored");
580         break;
581 
582     case QFILE_MONITOR_EVENT_ATTRIBUTES:
583         break;
584 
585     default:
586         g_assert_not_reached();
587     }
588 
589     if (entry) {
590         QTAILQ_INSERT_HEAD(&s->events, entry, next);
591     }
592 }
593 
594 static void usb_mtp_file_monitor_cleanup(MTPState *s)
595 {
596     MTPMonEntry *e, *p;
597 
598     QTAILQ_FOREACH_SAFE(e, &s->events, next, p) {
599         QTAILQ_REMOVE(&s->events, e, next);
600         g_free(e);
601     }
602 
603     qemu_file_monitor_free(s->file_monitor);
604     s->file_monitor = NULL;
605 }
606 
607 
608 static void usb_mtp_object_readdir(MTPState *s, MTPObject *o)
609 {
610     struct dirent *entry;
611     DIR *dir;
612     int fd;
613     Error *err = NULL;
614 
615     if (o->have_children) {
616         return;
617     }
618     o->have_children = true;
619 
620     fd = open(o->path, O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
621     if (fd < 0) {
622         return;
623     }
624     dir = fdopendir(fd);
625     if (!dir) {
626         close(fd);
627         return;
628     }
629 
630     if (s->file_monitor) {
631         int64_t id = qemu_file_monitor_add_watch(s->file_monitor, o->path, NULL,
632                                                  file_monitor_event, s, &err);
633         if (id == -1) {
634             error_reportf_err(err,
635                               "usb-mtp: failed to add watch for %s: ",
636                               o->path);
637         } else {
638             trace_usb_mtp_file_monitor_event(s->dev.addr, o->path,
639                                              "Watch Added");
640             o->watchid = id;
641         }
642     }
643 
644     while ((entry = readdir(dir)) != NULL) {
645         usb_mtp_add_child(s, o, entry->d_name);
646     }
647     closedir(dir);
648 }
649 
650 /* ----------------------------------------------------------------------- */
651 
652 static MTPData *usb_mtp_data_alloc(MTPControl *c)
653 {
654     MTPData *data = g_new0(MTPData, 1);
655 
656     data->code  = c->code;
657     data->trans = c->trans;
658     data->fd    = -1;
659     data->first = true;
660     return data;
661 }
662 
663 static void usb_mtp_data_free(MTPData *data)
664 {
665     if (data == NULL) {
666         return;
667     }
668     if (data->fd != -1) {
669         close(data->fd);
670     }
671     g_free(data->data);
672     g_free(data);
673 }
674 
675 static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
676 {
677     if (data->length + bytes <= data->alloc) {
678         return;
679     }
680     data->alloc = (data->length + bytes + 0xff) & ~0xff;
681     data->data  = g_realloc(data->data, data->alloc);
682 }
683 
684 static void usb_mtp_add_u8(MTPData *data, uint8_t val)
685 {
686     usb_mtp_realloc(data, 1);
687     data->data[data->length++] = val;
688 }
689 
690 static void usb_mtp_add_u16(MTPData *data, uint16_t val)
691 {
692     usb_mtp_realloc(data, 2);
693     data->data[data->length++] = (val >> 0) & 0xff;
694     data->data[data->length++] = (val >> 8) & 0xff;
695 }
696 
697 static void usb_mtp_add_u32(MTPData *data, uint32_t val)
698 {
699     usb_mtp_realloc(data, 4);
700     data->data[data->length++] = (val >>  0) & 0xff;
701     data->data[data->length++] = (val >>  8) & 0xff;
702     data->data[data->length++] = (val >> 16) & 0xff;
703     data->data[data->length++] = (val >> 24) & 0xff;
704 }
705 
706 static void usb_mtp_add_u64(MTPData *data, uint64_t val)
707 {
708     usb_mtp_realloc(data, 8);
709     data->data[data->length++] = (val >>  0) & 0xff;
710     data->data[data->length++] = (val >>  8) & 0xff;
711     data->data[data->length++] = (val >> 16) & 0xff;
712     data->data[data->length++] = (val >> 24) & 0xff;
713     data->data[data->length++] = (val >> 32) & 0xff;
714     data->data[data->length++] = (val >> 40) & 0xff;
715     data->data[data->length++] = (val >> 48) & 0xff;
716     data->data[data->length++] = (val >> 56) & 0xff;
717 }
718 
719 static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
720                                   const uint16_t *vals)
721 {
722     int i;
723 
724     usb_mtp_add_u32(data, len);
725     for (i = 0; i < len; i++) {
726         usb_mtp_add_u16(data, vals[i]);
727     }
728 }
729 
730 static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
731                                   const uint32_t *vals)
732 {
733     int i;
734 
735     usb_mtp_add_u32(data, len);
736     for (i = 0; i < len; i++) {
737         usb_mtp_add_u32(data, vals[i]);
738     }
739 }
740 
741 static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
742 {
743     uint32_t len = wcslen(str);
744     int i;
745 
746     if (len > 0) {
747         len++; /* include terminating L'\0' */
748     }
749 
750     usb_mtp_add_u8(data, len);
751     for (i = 0; i < len; i++) {
752         usb_mtp_add_u16(data, str[i]);
753     }
754 }
755 
756 static void usb_mtp_add_str(MTPData *data, const char *str)
757 {
758     uint32_t len = strlen(str)+1;
759     wchar_t *wstr = g_new(wchar_t, len);
760     size_t ret;
761 
762     ret = mbstowcs(wstr, str, len);
763     if (ret == -1) {
764         usb_mtp_add_wstr(data, L"Oops");
765     } else {
766         usb_mtp_add_wstr(data, wstr);
767     }
768 
769     g_free(wstr);
770 }
771 
772 static void usb_mtp_add_time(MTPData *data, time_t time)
773 {
774     char buf[16];
775     struct tm tm;
776 
777     gmtime_r(&time, &tm);
778     strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm);
779     usb_mtp_add_str(data, buf);
780 }
781 
782 /* ----------------------------------------------------------------------- */
783 
784 static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans,
785                                  int argc, uint32_t arg0, uint32_t arg1,
786                                  uint32_t arg2)
787 {
788     MTPControl *c = g_new0(MTPControl, 1);
789 
790     c->code  = code;
791     c->trans = trans;
792     c->argc  = argc;
793     if (argc > 0) {
794         c->argv[0] = arg0;
795     }
796     if (argc > 1) {
797         c->argv[1] = arg1;
798     }
799     if (argc > 2) {
800         c->argv[2] = arg2;
801     }
802 
803     assert(s->result == NULL);
804     s->result = c;
805 }
806 
807 /* ----------------------------------------------------------------------- */
808 
809 static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
810 {
811     static const uint16_t ops[] = {
812         CMD_GET_DEVICE_INFO,
813         CMD_OPEN_SESSION,
814         CMD_CLOSE_SESSION,
815         CMD_GET_STORAGE_IDS,
816         CMD_GET_STORAGE_INFO,
817         CMD_GET_NUM_OBJECTS,
818         CMD_GET_OBJECT_HANDLES,
819         CMD_GET_OBJECT_INFO,
820         CMD_DELETE_OBJECT,
821         CMD_SEND_OBJECT_INFO,
822         CMD_SEND_OBJECT,
823         CMD_GET_OBJECT,
824         CMD_GET_PARTIAL_OBJECT,
825         CMD_GET_OBJECT_PROPS_SUPPORTED,
826         CMD_GET_OBJECT_PROP_DESC,
827         CMD_GET_OBJECT_PROP_VALUE,
828     };
829     static const uint16_t fmt[] = {
830         FMT_UNDEFINED_OBJECT,
831         FMT_ASSOCIATION,
832     };
833     MTPData *d = usb_mtp_data_alloc(c);
834 
835     trace_usb_mtp_op_get_device_info(s->dev.addr);
836 
837     usb_mtp_add_u16(d, 100);
838     usb_mtp_add_u32(d, 0x00000006);
839     usb_mtp_add_u16(d, 0x0064);
840     usb_mtp_add_wstr(d, L"");
841     usb_mtp_add_u16(d, 0x0000);
842 
843     usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops);
844     usb_mtp_add_u16_array(d, 0, NULL);
845     usb_mtp_add_u16_array(d, 0, NULL);
846     usb_mtp_add_u16_array(d, 0, NULL);
847     usb_mtp_add_u16_array(d, ARRAY_SIZE(fmt), fmt);
848 
849     usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER);
850     usb_mtp_add_wstr(d, L"" MTP_PRODUCT);
851     usb_mtp_add_wstr(d, L"0.1");
852     usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef");
853 
854     return d;
855 }
856 
857 static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
858 {
859     static const uint32_t ids[] = {
860         QEMU_STORAGE_ID,
861     };
862     MTPData *d = usb_mtp_data_alloc(c);
863 
864     trace_usb_mtp_op_get_storage_ids(s->dev.addr);
865 
866     usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
867 
868     return d;
869 }
870 
871 static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
872 {
873     MTPData *d = usb_mtp_data_alloc(c);
874     struct statvfs buf;
875     int rc;
876 
877     trace_usb_mtp_op_get_storage_info(s->dev.addr);
878 
879     if (FLAG_SET(s, MTP_FLAG_WRITABLE)) {
880         usb_mtp_add_u16(d, 0x0003);
881         usb_mtp_add_u16(d, 0x0002);
882         usb_mtp_add_u16(d, 0x0000);
883     } else {
884         usb_mtp_add_u16(d, 0x0001);
885         usb_mtp_add_u16(d, 0x0002);
886         usb_mtp_add_u16(d, 0x0001);
887     }
888 
889     rc = statvfs(s->root, &buf);
890     if (rc == 0) {
891         usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks);
892         usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks);
893         usb_mtp_add_u32(d, buf.f_ffree);
894     } else {
895         usb_mtp_add_u64(d, 0xffffffff);
896         usb_mtp_add_u64(d, 0xffffffff);
897         usb_mtp_add_u32(d, 0xffffffff);
898     }
899 
900     usb_mtp_add_str(d, s->desc);
901     usb_mtp_add_wstr(d, L"123456789abcdef");
902     return d;
903 }
904 
905 static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
906                                            MTPObject *o)
907 {
908     MTPData *d = usb_mtp_data_alloc(c);
909     uint32_t i = 0, handles[o->nchildren];
910     MTPObject *iter;
911 
912     trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
913 
914     QLIST_FOREACH(iter, &o->children, list) {
915         handles[i++] = iter->handle;
916     }
917     assert(i == o->nchildren);
918     usb_mtp_add_u32_array(d, o->nchildren, handles);
919 
920     return d;
921 }
922 
923 static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
924                                         MTPObject *o)
925 {
926     MTPData *d = usb_mtp_data_alloc(c);
927 
928     trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
929 
930     usb_mtp_add_u32(d, QEMU_STORAGE_ID);
931     usb_mtp_add_u16(d, o->format);
932     usb_mtp_add_u16(d, 0);
933 
934     if (o->stat.st_size > 0xFFFFFFFF) {
935         usb_mtp_add_u32(d, 0xFFFFFFFF);
936     } else {
937         usb_mtp_add_u32(d, o->stat.st_size);
938     }
939 
940     usb_mtp_add_u16(d, 0);
941     usb_mtp_add_u32(d, 0);
942     usb_mtp_add_u32(d, 0);
943     usb_mtp_add_u32(d, 0);
944     usb_mtp_add_u32(d, 0);
945     usb_mtp_add_u32(d, 0);
946     usb_mtp_add_u32(d, 0);
947 
948     if (o->parent) {
949         usb_mtp_add_u32(d, o->parent->handle);
950     } else {
951         usb_mtp_add_u32(d, 0);
952     }
953     if (o->format == FMT_ASSOCIATION) {
954         usb_mtp_add_u16(d, 0x0001);
955         usb_mtp_add_u32(d, 0x00000001);
956         usb_mtp_add_u32(d, 0);
957     } else {
958         usb_mtp_add_u16(d, 0);
959         usb_mtp_add_u32(d, 0);
960         usb_mtp_add_u32(d, 0);
961     }
962 
963     usb_mtp_add_str(d, o->name);
964     usb_mtp_add_time(d, o->stat.st_ctime);
965     usb_mtp_add_time(d, o->stat.st_mtime);
966     usb_mtp_add_wstr(d, L"");
967 
968     return d;
969 }
970 
971 static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
972                                    MTPObject *o)
973 {
974     MTPData *d = usb_mtp_data_alloc(c);
975 
976     trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
977 
978     d->fd = open(o->path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
979     if (d->fd == -1) {
980         usb_mtp_data_free(d);
981         return NULL;
982     }
983     d->length = o->stat.st_size;
984     d->alloc  = 512;
985     d->data   = g_malloc(d->alloc);
986     return d;
987 }
988 
989 static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
990                                            MTPObject *o)
991 {
992     MTPData *d;
993     off_t offset;
994 
995     if (c->argc <= 2) {
996         return NULL;
997     }
998     trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
999                                         c->argv[1], c->argv[2]);
1000 
1001     d = usb_mtp_data_alloc(c);
1002     d->fd = open(o->path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
1003     if (d->fd == -1) {
1004         usb_mtp_data_free(d);
1005         return NULL;
1006     }
1007 
1008     offset = c->argv[1];
1009     if (offset > o->stat.st_size) {
1010         offset = o->stat.st_size;
1011     }
1012     if (lseek(d->fd, offset, SEEK_SET) < 0) {
1013         usb_mtp_data_free(d);
1014         return NULL;
1015     }
1016 
1017     d->length = c->argv[2];
1018     if (d->length > o->stat.st_size - offset) {
1019         d->length = o->stat.st_size - offset;
1020     }
1021 
1022     return d;
1023 }
1024 
1025 static MTPData *usb_mtp_get_object_props_supported(MTPState *s, MTPControl *c)
1026 {
1027     static const uint16_t props[] = {
1028         PROP_STORAGE_ID,
1029         PROP_OBJECT_FORMAT,
1030         PROP_OBJECT_COMPRESSED_SIZE,
1031         PROP_PARENT_OBJECT,
1032         PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER,
1033         PROP_NAME,
1034     };
1035     MTPData *d = usb_mtp_data_alloc(c);
1036     usb_mtp_add_u16_array(d, ARRAY_SIZE(props), props);
1037 
1038     return d;
1039 }
1040 
1041 static MTPData *usb_mtp_get_object_prop_desc(MTPState *s, MTPControl *c)
1042 {
1043     MTPData *d = usb_mtp_data_alloc(c);
1044     switch (c->argv[0]) {
1045     case PROP_STORAGE_ID:
1046         usb_mtp_add_u16(d, PROP_STORAGE_ID);
1047         usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1048         usb_mtp_add_u8(d, 0x00);
1049         usb_mtp_add_u32(d, 0x00000000);
1050         usb_mtp_add_u32(d, 0x00000000);
1051         usb_mtp_add_u8(d, 0x00);
1052         break;
1053     case PROP_OBJECT_FORMAT:
1054         usb_mtp_add_u16(d, PROP_OBJECT_FORMAT);
1055         usb_mtp_add_u16(d, DATA_TYPE_UINT16);
1056         usb_mtp_add_u8(d, 0x00);
1057         usb_mtp_add_u16(d, 0x0000);
1058         usb_mtp_add_u32(d, 0x00000000);
1059         usb_mtp_add_u8(d, 0x00);
1060         break;
1061     case PROP_OBJECT_COMPRESSED_SIZE:
1062         usb_mtp_add_u16(d, PROP_OBJECT_COMPRESSED_SIZE);
1063         usb_mtp_add_u16(d, DATA_TYPE_UINT64);
1064         usb_mtp_add_u8(d, 0x00);
1065         usb_mtp_add_u64(d, 0x0000000000000000);
1066         usb_mtp_add_u32(d, 0x00000000);
1067         usb_mtp_add_u8(d, 0x00);
1068         break;
1069     case PROP_PARENT_OBJECT:
1070         usb_mtp_add_u16(d, PROP_PARENT_OBJECT);
1071         usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1072         usb_mtp_add_u8(d, 0x00);
1073         usb_mtp_add_u32(d, 0x00000000);
1074         usb_mtp_add_u32(d, 0x00000000);
1075         usb_mtp_add_u8(d, 0x00);
1076         break;
1077     case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1078         usb_mtp_add_u16(d, PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER);
1079         usb_mtp_add_u16(d, DATA_TYPE_UINT128);
1080         usb_mtp_add_u8(d, 0x00);
1081         usb_mtp_add_u64(d, 0x0000000000000000);
1082         usb_mtp_add_u64(d, 0x0000000000000000);
1083         usb_mtp_add_u32(d, 0x00000000);
1084         usb_mtp_add_u8(d, 0x00);
1085         break;
1086     case PROP_NAME:
1087         usb_mtp_add_u16(d, PROP_NAME);
1088         usb_mtp_add_u16(d, DATA_TYPE_STRING);
1089         usb_mtp_add_u8(d, 0x00);
1090         usb_mtp_add_u8(d, 0x00);
1091         usb_mtp_add_u32(d, 0x00000000);
1092         usb_mtp_add_u8(d, 0x00);
1093         break;
1094     default:
1095         usb_mtp_data_free(d);
1096         return NULL;
1097     }
1098 
1099     return d;
1100 }
1101 
1102 static MTPData *usb_mtp_get_object_prop_value(MTPState *s, MTPControl *c,
1103                                               MTPObject *o)
1104 {
1105     MTPData *d = usb_mtp_data_alloc(c);
1106     switch (c->argv[1]) {
1107     case PROP_STORAGE_ID:
1108         usb_mtp_add_u32(d, QEMU_STORAGE_ID);
1109         break;
1110     case PROP_OBJECT_FORMAT:
1111         usb_mtp_add_u16(d, o->format);
1112         break;
1113     case PROP_OBJECT_COMPRESSED_SIZE:
1114         usb_mtp_add_u64(d, o->stat.st_size);
1115         break;
1116     case PROP_PARENT_OBJECT:
1117         if (o->parent == NULL) {
1118             usb_mtp_add_u32(d, 0x00000000);
1119         } else {
1120             usb_mtp_add_u32(d, o->parent->handle);
1121         }
1122         break;
1123     case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1124         /* Should be persistent between sessions,
1125          * but using our objedt ID is "good enough"
1126          * for now */
1127         usb_mtp_add_u64(d, 0x0000000000000000);
1128         usb_mtp_add_u64(d, o->handle);
1129         break;
1130     case PROP_NAME:
1131         usb_mtp_add_str(d, o->name);
1132         break;
1133     default:
1134         usb_mtp_data_free(d);
1135         return NULL;
1136     }
1137 
1138     return d;
1139 }
1140 
1141 /*
1142  * Return values when object @o is deleted.
1143  * If at least one of the deletions succeeded,
1144  * DELETE_SUCCESS is set and if at least one
1145  * of the deletions failed, DELETE_FAILURE is
1146  * set. Both bits being set (DELETE_PARTIAL)
1147  * signifies a  RES_PARTIAL_DELETE being sent
1148  * back to the initiator.
1149  */
1150 enum {
1151     DELETE_SUCCESS = (1 << 0),
1152     DELETE_FAILURE = (1 << 1),
1153     DELETE_PARTIAL = (DELETE_FAILURE | DELETE_SUCCESS),
1154 };
1155 
1156 static int usb_mtp_deletefn(MTPState *s, MTPObject *o, uint32_t trans)
1157 {
1158     MTPObject *iter, *iter2;
1159     int ret = 0;
1160 
1161     /*
1162      * TODO: Add support for Protection Status
1163      */
1164 
1165     QLIST_FOREACH(iter, &o->children, list) {
1166         if (iter->format == FMT_ASSOCIATION) {
1167             QLIST_FOREACH(iter2, &iter->children, list) {
1168                 ret |= usb_mtp_deletefn(s, iter2, trans);
1169             }
1170         }
1171     }
1172 
1173     if (o->format == FMT_UNDEFINED_OBJECT) {
1174         if (remove(o->path)) {
1175             ret |= DELETE_FAILURE;
1176         } else {
1177             usb_mtp_object_free(s, o);
1178             ret |= DELETE_SUCCESS;
1179         }
1180     } else if (o->format == FMT_ASSOCIATION) {
1181         if (rmdir(o->path)) {
1182             ret |= DELETE_FAILURE;
1183         } else {
1184             usb_mtp_object_free(s, o);
1185             ret |= DELETE_SUCCESS;
1186         }
1187     }
1188 
1189     return ret;
1190 }
1191 
1192 static void usb_mtp_object_delete(MTPState *s, uint32_t handle,
1193                                   uint32_t format_code, uint32_t trans)
1194 {
1195     MTPObject *o;
1196     int ret;
1197 
1198     /* Return error if store is read-only */
1199     if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1200         usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1201                              trans, 0, 0, 0, 0);
1202         return;
1203     }
1204 
1205     if (format_code != 0) {
1206         usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1207                              trans, 0, 0, 0, 0);
1208         return;
1209     }
1210 
1211     if (handle == 0xFFFFFFF) {
1212         o = QTAILQ_FIRST(&s->objects);
1213     } else {
1214         o = usb_mtp_object_lookup(s, handle);
1215     }
1216     if (o == NULL) {
1217         usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1218                              trans, 0, 0, 0, 0);
1219         return;
1220     }
1221 
1222     ret = usb_mtp_deletefn(s, o, trans);
1223     switch (ret) {
1224     case DELETE_SUCCESS:
1225         usb_mtp_queue_result(s, RES_OK, trans,
1226                              0, 0, 0, 0);
1227         break;
1228     case DELETE_FAILURE:
1229         usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1230                              trans, 0, 0, 0, 0);
1231         break;
1232     case DELETE_PARTIAL:
1233         usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1234                              trans, 0, 0, 0, 0);
1235         break;
1236     default:
1237         g_assert_not_reached();
1238     }
1239 
1240     return;
1241 }
1242 
1243 static void usb_mtp_command(MTPState *s, MTPControl *c)
1244 {
1245     MTPData *data_in = NULL;
1246     MTPObject *o = NULL;
1247     uint32_t nres = 0, res0 = 0;
1248     Error *err = NULL;
1249 
1250     /* sanity checks */
1251     if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
1252         usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
1253                              c->trans, 0, 0, 0, 0);
1254         return;
1255     }
1256 
1257     /* process commands */
1258     switch (c->code) {
1259     case CMD_GET_DEVICE_INFO:
1260         data_in = usb_mtp_get_device_info(s, c);
1261         break;
1262     case CMD_OPEN_SESSION:
1263         if (s->session) {
1264             usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
1265                                  c->trans, 1, s->session, 0, 0);
1266             return;
1267         }
1268         if (c->argv[0] == 0) {
1269             usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
1270                                  c->trans, 0, 0, 0, 0);
1271             return;
1272         }
1273         trace_usb_mtp_op_open_session(s->dev.addr);
1274         s->session = c->argv[0];
1275         usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
1276 
1277         s->file_monitor = qemu_file_monitor_new(&err);
1278         if (err) {
1279             error_reportf_err(err,
1280                               "usb-mtp: file monitoring init failed: ");
1281         } else {
1282             QTAILQ_INIT(&s->events);
1283         }
1284         break;
1285     case CMD_CLOSE_SESSION:
1286         trace_usb_mtp_op_close_session(s->dev.addr);
1287         s->session = 0;
1288         s->next_handle = 0;
1289         usb_mtp_file_monitor_cleanup(s);
1290         usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1291         assert(QTAILQ_EMPTY(&s->objects));
1292         break;
1293     case CMD_GET_STORAGE_IDS:
1294         data_in = usb_mtp_get_storage_ids(s, c);
1295         break;
1296     case CMD_GET_STORAGE_INFO:
1297         if (c->argv[0] != QEMU_STORAGE_ID &&
1298             c->argv[0] != 0xffffffff) {
1299             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1300                                  c->trans, 0, 0, 0, 0);
1301             return;
1302         }
1303         data_in = usb_mtp_get_storage_info(s, c);
1304         break;
1305     case CMD_GET_NUM_OBJECTS:
1306     case CMD_GET_OBJECT_HANDLES:
1307         if (c->argv[0] != QEMU_STORAGE_ID &&
1308             c->argv[0] != 0xffffffff) {
1309             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1310                                  c->trans, 0, 0, 0, 0);
1311             return;
1312         }
1313         if (c->argv[1] != 0x00000000) {
1314             usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1315                                  c->trans, 0, 0, 0, 0);
1316             return;
1317         }
1318         if (c->argv[2] == 0x00000000 ||
1319             c->argv[2] == 0xffffffff) {
1320             o = QTAILQ_FIRST(&s->objects);
1321         } else {
1322             o = usb_mtp_object_lookup(s, c->argv[2]);
1323         }
1324         if (o == NULL) {
1325             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1326                                  c->trans, 0, 0, 0, 0);
1327             return;
1328         }
1329         if (o->format != FMT_ASSOCIATION) {
1330             usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
1331                                  c->trans, 0, 0, 0, 0);
1332             return;
1333         }
1334         usb_mtp_object_readdir(s, o);
1335         if (c->code == CMD_GET_NUM_OBJECTS) {
1336             trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
1337             nres = 1;
1338             res0 = o->nchildren;
1339         } else {
1340             data_in = usb_mtp_get_object_handles(s, c, o);
1341         }
1342         break;
1343     case CMD_GET_OBJECT_INFO:
1344         o = usb_mtp_object_lookup(s, c->argv[0]);
1345         if (o == NULL) {
1346             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1347                                  c->trans, 0, 0, 0, 0);
1348             return;
1349         }
1350         data_in = usb_mtp_get_object_info(s, c, o);
1351         break;
1352     case CMD_GET_OBJECT:
1353         o = usb_mtp_object_lookup(s, c->argv[0]);
1354         if (o == NULL) {
1355             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1356                                  c->trans, 0, 0, 0, 0);
1357             return;
1358         }
1359         if (o->format == FMT_ASSOCIATION) {
1360             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1361                                  c->trans, 0, 0, 0, 0);
1362             return;
1363         }
1364         data_in = usb_mtp_get_object(s, c, o);
1365         if (data_in == NULL) {
1366             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1367                                  c->trans, 0, 0, 0, 0);
1368             return;
1369         }
1370         break;
1371     case CMD_DELETE_OBJECT:
1372         usb_mtp_object_delete(s, c->argv[0], c->argv[1], c->trans);
1373         return;
1374     case CMD_GET_PARTIAL_OBJECT:
1375         o = usb_mtp_object_lookup(s, c->argv[0]);
1376         if (o == NULL) {
1377             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1378                                  c->trans, 0, 0, 0, 0);
1379             return;
1380         }
1381         if (o->format == FMT_ASSOCIATION) {
1382             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1383                                  c->trans, 0, 0, 0, 0);
1384             return;
1385         }
1386         data_in = usb_mtp_get_partial_object(s, c, o);
1387         if (data_in == NULL) {
1388             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1389                                  c->trans, 0, 0, 0, 0);
1390             return;
1391         }
1392         nres = 1;
1393         res0 = data_in->length;
1394         break;
1395     case CMD_SEND_OBJECT_INFO:
1396         /* Return error if store is read-only */
1397         if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1398             usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1399                                  c->trans, 0, 0, 0, 0);
1400         } else if (c->argv[0] && (c->argv[0] != QEMU_STORAGE_ID)) {
1401             /* First parameter points to storage id or is 0 */
1402             usb_mtp_queue_result(s, RES_STORE_NOT_AVAILABLE, c->trans,
1403                                  0, 0, 0, 0);
1404         } else if (c->argv[1] && !c->argv[0]) {
1405             /* If second parameter is specified, first must also be specified */
1406             usb_mtp_queue_result(s, RES_DESTINATION_UNSUPPORTED, c->trans,
1407                                  0, 0, 0, 0);
1408         } else {
1409             uint32_t handle = c->argv[1];
1410             if (handle == 0xFFFFFFFF || handle == 0) {
1411                 /* root object */
1412                 o = QTAILQ_FIRST(&s->objects);
1413             } else {
1414                 o = usb_mtp_object_lookup(s, handle);
1415             }
1416             if (o == NULL) {
1417                 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, c->trans,
1418                                      0, 0, 0, 0);
1419             } else if (o->format != FMT_ASSOCIATION) {
1420                 usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT, c->trans,
1421                                      0, 0, 0, 0);
1422             }
1423         }
1424         if (o) {
1425             s->dataset.parent_handle = o->handle;
1426         }
1427         s->data_out = usb_mtp_data_alloc(c);
1428         return;
1429     case CMD_SEND_OBJECT:
1430         if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1431             usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1432                                  c->trans, 0, 0, 0, 0);
1433             return;
1434         }
1435         if (!s->write_pending) {
1436             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO,
1437                                  c->trans, 0, 0, 0, 0);
1438             return;
1439         }
1440         s->data_out = usb_mtp_data_alloc(c);
1441         return;
1442     case CMD_GET_OBJECT_PROPS_SUPPORTED:
1443         if (c->argv[0] != FMT_UNDEFINED_OBJECT &&
1444             c->argv[0] != FMT_ASSOCIATION) {
1445             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1446                                  c->trans, 0, 0, 0, 0);
1447             return;
1448         }
1449         data_in = usb_mtp_get_object_props_supported(s, c);
1450         break;
1451     case CMD_GET_OBJECT_PROP_DESC:
1452         if (c->argv[1] != FMT_UNDEFINED_OBJECT &&
1453             c->argv[1] != FMT_ASSOCIATION) {
1454             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1455                                  c->trans, 0, 0, 0, 0);
1456             return;
1457         }
1458         data_in = usb_mtp_get_object_prop_desc(s, c);
1459         if (data_in == NULL) {
1460             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1461                                  c->trans, 0, 0, 0, 0);
1462             return;
1463         }
1464         break;
1465     case CMD_GET_OBJECT_PROP_VALUE:
1466         o = usb_mtp_object_lookup(s, c->argv[0]);
1467         if (o == NULL) {
1468             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1469                                  c->trans, 0, 0, 0, 0);
1470             return;
1471         }
1472         data_in = usb_mtp_get_object_prop_value(s, c, o);
1473         if (data_in == NULL) {
1474             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1475                                  c->trans, 0, 0, 0, 0);
1476             return;
1477         }
1478         break;
1479     default:
1480         trace_usb_mtp_op_unknown(s->dev.addr, c->code);
1481         usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
1482                              c->trans, 0, 0, 0, 0);
1483         return;
1484     }
1485 
1486     /* return results on success */
1487     if (data_in) {
1488         assert(s->data_in == NULL);
1489         s->data_in = data_in;
1490     }
1491     usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0, 0);
1492 }
1493 
1494 /* ----------------------------------------------------------------------- */
1495 
1496 static void usb_mtp_handle_reset(USBDevice *dev)
1497 {
1498     MTPState *s = USB_MTP(dev);
1499 
1500     trace_usb_mtp_reset(s->dev.addr);
1501 
1502     usb_mtp_file_monitor_cleanup(s);
1503     usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1504     s->session = 0;
1505     usb_mtp_data_free(s->data_in);
1506     s->data_in = NULL;
1507     usb_mtp_data_free(s->data_out);
1508     s->data_out = NULL;
1509     g_free(s->result);
1510     s->result = NULL;
1511 }
1512 
1513 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
1514                                    int request, int value, int index,
1515                                    int length, uint8_t *data)
1516 {
1517     int ret;
1518     MTPState *s = USB_MTP(dev);
1519     uint16_t *event = (uint16_t *)data;
1520 
1521     switch (request) {
1522     case ClassInterfaceOutRequest | 0x64:
1523         if (*event == EVT_CANCEL_TRANSACTION) {
1524             g_free(s->result);
1525             s->result = NULL;
1526             usb_mtp_data_free(s->data_in);
1527             s->data_in = NULL;
1528             if (s->write_pending) {
1529                 g_free(s->dataset.filename);
1530                 s->write_pending = false;
1531                 s->dataset.size = 0;
1532             }
1533             usb_mtp_data_free(s->data_out);
1534             s->data_out = NULL;
1535         } else {
1536             p->status = USB_RET_STALL;
1537         }
1538         break;
1539     default:
1540         ret = usb_desc_handle_control(dev, p, request,
1541                                       value, index, length, data);
1542         if (ret >= 0) {
1543             return;
1544         }
1545     }
1546 
1547     trace_usb_mtp_stall(dev->addr, "unknown control request");
1548 }
1549 
1550 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
1551 {
1552     /* we don't use async packets, so this should never be called */
1553     fprintf(stderr, "%s\n", __func__);
1554 }
1555 
1556 static char *utf16_to_str(uint8_t len, uint8_t *str16)
1557 {
1558     wchar_t *wstr = g_new0(wchar_t, len + 1);
1559     int count, dlen;
1560     char *dest;
1561 
1562     for (count = 0; count < len; count++) {
1563         /* FIXME: not working for surrogate pairs */
1564         wstr[count] = lduw_le_p(str16 + (count * 2));
1565     }
1566     wstr[count] = 0;
1567 
1568     dlen = wcstombs(NULL, wstr, 0) + 1;
1569     dest = g_malloc(dlen);
1570     wcstombs(dest, wstr, dlen);
1571     g_free(wstr);
1572     return dest;
1573 }
1574 
1575 /* Wrapper around write, returns 0 on failure */
1576 static uint64_t write_retry(int fd, void *buf, uint64_t size, off_t offset)
1577 {
1578         uint64_t ret = 0;
1579 
1580         if (lseek(fd, offset, SEEK_SET) < 0) {
1581             goto done;
1582         }
1583 
1584         ret = qemu_write_full(fd, buf, size);
1585 
1586 done:
1587         return ret;
1588 }
1589 
1590 static int usb_mtp_update_object(MTPObject *parent, char *name)
1591 {
1592     int ret = 0;
1593 
1594     MTPObject *o =
1595         usb_mtp_object_lookup_name(parent, name, strlen(name));
1596 
1597     if (o) {
1598         ret = lstat(o->path, &o->stat);
1599     }
1600 
1601     return ret;
1602 }
1603 
1604 static void usb_mtp_write_data(MTPState *s, uint32_t handle)
1605 {
1606     MTPData *d = s->data_out;
1607     MTPObject *parent =
1608         usb_mtp_object_lookup(s, s->dataset.parent_handle);
1609     char *path = NULL;
1610     uint64_t rc;
1611     mode_t mask = 0644;
1612     int ret = 0;
1613 
1614     assert(d != NULL);
1615 
1616     switch (d->write_status) {
1617     case WRITE_START:
1618         if (!parent || !s->write_pending) {
1619             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, d->trans,
1620                 0, 0, 0, 0);
1621             return;
1622         }
1623 
1624         if (s->dataset.filename) {
1625             path = g_strdup_printf("%s/%s", parent->path, s->dataset.filename);
1626             if (s->dataset.format == FMT_ASSOCIATION) {
1627                 ret = mkdir(path, mask);
1628                 if (!ret) {
1629                     usb_mtp_queue_result(s, RES_OK, d->trans, 3,
1630                                          QEMU_STORAGE_ID,
1631                                          s->dataset.parent_handle,
1632                                          handle);
1633                     goto close;
1634                 }
1635                 goto done;
1636             }
1637 
1638             d->fd = open(path, O_CREAT | O_WRONLY |
1639                          O_CLOEXEC | O_NOFOLLOW, mask);
1640             if (d->fd == -1) {
1641                 ret = 1;
1642                 goto done;
1643             }
1644 
1645             /* Return success if initiator sent 0 sized data */
1646             if (!s->dataset.size) {
1647                 goto done;
1648             }
1649             if (d->length != MTP_WRITE_BUF_SZ && !d->pending) {
1650                 d->write_status = WRITE_END;
1651             }
1652         }
1653         /* fall through */
1654     case WRITE_CONTINUE:
1655     case WRITE_END:
1656         rc = write_retry(d->fd, d->data, d->data_offset,
1657                          d->offset - d->data_offset);
1658         if (rc != d->data_offset) {
1659             ret = 1;
1660             goto done;
1661         }
1662         if (d->write_status != WRITE_END) {
1663             g_free(path);
1664             return;
1665         } else {
1666             /*
1667              * Return an incomplete transfer if file size doesn't match
1668              * for < 4G file or if lstat fails which will result in an incorrect
1669              * file size
1670              */
1671             if ((s->dataset.size != 0xFFFFFFFF &&
1672                  d->offset != s->dataset.size) ||
1673                 usb_mtp_update_object(parent, s->dataset.filename)) {
1674                 usb_mtp_queue_result(s, RES_INCOMPLETE_TRANSFER, d->trans,
1675                                      0, 0, 0, 0);
1676                 goto close;
1677             }
1678         }
1679     }
1680 
1681 done:
1682     if (ret) {
1683         usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1684                              0, 0, 0, 0);
1685     } else {
1686         usb_mtp_queue_result(s, RES_OK, d->trans,
1687                              0, 0, 0, 0);
1688     }
1689 close:
1690     /*
1691      * The write dataset is kept around and freed only
1692      * on success or if another write request comes in
1693      */
1694     if (d->fd != -1) {
1695         close(d->fd);
1696         d->fd = -1;
1697     }
1698     g_free(s->dataset.filename);
1699     s->dataset.size = 0;
1700     g_free(path);
1701     s->write_pending = false;
1702 }
1703 
1704 static void usb_mtp_write_metadata(MTPState *s, uint64_t dlen)
1705 {
1706     MTPData *d = s->data_out;
1707     ObjectInfo *dataset = (ObjectInfo *)d->data;
1708     char *filename;
1709     MTPObject *o;
1710     MTPObject *p = usb_mtp_object_lookup(s, s->dataset.parent_handle);
1711     uint32_t next_handle = s->next_handle;
1712     size_t filename_chars = dlen - offsetof(ObjectInfo, filename);
1713 
1714     /*
1715      * filename is utf-16. We're intentionally doing
1716      * integer division to truncate if malicious guest
1717      * sent an odd number of bytes.
1718      */
1719     filename_chars /= 2;
1720 
1721     assert(!s->write_pending);
1722     assert(p != NULL);
1723 
1724     filename = utf16_to_str(MIN(dataset->length, filename_chars),
1725                             dataset->filename);
1726 
1727     if (strchr(filename, '/')) {
1728         usb_mtp_queue_result(s, RES_PARAMETER_NOT_SUPPORTED, d->trans,
1729                              0, 0, 0, 0);
1730         g_free(filename);
1731         return;
1732     }
1733 
1734     o = usb_mtp_object_lookup_name(p, filename, -1);
1735     if (o != NULL) {
1736         next_handle = o->handle;
1737     }
1738 
1739     s->dataset.filename = filename;
1740     s->dataset.format = dataset->format;
1741     s->dataset.size = dataset->size;
1742     s->write_pending = true;
1743 
1744     if (s->dataset.format == FMT_ASSOCIATION) {
1745         usb_mtp_write_data(s, next_handle);
1746     } else {
1747         usb_mtp_queue_result(s, RES_OK, d->trans, 3, QEMU_STORAGE_ID,
1748                              s->dataset.parent_handle, next_handle);
1749     }
1750 }
1751 
1752 static void usb_mtp_get_data(MTPState *s, mtp_container *container,
1753                              USBPacket *p)
1754 {
1755     MTPData *d = s->data_out;
1756     uint64_t dlen;
1757     uint32_t data_len = p->iov.size;
1758     uint64_t total_len;
1759 
1760     if (!d) {
1761             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, 0,
1762                                  0, 0, 0, 0);
1763             return;
1764     }
1765     if (d->first) {
1766         /* Total length of incoming data */
1767         total_len = cpu_to_le32(container->length) - sizeof(mtp_container);
1768         /* Length of data in this packet */
1769         data_len -= sizeof(mtp_container);
1770         if (total_len < MTP_WRITE_BUF_SZ) {
1771                 usb_mtp_realloc(d, total_len);
1772                 d->length += total_len;
1773         } else {
1774                 usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - sizeof(mtp_container));
1775                 d->length += MTP_WRITE_BUF_SZ - sizeof(mtp_container);
1776         }
1777         d->offset = 0;
1778         d->first = false;
1779         d->pending = false;
1780         d->data_offset = 0;
1781         d->write_status = WRITE_START;
1782     }
1783 
1784     if (d->pending) {
1785         memset(d->data, 0, d->length);
1786         if (d->length != MTP_WRITE_BUF_SZ) {
1787             usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - d->length);
1788             d->length += (MTP_WRITE_BUF_SZ - d->length);
1789         }
1790         d->pending = false;
1791         d->write_status = WRITE_CONTINUE;
1792         d->data_offset = 0;
1793     }
1794 
1795     if (d->length - d->data_offset > data_len) {
1796         dlen = data_len;
1797     } else {
1798         dlen = d->length - d->data_offset;
1799     }
1800 
1801     switch (d->code) {
1802     case CMD_SEND_OBJECT_INFO:
1803         usb_packet_copy(p, d->data + d->data_offset, dlen);
1804         d->offset += dlen;
1805         d->data_offset += dlen;
1806         if (d->data_offset == d->length) {
1807             /* The operation might have already failed */
1808             if (!s->result) {
1809                 usb_mtp_write_metadata(s, dlen);
1810             }
1811             usb_mtp_data_free(s->data_out);
1812             s->data_out = NULL;
1813             return;
1814         }
1815         break;
1816     case CMD_SEND_OBJECT:
1817         usb_packet_copy(p, d->data + d->data_offset, dlen);
1818         d->offset += dlen;
1819         d->data_offset += dlen;
1820         if ((p->iov.size % 64) || !p->iov.size) {
1821             assert((s->dataset.size == 0xFFFFFFFF) ||
1822                    (s->dataset.size == d->offset));
1823 
1824             if (d->length == MTP_WRITE_BUF_SZ) {
1825                 d->write_status = WRITE_END;
1826             } else {
1827                 d->write_status = WRITE_START;
1828             }
1829             usb_mtp_write_data(s, 0);
1830             usb_mtp_data_free(s->data_out);
1831             s->data_out = NULL;
1832             return;
1833         }
1834         if (d->data_offset == d->length) {
1835             d->pending = true;
1836             usb_mtp_write_data(s, 0);
1837         }
1838         break;
1839     default:
1840         p->status = USB_RET_STALL;
1841         return;
1842     }
1843 }
1844 
1845 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
1846 {
1847     MTPState *s = USB_MTP(dev);
1848     MTPControl cmd;
1849     mtp_container container;
1850     uint32_t params[5];
1851     uint16_t container_type;
1852     int i, rc;
1853 
1854     switch (p->ep->nr) {
1855     case EP_DATA_IN:
1856         if (s->data_out != NULL) {
1857             /* guest bug */
1858             trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
1859             p->status = USB_RET_STALL;
1860             return;
1861         }
1862         if (p->iov.size < sizeof(container)) {
1863             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1864             p->status = USB_RET_STALL;
1865             return;
1866         }
1867         if (s->data_in !=  NULL) {
1868             MTPData *d = s->data_in;
1869             uint64_t dlen = d->length - d->offset;
1870             if (d->first) {
1871                 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
1872                 if (d->length + sizeof(container) > 0xFFFFFFFF) {
1873                     container.length = cpu_to_le32(0xFFFFFFFF);
1874                 } else {
1875                     container.length =
1876                         cpu_to_le32(d->length + sizeof(container));
1877                 }
1878                 container.type   = cpu_to_le16(TYPE_DATA);
1879                 container.code   = cpu_to_le16(d->code);
1880                 container.trans  = cpu_to_le32(d->trans);
1881                 usb_packet_copy(p, &container, sizeof(container));
1882                 d->first = false;
1883                 if (dlen > p->iov.size - sizeof(container)) {
1884                     dlen = p->iov.size - sizeof(container);
1885                 }
1886             } else {
1887                 if (dlen > p->iov.size) {
1888                     dlen = p->iov.size;
1889                 }
1890             }
1891             if (d->fd == -1) {
1892                 usb_packet_copy(p, d->data + d->offset, dlen);
1893             } else {
1894                 if (d->alloc < p->iov.size) {
1895                     d->alloc = p->iov.size;
1896                     d->data = g_realloc(d->data, d->alloc);
1897                 }
1898                 rc = read(d->fd, d->data, dlen);
1899                 if (rc != dlen) {
1900                     memset(d->data, 0, dlen);
1901                     s->result->code = RES_INCOMPLETE_TRANSFER;
1902                 }
1903                 usb_packet_copy(p, d->data, dlen);
1904             }
1905             d->offset += dlen;
1906             if (d->offset == d->length) {
1907                 usb_mtp_data_free(s->data_in);
1908                 s->data_in = NULL;
1909             }
1910         } else if (s->result != NULL) {
1911             MTPControl *r = s->result;
1912             int length = sizeof(container) + r->argc * sizeof(uint32_t);
1913             if (r->code == RES_OK) {
1914                 trace_usb_mtp_success(s->dev.addr, r->trans,
1915                                       (r->argc > 0) ? r->argv[0] : 0,
1916                                       (r->argc > 1) ? r->argv[1] : 0);
1917             } else {
1918                 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
1919                                     (r->argc > 0) ? r->argv[0] : 0,
1920                                     (r->argc > 1) ? r->argv[1] : 0);
1921             }
1922             container.length = cpu_to_le32(length);
1923             container.type   = cpu_to_le16(TYPE_RESPONSE);
1924             container.code   = cpu_to_le16(r->code);
1925             container.trans  = cpu_to_le32(r->trans);
1926             for (i = 0; i < r->argc; i++) {
1927                 params[i] = cpu_to_le32(r->argv[i]);
1928             }
1929             usb_packet_copy(p, &container, sizeof(container));
1930             usb_packet_copy(p, &params, length - sizeof(container));
1931             g_free(s->result);
1932             s->result = NULL;
1933         }
1934         break;
1935     case EP_DATA_OUT:
1936         if (p->iov.size < sizeof(container)) {
1937             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1938             p->status = USB_RET_STALL;
1939             return;
1940         }
1941         if ((s->data_out != NULL) && !s->data_out->first) {
1942             container_type = TYPE_DATA;
1943         } else {
1944             usb_packet_copy(p, &container, sizeof(container));
1945             container_type = le16_to_cpu(container.type);
1946         }
1947         switch (container_type) {
1948         case TYPE_COMMAND:
1949             if (s->data_in || s->data_out || s->result) {
1950                 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1951                 p->status = USB_RET_STALL;
1952                 return;
1953             }
1954             cmd.code = le16_to_cpu(container.code);
1955             cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1956                 / sizeof(uint32_t);
1957             cmd.trans = le32_to_cpu(container.trans);
1958             if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1959                 cmd.argc = ARRAY_SIZE(cmd.argv);
1960             }
1961             if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1962                 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1963                 p->status = USB_RET_STALL;
1964                 return;
1965             }
1966             usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1967             for (i = 0; i < cmd.argc; i++) {
1968                 cmd.argv[i] = le32_to_cpu(params[i]);
1969             }
1970             trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1971                                   (cmd.argc > 0) ? cmd.argv[0] : 0,
1972                                   (cmd.argc > 1) ? cmd.argv[1] : 0,
1973                                   (cmd.argc > 2) ? cmd.argv[2] : 0,
1974                                   (cmd.argc > 3) ? cmd.argv[3] : 0,
1975                                   (cmd.argc > 4) ? cmd.argv[4] : 0);
1976             usb_mtp_command(s, &cmd);
1977             break;
1978         case TYPE_DATA:
1979             /* One of the previous transfers has already errored but the
1980              * responder is still sending data associated with it
1981              */
1982             if (s->result != NULL) {
1983                 return;
1984             }
1985             usb_mtp_get_data(s, &container, p);
1986             break;
1987         default:
1988             /* not needed as long as the mtp device is read-only */
1989             p->status = USB_RET_STALL;
1990             return;
1991         }
1992         break;
1993     case EP_EVENT:
1994         if (!QTAILQ_EMPTY(&s->events)) {
1995             struct MTPMonEntry *e = QTAILQ_LAST(&s->events);
1996             uint32_t handle;
1997             int len = sizeof(container) + sizeof(uint32_t);
1998 
1999             if (p->iov.size < len) {
2000                 trace_usb_mtp_stall(s->dev.addr,
2001                                     "packet too small to send event");
2002                 p->status = USB_RET_STALL;
2003                 return;
2004             }
2005 
2006             QTAILQ_REMOVE(&s->events, e, next);
2007             container.length = cpu_to_le32(len);
2008             container.type = cpu_to_le32(TYPE_EVENT);
2009             container.code = cpu_to_le16(e->event);
2010             container.trans = 0; /* no trans specific events */
2011             handle = cpu_to_le32(e->handle);
2012             usb_packet_copy(p, &container, sizeof(container));
2013             usb_packet_copy(p, &handle, sizeof(uint32_t));
2014             g_free(e);
2015             return;
2016         }
2017         p->status = USB_RET_NAK;
2018         return;
2019     default:
2020         trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
2021         p->status = USB_RET_STALL;
2022         return;
2023     }
2024 
2025     if (p->actual_length == 0) {
2026         trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
2027         p->status = USB_RET_NAK;
2028         return;
2029     } else {
2030         trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
2031                            p->iov.size);
2032         return;
2033     }
2034 }
2035 
2036 static void usb_mtp_realize(USBDevice *dev, Error **errp)
2037 {
2038     MTPState *s = USB_MTP(dev);
2039 
2040     if ((s->root == NULL) || !g_path_is_absolute(s->root)) {
2041         error_setg(errp, "usb-mtp: rootdir must be configured and be an absolute path");
2042         return;
2043     }
2044 
2045     if (access(s->root, R_OK) != 0) {
2046         error_setg(errp, "usb-mtp: rootdir does not exist/not readable");
2047         return;
2048     } else if (!s->readonly && access(s->root, W_OK) != 0) {
2049         error_setg(errp, "usb-mtp: rootdir does not have write permissions");
2050         return;
2051     }
2052 
2053     /* Mark store as RW */
2054     if (!s->readonly) {
2055         s->flags |= (1 << MTP_FLAG_WRITABLE);
2056     }
2057 
2058     if (s->desc == NULL) {
2059         /*
2060          * This does not check if path exists
2061          * but we have the checks above
2062          */
2063         s->desc = g_path_get_basename(s->root);
2064     }
2065 
2066     usb_desc_create_serial(dev);
2067     usb_desc_init(dev);
2068     QTAILQ_INIT(&s->objects);
2069 
2070 }
2071 
2072 static const VMStateDescription vmstate_usb_mtp = {
2073     .name = "usb-mtp",
2074     .unmigratable = 1,
2075     .version_id = 1,
2076     .minimum_version_id = 1,
2077     .fields = (VMStateField[]) {
2078         VMSTATE_USB_DEVICE(dev, MTPState),
2079         VMSTATE_END_OF_LIST()
2080     }
2081 };
2082 
2083 static Property mtp_properties[] = {
2084     DEFINE_PROP_STRING("rootdir", MTPState, root),
2085     DEFINE_PROP_STRING("desc", MTPState, desc),
2086     DEFINE_PROP_BOOL("readonly", MTPState, readonly, true),
2087     DEFINE_PROP_END_OF_LIST(),
2088 };
2089 
2090 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
2091 {
2092     DeviceClass *dc = DEVICE_CLASS(klass);
2093     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2094 
2095     uc->realize        = usb_mtp_realize;
2096     uc->product_desc   = "QEMU USB MTP";
2097     uc->usb_desc       = &desc;
2098     uc->cancel_packet  = usb_mtp_cancel_packet;
2099     uc->handle_attach  = usb_desc_attach;
2100     uc->handle_reset   = usb_mtp_handle_reset;
2101     uc->handle_control = usb_mtp_handle_control;
2102     uc->handle_data    = usb_mtp_handle_data;
2103     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2104     dc->desc = "USB Media Transfer Protocol device";
2105     dc->fw_name = "mtp";
2106     dc->vmsd = &vmstate_usb_mtp;
2107     device_class_set_props(dc, mtp_properties);
2108 }
2109 
2110 static TypeInfo mtp_info = {
2111     .name          = TYPE_USB_MTP,
2112     .parent        = TYPE_USB_DEVICE,
2113     .instance_size = sizeof(MTPState),
2114     .class_init    = usb_mtp_class_initfn,
2115 };
2116 
2117 static void usb_mtp_register_types(void)
2118 {
2119     type_register_static(&mtp_info);
2120 }
2121 
2122 type_init(usb_mtp_register_types)
2123