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