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