xref: /openbmc/qemu/hw/usb/dev-mtp.c (revision 438c78da)
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(events, 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 
657     if (o->have_children) {
658         return;
659     }
660     o->have_children = true;
661 
662     dir = opendir(o->path);
663     if (!dir) {
664         return;
665     }
666 #ifdef CONFIG_INOTIFY1
667     int watchfd = usb_mtp_add_watch(s->inotifyfd, o->path);
668     if (watchfd == -1) {
669         fprintf(stderr, "usb-mtp: failed to add watch for %s\n", o->path);
670     } else {
671         trace_usb_mtp_inotify_event(s->dev.addr, o->path,
672                                     0, "Watch Added");
673         o->watchfd = watchfd;
674     }
675 #endif
676     while ((entry = readdir(dir)) != NULL) {
677         usb_mtp_add_child(s, o, entry->d_name);
678     }
679     closedir(dir);
680 }
681 
682 /* ----------------------------------------------------------------------- */
683 
684 static MTPData *usb_mtp_data_alloc(MTPControl *c)
685 {
686     MTPData *data = g_new0(MTPData, 1);
687 
688     data->code  = c->code;
689     data->trans = c->trans;
690     data->fd    = -1;
691     data->first = true;
692     return data;
693 }
694 
695 static void usb_mtp_data_free(MTPData *data)
696 {
697     if (data == NULL) {
698         return;
699     }
700     if (data->fd != -1) {
701         close(data->fd);
702     }
703     g_free(data->data);
704     g_free(data);
705 }
706 
707 static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
708 {
709     if (data->length + bytes <= data->alloc) {
710         return;
711     }
712     data->alloc = (data->length + bytes + 0xff) & ~0xff;
713     data->data  = g_realloc(data->data, data->alloc);
714 }
715 
716 static void usb_mtp_add_u8(MTPData *data, uint8_t val)
717 {
718     usb_mtp_realloc(data, 1);
719     data->data[data->length++] = val;
720 }
721 
722 static void usb_mtp_add_u16(MTPData *data, uint16_t val)
723 {
724     usb_mtp_realloc(data, 2);
725     data->data[data->length++] = (val >> 0) & 0xff;
726     data->data[data->length++] = (val >> 8) & 0xff;
727 }
728 
729 static void usb_mtp_add_u32(MTPData *data, uint32_t val)
730 {
731     usb_mtp_realloc(data, 4);
732     data->data[data->length++] = (val >>  0) & 0xff;
733     data->data[data->length++] = (val >>  8) & 0xff;
734     data->data[data->length++] = (val >> 16) & 0xff;
735     data->data[data->length++] = (val >> 24) & 0xff;
736 }
737 
738 static void usb_mtp_add_u64(MTPData *data, uint64_t val)
739 {
740     usb_mtp_realloc(data, 8);
741     data->data[data->length++] = (val >>  0) & 0xff;
742     data->data[data->length++] = (val >>  8) & 0xff;
743     data->data[data->length++] = (val >> 16) & 0xff;
744     data->data[data->length++] = (val >> 24) & 0xff;
745     data->data[data->length++] = (val >> 32) & 0xff;
746     data->data[data->length++] = (val >> 40) & 0xff;
747     data->data[data->length++] = (val >> 48) & 0xff;
748     data->data[data->length++] = (val >> 56) & 0xff;
749 }
750 
751 static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
752                                   const uint16_t *vals)
753 {
754     int i;
755 
756     usb_mtp_add_u32(data, len);
757     for (i = 0; i < len; i++) {
758         usb_mtp_add_u16(data, vals[i]);
759     }
760 }
761 
762 static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
763                                   const uint32_t *vals)
764 {
765     int i;
766 
767     usb_mtp_add_u32(data, len);
768     for (i = 0; i < len; i++) {
769         usb_mtp_add_u32(data, vals[i]);
770     }
771 }
772 
773 static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
774 {
775     uint32_t len = wcslen(str);
776     int i;
777 
778     if (len > 0) {
779         len++; /* include terminating L'\0' */
780     }
781 
782     usb_mtp_add_u8(data, len);
783     for (i = 0; i < len; i++) {
784         usb_mtp_add_u16(data, str[i]);
785     }
786 }
787 
788 static void usb_mtp_add_str(MTPData *data, const char *str)
789 {
790     uint32_t len = strlen(str)+1;
791     wchar_t *wstr = g_new(wchar_t, len);
792     size_t ret;
793 
794     ret = mbstowcs(wstr, str, len);
795     if (ret == -1) {
796         usb_mtp_add_wstr(data, L"Oops");
797     } else {
798         usb_mtp_add_wstr(data, wstr);
799     }
800 
801     g_free(wstr);
802 }
803 
804 static void usb_mtp_add_time(MTPData *data, time_t time)
805 {
806     char buf[16];
807     struct tm tm;
808 
809     gmtime_r(&time, &tm);
810     strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm);
811     usb_mtp_add_str(data, buf);
812 }
813 
814 /* ----------------------------------------------------------------------- */
815 
816 static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans,
817                                  int argc, uint32_t arg0, uint32_t arg1,
818                                  uint32_t arg2)
819 {
820     MTPControl *c = g_new0(MTPControl, 1);
821 
822     c->code  = code;
823     c->trans = trans;
824     c->argc  = argc;
825     if (argc > 0) {
826         c->argv[0] = arg0;
827     }
828     if (argc > 1) {
829         c->argv[1] = arg1;
830     }
831     if (argc > 2) {
832         c->argv[2] = arg2;
833     }
834 
835     assert(s->result == NULL);
836     s->result = c;
837 }
838 
839 /* ----------------------------------------------------------------------- */
840 
841 static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
842 {
843     static const uint16_t ops[] = {
844         CMD_GET_DEVICE_INFO,
845         CMD_OPEN_SESSION,
846         CMD_CLOSE_SESSION,
847         CMD_GET_STORAGE_IDS,
848         CMD_GET_STORAGE_INFO,
849         CMD_GET_NUM_OBJECTS,
850         CMD_GET_OBJECT_HANDLES,
851         CMD_GET_OBJECT_INFO,
852         CMD_DELETE_OBJECT,
853         CMD_SEND_OBJECT_INFO,
854         CMD_SEND_OBJECT,
855         CMD_GET_OBJECT,
856         CMD_GET_PARTIAL_OBJECT,
857         CMD_GET_OBJECT_PROPS_SUPPORTED,
858         CMD_GET_OBJECT_PROP_DESC,
859         CMD_GET_OBJECT_PROP_VALUE,
860     };
861     static const uint16_t fmt[] = {
862         FMT_UNDEFINED_OBJECT,
863         FMT_ASSOCIATION,
864     };
865     MTPData *d = usb_mtp_data_alloc(c);
866 
867     trace_usb_mtp_op_get_device_info(s->dev.addr);
868 
869     usb_mtp_add_u16(d, 100);
870     usb_mtp_add_u32(d, 0x00000006);
871     usb_mtp_add_u16(d, 0x0064);
872     usb_mtp_add_wstr(d, L"");
873     usb_mtp_add_u16(d, 0x0000);
874 
875     usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops);
876     usb_mtp_add_u16_array(d, 0, NULL);
877     usb_mtp_add_u16_array(d, 0, NULL);
878     usb_mtp_add_u16_array(d, 0, NULL);
879     usb_mtp_add_u16_array(d, ARRAY_SIZE(fmt), fmt);
880 
881     usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER);
882     usb_mtp_add_wstr(d, L"" MTP_PRODUCT);
883     usb_mtp_add_wstr(d, L"0.1");
884     usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef");
885 
886     return d;
887 }
888 
889 static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
890 {
891     static const uint32_t ids[] = {
892         QEMU_STORAGE_ID,
893     };
894     MTPData *d = usb_mtp_data_alloc(c);
895 
896     trace_usb_mtp_op_get_storage_ids(s->dev.addr);
897 
898     usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
899 
900     return d;
901 }
902 
903 static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
904 {
905     MTPData *d = usb_mtp_data_alloc(c);
906     struct statvfs buf;
907     int rc;
908 
909     trace_usb_mtp_op_get_storage_info(s->dev.addr);
910 
911     if (FLAG_SET(s, MTP_FLAG_WRITABLE)) {
912         usb_mtp_add_u16(d, 0x0003);
913         usb_mtp_add_u16(d, 0x0002);
914         usb_mtp_add_u16(d, 0x0000);
915     } else {
916         usb_mtp_add_u16(d, 0x0001);
917         usb_mtp_add_u16(d, 0x0002);
918         usb_mtp_add_u16(d, 0x0001);
919     }
920 
921     rc = statvfs(s->root, &buf);
922     if (rc == 0) {
923         usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks);
924         usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks);
925         usb_mtp_add_u32(d, buf.f_ffree);
926     } else {
927         usb_mtp_add_u64(d, 0xffffffff);
928         usb_mtp_add_u64(d, 0xffffffff);
929         usb_mtp_add_u32(d, 0xffffffff);
930     }
931 
932     usb_mtp_add_str(d, s->desc);
933     usb_mtp_add_wstr(d, L"123456789abcdef");
934     return d;
935 }
936 
937 static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
938                                            MTPObject *o)
939 {
940     MTPData *d = usb_mtp_data_alloc(c);
941     uint32_t i = 0, handles[o->nchildren];
942     MTPObject *iter;
943 
944     trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
945 
946     QLIST_FOREACH(iter, &o->children, list) {
947         handles[i++] = iter->handle;
948     }
949     assert(i == o->nchildren);
950     usb_mtp_add_u32_array(d, o->nchildren, handles);
951 
952     return d;
953 }
954 
955 static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
956                                         MTPObject *o)
957 {
958     MTPData *d = usb_mtp_data_alloc(c);
959 
960     trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
961 
962     usb_mtp_add_u32(d, QEMU_STORAGE_ID);
963     usb_mtp_add_u16(d, o->format);
964     usb_mtp_add_u16(d, 0);
965 
966     if (o->stat.st_size > 0xFFFFFFFF) {
967         usb_mtp_add_u32(d, 0xFFFFFFFF);
968     } else {
969         usb_mtp_add_u32(d, o->stat.st_size);
970     }
971 
972     usb_mtp_add_u16(d, 0);
973     usb_mtp_add_u32(d, 0);
974     usb_mtp_add_u32(d, 0);
975     usb_mtp_add_u32(d, 0);
976     usb_mtp_add_u32(d, 0);
977     usb_mtp_add_u32(d, 0);
978     usb_mtp_add_u32(d, 0);
979 
980     if (o->parent) {
981         usb_mtp_add_u32(d, o->parent->handle);
982     } else {
983         usb_mtp_add_u32(d, 0);
984     }
985     if (o->format == FMT_ASSOCIATION) {
986         usb_mtp_add_u16(d, 0x0001);
987         usb_mtp_add_u32(d, 0x00000001);
988         usb_mtp_add_u32(d, 0);
989     } else {
990         usb_mtp_add_u16(d, 0);
991         usb_mtp_add_u32(d, 0);
992         usb_mtp_add_u32(d, 0);
993     }
994 
995     usb_mtp_add_str(d, o->name);
996     usb_mtp_add_time(d, o->stat.st_ctime);
997     usb_mtp_add_time(d, o->stat.st_mtime);
998     usb_mtp_add_wstr(d, L"");
999 
1000     return d;
1001 }
1002 
1003 static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
1004                                    MTPObject *o)
1005 {
1006     MTPData *d = usb_mtp_data_alloc(c);
1007 
1008     trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
1009 
1010     d->fd = open(o->path, O_RDONLY);
1011     if (d->fd == -1) {
1012         usb_mtp_data_free(d);
1013         return NULL;
1014     }
1015     d->length = o->stat.st_size;
1016     d->alloc  = 512;
1017     d->data   = g_malloc(d->alloc);
1018     return d;
1019 }
1020 
1021 static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
1022                                            MTPObject *o)
1023 {
1024     MTPData *d;
1025     off_t offset;
1026 
1027     if (c->argc <= 2) {
1028         return NULL;
1029     }
1030     trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
1031                                         c->argv[1], c->argv[2]);
1032 
1033     d = usb_mtp_data_alloc(c);
1034     d->fd = open(o->path, O_RDONLY);
1035     if (d->fd == -1) {
1036         usb_mtp_data_free(d);
1037         return NULL;
1038     }
1039 
1040     offset = c->argv[1];
1041     if (offset > o->stat.st_size) {
1042         offset = o->stat.st_size;
1043     }
1044     if (lseek(d->fd, offset, SEEK_SET) < 0) {
1045         usb_mtp_data_free(d);
1046         return NULL;
1047     }
1048 
1049     d->length = c->argv[2];
1050     if (d->length > o->stat.st_size - offset) {
1051         d->length = o->stat.st_size - offset;
1052     }
1053 
1054     return d;
1055 }
1056 
1057 static MTPData *usb_mtp_get_object_props_supported(MTPState *s, MTPControl *c)
1058 {
1059     static const uint16_t props[] = {
1060         PROP_STORAGE_ID,
1061         PROP_OBJECT_FORMAT,
1062         PROP_OBJECT_COMPRESSED_SIZE,
1063         PROP_PARENT_OBJECT,
1064         PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER,
1065         PROP_NAME,
1066     };
1067     MTPData *d = usb_mtp_data_alloc(c);
1068     usb_mtp_add_u16_array(d, ARRAY_SIZE(props), props);
1069 
1070     return d;
1071 }
1072 
1073 static MTPData *usb_mtp_get_object_prop_desc(MTPState *s, MTPControl *c)
1074 {
1075     MTPData *d = usb_mtp_data_alloc(c);
1076     switch (c->argv[0]) {
1077     case PROP_STORAGE_ID:
1078         usb_mtp_add_u16(d, PROP_STORAGE_ID);
1079         usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1080         usb_mtp_add_u8(d, 0x00);
1081         usb_mtp_add_u32(d, 0x00000000);
1082         usb_mtp_add_u32(d, 0x00000000);
1083         usb_mtp_add_u8(d, 0x00);
1084         break;
1085     case PROP_OBJECT_FORMAT:
1086         usb_mtp_add_u16(d, PROP_OBJECT_FORMAT);
1087         usb_mtp_add_u16(d, DATA_TYPE_UINT16);
1088         usb_mtp_add_u8(d, 0x00);
1089         usb_mtp_add_u16(d, 0x0000);
1090         usb_mtp_add_u32(d, 0x00000000);
1091         usb_mtp_add_u8(d, 0x00);
1092         break;
1093     case PROP_OBJECT_COMPRESSED_SIZE:
1094         usb_mtp_add_u16(d, PROP_OBJECT_COMPRESSED_SIZE);
1095         usb_mtp_add_u16(d, DATA_TYPE_UINT64);
1096         usb_mtp_add_u8(d, 0x00);
1097         usb_mtp_add_u64(d, 0x0000000000000000);
1098         usb_mtp_add_u32(d, 0x00000000);
1099         usb_mtp_add_u8(d, 0x00);
1100         break;
1101     case PROP_PARENT_OBJECT:
1102         usb_mtp_add_u16(d, PROP_PARENT_OBJECT);
1103         usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1104         usb_mtp_add_u8(d, 0x00);
1105         usb_mtp_add_u32(d, 0x00000000);
1106         usb_mtp_add_u32(d, 0x00000000);
1107         usb_mtp_add_u8(d, 0x00);
1108         break;
1109     case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1110         usb_mtp_add_u16(d, PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER);
1111         usb_mtp_add_u16(d, DATA_TYPE_UINT128);
1112         usb_mtp_add_u8(d, 0x00);
1113         usb_mtp_add_u64(d, 0x0000000000000000);
1114         usb_mtp_add_u64(d, 0x0000000000000000);
1115         usb_mtp_add_u32(d, 0x00000000);
1116         usb_mtp_add_u8(d, 0x00);
1117         break;
1118     case PROP_NAME:
1119         usb_mtp_add_u16(d, PROP_NAME);
1120         usb_mtp_add_u16(d, DATA_TYPE_STRING);
1121         usb_mtp_add_u8(d, 0x00);
1122         usb_mtp_add_u8(d, 0x00);
1123         usb_mtp_add_u32(d, 0x00000000);
1124         usb_mtp_add_u8(d, 0x00);
1125         break;
1126     default:
1127         usb_mtp_data_free(d);
1128         return NULL;
1129     }
1130 
1131     return d;
1132 }
1133 
1134 static MTPData *usb_mtp_get_object_prop_value(MTPState *s, MTPControl *c,
1135                                               MTPObject *o)
1136 {
1137     MTPData *d = usb_mtp_data_alloc(c);
1138     switch (c->argv[1]) {
1139     case PROP_STORAGE_ID:
1140         usb_mtp_add_u32(d, QEMU_STORAGE_ID);
1141         break;
1142     case PROP_OBJECT_FORMAT:
1143         usb_mtp_add_u16(d, o->format);
1144         break;
1145     case PROP_OBJECT_COMPRESSED_SIZE:
1146         usb_mtp_add_u64(d, o->stat.st_size);
1147         break;
1148     case PROP_PARENT_OBJECT:
1149         if (o->parent == NULL) {
1150             usb_mtp_add_u32(d, 0x00000000);
1151         } else {
1152             usb_mtp_add_u32(d, o->parent->handle);
1153         }
1154         break;
1155     case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1156         /* Should be persistent between sessions,
1157          * but using our objedt ID is "good enough"
1158          * for now */
1159         usb_mtp_add_u64(d, 0x0000000000000000);
1160         usb_mtp_add_u64(d, o->handle);
1161         break;
1162     case PROP_NAME:
1163         usb_mtp_add_str(d, o->name);
1164         break;
1165     default:
1166         usb_mtp_data_free(d);
1167         return NULL;
1168     }
1169 
1170     return d;
1171 }
1172 
1173 /* Return correct return code for a delete event */
1174 enum {
1175     ALL_DELETE,
1176     PARTIAL_DELETE,
1177     READ_ONLY,
1178 };
1179 
1180 /* Assumes that children, if any, have been already freed */
1181 static void usb_mtp_object_free_one(MTPState *s, MTPObject *o)
1182 {
1183 #ifndef CONFIG_INOTIFY1
1184     assert(o->nchildren == 0);
1185     QTAILQ_REMOVE(&s->objects, o, next);
1186     g_free(o->name);
1187     g_free(o->path);
1188     g_free(o);
1189 #endif
1190 }
1191 
1192 static int usb_mtp_deletefn(MTPState *s, MTPObject *o, uint32_t trans)
1193 {
1194     MTPObject *iter, *iter2;
1195     bool partial_delete = false;
1196     bool success = false;
1197 
1198     /*
1199      * TODO: Add support for Protection Status
1200      */
1201 
1202     QLIST_FOREACH(iter, &o->children, list) {
1203         if (iter->format == FMT_ASSOCIATION) {
1204             QLIST_FOREACH(iter2, &iter->children, list) {
1205                 usb_mtp_deletefn(s, iter2, trans);
1206             }
1207         }
1208     }
1209 
1210     if (o->format == FMT_UNDEFINED_OBJECT) {
1211         if (remove(o->path)) {
1212             partial_delete = true;
1213         } else {
1214             usb_mtp_object_free_one(s, o);
1215             success = true;
1216         }
1217     }
1218 
1219     if (o->format == FMT_ASSOCIATION) {
1220         if (rmdir(o->path)) {
1221             partial_delete = true;
1222         } else {
1223             usb_mtp_object_free_one(s, o);
1224             success = true;
1225         }
1226     }
1227 
1228     if (success && partial_delete) {
1229         return PARTIAL_DELETE;
1230     }
1231     if (!success && partial_delete) {
1232         return READ_ONLY;
1233     }
1234     return ALL_DELETE;
1235 }
1236 
1237 static void usb_mtp_object_delete(MTPState *s, uint32_t handle,
1238                                   uint32_t format_code, uint32_t trans)
1239 {
1240     MTPObject *o;
1241     int ret;
1242 
1243     /* Return error if store is read-only */
1244     if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1245         usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1246                              trans, 0, 0, 0, 0);
1247         return;
1248     }
1249 
1250     if (format_code != 0) {
1251         usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1252                              trans, 0, 0, 0, 0);
1253         return;
1254     }
1255 
1256     if (handle == 0xFFFFFFF) {
1257         o = QTAILQ_FIRST(&s->objects);
1258     } else {
1259         o = usb_mtp_object_lookup(s, handle);
1260     }
1261     if (o == NULL) {
1262         usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1263                              trans, 0, 0, 0, 0);
1264         return;
1265     }
1266 
1267     ret = usb_mtp_deletefn(s, o, trans);
1268     if (ret == PARTIAL_DELETE) {
1269         usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1270                              trans, 0, 0, 0, 0);
1271         return;
1272     } else if (ret == READ_ONLY) {
1273         usb_mtp_queue_result(s, RES_STORE_READ_ONLY, trans,
1274                              0, 0, 0, 0);
1275         return;
1276     } else {
1277         usb_mtp_queue_result(s, RES_OK, trans,
1278                              0, 0, 0, 0);
1279         return;
1280     }
1281 }
1282 
1283 static void usb_mtp_command(MTPState *s, MTPControl *c)
1284 {
1285     MTPData *data_in = NULL;
1286     MTPObject *o = NULL;
1287     uint32_t nres = 0, res0 = 0;
1288 
1289     /* sanity checks */
1290     if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
1291         usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
1292                              c->trans, 0, 0, 0, 0);
1293         return;
1294     }
1295 
1296     /* process commands */
1297     switch (c->code) {
1298     case CMD_GET_DEVICE_INFO:
1299         data_in = usb_mtp_get_device_info(s, c);
1300         break;
1301     case CMD_OPEN_SESSION:
1302         if (s->session) {
1303             usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
1304                                  c->trans, 1, s->session, 0, 0);
1305             return;
1306         }
1307         if (c->argv[0] == 0) {
1308             usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
1309                                  c->trans, 0, 0, 0, 0);
1310             return;
1311         }
1312         trace_usb_mtp_op_open_session(s->dev.addr);
1313         s->session = c->argv[0];
1314         usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
1315 #ifdef CONFIG_INOTIFY1
1316         if (usb_mtp_inotify_init(s)) {
1317             fprintf(stderr, "usb-mtp: file monitoring init failed\n");
1318         }
1319 #endif
1320         break;
1321     case CMD_CLOSE_SESSION:
1322         trace_usb_mtp_op_close_session(s->dev.addr);
1323         s->session = 0;
1324         s->next_handle = 0;
1325 #ifdef CONFIG_INOTIFY1
1326         usb_mtp_inotify_cleanup(s);
1327 #endif
1328         usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1329         assert(QTAILQ_EMPTY(&s->objects));
1330         break;
1331     case CMD_GET_STORAGE_IDS:
1332         data_in = usb_mtp_get_storage_ids(s, c);
1333         break;
1334     case CMD_GET_STORAGE_INFO:
1335         if (c->argv[0] != QEMU_STORAGE_ID &&
1336             c->argv[0] != 0xffffffff) {
1337             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1338                                  c->trans, 0, 0, 0, 0);
1339             return;
1340         }
1341         data_in = usb_mtp_get_storage_info(s, c);
1342         break;
1343     case CMD_GET_NUM_OBJECTS:
1344     case CMD_GET_OBJECT_HANDLES:
1345         if (c->argv[0] != QEMU_STORAGE_ID &&
1346             c->argv[0] != 0xffffffff) {
1347             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1348                                  c->trans, 0, 0, 0, 0);
1349             return;
1350         }
1351         if (c->argv[1] != 0x00000000) {
1352             usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1353                                  c->trans, 0, 0, 0, 0);
1354             return;
1355         }
1356         if (c->argv[2] == 0x00000000 ||
1357             c->argv[2] == 0xffffffff) {
1358             o = QTAILQ_FIRST(&s->objects);
1359         } else {
1360             o = usb_mtp_object_lookup(s, c->argv[2]);
1361         }
1362         if (o == NULL) {
1363             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1364                                  c->trans, 0, 0, 0, 0);
1365             return;
1366         }
1367         if (o->format != FMT_ASSOCIATION) {
1368             usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
1369                                  c->trans, 0, 0, 0, 0);
1370             return;
1371         }
1372         usb_mtp_object_readdir(s, o);
1373         if (c->code == CMD_GET_NUM_OBJECTS) {
1374             trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
1375             nres = 1;
1376             res0 = o->nchildren;
1377         } else {
1378             data_in = usb_mtp_get_object_handles(s, c, o);
1379         }
1380         break;
1381     case CMD_GET_OBJECT_INFO:
1382         o = usb_mtp_object_lookup(s, c->argv[0]);
1383         if (o == NULL) {
1384             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1385                                  c->trans, 0, 0, 0, 0);
1386             return;
1387         }
1388         data_in = usb_mtp_get_object_info(s, c, o);
1389         break;
1390     case CMD_GET_OBJECT:
1391         o = usb_mtp_object_lookup(s, c->argv[0]);
1392         if (o == NULL) {
1393             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1394                                  c->trans, 0, 0, 0, 0);
1395             return;
1396         }
1397         if (o->format == FMT_ASSOCIATION) {
1398             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1399                                  c->trans, 0, 0, 0, 0);
1400             return;
1401         }
1402         data_in = usb_mtp_get_object(s, c, o);
1403         if (data_in == NULL) {
1404             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1405                                  c->trans, 0, 0, 0, 0);
1406             return;
1407         }
1408         break;
1409     case CMD_DELETE_OBJECT:
1410         usb_mtp_object_delete(s, c->argv[0], c->argv[1], c->trans);
1411         return;
1412     case CMD_GET_PARTIAL_OBJECT:
1413         o = usb_mtp_object_lookup(s, c->argv[0]);
1414         if (o == NULL) {
1415             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1416                                  c->trans, 0, 0, 0, 0);
1417             return;
1418         }
1419         if (o->format == FMT_ASSOCIATION) {
1420             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1421                                  c->trans, 0, 0, 0, 0);
1422             return;
1423         }
1424         data_in = usb_mtp_get_partial_object(s, c, o);
1425         if (data_in == NULL) {
1426             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1427                                  c->trans, 0, 0, 0, 0);
1428             return;
1429         }
1430         nres = 1;
1431         res0 = data_in->length;
1432         break;
1433     case CMD_SEND_OBJECT_INFO:
1434         /* Return error if store is read-only */
1435         if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1436             usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1437                                  c->trans, 0, 0, 0, 0);
1438         } else if (c->argv[0] && (c->argv[0] != QEMU_STORAGE_ID)) {
1439             /* First parameter points to storage id or is 0 */
1440             usb_mtp_queue_result(s, RES_STORE_NOT_AVAILABLE, c->trans,
1441                                  0, 0, 0, 0);
1442         } else if (c->argv[1] && !c->argv[0]) {
1443             /* If second parameter is specified, first must also be specified */
1444             usb_mtp_queue_result(s, RES_DESTINATION_UNSUPPORTED, c->trans,
1445                                  0, 0, 0, 0);
1446         } else {
1447             uint32_t handle = c->argv[1];
1448             if (handle == 0xFFFFFFFF || handle == 0) {
1449                 /* root object */
1450                 o = QTAILQ_FIRST(&s->objects);
1451             } else {
1452                 o = usb_mtp_object_lookup(s, handle);
1453             }
1454             if (o == NULL) {
1455                 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, c->trans,
1456                                      0, 0, 0, 0);
1457             } else if (o->format != FMT_ASSOCIATION) {
1458                 usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT, c->trans,
1459                                      0, 0, 0, 0);
1460             }
1461         }
1462         if (o) {
1463             s->dataset.parent_handle = o->handle;
1464         }
1465         s->data_out = usb_mtp_data_alloc(c);
1466         return;
1467     case CMD_SEND_OBJECT:
1468         if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1469             usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1470                                  c->trans, 0, 0, 0, 0);
1471             return;
1472         }
1473         if (!s->write_pending) {
1474             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO,
1475                                  c->trans, 0, 0, 0, 0);
1476             return;
1477         }
1478         s->data_out = usb_mtp_data_alloc(c);
1479         return;
1480     case CMD_GET_OBJECT_PROPS_SUPPORTED:
1481         if (c->argv[0] != FMT_UNDEFINED_OBJECT &&
1482             c->argv[0] != FMT_ASSOCIATION) {
1483             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1484                                  c->trans, 0, 0, 0, 0);
1485             return;
1486         }
1487         data_in = usb_mtp_get_object_props_supported(s, c);
1488         break;
1489     case CMD_GET_OBJECT_PROP_DESC:
1490         if (c->argv[1] != FMT_UNDEFINED_OBJECT &&
1491             c->argv[1] != FMT_ASSOCIATION) {
1492             usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1493                                  c->trans, 0, 0, 0, 0);
1494             return;
1495         }
1496         data_in = usb_mtp_get_object_prop_desc(s, c);
1497         if (data_in == NULL) {
1498             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1499                                  c->trans, 0, 0, 0, 0);
1500             return;
1501         }
1502         break;
1503     case CMD_GET_OBJECT_PROP_VALUE:
1504         o = usb_mtp_object_lookup(s, c->argv[0]);
1505         if (o == NULL) {
1506             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1507                                  c->trans, 0, 0, 0, 0);
1508             return;
1509         }
1510         data_in = usb_mtp_get_object_prop_value(s, c, o);
1511         if (data_in == NULL) {
1512             usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1513                                  c->trans, 0, 0, 0, 0);
1514             return;
1515         }
1516         break;
1517     default:
1518         trace_usb_mtp_op_unknown(s->dev.addr, c->code);
1519         usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
1520                              c->trans, 0, 0, 0, 0);
1521         return;
1522     }
1523 
1524     /* return results on success */
1525     if (data_in) {
1526         assert(s->data_in == NULL);
1527         s->data_in = data_in;
1528     }
1529     usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0, 0);
1530 }
1531 
1532 /* ----------------------------------------------------------------------- */
1533 
1534 static void usb_mtp_handle_reset(USBDevice *dev)
1535 {
1536     MTPState *s = USB_MTP(dev);
1537 
1538     trace_usb_mtp_reset(s->dev.addr);
1539 
1540 #ifdef CONFIG_INOTIFY1
1541     usb_mtp_inotify_cleanup(s);
1542 #endif
1543     usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1544     s->session = 0;
1545     usb_mtp_data_free(s->data_in);
1546     s->data_in = NULL;
1547     usb_mtp_data_free(s->data_out);
1548     s->data_out = NULL;
1549     g_free(s->result);
1550     s->result = NULL;
1551 }
1552 
1553 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
1554                                    int request, int value, int index,
1555                                    int length, uint8_t *data)
1556 {
1557     int ret;
1558     MTPState *s = USB_MTP(dev);
1559     uint16_t *event = (uint16_t *)data;
1560 
1561     switch (request) {
1562     case ClassInterfaceOutRequest | 0x64:
1563         if (*event == EVT_CANCEL_TRANSACTION) {
1564             g_free(s->result);
1565             s->result = NULL;
1566             usb_mtp_data_free(s->data_in);
1567             s->data_in = NULL;
1568             if (s->write_pending) {
1569                 g_free(s->dataset.filename);
1570                 s->write_pending = false;
1571                 s->dataset.size = 0;
1572             }
1573             usb_mtp_data_free(s->data_out);
1574             s->data_out = NULL;
1575         } else {
1576             p->status = USB_RET_STALL;
1577         }
1578         break;
1579     default:
1580         ret = usb_desc_handle_control(dev, p, request,
1581                                       value, index, length, data);
1582         if (ret >= 0) {
1583             return;
1584         }
1585     }
1586 
1587     trace_usb_mtp_stall(dev->addr, "unknown control request");
1588 }
1589 
1590 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
1591 {
1592     /* we don't use async packets, so this should never be called */
1593     fprintf(stderr, "%s\n", __func__);
1594 }
1595 
1596 static void utf16_to_str(uint8_t len, uint16_t *arr, char *name)
1597 {
1598     int count;
1599     wchar_t *wstr = g_new0(wchar_t, len);
1600 
1601     for (count = 0; count < len; count++) {
1602         wstr[count] = (wchar_t)arr[count];
1603     }
1604 
1605     wcstombs(name, wstr, len);
1606     g_free(wstr);
1607 }
1608 
1609 /* Wrapper around write, returns 0 on failure */
1610 static uint64_t write_retry(int fd, void *buf, uint64_t size)
1611 {
1612         uint64_t bytes_left = size, ret;
1613 
1614         while (bytes_left > 0) {
1615                 ret = write(fd, buf, bytes_left);
1616                 if ((ret == -1) && (errno != EINTR || errno != EAGAIN ||
1617                                     errno != EWOULDBLOCK)) {
1618                         break;
1619                 }
1620                 bytes_left -= ret;
1621                 buf += ret;
1622         }
1623 
1624         return size - bytes_left;
1625 }
1626 
1627 static void usb_mtp_write_data(MTPState *s)
1628 {
1629     MTPData *d = s->data_out;
1630     MTPObject *parent =
1631         usb_mtp_object_lookup(s, s->dataset.parent_handle);
1632     char *path = NULL;
1633     uint64_t rc;
1634     mode_t mask = 0644;
1635 
1636     assert(d != NULL);
1637 
1638     if (parent == NULL || !s->write_pending) {
1639         usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, d->trans,
1640                              0, 0, 0, 0);
1641         return;
1642     }
1643 
1644     if (s->dataset.filename) {
1645         path = g_strdup_printf("%s/%s", parent->path, s->dataset.filename);
1646         if (s->dataset.format == FMT_ASSOCIATION) {
1647             d->fd = mkdir(path, mask);
1648             goto free;
1649         }
1650         if ((s->dataset.size != 0xFFFFFFFF) && (s->dataset.size < d->length)) {
1651             usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1652                                  0, 0, 0, 0);
1653             goto done;
1654         }
1655         d->fd = open(path, O_CREAT | O_WRONLY, mask);
1656         if (d->fd == -1) {
1657             usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1658                                  0, 0, 0, 0);
1659             goto done;
1660         }
1661 
1662         /*
1663          * Return success if initiator sent 0 sized data
1664          */
1665         if (!s->dataset.size) {
1666             goto success;
1667         }
1668 
1669         rc = write_retry(d->fd, d->data, d->offset);
1670         if (rc != d->offset) {
1671             usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1672                                  0, 0, 0, 0);
1673             goto done;
1674             }
1675         /* Only for < 4G file sizes */
1676         if (s->dataset.size != 0xFFFFFFFF && rc != s->dataset.size) {
1677             usb_mtp_queue_result(s, RES_INCOMPLETE_TRANSFER, d->trans,
1678                                  0, 0, 0, 0);
1679             goto done;
1680         }
1681     }
1682 
1683 success:
1684     usb_mtp_queue_result(s, RES_OK, d->trans,
1685                          0, 0, 0, 0);
1686 
1687 done:
1688     /*
1689      * The write dataset is kept around and freed only
1690      * on success or if another write request comes in
1691      */
1692     if (d->fd != -1) {
1693         close(d->fd);
1694     }
1695 free:
1696     g_free(s->dataset.filename);
1697     s->dataset.size = 0;
1698     g_free(path);
1699     s->write_pending = false;
1700 }
1701 
1702 static void usb_mtp_write_metadata(MTPState *s)
1703 {
1704     MTPData *d = s->data_out;
1705     ObjectInfo *dataset = (ObjectInfo *)d->data;
1706     char *filename = g_new0(char, dataset->length);
1707     MTPObject *o;
1708     MTPObject *p = usb_mtp_object_lookup(s, s->dataset.parent_handle);
1709     uint32_t next_handle = s->next_handle;
1710 
1711     assert(!s->write_pending);
1712     assert(p != NULL);
1713 
1714     utf16_to_str(dataset->length, dataset->filename, filename);
1715 
1716     o = usb_mtp_object_lookup_name(p, filename, dataset->length);
1717     if (o != NULL) {
1718         next_handle = o->handle;
1719     }
1720 
1721     s->dataset.filename = filename;
1722     s->dataset.format = dataset->format;
1723     s->dataset.size = dataset->size;
1724     s->dataset.filename = filename;
1725     s->write_pending = true;
1726 
1727     if (s->dataset.format == FMT_ASSOCIATION) {
1728         usb_mtp_write_data(s);
1729         /* next_handle will be allocated to the newly created dir */
1730         if (d->fd == -1) {
1731             usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1732                                  0, 0, 0, 0);
1733             return;
1734         }
1735         d->fd = -1;
1736     }
1737 
1738     usb_mtp_queue_result(s, RES_OK, d->trans, 3, QEMU_STORAGE_ID,
1739                          s->dataset.parent_handle, next_handle);
1740 }
1741 
1742 static void usb_mtp_get_data(MTPState *s, mtp_container *container,
1743                              USBPacket *p)
1744 {
1745     MTPData *d = s->data_out;
1746     uint64_t dlen;
1747     uint32_t data_len = p->iov.size;
1748     uint64_t total_len;
1749 
1750     if (!d) {
1751             usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, 0,
1752                                  0, 0, 0, 0);
1753             return;
1754     }
1755     if (d->first) {
1756         /* Total length of incoming data */
1757         total_len = cpu_to_le32(container->length) - sizeof(mtp_container);
1758         /* Length of data in this packet */
1759         data_len -= sizeof(mtp_container);
1760         usb_mtp_realloc(d, total_len);
1761         d->length += total_len;
1762         d->offset = 0;
1763         d->cached_length = total_len;
1764         d->first = false;
1765         d->pending = false;
1766     }
1767 
1768     if (d->pending) {
1769         usb_mtp_realloc(d, d->cached_length);
1770         d->length += d->cached_length;
1771         d->pending = false;
1772     }
1773 
1774     if (d->length - d->offset > data_len) {
1775         dlen = data_len;
1776     } else {
1777         dlen = d->length - d->offset;
1778         /* Check for cached data for large files */
1779         if ((s->dataset.size == 0xFFFFFFFF) && (dlen < p->iov.size)) {
1780             usb_mtp_realloc(d, p->iov.size - dlen);
1781             d->length += p->iov.size - dlen;
1782             dlen = p->iov.size;
1783         }
1784     }
1785 
1786     switch (d->code) {
1787     case CMD_SEND_OBJECT_INFO:
1788         usb_packet_copy(p, d->data + d->offset, dlen);
1789         d->offset += dlen;
1790         if (d->offset == d->length) {
1791             /* The operation might have already failed */
1792             if (!s->result) {
1793                 usb_mtp_write_metadata(s);
1794             }
1795             usb_mtp_data_free(s->data_out);
1796             s->data_out = NULL;
1797             return;
1798         }
1799         break;
1800     case CMD_SEND_OBJECT:
1801         usb_packet_copy(p, d->data + d->offset, dlen);
1802         d->offset += dlen;
1803         if ((p->iov.size % 64) || !p->iov.size) {
1804             assert((s->dataset.size == 0xFFFFFFFF) ||
1805                    (s->dataset.size == d->length));
1806 
1807             usb_mtp_write_data(s);
1808             usb_mtp_data_free(s->data_out);
1809             s->data_out = NULL;
1810             return;
1811         }
1812         if (d->offset == d->length) {
1813             d->pending = true;
1814         }
1815         break;
1816     default:
1817         p->status = USB_RET_STALL;
1818         return;
1819     }
1820 }
1821 
1822 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
1823 {
1824     MTPState *s = USB_MTP(dev);
1825     MTPControl cmd;
1826     mtp_container container;
1827     uint32_t params[5];
1828     uint16_t container_type;
1829     int i, rc;
1830 
1831     switch (p->ep->nr) {
1832     case EP_DATA_IN:
1833         if (s->data_out != NULL) {
1834             /* guest bug */
1835             trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
1836             p->status = USB_RET_STALL;
1837             return;
1838         }
1839         if (p->iov.size < sizeof(container)) {
1840             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1841             p->status = USB_RET_STALL;
1842             return;
1843         }
1844         if (s->data_in !=  NULL) {
1845             MTPData *d = s->data_in;
1846             uint64_t dlen = d->length - d->offset;
1847             if (d->first) {
1848                 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
1849                 if (d->length + sizeof(container) > 0xFFFFFFFF) {
1850                     container.length = cpu_to_le32(0xFFFFFFFF);
1851                 } else {
1852                     container.length =
1853                         cpu_to_le32(d->length + sizeof(container));
1854                 }
1855                 container.type   = cpu_to_le16(TYPE_DATA);
1856                 container.code   = cpu_to_le16(d->code);
1857                 container.trans  = cpu_to_le32(d->trans);
1858                 usb_packet_copy(p, &container, sizeof(container));
1859                 d->first = false;
1860                 if (dlen > p->iov.size - sizeof(container)) {
1861                     dlen = p->iov.size - sizeof(container);
1862                 }
1863             } else {
1864                 if (dlen > p->iov.size) {
1865                     dlen = p->iov.size;
1866                 }
1867             }
1868             if (d->fd == -1) {
1869                 usb_packet_copy(p, d->data + d->offset, dlen);
1870             } else {
1871                 if (d->alloc < p->iov.size) {
1872                     d->alloc = p->iov.size;
1873                     d->data = g_realloc(d->data, d->alloc);
1874                 }
1875                 rc = read(d->fd, d->data, dlen);
1876                 if (rc != dlen) {
1877                     memset(d->data, 0, dlen);
1878                     s->result->code = RES_INCOMPLETE_TRANSFER;
1879                 }
1880                 usb_packet_copy(p, d->data, dlen);
1881             }
1882             d->offset += dlen;
1883             if (d->offset == d->length) {
1884                 usb_mtp_data_free(s->data_in);
1885                 s->data_in = NULL;
1886             }
1887         } else if (s->result != NULL) {
1888             MTPControl *r = s->result;
1889             int length = sizeof(container) + r->argc * sizeof(uint32_t);
1890             if (r->code == RES_OK) {
1891                 trace_usb_mtp_success(s->dev.addr, r->trans,
1892                                       (r->argc > 0) ? r->argv[0] : 0,
1893                                       (r->argc > 1) ? r->argv[1] : 0);
1894             } else {
1895                 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
1896                                     (r->argc > 0) ? r->argv[0] : 0,
1897                                     (r->argc > 1) ? r->argv[1] : 0);
1898             }
1899             container.length = cpu_to_le32(length);
1900             container.type   = cpu_to_le16(TYPE_RESPONSE);
1901             container.code   = cpu_to_le16(r->code);
1902             container.trans  = cpu_to_le32(r->trans);
1903             for (i = 0; i < r->argc; i++) {
1904                 params[i] = cpu_to_le32(r->argv[i]);
1905             }
1906             usb_packet_copy(p, &container, sizeof(container));
1907             usb_packet_copy(p, &params, length - sizeof(container));
1908             g_free(s->result);
1909             s->result = NULL;
1910         }
1911         break;
1912     case EP_DATA_OUT:
1913         if (p->iov.size < sizeof(container)) {
1914             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1915             p->status = USB_RET_STALL;
1916             return;
1917         }
1918         if ((s->data_out != NULL) && !s->data_out->first) {
1919             container_type = TYPE_DATA;
1920         } else {
1921             usb_packet_copy(p, &container, sizeof(container));
1922             container_type = le16_to_cpu(container.type);
1923         }
1924         switch (container_type) {
1925         case TYPE_COMMAND:
1926             if (s->data_in || s->data_out || s->result) {
1927                 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1928                 p->status = USB_RET_STALL;
1929                 return;
1930             }
1931             cmd.code = le16_to_cpu(container.code);
1932             cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1933                 / sizeof(uint32_t);
1934             cmd.trans = le32_to_cpu(container.trans);
1935             if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1936                 cmd.argc = ARRAY_SIZE(cmd.argv);
1937             }
1938             if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1939                 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1940                 p->status = USB_RET_STALL;
1941                 return;
1942             }
1943             usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1944             for (i = 0; i < cmd.argc; i++) {
1945                 cmd.argv[i] = le32_to_cpu(params[i]);
1946             }
1947             trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1948                                   (cmd.argc > 0) ? cmd.argv[0] : 0,
1949                                   (cmd.argc > 1) ? cmd.argv[1] : 0,
1950                                   (cmd.argc > 2) ? cmd.argv[2] : 0,
1951                                   (cmd.argc > 3) ? cmd.argv[3] : 0,
1952                                   (cmd.argc > 4) ? cmd.argv[4] : 0);
1953             usb_mtp_command(s, &cmd);
1954             break;
1955         case TYPE_DATA:
1956             /* One of the previous transfers has already errored but the
1957              * responder is still sending data associated with it
1958              */
1959             if (s->result != NULL) {
1960                 return;
1961             }
1962             usb_mtp_get_data(s, &container, p);
1963             break;
1964         default:
1965             /* not needed as long as the mtp device is read-only */
1966             p->status = USB_RET_STALL;
1967             return;
1968         }
1969         break;
1970     case EP_EVENT:
1971 #ifdef CONFIG_INOTIFY1
1972         if (!QTAILQ_EMPTY(&s->events)) {
1973             struct MTPMonEntry *e = QTAILQ_LAST(&s->events, events);
1974             uint32_t handle;
1975             int len = sizeof(container) + sizeof(uint32_t);
1976 
1977             if (p->iov.size < len) {
1978                 trace_usb_mtp_stall(s->dev.addr,
1979                                     "packet too small to send event");
1980                 p->status = USB_RET_STALL;
1981                 return;
1982             }
1983 
1984             QTAILQ_REMOVE(&s->events, e, next);
1985             container.length = cpu_to_le32(len);
1986             container.type = cpu_to_le32(TYPE_EVENT);
1987             container.code = cpu_to_le16(e->event);
1988             container.trans = 0; /* no trans specific events */
1989             handle = cpu_to_le32(e->handle);
1990             usb_packet_copy(p, &container, sizeof(container));
1991             usb_packet_copy(p, &handle, sizeof(uint32_t));
1992             g_free(e);
1993             return;
1994         }
1995 #endif
1996         p->status = USB_RET_NAK;
1997         return;
1998     default:
1999         trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
2000         p->status = USB_RET_STALL;
2001         return;
2002     }
2003 
2004     if (p->actual_length == 0) {
2005         trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
2006         p->status = USB_RET_NAK;
2007         return;
2008     } else {
2009         trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
2010                            p->iov.size);
2011         return;
2012     }
2013 }
2014 
2015 static void usb_mtp_realize(USBDevice *dev, Error **errp)
2016 {
2017     MTPState *s = USB_MTP(dev);
2018 
2019     usb_desc_create_serial(dev);
2020     usb_desc_init(dev);
2021     QTAILQ_INIT(&s->objects);
2022     if (s->desc == NULL) {
2023         if (s->root == NULL) {
2024             error_setg(errp, "usb-mtp: rootdir property must be configured");
2025             return;
2026         }
2027         s->desc = strrchr(s->root, '/');
2028         if (s->desc && s->desc[0]) {
2029             s->desc = g_strdup(s->desc + 1);
2030         } else {
2031             s->desc = g_strdup("none");
2032         }
2033     }
2034     /* Mark store as RW */
2035     if (!s->readonly) {
2036         s->flags |= (1 << MTP_FLAG_WRITABLE);
2037     }
2038 
2039 }
2040 
2041 static const VMStateDescription vmstate_usb_mtp = {
2042     .name = "usb-mtp",
2043     .unmigratable = 1,
2044     .version_id = 1,
2045     .minimum_version_id = 1,
2046     .fields = (VMStateField[]) {
2047         VMSTATE_USB_DEVICE(dev, MTPState),
2048         VMSTATE_END_OF_LIST()
2049     }
2050 };
2051 
2052 static Property mtp_properties[] = {
2053     DEFINE_PROP_STRING("rootdir", MTPState, root),
2054     DEFINE_PROP_STRING("desc", MTPState, desc),
2055     DEFINE_PROP_BOOL("readonly", MTPState, readonly, true),
2056     DEFINE_PROP_END_OF_LIST(),
2057 };
2058 
2059 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
2060 {
2061     DeviceClass *dc = DEVICE_CLASS(klass);
2062     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2063 
2064     uc->realize        = usb_mtp_realize;
2065     uc->product_desc   = "QEMU USB MTP";
2066     uc->usb_desc       = &desc;
2067     uc->cancel_packet  = usb_mtp_cancel_packet;
2068     uc->handle_attach  = usb_desc_attach;
2069     uc->handle_reset   = usb_mtp_handle_reset;
2070     uc->handle_control = usb_mtp_handle_control;
2071     uc->handle_data    = usb_mtp_handle_data;
2072     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2073     dc->desc = "USB Media Transfer Protocol device";
2074     dc->fw_name = "mtp";
2075     dc->vmsd = &vmstate_usb_mtp;
2076     dc->props = mtp_properties;
2077 }
2078 
2079 static TypeInfo mtp_info = {
2080     .name          = TYPE_USB_MTP,
2081     .parent        = TYPE_USB_DEVICE,
2082     .instance_size = sizeof(MTPState),
2083     .class_init    = usb_mtp_class_initfn,
2084 };
2085 
2086 static void usb_mtp_register_types(void)
2087 {
2088     type_register_static(&mtp_info);
2089 }
2090 
2091 type_init(usb_mtp_register_types)
2092