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