xref: /openbmc/qemu/hw/usb/dev-mtp.c (revision 35d08458)
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 <wchar.h>
13 #include <dirent.h>
14 #include <unistd.h>
15 
16 #include <sys/stat.h>
17 #include <sys/statvfs.h>
18 
19 #include "qemu-common.h"
20 #include "qemu/iov.h"
21 #include "trace.h"
22 #include "hw/usb.h"
23 #include "hw/usb/desc.h"
24 
25 /* ----------------------------------------------------------------------- */
26 
27 enum mtp_container_type {
28     TYPE_COMMAND  = 1,
29     TYPE_DATA     = 2,
30     TYPE_RESPONSE = 3,
31     TYPE_EVENT    = 4,
32 };
33 
34 enum mtp_code {
35     /* command codes */
36     CMD_GET_DEVICE_INFO            = 0x1001,
37     CMD_OPEN_SESSION               = 0x1002,
38     CMD_CLOSE_SESSION              = 0x1003,
39     CMD_GET_STORAGE_IDS            = 0x1004,
40     CMD_GET_STORAGE_INFO           = 0x1005,
41     CMD_GET_NUM_OBJECTS            = 0x1006,
42     CMD_GET_OBJECT_HANDLES         = 0x1007,
43     CMD_GET_OBJECT_INFO            = 0x1008,
44     CMD_GET_OBJECT                 = 0x1009,
45     CMD_GET_PARTIAL_OBJECT         = 0x101b,
46 
47     /* response codes */
48     RES_OK                         = 0x2001,
49     RES_SESSION_NOT_OPEN           = 0x2003,
50     RES_INVALID_TRANSACTION_ID     = 0x2004,
51     RES_OPERATION_NOT_SUPPORTED    = 0x2005,
52     RES_PARAMETER_NOT_SUPPORTED    = 0x2006,
53     RES_INCOMPLETE_TRANSFER        = 0x2007,
54     RES_INVALID_STORAGE_ID         = 0x2008,
55     RES_INVALID_OBJECT_HANDLE      = 0x2009,
56     RES_SPEC_BY_FORMAT_UNSUPPORTED = 0x2014,
57     RES_INVALID_PARENT_OBJECT      = 0x201a,
58     RES_INVALID_PARAMETER          = 0x201d,
59     RES_SESSION_ALREADY_OPEN       = 0x201e,
60 
61     /* format codes */
62     FMT_UNDEFINED_OBJECT           = 0x3000,
63     FMT_ASSOCIATION                = 0x3001,
64 };
65 
66 typedef struct {
67     uint32_t length;
68     uint16_t type;
69     uint16_t code;
70     uint32_t trans;
71 } QEMU_PACKED mtp_container;
72 
73 /* ----------------------------------------------------------------------- */
74 
75 typedef struct MTPState MTPState;
76 typedef struct MTPControl MTPControl;
77 typedef struct MTPData MTPData;
78 typedef struct MTPObject MTPObject;
79 
80 enum {
81     EP_DATA_IN = 1,
82     EP_DATA_OUT,
83     EP_EVENT,
84 };
85 
86 struct MTPControl {
87     uint16_t     code;
88     uint32_t     trans;
89     int          argc;
90     uint32_t     argv[5];
91 };
92 
93 struct MTPData {
94     uint16_t     code;
95     uint32_t     trans;
96     uint32_t     offset;
97     uint32_t     length;
98     uint32_t     alloc;
99     uint8_t      *data;
100     bool         first;
101     int          fd;
102 };
103 
104 struct MTPObject {
105     uint32_t     handle;
106     uint16_t     format;
107     char         *name;
108     char         *path;
109     struct stat  stat;
110     MTPObject    *parent;
111     MTPObject    **children;
112     int32_t      nchildren;
113     QTAILQ_ENTRY(MTPObject) next;
114 };
115 
116 struct MTPState {
117     USBDevice    dev;
118     char         *root;
119     char         *desc;
120     uint32_t     flags;
121 
122     MTPData      *data_in;
123     MTPData      *data_out;
124     MTPControl   *result;
125     uint32_t     session;
126     uint32_t     next_handle;
127 
128     QTAILQ_HEAD(, MTPObject) objects;
129 };
130 
131 #define QEMU_STORAGE_ID 0x00010001
132 
133 #define MTP_FLAG_WRITABLE 0
134 
135 #define FLAG_SET(_mtp, _flag)  ((_mtp)->flags & (1 << (_flag)))
136 
137 /* ----------------------------------------------------------------------- */
138 
139 #define MTP_MANUFACTURER  "QEMU"
140 #define MTP_PRODUCT       "QEMU filesharing"
141 
142 enum {
143     STR_MANUFACTURER = 1,
144     STR_PRODUCT,
145     STR_SERIALNUMBER,
146     STR_CONFIG_FULL,
147     STR_CONFIG_HIGH,
148     STR_CONFIG_SUPER,
149 };
150 
151 static const USBDescStrings desc_strings = {
152     [STR_MANUFACTURER] = MTP_MANUFACTURER,
153     [STR_PRODUCT]      = MTP_PRODUCT,
154     [STR_SERIALNUMBER] = "34617",
155     [STR_CONFIG_FULL]  = "Full speed config (usb 1.1)",
156     [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
157     [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
158 };
159 
160 static const USBDescIface desc_iface_full = {
161     .bInterfaceNumber              = 0,
162     .bNumEndpoints                 = 3,
163     .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
164     .bInterfaceSubClass            = 0x01,
165     .bInterfaceProtocol            = 0x01,
166     .eps = (USBDescEndpoint[]) {
167         {
168             .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
169             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
170             .wMaxPacketSize        = 64,
171         },{
172             .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
173             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
174             .wMaxPacketSize        = 64,
175         },{
176             .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
177             .bmAttributes          = USB_ENDPOINT_XFER_INT,
178             .wMaxPacketSize        = 8,
179             .bInterval             = 0x0a,
180         },
181     }
182 };
183 
184 static const USBDescDevice desc_device_full = {
185     .bcdUSB                        = 0x0200,
186     .bMaxPacketSize0               = 8,
187     .bNumConfigurations            = 1,
188     .confs = (USBDescConfig[]) {
189         {
190             .bNumInterfaces        = 1,
191             .bConfigurationValue   = 1,
192             .iConfiguration        = STR_CONFIG_FULL,
193             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
194             .bMaxPower             = 2,
195             .nif = 1,
196             .ifs = &desc_iface_full,
197         },
198     },
199 };
200 
201 static const USBDescIface desc_iface_high = {
202     .bInterfaceNumber              = 0,
203     .bNumEndpoints                 = 3,
204     .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
205     .bInterfaceSubClass            = 0x01,
206     .bInterfaceProtocol            = 0x01,
207     .eps = (USBDescEndpoint[]) {
208         {
209             .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
210             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
211             .wMaxPacketSize        = 512,
212         },{
213             .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
214             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
215             .wMaxPacketSize        = 512,
216         },{
217             .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
218             .bmAttributes          = USB_ENDPOINT_XFER_INT,
219             .wMaxPacketSize        = 8,
220             .bInterval             = 0x0a,
221         },
222     }
223 };
224 
225 static const USBDescDevice desc_device_high = {
226     .bcdUSB                        = 0x0200,
227     .bMaxPacketSize0               = 64,
228     .bNumConfigurations            = 1,
229     .confs = (USBDescConfig[]) {
230         {
231             .bNumInterfaces        = 1,
232             .bConfigurationValue   = 1,
233             .iConfiguration        = STR_CONFIG_HIGH,
234             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
235             .bMaxPower             = 2,
236             .nif = 1,
237             .ifs = &desc_iface_high,
238         },
239     },
240 };
241 
242 static const USBDescMSOS desc_msos = {
243     .CompatibleID = "MTP",
244     .SelectiveSuspendEnabled = true,
245 };
246 
247 static const USBDesc desc = {
248     .id = {
249         .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
250         .idProduct         = 0x0004,
251         .bcdDevice         = 0,
252         .iManufacturer     = STR_MANUFACTURER,
253         .iProduct          = STR_PRODUCT,
254         .iSerialNumber     = STR_SERIALNUMBER,
255     },
256     .full  = &desc_device_full,
257     .high  = &desc_device_high,
258     .str   = desc_strings,
259     .msos  = &desc_msos,
260 };
261 
262 /* ----------------------------------------------------------------------- */
263 
264 static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle,
265                                        MTPObject *parent, char *name)
266 {
267     MTPObject *o = g_new0(MTPObject, 1);
268 
269     if (name[0] == '.') {
270         goto ignore;
271     }
272 
273     o->handle = handle;
274     o->parent = parent;
275     o->name = g_strdup(name);
276     o->nchildren = -1;
277     if (parent == NULL) {
278         o->path = g_strdup(name);
279     } else {
280         o->path = g_strdup_printf("%s/%s", parent->path, name);
281     }
282 
283     if (lstat(o->path, &o->stat) != 0) {
284         goto ignore;
285     }
286     if (S_ISREG(o->stat.st_mode)) {
287         o->format = FMT_UNDEFINED_OBJECT;
288     } else if (S_ISDIR(o->stat.st_mode)) {
289         o->format = FMT_ASSOCIATION;
290     } else {
291         goto ignore;
292     }
293 
294     if (access(o->path, R_OK) != 0) {
295         goto ignore;
296     }
297 
298     trace_usb_mtp_object_alloc(s->dev.addr, o->handle, o->path);
299 
300     QTAILQ_INSERT_TAIL(&s->objects, o, next);
301     return o;
302 
303 ignore:
304     g_free(o->name);
305     g_free(o->path);
306     g_free(o);
307     return NULL;
308 }
309 
310 static void usb_mtp_object_free(MTPState *s, MTPObject *o)
311 {
312     int i;
313 
314     trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path);
315 
316     QTAILQ_REMOVE(&s->objects, o, next);
317     for (i = 0; i < o->nchildren; i++) {
318         usb_mtp_object_free(s, o->children[i]);
319     }
320     g_free(o->children);
321     g_free(o->name);
322     g_free(o->path);
323     g_free(o);
324 }
325 
326 static MTPObject *usb_mtp_object_lookup(MTPState *s, uint32_t handle)
327 {
328     MTPObject *o;
329 
330     QTAILQ_FOREACH(o, &s->objects, next) {
331         if (o->handle == handle) {
332             return o;
333         }
334     }
335     return NULL;
336 }
337 
338 static void usb_mtp_object_readdir(MTPState *s, MTPObject *o)
339 {
340     struct dirent *entry;
341     DIR *dir;
342 
343     o->nchildren = 0;
344     dir = opendir(o->path);
345     if (!dir) {
346         return;
347     }
348     while ((entry = readdir(dir)) != NULL) {
349         if ((o->nchildren % 32) == 0) {
350             o->children = g_realloc(o->children,
351                                     (o->nchildren + 32) * sizeof(MTPObject *));
352         }
353         o->children[o->nchildren] =
354             usb_mtp_object_alloc(s, s->next_handle++, o, entry->d_name);
355         if (o->children[o->nchildren] != NULL) {
356             o->nchildren++;
357         }
358     }
359     closedir(dir);
360 }
361 
362 /* ----------------------------------------------------------------------- */
363 
364 static MTPData *usb_mtp_data_alloc(MTPControl *c)
365 {
366     MTPData *data = g_new0(MTPData, 1);
367 
368     data->code  = c->code;
369     data->trans = c->trans;
370     data->fd    = -1;
371     data->first = true;
372     return data;
373 }
374 
375 static void usb_mtp_data_free(MTPData *data)
376 {
377     if (data == NULL) {
378         return;
379     }
380     if (data->fd != -1) {
381         close(data->fd);
382     }
383     g_free(data->data);
384     g_free(data);
385 }
386 
387 static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
388 {
389     if (data->length + bytes <= data->alloc) {
390         return;
391     }
392     data->alloc = (data->length + bytes + 0xff) & ~0xff;
393     data->data  = g_realloc(data->data, data->alloc);
394 }
395 
396 static void usb_mtp_add_u8(MTPData *data, uint8_t val)
397 {
398     usb_mtp_realloc(data, 1);
399     data->data[data->length++] = val;
400 }
401 
402 static void usb_mtp_add_u16(MTPData *data, uint16_t val)
403 {
404     usb_mtp_realloc(data, 2);
405     data->data[data->length++] = (val >> 0) & 0xff;
406     data->data[data->length++] = (val >> 8) & 0xff;
407 }
408 
409 static void usb_mtp_add_u32(MTPData *data, uint32_t val)
410 {
411     usb_mtp_realloc(data, 4);
412     data->data[data->length++] = (val >>  0) & 0xff;
413     data->data[data->length++] = (val >>  8) & 0xff;
414     data->data[data->length++] = (val >> 16) & 0xff;
415     data->data[data->length++] = (val >> 24) & 0xff;
416 }
417 
418 static void usb_mtp_add_u64(MTPData *data, uint64_t val)
419 {
420     usb_mtp_realloc(data, 8);
421     data->data[data->length++] = (val >>  0) & 0xff;
422     data->data[data->length++] = (val >>  8) & 0xff;
423     data->data[data->length++] = (val >> 16) & 0xff;
424     data->data[data->length++] = (val >> 24) & 0xff;
425     data->data[data->length++] = (val >> 32) & 0xff;
426     data->data[data->length++] = (val >> 40) & 0xff;
427     data->data[data->length++] = (val >> 48) & 0xff;
428     data->data[data->length++] = (val >> 56) & 0xff;
429 }
430 
431 static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
432                                   const uint16_t *vals)
433 {
434     int i;
435 
436     usb_mtp_add_u32(data, len);
437     for (i = 0; i < len; i++) {
438         usb_mtp_add_u16(data, vals[i]);
439     }
440 }
441 
442 static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
443                                   const uint32_t *vals)
444 {
445     int i;
446 
447     usb_mtp_add_u32(data, len);
448     for (i = 0; i < len; i++) {
449         usb_mtp_add_u32(data, vals[i]);
450     }
451 }
452 
453 static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
454 {
455     uint32_t len = wcslen(str);
456     int i;
457 
458     if (len > 0) {
459         len++; /* include terminating L'\0' */
460     }
461 
462     usb_mtp_add_u8(data, len);
463     for (i = 0; i < len; i++) {
464         usb_mtp_add_u16(data, str[i]);
465     }
466 }
467 
468 static void usb_mtp_add_str(MTPData *data, const char *str)
469 {
470     uint32_t len = strlen(str)+1;
471     wchar_t wstr[len];
472     size_t ret;
473 
474     ret = mbstowcs(wstr, str, len);
475     if (ret == -1) {
476         usb_mtp_add_wstr(data, L"Oops");
477     } else {
478         usb_mtp_add_wstr(data, wstr);
479     }
480 }
481 
482 static void usb_mtp_add_time(MTPData *data, time_t time)
483 {
484     char buf[16];
485     struct tm tm;
486 
487     gmtime_r(&time, &tm);
488     strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm);
489     usb_mtp_add_str(data, buf);
490 }
491 
492 /* ----------------------------------------------------------------------- */
493 
494 static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans,
495                                  int argc, uint32_t arg0, uint32_t arg1)
496 {
497     MTPControl *c = g_new0(MTPControl, 1);
498 
499     c->code  = code;
500     c->trans = trans;
501     c->argc  = argc;
502     if (argc > 0) {
503         c->argv[0] = arg0;
504     }
505     if (argc > 1) {
506         c->argv[1] = arg1;
507     }
508 
509     assert(s->result == NULL);
510     s->result = c;
511 }
512 
513 /* ----------------------------------------------------------------------- */
514 
515 static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
516 {
517     static const uint16_t ops[] = {
518         CMD_GET_DEVICE_INFO,
519         CMD_OPEN_SESSION,
520         CMD_CLOSE_SESSION,
521         CMD_GET_STORAGE_IDS,
522         CMD_GET_STORAGE_INFO,
523         CMD_GET_NUM_OBJECTS,
524         CMD_GET_OBJECT_HANDLES,
525         CMD_GET_OBJECT_INFO,
526         CMD_GET_OBJECT,
527         CMD_GET_PARTIAL_OBJECT,
528     };
529     static const uint16_t fmt[] = {
530         FMT_UNDEFINED_OBJECT,
531         FMT_ASSOCIATION,
532     };
533     MTPData *d = usb_mtp_data_alloc(c);
534 
535     trace_usb_mtp_op_get_device_info(s->dev.addr);
536 
537     usb_mtp_add_u16(d, 100);
538     usb_mtp_add_u32(d, 0xffffffff);
539     usb_mtp_add_u16(d, 0x0101);
540     usb_mtp_add_wstr(d, L"");
541     usb_mtp_add_u16(d, 0x0000);
542 
543     usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops);
544     usb_mtp_add_u16_array(d, 0, NULL);
545     usb_mtp_add_u16_array(d, 0, NULL);
546     usb_mtp_add_u16_array(d, 0, NULL);
547     usb_mtp_add_u16_array(d, ARRAY_SIZE(fmt), fmt);
548 
549     usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER);
550     usb_mtp_add_wstr(d, L"" MTP_PRODUCT);
551     usb_mtp_add_wstr(d, L"0.1");
552     usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef");
553 
554     return d;
555 }
556 
557 static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
558 {
559     static const uint32_t ids[] = {
560         QEMU_STORAGE_ID,
561     };
562     MTPData *d = usb_mtp_data_alloc(c);
563 
564     trace_usb_mtp_op_get_storage_ids(s->dev.addr);
565 
566     usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
567 
568     return d;
569 }
570 
571 static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
572 {
573     MTPData *d = usb_mtp_data_alloc(c);
574     struct statvfs buf;
575     int rc;
576 
577     trace_usb_mtp_op_get_storage_info(s->dev.addr);
578 
579     if (FLAG_SET(s, MTP_FLAG_WRITABLE)) {
580         usb_mtp_add_u16(d, 0x0003);
581         usb_mtp_add_u16(d, 0x0002);
582         usb_mtp_add_u16(d, 0x0000);
583     } else {
584         usb_mtp_add_u16(d, 0x0001);
585         usb_mtp_add_u16(d, 0x0002);
586         usb_mtp_add_u16(d, 0x0001);
587     }
588 
589     rc = statvfs(s->root, &buf);
590     if (rc == 0) {
591         usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks);
592         usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks);
593         usb_mtp_add_u32(d, buf.f_ffree);
594     } else {
595         usb_mtp_add_u64(d, 0xffffffff);
596         usb_mtp_add_u64(d, 0xffffffff);
597         usb_mtp_add_u32(d, 0xffffffff);
598     }
599 
600     usb_mtp_add_str(d, s->desc);
601     usb_mtp_add_wstr(d, L"123456789abcdef");
602     return d;
603 }
604 
605 static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
606                                            MTPObject *o)
607 {
608     MTPData *d = usb_mtp_data_alloc(c);
609     uint32_t i, handles[o->nchildren];
610 
611     trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
612 
613     for (i = 0; i < o->nchildren; i++) {
614         handles[i] = o->children[i]->handle;
615     }
616     usb_mtp_add_u32_array(d, o->nchildren, handles);
617 
618     return d;
619 }
620 
621 static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
622                                         MTPObject *o)
623 {
624     MTPData *d = usb_mtp_data_alloc(c);
625 
626     trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
627 
628     usb_mtp_add_u32(d, QEMU_STORAGE_ID);
629     usb_mtp_add_u16(d, o->format);
630     usb_mtp_add_u16(d, 0);
631     usb_mtp_add_u32(d, o->stat.st_size);
632 
633     usb_mtp_add_u16(d, 0);
634     usb_mtp_add_u32(d, 0);
635     usb_mtp_add_u32(d, 0);
636     usb_mtp_add_u32(d, 0);
637     usb_mtp_add_u32(d, 0);
638     usb_mtp_add_u32(d, 0);
639     usb_mtp_add_u32(d, 0);
640 
641     if (o->parent) {
642         usb_mtp_add_u32(d, o->parent->handle);
643     } else {
644         usb_mtp_add_u32(d, 0);
645     }
646     if (o->format == FMT_ASSOCIATION) {
647         usb_mtp_add_u16(d, 0x0001);
648         usb_mtp_add_u32(d, 0x00000001);
649         usb_mtp_add_u32(d, 0);
650     } else {
651         usb_mtp_add_u16(d, 0);
652         usb_mtp_add_u32(d, 0);
653         usb_mtp_add_u32(d, 0);
654     }
655 
656     usb_mtp_add_str(d, o->name);
657     usb_mtp_add_time(d, o->stat.st_ctime);
658     usb_mtp_add_time(d, o->stat.st_mtime);
659     usb_mtp_add_wstr(d, L"");
660 
661     return d;
662 }
663 
664 static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
665                                    MTPObject *o)
666 {
667     MTPData *d = usb_mtp_data_alloc(c);
668 
669     trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
670 
671     d->fd = open(o->path, O_RDONLY);
672     if (d->fd == -1) {
673         usb_mtp_data_free(d);
674         return NULL;
675     }
676     d->length = o->stat.st_size;
677     d->alloc  = 512;
678     d->data   = g_malloc(d->alloc);
679     return d;
680 }
681 
682 static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
683                                            MTPObject *o)
684 {
685     MTPData *d = usb_mtp_data_alloc(c);
686     off_t offset;
687 
688     trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
689                                         c->argv[1], c->argv[2]);
690 
691     d->fd = open(o->path, O_RDONLY);
692     if (d->fd == -1) {
693         usb_mtp_data_free(d);
694         return NULL;
695     }
696 
697     offset = c->argv[1];
698     if (offset > o->stat.st_size) {
699         offset = o->stat.st_size;
700     }
701     lseek(d->fd, offset, SEEK_SET);
702 
703     d->length = c->argv[2];
704     if (d->length > o->stat.st_size - offset) {
705         d->length = o->stat.st_size - offset;
706     }
707 
708     return d;
709 }
710 
711 static void usb_mtp_command(MTPState *s, MTPControl *c)
712 {
713     MTPData *data_in = NULL;
714     MTPObject *o;
715     uint32_t nres = 0, res0 = 0;
716 
717     /* sanity checks */
718     if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
719         usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
720                              c->trans, 0, 0, 0);
721         return;
722     }
723 
724     /* process commands */
725     switch (c->code) {
726     case CMD_GET_DEVICE_INFO:
727         data_in = usb_mtp_get_device_info(s, c);
728         break;
729     case CMD_OPEN_SESSION:
730         if (s->session) {
731             usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
732                                  c->trans, 1, s->session, 0);
733             return;
734         }
735         if (c->argv[0] == 0) {
736             usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
737                                  c->trans, 0, 0, 0);
738             return;
739         }
740         trace_usb_mtp_op_open_session(s->dev.addr);
741         s->session = c->argv[0];
742         usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
743         break;
744     case CMD_CLOSE_SESSION:
745         trace_usb_mtp_op_close_session(s->dev.addr);
746         s->session = 0;
747         s->next_handle = 0;
748         usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
749         assert(QTAILQ_EMPTY(&s->objects));
750         break;
751     case CMD_GET_STORAGE_IDS:
752         data_in = usb_mtp_get_storage_ids(s, c);
753         break;
754     case CMD_GET_STORAGE_INFO:
755         if (c->argv[0] != QEMU_STORAGE_ID &&
756             c->argv[0] != 0xffffffff) {
757             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
758                                  c->trans, 0, 0, 0);
759             return;
760         }
761         data_in = usb_mtp_get_storage_info(s, c);
762         break;
763     case CMD_GET_NUM_OBJECTS:
764     case CMD_GET_OBJECT_HANDLES:
765         if (c->argv[0] != QEMU_STORAGE_ID &&
766             c->argv[0] != 0xffffffff) {
767             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
768                                  c->trans, 0, 0, 0);
769             return;
770         }
771         if (c->argv[1] != 0x00000000) {
772             usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
773                                  c->trans, 0, 0, 0);
774             return;
775         }
776         if (c->argv[2] == 0x00000000 ||
777             c->argv[2] == 0xffffffff) {
778             o = QTAILQ_FIRST(&s->objects);
779         } else {
780             o = usb_mtp_object_lookup(s, c->argv[2]);
781         }
782         if (o == NULL) {
783             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
784                                  c->trans, 0, 0, 0);
785             return;
786         }
787         if (o->format != FMT_ASSOCIATION) {
788             usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
789                                  c->trans, 0, 0, 0);
790             return;
791         }
792         if (o->nchildren == -1) {
793             usb_mtp_object_readdir(s, o);
794         }
795         if (c->code == CMD_GET_NUM_OBJECTS) {
796             trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
797             nres = 1;
798             res0 = o->nchildren;
799         } else {
800             data_in = usb_mtp_get_object_handles(s, c, o);
801         }
802         break;
803     case CMD_GET_OBJECT_INFO:
804         o = usb_mtp_object_lookup(s, c->argv[0]);
805         if (o == NULL) {
806             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
807                                  c->trans, 0, 0, 0);
808             return;
809         }
810         data_in = usb_mtp_get_object_info(s, c, o);
811         break;
812     case CMD_GET_OBJECT:
813         o = usb_mtp_object_lookup(s, c->argv[0]);
814         if (o == NULL) {
815             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
816                                  c->trans, 0, 0, 0);
817             return;
818         }
819         if (o->format == FMT_ASSOCIATION) {
820             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
821                                  c->trans, 0, 0, 0);
822             return;
823         }
824         data_in = usb_mtp_get_object(s, c, o);
825         if (NULL == data_in) {
826             fprintf(stderr, "%s: TODO: handle error\n", __func__);
827         }
828         break;
829     case CMD_GET_PARTIAL_OBJECT:
830         o = usb_mtp_object_lookup(s, c->argv[0]);
831         if (o == NULL) {
832             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
833                                  c->trans, 0, 0, 0);
834             return;
835         }
836         if (o->format == FMT_ASSOCIATION) {
837             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
838                                  c->trans, 0, 0, 0);
839             return;
840         }
841         data_in = usb_mtp_get_partial_object(s, c, o);
842         if (NULL == data_in) {
843             fprintf(stderr, "%s: TODO: handle error\n", __func__);
844         }
845         nres = 1;
846         res0 = data_in->length;
847         break;
848     default:
849         trace_usb_mtp_op_unknown(s->dev.addr, c->code);
850         usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
851                              c->trans, 0, 0, 0);
852         return;
853     }
854 
855     /* return results on success */
856     if (data_in) {
857         assert(s->data_in == NULL);
858         s->data_in = data_in;
859     }
860     usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0);
861 }
862 
863 /* ----------------------------------------------------------------------- */
864 
865 static void usb_mtp_handle_reset(USBDevice *dev)
866 {
867     MTPState *s = DO_UPCAST(MTPState, dev, dev);
868 
869     trace_usb_mtp_reset(s->dev.addr);
870 
871     s->session = 0;
872     usb_mtp_data_free(s->data_in);
873     s->data_in = NULL;
874     usb_mtp_data_free(s->data_out);
875     s->data_out = NULL;
876     g_free(s->result);
877     s->result = NULL;
878 }
879 
880 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
881                                    int request, int value, int index,
882                                    int length, uint8_t *data)
883 {
884     int ret;
885 
886     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
887     if (ret >= 0) {
888         return;
889     }
890 
891     trace_usb_mtp_stall(dev->addr, "unknown control request");
892     p->status = USB_RET_STALL;
893 }
894 
895 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
896 {
897     /* we don't use async packets, so this should never be called */
898     fprintf(stderr, "%s\n", __func__);
899 }
900 
901 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
902 {
903     MTPState *s = DO_UPCAST(MTPState, dev, dev);
904     MTPControl cmd;
905     mtp_container container;
906     uint32_t params[5];
907     int i, rc;
908 
909     switch (p->ep->nr) {
910     case EP_DATA_IN:
911         if (s->data_out != NULL) {
912             /* guest bug */
913             trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
914             p->status = USB_RET_STALL;
915             return;
916         }
917         if (p->iov.size < sizeof(container)) {
918             trace_usb_mtp_stall(s->dev.addr, "packet too small");
919             p->status = USB_RET_STALL;
920             return;
921         }
922         if (s->data_in !=  NULL) {
923             MTPData *d = s->data_in;
924             int dlen = d->length - d->offset;
925             if (d->first) {
926                 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
927                 container.length = cpu_to_le32(d->length + sizeof(container));
928                 container.type   = cpu_to_le16(TYPE_DATA);
929                 container.code   = cpu_to_le16(d->code);
930                 container.trans  = cpu_to_le32(d->trans);
931                 usb_packet_copy(p, &container, sizeof(container));
932                 d->first = false;
933                 if (dlen > p->iov.size - sizeof(container)) {
934                     dlen = p->iov.size - sizeof(container);
935                 }
936             } else {
937                 if (dlen > p->iov.size) {
938                     dlen = p->iov.size;
939                 }
940             }
941             if (d->fd == -1) {
942                 usb_packet_copy(p, d->data + d->offset, dlen);
943             } else {
944                 if (d->alloc < p->iov.size) {
945                     d->alloc = p->iov.size;
946                     d->data = g_realloc(d->data, d->alloc);
947                 }
948                 rc = read(d->fd, d->data, dlen);
949                 if (rc != dlen) {
950                     memset(d->data, 0, dlen);
951                     s->result->code = RES_INCOMPLETE_TRANSFER;
952                 }
953                 usb_packet_copy(p, d->data, dlen);
954             }
955             d->offset += dlen;
956             if (d->offset == d->length) {
957                 usb_mtp_data_free(s->data_in);
958                 s->data_in = NULL;
959             }
960         } else if (s->result != NULL) {
961             MTPControl *r = s->result;
962             int length = sizeof(container) + r->argc * sizeof(uint32_t);
963             if (r->code == RES_OK) {
964                 trace_usb_mtp_success(s->dev.addr, r->trans,
965                                       (r->argc > 0) ? r->argv[0] : 0,
966                                       (r->argc > 1) ? r->argv[1] : 0);
967             } else {
968                 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
969                                     (r->argc > 0) ? r->argv[0] : 0,
970                                     (r->argc > 1) ? r->argv[1] : 0);
971             }
972             container.length = cpu_to_le32(length);
973             container.type   = cpu_to_le16(TYPE_RESPONSE);
974             container.code   = cpu_to_le16(r->code);
975             container.trans  = cpu_to_le32(r->trans);
976             for (i = 0; i < r->argc; i++) {
977                 params[i] = cpu_to_le32(r->argv[i]);
978             }
979             usb_packet_copy(p, &container, sizeof(container));
980             usb_packet_copy(p, &params, length - sizeof(container));
981             g_free(s->result);
982             s->result = NULL;
983         }
984         break;
985     case EP_DATA_OUT:
986         if (p->iov.size < sizeof(container)) {
987             trace_usb_mtp_stall(s->dev.addr, "packet too small");
988             p->status = USB_RET_STALL;
989             return;
990         }
991         usb_packet_copy(p, &container, sizeof(container));
992         switch (le16_to_cpu(container.type)) {
993         case TYPE_COMMAND:
994             if (s->data_in || s->data_out || s->result) {
995                 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
996                 p->status = USB_RET_STALL;
997                 return;
998             }
999             cmd.code = le16_to_cpu(container.code);
1000             cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1001                 / sizeof(uint32_t);
1002             cmd.trans = le32_to_cpu(container.trans);
1003             if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1004                 cmd.argc = ARRAY_SIZE(cmd.argv);
1005             }
1006             if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1007                 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1008                 p->status = USB_RET_STALL;
1009                 return;
1010             }
1011             usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1012             for (i = 0; i < cmd.argc; i++) {
1013                 cmd.argv[i] = le32_to_cpu(params[i]);
1014             }
1015             trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1016                                   (cmd.argc > 0) ? cmd.argv[0] : 0,
1017                                   (cmd.argc > 1) ? cmd.argv[1] : 0,
1018                                   (cmd.argc > 2) ? cmd.argv[2] : 0,
1019                                   (cmd.argc > 3) ? cmd.argv[3] : 0,
1020                                   (cmd.argc > 4) ? cmd.argv[4] : 0);
1021             usb_mtp_command(s, &cmd);
1022             break;
1023         default:
1024             /* not needed as long as the mtp device is read-only */
1025             p->status = USB_RET_STALL;
1026             return;
1027         }
1028         break;
1029     case EP_EVENT:
1030         p->status = USB_RET_NAK;
1031         return;
1032     default:
1033         trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
1034         p->status = USB_RET_STALL;
1035         return;
1036     }
1037 
1038     if (p->actual_length == 0) {
1039         trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
1040         p->status = USB_RET_NAK;
1041         return;
1042     } else {
1043         trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
1044                            p->iov.size);
1045         return;
1046     }
1047 }
1048 
1049 static int usb_mtp_initfn(USBDevice *dev)
1050 {
1051     MTPState *s = DO_UPCAST(MTPState, dev, dev);
1052 
1053     usb_desc_create_serial(dev);
1054     usb_desc_init(dev);
1055     QTAILQ_INIT(&s->objects);
1056     if (s->desc == NULL) {
1057         s->desc = strrchr(s->root, '/');
1058         if (s->desc && s->desc[0]) {
1059             s->desc = g_strdup(s->desc + 1);
1060         } else {
1061             s->desc = g_strdup("none");
1062         }
1063     }
1064     return 0;
1065 }
1066 
1067 static const VMStateDescription vmstate_usb_mtp = {
1068     .name = "usb-mtp",
1069     .unmigratable = 1,
1070     .version_id = 1,
1071     .minimum_version_id = 1,
1072     .fields = (VMStateField[]) {
1073         VMSTATE_USB_DEVICE(dev, MTPState),
1074         VMSTATE_END_OF_LIST()
1075     }
1076 };
1077 
1078 static Property mtp_properties[] = {
1079     DEFINE_PROP_STRING("root", MTPState, root),
1080     DEFINE_PROP_STRING("desc", MTPState, desc),
1081     DEFINE_PROP_END_OF_LIST(),
1082 };
1083 
1084 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
1085 {
1086     DeviceClass *dc = DEVICE_CLASS(klass);
1087     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1088 
1089     uc->init           = usb_mtp_initfn;
1090     uc->product_desc   = "QEMU USB MTP";
1091     uc->usb_desc       = &desc;
1092     uc->cancel_packet  = usb_mtp_cancel_packet;
1093     uc->handle_attach  = usb_desc_attach;
1094     uc->handle_reset   = usb_mtp_handle_reset;
1095     uc->handle_control = usb_mtp_handle_control;
1096     uc->handle_data    = usb_mtp_handle_data;
1097     dc->fw_name = "mtp";
1098     dc->vmsd = &vmstate_usb_mtp;
1099     dc->props = mtp_properties;
1100 }
1101 
1102 static TypeInfo mtp_info = {
1103     .name          = "usb-mtp",
1104     .parent        = TYPE_USB_DEVICE,
1105     .instance_size = sizeof(MTPState),
1106     .class_init    = usb_mtp_class_initfn,
1107 };
1108 
1109 static void usb_mtp_register_types(void)
1110 {
1111     type_register_static(&mtp_info);
1112 }
1113 
1114 type_init(usb_mtp_register_types)
1115