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