xref: /openbmc/qemu/hw/usb/dev-mtp.c (revision 0a9516c2)
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_renew(MTPObject *, o->children, o->nchildren + 32);
363         }
364         o->children[o->nchildren] =
365             usb_mtp_object_alloc(s, s->next_handle++, o, entry->d_name);
366         if (o->children[o->nchildren] != NULL) {
367             o->nchildren++;
368         }
369     }
370     closedir(dir);
371 }
372 
373 /* ----------------------------------------------------------------------- */
374 
375 static MTPData *usb_mtp_data_alloc(MTPControl *c)
376 {
377     MTPData *data = g_new0(MTPData, 1);
378 
379     data->code  = c->code;
380     data->trans = c->trans;
381     data->fd    = -1;
382     data->first = true;
383     return data;
384 }
385 
386 static void usb_mtp_data_free(MTPData *data)
387 {
388     if (data == NULL) {
389         return;
390     }
391     if (data->fd != -1) {
392         close(data->fd);
393     }
394     g_free(data->data);
395     g_free(data);
396 }
397 
398 static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
399 {
400     if (data->length + bytes <= data->alloc) {
401         return;
402     }
403     data->alloc = (data->length + bytes + 0xff) & ~0xff;
404     data->data  = g_realloc(data->data, data->alloc);
405 }
406 
407 static void usb_mtp_add_u8(MTPData *data, uint8_t val)
408 {
409     usb_mtp_realloc(data, 1);
410     data->data[data->length++] = val;
411 }
412 
413 static void usb_mtp_add_u16(MTPData *data, uint16_t val)
414 {
415     usb_mtp_realloc(data, 2);
416     data->data[data->length++] = (val >> 0) & 0xff;
417     data->data[data->length++] = (val >> 8) & 0xff;
418 }
419 
420 static void usb_mtp_add_u32(MTPData *data, uint32_t val)
421 {
422     usb_mtp_realloc(data, 4);
423     data->data[data->length++] = (val >>  0) & 0xff;
424     data->data[data->length++] = (val >>  8) & 0xff;
425     data->data[data->length++] = (val >> 16) & 0xff;
426     data->data[data->length++] = (val >> 24) & 0xff;
427 }
428 
429 static void usb_mtp_add_u64(MTPData *data, uint64_t val)
430 {
431     usb_mtp_realloc(data, 8);
432     data->data[data->length++] = (val >>  0) & 0xff;
433     data->data[data->length++] = (val >>  8) & 0xff;
434     data->data[data->length++] = (val >> 16) & 0xff;
435     data->data[data->length++] = (val >> 24) & 0xff;
436     data->data[data->length++] = (val >> 32) & 0xff;
437     data->data[data->length++] = (val >> 40) & 0xff;
438     data->data[data->length++] = (val >> 48) & 0xff;
439     data->data[data->length++] = (val >> 56) & 0xff;
440 }
441 
442 static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
443                                   const uint16_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_u16(data, vals[i]);
450     }
451 }
452 
453 static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
454                                   const uint32_t *vals)
455 {
456     int i;
457 
458     usb_mtp_add_u32(data, len);
459     for (i = 0; i < len; i++) {
460         usb_mtp_add_u32(data, vals[i]);
461     }
462 }
463 
464 static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
465 {
466     uint32_t len = wcslen(str);
467     int i;
468 
469     if (len > 0) {
470         len++; /* include terminating L'\0' */
471     }
472 
473     usb_mtp_add_u8(data, len);
474     for (i = 0; i < len; i++) {
475         usb_mtp_add_u16(data, str[i]);
476     }
477 }
478 
479 static void usb_mtp_add_str(MTPData *data, const char *str)
480 {
481     uint32_t len = strlen(str)+1;
482     wchar_t wstr[len];
483     size_t ret;
484 
485     ret = mbstowcs(wstr, str, len);
486     if (ret == -1) {
487         usb_mtp_add_wstr(data, L"Oops");
488     } else {
489         usb_mtp_add_wstr(data, wstr);
490     }
491 }
492 
493 static void usb_mtp_add_time(MTPData *data, time_t time)
494 {
495     char buf[16];
496     struct tm tm;
497 
498     gmtime_r(&time, &tm);
499     strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm);
500     usb_mtp_add_str(data, buf);
501 }
502 
503 /* ----------------------------------------------------------------------- */
504 
505 static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans,
506                                  int argc, uint32_t arg0, uint32_t arg1)
507 {
508     MTPControl *c = g_new0(MTPControl, 1);
509 
510     c->code  = code;
511     c->trans = trans;
512     c->argc  = argc;
513     if (argc > 0) {
514         c->argv[0] = arg0;
515     }
516     if (argc > 1) {
517         c->argv[1] = arg1;
518     }
519 
520     assert(s->result == NULL);
521     s->result = c;
522 }
523 
524 /* ----------------------------------------------------------------------- */
525 
526 static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
527 {
528     static const uint16_t ops[] = {
529         CMD_GET_DEVICE_INFO,
530         CMD_OPEN_SESSION,
531         CMD_CLOSE_SESSION,
532         CMD_GET_STORAGE_IDS,
533         CMD_GET_STORAGE_INFO,
534         CMD_GET_NUM_OBJECTS,
535         CMD_GET_OBJECT_HANDLES,
536         CMD_GET_OBJECT_INFO,
537         CMD_GET_OBJECT,
538         CMD_GET_PARTIAL_OBJECT,
539     };
540     static const uint16_t fmt[] = {
541         FMT_UNDEFINED_OBJECT,
542         FMT_ASSOCIATION,
543     };
544     MTPData *d = usb_mtp_data_alloc(c);
545 
546     trace_usb_mtp_op_get_device_info(s->dev.addr);
547 
548     usb_mtp_add_u16(d, 100);
549     usb_mtp_add_u32(d, 0xffffffff);
550     usb_mtp_add_u16(d, 0x0101);
551     usb_mtp_add_wstr(d, L"");
552     usb_mtp_add_u16(d, 0x0000);
553 
554     usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops);
555     usb_mtp_add_u16_array(d, 0, NULL);
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, ARRAY_SIZE(fmt), fmt);
559 
560     usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER);
561     usb_mtp_add_wstr(d, L"" MTP_PRODUCT);
562     usb_mtp_add_wstr(d, L"0.1");
563     usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef");
564 
565     return d;
566 }
567 
568 static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
569 {
570     static const uint32_t ids[] = {
571         QEMU_STORAGE_ID,
572     };
573     MTPData *d = usb_mtp_data_alloc(c);
574 
575     trace_usb_mtp_op_get_storage_ids(s->dev.addr);
576 
577     usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
578 
579     return d;
580 }
581 
582 static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
583 {
584     MTPData *d = usb_mtp_data_alloc(c);
585     struct statvfs buf;
586     int rc;
587 
588     trace_usb_mtp_op_get_storage_info(s->dev.addr);
589 
590     if (FLAG_SET(s, MTP_FLAG_WRITABLE)) {
591         usb_mtp_add_u16(d, 0x0003);
592         usb_mtp_add_u16(d, 0x0002);
593         usb_mtp_add_u16(d, 0x0000);
594     } else {
595         usb_mtp_add_u16(d, 0x0001);
596         usb_mtp_add_u16(d, 0x0002);
597         usb_mtp_add_u16(d, 0x0001);
598     }
599 
600     rc = statvfs(s->root, &buf);
601     if (rc == 0) {
602         usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks);
603         usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks);
604         usb_mtp_add_u32(d, buf.f_ffree);
605     } else {
606         usb_mtp_add_u64(d, 0xffffffff);
607         usb_mtp_add_u64(d, 0xffffffff);
608         usb_mtp_add_u32(d, 0xffffffff);
609     }
610 
611     usb_mtp_add_str(d, s->desc);
612     usb_mtp_add_wstr(d, L"123456789abcdef");
613     return d;
614 }
615 
616 static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
617                                            MTPObject *o)
618 {
619     MTPData *d = usb_mtp_data_alloc(c);
620     uint32_t i, handles[o->nchildren];
621 
622     trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
623 
624     for (i = 0; i < o->nchildren; i++) {
625         handles[i] = o->children[i]->handle;
626     }
627     usb_mtp_add_u32_array(d, o->nchildren, handles);
628 
629     return d;
630 }
631 
632 static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
633                                         MTPObject *o)
634 {
635     MTPData *d = usb_mtp_data_alloc(c);
636 
637     trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
638 
639     usb_mtp_add_u32(d, QEMU_STORAGE_ID);
640     usb_mtp_add_u16(d, o->format);
641     usb_mtp_add_u16(d, 0);
642     usb_mtp_add_u32(d, o->stat.st_size);
643 
644     usb_mtp_add_u16(d, 0);
645     usb_mtp_add_u32(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 
652     if (o->parent) {
653         usb_mtp_add_u32(d, o->parent->handle);
654     } else {
655         usb_mtp_add_u32(d, 0);
656     }
657     if (o->format == FMT_ASSOCIATION) {
658         usb_mtp_add_u16(d, 0x0001);
659         usb_mtp_add_u32(d, 0x00000001);
660         usb_mtp_add_u32(d, 0);
661     } else {
662         usb_mtp_add_u16(d, 0);
663         usb_mtp_add_u32(d, 0);
664         usb_mtp_add_u32(d, 0);
665     }
666 
667     usb_mtp_add_str(d, o->name);
668     usb_mtp_add_time(d, o->stat.st_ctime);
669     usb_mtp_add_time(d, o->stat.st_mtime);
670     usb_mtp_add_wstr(d, L"");
671 
672     return d;
673 }
674 
675 static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
676                                    MTPObject *o)
677 {
678     MTPData *d = usb_mtp_data_alloc(c);
679 
680     trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
681 
682     d->fd = open(o->path, O_RDONLY);
683     if (d->fd == -1) {
684         usb_mtp_data_free(d);
685         return NULL;
686     }
687     d->length = o->stat.st_size;
688     d->alloc  = 512;
689     d->data   = g_malloc(d->alloc);
690     return d;
691 }
692 
693 static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
694                                            MTPObject *o)
695 {
696     MTPData *d = usb_mtp_data_alloc(c);
697     off_t offset;
698 
699     trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
700                                         c->argv[1], c->argv[2]);
701 
702     d->fd = open(o->path, O_RDONLY);
703     if (d->fd == -1) {
704         usb_mtp_data_free(d);
705         return NULL;
706     }
707 
708     offset = c->argv[1];
709     if (offset > o->stat.st_size) {
710         offset = o->stat.st_size;
711     }
712     if (lseek(d->fd, offset, SEEK_SET) < 0) {
713         usb_mtp_data_free(d);
714         return NULL;
715     }
716 
717     d->length = c->argv[2];
718     if (d->length > o->stat.st_size - offset) {
719         d->length = o->stat.st_size - offset;
720     }
721 
722     return d;
723 }
724 
725 static void usb_mtp_command(MTPState *s, MTPControl *c)
726 {
727     MTPData *data_in = NULL;
728     MTPObject *o;
729     uint32_t nres = 0, res0 = 0;
730 
731     /* sanity checks */
732     if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
733         usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
734                              c->trans, 0, 0, 0);
735         return;
736     }
737 
738     /* process commands */
739     switch (c->code) {
740     case CMD_GET_DEVICE_INFO:
741         data_in = usb_mtp_get_device_info(s, c);
742         break;
743     case CMD_OPEN_SESSION:
744         if (s->session) {
745             usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
746                                  c->trans, 1, s->session, 0);
747             return;
748         }
749         if (c->argv[0] == 0) {
750             usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
751                                  c->trans, 0, 0, 0);
752             return;
753         }
754         trace_usb_mtp_op_open_session(s->dev.addr);
755         s->session = c->argv[0];
756         usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
757         break;
758     case CMD_CLOSE_SESSION:
759         trace_usb_mtp_op_close_session(s->dev.addr);
760         s->session = 0;
761         s->next_handle = 0;
762         usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
763         assert(QTAILQ_EMPTY(&s->objects));
764         break;
765     case CMD_GET_STORAGE_IDS:
766         data_in = usb_mtp_get_storage_ids(s, c);
767         break;
768     case CMD_GET_STORAGE_INFO:
769         if (c->argv[0] != QEMU_STORAGE_ID &&
770             c->argv[0] != 0xffffffff) {
771             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
772                                  c->trans, 0, 0, 0);
773             return;
774         }
775         data_in = usb_mtp_get_storage_info(s, c);
776         break;
777     case CMD_GET_NUM_OBJECTS:
778     case CMD_GET_OBJECT_HANDLES:
779         if (c->argv[0] != QEMU_STORAGE_ID &&
780             c->argv[0] != 0xffffffff) {
781             usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
782                                  c->trans, 0, 0, 0);
783             return;
784         }
785         if (c->argv[1] != 0x00000000) {
786             usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
787                                  c->trans, 0, 0, 0);
788             return;
789         }
790         if (c->argv[2] == 0x00000000 ||
791             c->argv[2] == 0xffffffff) {
792             o = QTAILQ_FIRST(&s->objects);
793         } else {
794             o = usb_mtp_object_lookup(s, c->argv[2]);
795         }
796         if (o == NULL) {
797             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
798                                  c->trans, 0, 0, 0);
799             return;
800         }
801         if (o->format != FMT_ASSOCIATION) {
802             usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
803                                  c->trans, 0, 0, 0);
804             return;
805         }
806         usb_mtp_object_readdir(s, o);
807         if (c->code == CMD_GET_NUM_OBJECTS) {
808             trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
809             nres = 1;
810             res0 = o->nchildren;
811         } else {
812             data_in = usb_mtp_get_object_handles(s, c, o);
813         }
814         break;
815     case CMD_GET_OBJECT_INFO:
816         o = usb_mtp_object_lookup(s, c->argv[0]);
817         if (o == NULL) {
818             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
819                                  c->trans, 0, 0, 0);
820             return;
821         }
822         data_in = usb_mtp_get_object_info(s, c, o);
823         break;
824     case CMD_GET_OBJECT:
825         o = usb_mtp_object_lookup(s, c->argv[0]);
826         if (o == NULL) {
827             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
828                                  c->trans, 0, 0, 0);
829             return;
830         }
831         if (o->format == FMT_ASSOCIATION) {
832             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
833                                  c->trans, 0, 0, 0);
834             return;
835         }
836         data_in = usb_mtp_get_object(s, c, o);
837         if (data_in == NULL) {
838             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
839                                  c->trans, 0, 0, 0);
840             return;
841         }
842         break;
843     case CMD_GET_PARTIAL_OBJECT:
844         o = usb_mtp_object_lookup(s, c->argv[0]);
845         if (o == NULL) {
846             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
847                                  c->trans, 0, 0, 0);
848             return;
849         }
850         if (o->format == FMT_ASSOCIATION) {
851             usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
852                                  c->trans, 0, 0, 0);
853             return;
854         }
855         data_in = usb_mtp_get_partial_object(s, c, o);
856         if (data_in == NULL) {
857             usb_mtp_queue_result(s, RES_GENERAL_ERROR,
858                                  c->trans, 0, 0, 0);
859             return;
860         }
861         nres = 1;
862         res0 = data_in->length;
863         break;
864     default:
865         trace_usb_mtp_op_unknown(s->dev.addr, c->code);
866         usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
867                              c->trans, 0, 0, 0);
868         return;
869     }
870 
871     /* return results on success */
872     if (data_in) {
873         assert(s->data_in == NULL);
874         s->data_in = data_in;
875     }
876     usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0);
877 }
878 
879 /* ----------------------------------------------------------------------- */
880 
881 static void usb_mtp_handle_reset(USBDevice *dev)
882 {
883     MTPState *s = USB_MTP(dev);
884 
885     trace_usb_mtp_reset(s->dev.addr);
886 
887     s->session = 0;
888     usb_mtp_data_free(s->data_in);
889     s->data_in = NULL;
890     usb_mtp_data_free(s->data_out);
891     s->data_out = NULL;
892     g_free(s->result);
893     s->result = NULL;
894 }
895 
896 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
897                                    int request, int value, int index,
898                                    int length, uint8_t *data)
899 {
900     int ret;
901 
902     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
903     if (ret >= 0) {
904         return;
905     }
906 
907     trace_usb_mtp_stall(dev->addr, "unknown control request");
908     p->status = USB_RET_STALL;
909 }
910 
911 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
912 {
913     /* we don't use async packets, so this should never be called */
914     fprintf(stderr, "%s\n", __func__);
915 }
916 
917 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
918 {
919     MTPState *s = USB_MTP(dev);
920     MTPControl cmd;
921     mtp_container container;
922     uint32_t params[5];
923     int i, rc;
924 
925     switch (p->ep->nr) {
926     case EP_DATA_IN:
927         if (s->data_out != NULL) {
928             /* guest bug */
929             trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
930             p->status = USB_RET_STALL;
931             return;
932         }
933         if (p->iov.size < sizeof(container)) {
934             trace_usb_mtp_stall(s->dev.addr, "packet too small");
935             p->status = USB_RET_STALL;
936             return;
937         }
938         if (s->data_in !=  NULL) {
939             MTPData *d = s->data_in;
940             int dlen = d->length - d->offset;
941             if (d->first) {
942                 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
943                 container.length = cpu_to_le32(d->length + sizeof(container));
944                 container.type   = cpu_to_le16(TYPE_DATA);
945                 container.code   = cpu_to_le16(d->code);
946                 container.trans  = cpu_to_le32(d->trans);
947                 usb_packet_copy(p, &container, sizeof(container));
948                 d->first = false;
949                 if (dlen > p->iov.size - sizeof(container)) {
950                     dlen = p->iov.size - sizeof(container);
951                 }
952             } else {
953                 if (dlen > p->iov.size) {
954                     dlen = p->iov.size;
955                 }
956             }
957             if (d->fd == -1) {
958                 usb_packet_copy(p, d->data + d->offset, dlen);
959             } else {
960                 if (d->alloc < p->iov.size) {
961                     d->alloc = p->iov.size;
962                     d->data = g_realloc(d->data, d->alloc);
963                 }
964                 rc = read(d->fd, d->data, dlen);
965                 if (rc != dlen) {
966                     memset(d->data, 0, dlen);
967                     s->result->code = RES_INCOMPLETE_TRANSFER;
968                 }
969                 usb_packet_copy(p, d->data, dlen);
970             }
971             d->offset += dlen;
972             if (d->offset == d->length) {
973                 usb_mtp_data_free(s->data_in);
974                 s->data_in = NULL;
975             }
976         } else if (s->result != NULL) {
977             MTPControl *r = s->result;
978             int length = sizeof(container) + r->argc * sizeof(uint32_t);
979             if (r->code == RES_OK) {
980                 trace_usb_mtp_success(s->dev.addr, r->trans,
981                                       (r->argc > 0) ? r->argv[0] : 0,
982                                       (r->argc > 1) ? r->argv[1] : 0);
983             } else {
984                 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
985                                     (r->argc > 0) ? r->argv[0] : 0,
986                                     (r->argc > 1) ? r->argv[1] : 0);
987             }
988             container.length = cpu_to_le32(length);
989             container.type   = cpu_to_le16(TYPE_RESPONSE);
990             container.code   = cpu_to_le16(r->code);
991             container.trans  = cpu_to_le32(r->trans);
992             for (i = 0; i < r->argc; i++) {
993                 params[i] = cpu_to_le32(r->argv[i]);
994             }
995             usb_packet_copy(p, &container, sizeof(container));
996             usb_packet_copy(p, &params, length - sizeof(container));
997             g_free(s->result);
998             s->result = NULL;
999         }
1000         break;
1001     case EP_DATA_OUT:
1002         if (p->iov.size < sizeof(container)) {
1003             trace_usb_mtp_stall(s->dev.addr, "packet too small");
1004             p->status = USB_RET_STALL;
1005             return;
1006         }
1007         usb_packet_copy(p, &container, sizeof(container));
1008         switch (le16_to_cpu(container.type)) {
1009         case TYPE_COMMAND:
1010             if (s->data_in || s->data_out || s->result) {
1011                 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1012                 p->status = USB_RET_STALL;
1013                 return;
1014             }
1015             cmd.code = le16_to_cpu(container.code);
1016             cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1017                 / sizeof(uint32_t);
1018             cmd.trans = le32_to_cpu(container.trans);
1019             if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1020                 cmd.argc = ARRAY_SIZE(cmd.argv);
1021             }
1022             if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1023                 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1024                 p->status = USB_RET_STALL;
1025                 return;
1026             }
1027             usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1028             for (i = 0; i < cmd.argc; i++) {
1029                 cmd.argv[i] = le32_to_cpu(params[i]);
1030             }
1031             trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1032                                   (cmd.argc > 0) ? cmd.argv[0] : 0,
1033                                   (cmd.argc > 1) ? cmd.argv[1] : 0,
1034                                   (cmd.argc > 2) ? cmd.argv[2] : 0,
1035                                   (cmd.argc > 3) ? cmd.argv[3] : 0,
1036                                   (cmd.argc > 4) ? cmd.argv[4] : 0);
1037             usb_mtp_command(s, &cmd);
1038             break;
1039         default:
1040             /* not needed as long as the mtp device is read-only */
1041             p->status = USB_RET_STALL;
1042             return;
1043         }
1044         break;
1045     case EP_EVENT:
1046         p->status = USB_RET_NAK;
1047         return;
1048     default:
1049         trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
1050         p->status = USB_RET_STALL;
1051         return;
1052     }
1053 
1054     if (p->actual_length == 0) {
1055         trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
1056         p->status = USB_RET_NAK;
1057         return;
1058     } else {
1059         trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
1060                            p->iov.size);
1061         return;
1062     }
1063 }
1064 
1065 static void usb_mtp_realize(USBDevice *dev, Error **errp)
1066 {
1067     MTPState *s = USB_MTP(dev);
1068 
1069     usb_desc_create_serial(dev);
1070     usb_desc_init(dev);
1071     QTAILQ_INIT(&s->objects);
1072     if (s->desc == NULL) {
1073         if (s->root == NULL) {
1074             error_setg(errp, "usb-mtp: x-root property must be configured");
1075             return;
1076         }
1077         s->desc = strrchr(s->root, '/');
1078         if (s->desc && s->desc[0]) {
1079             s->desc = g_strdup(s->desc + 1);
1080         } else {
1081             s->desc = g_strdup("none");
1082         }
1083     }
1084 }
1085 
1086 static const VMStateDescription vmstate_usb_mtp = {
1087     .name = "usb-mtp",
1088     .unmigratable = 1,
1089     .version_id = 1,
1090     .minimum_version_id = 1,
1091     .fields = (VMStateField[]) {
1092         VMSTATE_USB_DEVICE(dev, MTPState),
1093         VMSTATE_END_OF_LIST()
1094     }
1095 };
1096 
1097 static Property mtp_properties[] = {
1098     DEFINE_PROP_STRING("x-root", MTPState, root),
1099     DEFINE_PROP_STRING("desc", MTPState, desc),
1100     DEFINE_PROP_END_OF_LIST(),
1101 };
1102 
1103 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
1104 {
1105     DeviceClass *dc = DEVICE_CLASS(klass);
1106     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1107 
1108     uc->realize        = usb_mtp_realize;
1109     uc->product_desc   = "QEMU USB MTP";
1110     uc->usb_desc       = &desc;
1111     uc->cancel_packet  = usb_mtp_cancel_packet;
1112     uc->handle_attach  = usb_desc_attach;
1113     uc->handle_reset   = usb_mtp_handle_reset;
1114     uc->handle_control = usb_mtp_handle_control;
1115     uc->handle_data    = usb_mtp_handle_data;
1116     dc->fw_name = "mtp";
1117     dc->vmsd = &vmstate_usb_mtp;
1118     dc->props = mtp_properties;
1119 }
1120 
1121 static TypeInfo mtp_info = {
1122     .name          = TYPE_USB_MTP,
1123     .parent        = TYPE_USB_DEVICE,
1124     .instance_size = sizeof(MTPState),
1125     .class_init    = usb_mtp_class_initfn,
1126 };
1127 
1128 static void usb_mtp_register_types(void)
1129 {
1130     type_register_static(&mtp_info);
1131 }
1132 
1133 type_init(usb_mtp_register_types)
1134