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