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