test-bdrv-drain: AIO_WAIT_WHILE() in job .commit/.abort
[qemu/ar7.git] / hw / usb / dev-mtp.c
blob3fdc4b0da1999ba08e77017d99db458431ae4672
1 /*
2 * Media Transfer Protocol implementation, backed by host filesystem.
4 * Copyright Red Hat, Inc 2014
6 * Author:
7 * Gerd Hoffmann <kraxel@redhat.com>
9 * This code is licensed under the GPL v2 or later.
12 #include "qemu/osdep.h"
13 #include "qapi/error.h"
14 #include <wchar.h>
15 #include <dirent.h>
17 #include <sys/statvfs.h>
18 #ifdef CONFIG_INOTIFY1
19 #include <sys/inotify.h>
20 #include "qemu/main-loop.h"
21 #endif
23 #include "qemu-common.h"
24 #include "qemu/iov.h"
25 #include "trace.h"
26 #include "hw/usb.h"
27 #include "desc.h"
29 /* ----------------------------------------------------------------------- */
31 enum mtp_container_type {
32 TYPE_COMMAND = 1,
33 TYPE_DATA = 2,
34 TYPE_RESPONSE = 3,
35 TYPE_EVENT = 4,
38 enum mtp_code {
39 /* command codes */
40 CMD_GET_DEVICE_INFO = 0x1001,
41 CMD_OPEN_SESSION = 0x1002,
42 CMD_CLOSE_SESSION = 0x1003,
43 CMD_GET_STORAGE_IDS = 0x1004,
44 CMD_GET_STORAGE_INFO = 0x1005,
45 CMD_GET_NUM_OBJECTS = 0x1006,
46 CMD_GET_OBJECT_HANDLES = 0x1007,
47 CMD_GET_OBJECT_INFO = 0x1008,
48 CMD_GET_OBJECT = 0x1009,
49 CMD_DELETE_OBJECT = 0x100b,
50 CMD_SEND_OBJECT_INFO = 0x100c,
51 CMD_SEND_OBJECT = 0x100d,
52 CMD_GET_PARTIAL_OBJECT = 0x101b,
53 CMD_GET_OBJECT_PROPS_SUPPORTED = 0x9801,
54 CMD_GET_OBJECT_PROP_DESC = 0x9802,
55 CMD_GET_OBJECT_PROP_VALUE = 0x9803,
57 /* response codes */
58 RES_OK = 0x2001,
59 RES_GENERAL_ERROR = 0x2002,
60 RES_SESSION_NOT_OPEN = 0x2003,
61 RES_INVALID_TRANSACTION_ID = 0x2004,
62 RES_OPERATION_NOT_SUPPORTED = 0x2005,
63 RES_PARAMETER_NOT_SUPPORTED = 0x2006,
64 RES_INCOMPLETE_TRANSFER = 0x2007,
65 RES_INVALID_STORAGE_ID = 0x2008,
66 RES_INVALID_OBJECT_HANDLE = 0x2009,
67 RES_INVALID_OBJECT_FORMAT_CODE = 0x200b,
68 RES_STORE_FULL = 0x200c,
69 RES_STORE_READ_ONLY = 0x200e,
70 RES_PARTIAL_DELETE = 0x2012,
71 RES_STORE_NOT_AVAILABLE = 0x2013,
72 RES_SPEC_BY_FORMAT_UNSUPPORTED = 0x2014,
73 RES_INVALID_OBJECTINFO = 0x2015,
74 RES_DESTINATION_UNSUPPORTED = 0x2020,
75 RES_INVALID_PARENT_OBJECT = 0x201a,
76 RES_INVALID_PARAMETER = 0x201d,
77 RES_SESSION_ALREADY_OPEN = 0x201e,
78 RES_INVALID_OBJECT_PROP_CODE = 0xA801,
80 /* format codes */
81 FMT_UNDEFINED_OBJECT = 0x3000,
82 FMT_ASSOCIATION = 0x3001,
84 /* event codes */
85 EVT_CANCEL_TRANSACTION = 0x4001,
86 EVT_OBJ_ADDED = 0x4002,
87 EVT_OBJ_REMOVED = 0x4003,
88 EVT_OBJ_INFO_CHANGED = 0x4007,
90 /* object properties */
91 PROP_STORAGE_ID = 0xDC01,
92 PROP_OBJECT_FORMAT = 0xDC02,
93 PROP_OBJECT_COMPRESSED_SIZE = 0xDC04,
94 PROP_PARENT_OBJECT = 0xDC0B,
95 PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER = 0xDC41,
96 PROP_NAME = 0xDC44,
99 enum mtp_data_type {
100 DATA_TYPE_UINT16 = 0x0004,
101 DATA_TYPE_UINT32 = 0x0006,
102 DATA_TYPE_UINT64 = 0x0008,
103 DATA_TYPE_UINT128 = 0x000a,
104 DATA_TYPE_STRING = 0xffff,
107 typedef struct {
108 uint32_t length;
109 uint16_t type;
110 uint16_t code;
111 uint32_t trans;
112 } QEMU_PACKED mtp_container;
114 /* ----------------------------------------------------------------------- */
116 typedef struct MTPState MTPState;
117 typedef struct MTPControl MTPControl;
118 typedef struct MTPData MTPData;
119 typedef struct MTPObject MTPObject;
121 enum {
122 EP_DATA_IN = 1,
123 EP_DATA_OUT,
124 EP_EVENT,
127 #ifdef CONFIG_INOTIFY1
128 typedef struct MTPMonEntry MTPMonEntry;
130 struct MTPMonEntry {
131 uint32_t event;
132 uint32_t handle;
134 QTAILQ_ENTRY(MTPMonEntry) next;
136 #endif
138 struct MTPControl {
139 uint16_t code;
140 uint32_t trans;
141 int argc;
142 uint32_t argv[5];
145 struct MTPData {
146 uint16_t code;
147 uint32_t trans;
148 uint64_t offset;
149 uint64_t length;
150 uint64_t alloc;
151 uint8_t *data;
152 bool first;
153 /* Used for >4G file sizes */
154 bool pending;
155 uint64_t cached_length;
156 int fd;
159 struct MTPObject {
160 uint32_t handle;
161 uint16_t format;
162 char *name;
163 char *path;
164 struct stat stat;
165 #ifdef CONFIG_INOTIFY1
166 /* inotify watch cookie */
167 int watchfd;
168 #endif
169 MTPObject *parent;
170 uint32_t nchildren;
171 QLIST_HEAD(, MTPObject) children;
172 QLIST_ENTRY(MTPObject) list;
173 bool have_children;
174 QTAILQ_ENTRY(MTPObject) next;
177 struct MTPState {
178 USBDevice dev;
179 char *root;
180 char *desc;
181 uint32_t flags;
183 MTPData *data_in;
184 MTPData *data_out;
185 MTPControl *result;
186 uint32_t session;
187 uint32_t next_handle;
188 bool readonly;
190 QTAILQ_HEAD(, MTPObject) objects;
191 #ifdef CONFIG_INOTIFY1
192 /* inotify descriptor */
193 int inotifyfd;
194 QTAILQ_HEAD(events, MTPMonEntry) events;
195 #endif
196 /* Responder is expecting a write operation */
197 bool write_pending;
198 struct {
199 uint32_t parent_handle;
200 uint16_t format;
201 uint32_t size;
202 char *filename;
203 } dataset;
207 * ObjectInfo dataset received from initiator
208 * Fields we don't care about are ignored
210 typedef struct {
211 uint32_t storage_id; /*unused*/
212 uint16_t format;
213 uint16_t protection_status; /*unused*/
214 uint32_t size;
215 uint16_t thumb_format; /*unused*/
216 uint32_t thumb_comp_sz; /*unused*/
217 uint32_t thumb_pix_width; /*unused*/
218 uint32_t thumb_pix_height; /*unused*/
219 uint32_t image_pix_width; /*unused*/
220 uint32_t image_pix_height; /*unused*/
221 uint32_t image_bit_depth; /*unused*/
222 uint32_t parent; /*unused*/
223 uint16_t assoc_type;
224 uint32_t assoc_desc;
225 uint32_t seq_no; /*unused*/
226 uint8_t length; /*part of filename field*/
227 uint16_t filename[0];
228 char date_created[0]; /*unused*/
229 char date_modified[0]; /*unused*/
230 char keywords[0]; /*unused*/
231 /* string and other data follows */
232 } QEMU_PACKED ObjectInfo;
234 #define TYPE_USB_MTP "usb-mtp"
235 #define USB_MTP(obj) OBJECT_CHECK(MTPState, (obj), TYPE_USB_MTP)
237 #define QEMU_STORAGE_ID 0x00010001
239 #define MTP_FLAG_WRITABLE 0
241 #define FLAG_SET(_mtp, _flag) ((_mtp)->flags & (1 << (_flag)))
243 /* ----------------------------------------------------------------------- */
245 #define MTP_MANUFACTURER "QEMU"
246 #define MTP_PRODUCT "QEMU filesharing"
248 enum {
249 STR_MANUFACTURER = 1,
250 STR_PRODUCT,
251 STR_SERIALNUMBER,
252 STR_MTP,
253 STR_CONFIG_FULL,
254 STR_CONFIG_HIGH,
255 STR_CONFIG_SUPER,
258 static const USBDescStrings desc_strings = {
259 [STR_MANUFACTURER] = MTP_MANUFACTURER,
260 [STR_PRODUCT] = MTP_PRODUCT,
261 [STR_SERIALNUMBER] = "34617",
262 [STR_MTP] = "MTP",
263 [STR_CONFIG_FULL] = "Full speed config (usb 1.1)",
264 [STR_CONFIG_HIGH] = "High speed config (usb 2.0)",
265 [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
268 static const USBDescIface desc_iface_full = {
269 .bInterfaceNumber = 0,
270 .bNumEndpoints = 3,
271 .bInterfaceClass = USB_CLASS_STILL_IMAGE,
272 .bInterfaceSubClass = 0x01,
273 .bInterfaceProtocol = 0x01,
274 .iInterface = STR_MTP,
275 .eps = (USBDescEndpoint[]) {
277 .bEndpointAddress = USB_DIR_IN | EP_DATA_IN,
278 .bmAttributes = USB_ENDPOINT_XFER_BULK,
279 .wMaxPacketSize = 64,
281 .bEndpointAddress = USB_DIR_OUT | EP_DATA_OUT,
282 .bmAttributes = USB_ENDPOINT_XFER_BULK,
283 .wMaxPacketSize = 64,
285 .bEndpointAddress = USB_DIR_IN | EP_EVENT,
286 .bmAttributes = USB_ENDPOINT_XFER_INT,
287 .wMaxPacketSize = 64,
288 .bInterval = 0x0a,
293 static const USBDescDevice desc_device_full = {
294 .bcdUSB = 0x0200,
295 .bMaxPacketSize0 = 8,
296 .bNumConfigurations = 1,
297 .confs = (USBDescConfig[]) {
299 .bNumInterfaces = 1,
300 .bConfigurationValue = 1,
301 .iConfiguration = STR_CONFIG_FULL,
302 .bmAttributes = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
303 .bMaxPower = 2,
304 .nif = 1,
305 .ifs = &desc_iface_full,
310 static const USBDescIface desc_iface_high = {
311 .bInterfaceNumber = 0,
312 .bNumEndpoints = 3,
313 .bInterfaceClass = USB_CLASS_STILL_IMAGE,
314 .bInterfaceSubClass = 0x01,
315 .bInterfaceProtocol = 0x01,
316 .iInterface = STR_MTP,
317 .eps = (USBDescEndpoint[]) {
319 .bEndpointAddress = USB_DIR_IN | EP_DATA_IN,
320 .bmAttributes = USB_ENDPOINT_XFER_BULK,
321 .wMaxPacketSize = 512,
323 .bEndpointAddress = USB_DIR_OUT | EP_DATA_OUT,
324 .bmAttributes = USB_ENDPOINT_XFER_BULK,
325 .wMaxPacketSize = 512,
327 .bEndpointAddress = USB_DIR_IN | EP_EVENT,
328 .bmAttributes = USB_ENDPOINT_XFER_INT,
329 .wMaxPacketSize = 64,
330 .bInterval = 0x0a,
335 static const USBDescDevice desc_device_high = {
336 .bcdUSB = 0x0200,
337 .bMaxPacketSize0 = 64,
338 .bNumConfigurations = 1,
339 .confs = (USBDescConfig[]) {
341 .bNumInterfaces = 1,
342 .bConfigurationValue = 1,
343 .iConfiguration = STR_CONFIG_HIGH,
344 .bmAttributes = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
345 .bMaxPower = 2,
346 .nif = 1,
347 .ifs = &desc_iface_high,
352 static const USBDescMSOS desc_msos = {
353 .CompatibleID = "MTP",
354 .SelectiveSuspendEnabled = true,
357 static const USBDesc desc = {
358 .id = {
359 .idVendor = 0x46f4, /* CRC16() of "QEMU" */
360 .idProduct = 0x0004,
361 .bcdDevice = 0,
362 .iManufacturer = STR_MANUFACTURER,
363 .iProduct = STR_PRODUCT,
364 .iSerialNumber = STR_SERIALNUMBER,
366 .full = &desc_device_full,
367 .high = &desc_device_high,
368 .str = desc_strings,
369 .msos = &desc_msos,
372 /* ----------------------------------------------------------------------- */
374 static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle,
375 MTPObject *parent, char *name)
377 MTPObject *o = g_new0(MTPObject, 1);
379 if (name[0] == '.') {
380 goto ignore;
383 o->handle = handle;
384 o->parent = parent;
385 o->name = g_strdup(name);
386 if (parent == NULL) {
387 o->path = g_strdup(name);
388 } else {
389 o->path = g_strdup_printf("%s/%s", parent->path, name);
392 if (lstat(o->path, &o->stat) != 0) {
393 goto ignore;
395 if (S_ISREG(o->stat.st_mode)) {
396 o->format = FMT_UNDEFINED_OBJECT;
397 } else if (S_ISDIR(o->stat.st_mode)) {
398 o->format = FMT_ASSOCIATION;
399 } else {
400 goto ignore;
403 if (access(o->path, R_OK) != 0) {
404 goto ignore;
407 trace_usb_mtp_object_alloc(s->dev.addr, o->handle, o->path);
409 QTAILQ_INSERT_TAIL(&s->objects, o, next);
410 return o;
412 ignore:
413 g_free(o->name);
414 g_free(o->path);
415 g_free(o);
416 return NULL;
419 static void usb_mtp_object_free(MTPState *s, MTPObject *o)
421 MTPObject *iter;
423 if (!o) {
424 return;
427 trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path);
429 QTAILQ_REMOVE(&s->objects, o, next);
430 if (o->parent) {
431 QLIST_REMOVE(o, list);
432 o->parent->nchildren--;
435 while (!QLIST_EMPTY(&o->children)) {
436 iter = QLIST_FIRST(&o->children);
437 usb_mtp_object_free(s, iter);
439 g_free(o->name);
440 g_free(o->path);
441 g_free(o);
444 static MTPObject *usb_mtp_object_lookup(MTPState *s, uint32_t handle)
446 MTPObject *o;
448 QTAILQ_FOREACH(o, &s->objects, next) {
449 if (o->handle == handle) {
450 return o;
453 return NULL;
456 static MTPObject *usb_mtp_add_child(MTPState *s, MTPObject *o,
457 char *name)
459 MTPObject *child =
460 usb_mtp_object_alloc(s, s->next_handle++, o, name);
462 if (child) {
463 trace_usb_mtp_add_child(s->dev.addr, child->handle, child->path);
464 QLIST_INSERT_HEAD(&o->children, child, list);
465 o->nchildren++;
467 if (child->format == FMT_ASSOCIATION) {
468 QLIST_INIT(&child->children);
472 return child;
475 static MTPObject *usb_mtp_object_lookup_name(MTPObject *parent,
476 char *name, int len)
478 MTPObject *iter;
480 QLIST_FOREACH(iter, &parent->children, list) {
481 if (strncmp(iter->name, name, len) == 0) {
482 return iter;
486 return NULL;
489 #ifdef CONFIG_INOTIFY1
490 static MTPObject *usb_mtp_object_lookup_wd(MTPState *s, int wd)
492 MTPObject *iter;
494 QTAILQ_FOREACH(iter, &s->objects, next) {
495 if (iter->watchfd == wd) {
496 return iter;
500 return NULL;
503 static void inotify_watchfn(void *arg)
505 MTPState *s = arg;
506 ssize_t bytes;
507 /* From the man page: atleast one event can be read */
508 int pos;
509 char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
511 for (;;) {
512 bytes = read(s->inotifyfd, buf, sizeof(buf));
513 pos = 0;
515 if (bytes <= 0) {
516 /* Better luck next time */
517 return;
521 * TODO: Ignore initiator initiated events.
522 * For now we are good because the store is RO
524 while (bytes > 0) {
525 char *p = buf + pos;
526 struct inotify_event *event = (struct inotify_event *)p;
527 int watchfd = 0;
528 uint32_t mask = event->mask & (IN_CREATE | IN_DELETE |
529 IN_MODIFY | IN_IGNORED);
530 MTPObject *parent = usb_mtp_object_lookup_wd(s, event->wd);
531 MTPMonEntry *entry = NULL;
532 MTPObject *o;
534 pos = pos + sizeof(struct inotify_event) + event->len;
535 bytes = bytes - pos;
537 if (!parent) {
538 continue;
541 switch (mask) {
542 case IN_CREATE:
543 if (usb_mtp_object_lookup_name
544 (parent, event->name, event->len)) {
545 /* Duplicate create event */
546 continue;
548 entry = g_new0(MTPMonEntry, 1);
549 entry->handle = s->next_handle;
550 entry->event = EVT_OBJ_ADDED;
551 o = usb_mtp_add_child(s, parent, event->name);
552 if (!o) {
553 g_free(entry);
554 continue;
556 o->watchfd = watchfd;
557 trace_usb_mtp_inotify_event(s->dev.addr, event->name,
558 event->mask, "Obj Added");
559 break;
561 case IN_DELETE:
563 * The kernel issues a IN_IGNORED event
564 * when a dir containing a watchpoint is
565 * deleted, so we don't have to delete the
566 * watchpoint
568 o = usb_mtp_object_lookup_name(parent, event->name, event->len);
569 if (!o) {
570 continue;
572 entry = g_new0(MTPMonEntry, 1);
573 entry->handle = o->handle;
574 entry->event = EVT_OBJ_REMOVED;
575 trace_usb_mtp_inotify_event(s->dev.addr, o->path,
576 event->mask, "Obj Deleted");
577 usb_mtp_object_free(s, o);
578 break;
580 case IN_MODIFY:
581 o = usb_mtp_object_lookup_name(parent, event->name, event->len);
582 if (!o) {
583 continue;
585 entry = g_new0(MTPMonEntry, 1);
586 entry->handle = o->handle;
587 entry->event = EVT_OBJ_INFO_CHANGED;
588 trace_usb_mtp_inotify_event(s->dev.addr, o->path,
589 event->mask, "Obj Modified");
590 break;
592 case IN_IGNORED:
593 trace_usb_mtp_inotify_event(s->dev.addr, parent->path,
594 event->mask, "Obj parent dir ignored");
595 break;
597 default:
598 fprintf(stderr, "usb-mtp: failed to parse inotify event\n");
599 continue;
602 if (entry) {
603 QTAILQ_INSERT_HEAD(&s->events, entry, next);
609 static int usb_mtp_inotify_init(MTPState *s)
611 int fd;
613 fd = inotify_init1(IN_NONBLOCK);
614 if (fd == -1) {
615 return 1;
618 QTAILQ_INIT(&s->events);
619 s->inotifyfd = fd;
621 qemu_set_fd_handler(fd, inotify_watchfn, NULL, s);
623 return 0;
626 static void usb_mtp_inotify_cleanup(MTPState *s)
628 MTPMonEntry *e, *p;
630 if (!s->inotifyfd) {
631 return;
634 qemu_set_fd_handler(s->inotifyfd, NULL, NULL, s);
635 close(s->inotifyfd);
637 QTAILQ_FOREACH_SAFE(e, &s->events, next, p) {
638 QTAILQ_REMOVE(&s->events, e, next);
639 g_free(e);
643 static int usb_mtp_add_watch(int inotifyfd, char *path)
645 uint32_t mask = IN_CREATE | IN_DELETE | IN_MODIFY |
646 IN_ISDIR;
648 return inotify_add_watch(inotifyfd, path, mask);
650 #endif
652 static void usb_mtp_object_readdir(MTPState *s, MTPObject *o)
654 struct dirent *entry;
655 DIR *dir;
657 if (o->have_children) {
658 return;
660 o->have_children = true;
662 dir = opendir(o->path);
663 if (!dir) {
664 return;
666 #ifdef CONFIG_INOTIFY1
667 int watchfd = usb_mtp_add_watch(s->inotifyfd, o->path);
668 if (watchfd == -1) {
669 fprintf(stderr, "usb-mtp: failed to add watch for %s\n", o->path);
670 } else {
671 trace_usb_mtp_inotify_event(s->dev.addr, o->path,
672 0, "Watch Added");
673 o->watchfd = watchfd;
675 #endif
676 while ((entry = readdir(dir)) != NULL) {
677 usb_mtp_add_child(s, o, entry->d_name);
679 closedir(dir);
682 /* ----------------------------------------------------------------------- */
684 static MTPData *usb_mtp_data_alloc(MTPControl *c)
686 MTPData *data = g_new0(MTPData, 1);
688 data->code = c->code;
689 data->trans = c->trans;
690 data->fd = -1;
691 data->first = true;
692 return data;
695 static void usb_mtp_data_free(MTPData *data)
697 if (data == NULL) {
698 return;
700 if (data->fd != -1) {
701 close(data->fd);
703 g_free(data->data);
704 g_free(data);
707 static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
709 if (data->length + bytes <= data->alloc) {
710 return;
712 data->alloc = (data->length + bytes + 0xff) & ~0xff;
713 data->data = g_realloc(data->data, data->alloc);
716 static void usb_mtp_add_u8(MTPData *data, uint8_t val)
718 usb_mtp_realloc(data, 1);
719 data->data[data->length++] = val;
722 static void usb_mtp_add_u16(MTPData *data, uint16_t val)
724 usb_mtp_realloc(data, 2);
725 data->data[data->length++] = (val >> 0) & 0xff;
726 data->data[data->length++] = (val >> 8) & 0xff;
729 static void usb_mtp_add_u32(MTPData *data, uint32_t val)
731 usb_mtp_realloc(data, 4);
732 data->data[data->length++] = (val >> 0) & 0xff;
733 data->data[data->length++] = (val >> 8) & 0xff;
734 data->data[data->length++] = (val >> 16) & 0xff;
735 data->data[data->length++] = (val >> 24) & 0xff;
738 static void usb_mtp_add_u64(MTPData *data, uint64_t val)
740 usb_mtp_realloc(data, 8);
741 data->data[data->length++] = (val >> 0) & 0xff;
742 data->data[data->length++] = (val >> 8) & 0xff;
743 data->data[data->length++] = (val >> 16) & 0xff;
744 data->data[data->length++] = (val >> 24) & 0xff;
745 data->data[data->length++] = (val >> 32) & 0xff;
746 data->data[data->length++] = (val >> 40) & 0xff;
747 data->data[data->length++] = (val >> 48) & 0xff;
748 data->data[data->length++] = (val >> 56) & 0xff;
751 static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
752 const uint16_t *vals)
754 int i;
756 usb_mtp_add_u32(data, len);
757 for (i = 0; i < len; i++) {
758 usb_mtp_add_u16(data, vals[i]);
762 static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
763 const uint32_t *vals)
765 int i;
767 usb_mtp_add_u32(data, len);
768 for (i = 0; i < len; i++) {
769 usb_mtp_add_u32(data, vals[i]);
773 static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
775 uint32_t len = wcslen(str);
776 int i;
778 if (len > 0) {
779 len++; /* include terminating L'\0' */
782 usb_mtp_add_u8(data, len);
783 for (i = 0; i < len; i++) {
784 usb_mtp_add_u16(data, str[i]);
788 static void usb_mtp_add_str(MTPData *data, const char *str)
790 uint32_t len = strlen(str)+1;
791 wchar_t *wstr = g_new(wchar_t, len);
792 size_t ret;
794 ret = mbstowcs(wstr, str, len);
795 if (ret == -1) {
796 usb_mtp_add_wstr(data, L"Oops");
797 } else {
798 usb_mtp_add_wstr(data, wstr);
801 g_free(wstr);
804 static void usb_mtp_add_time(MTPData *data, time_t time)
806 char buf[16];
807 struct tm tm;
809 gmtime_r(&time, &tm);
810 strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm);
811 usb_mtp_add_str(data, buf);
814 /* ----------------------------------------------------------------------- */
816 static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans,
817 int argc, uint32_t arg0, uint32_t arg1,
818 uint32_t arg2)
820 MTPControl *c = g_new0(MTPControl, 1);
822 c->code = code;
823 c->trans = trans;
824 c->argc = argc;
825 if (argc > 0) {
826 c->argv[0] = arg0;
828 if (argc > 1) {
829 c->argv[1] = arg1;
831 if (argc > 2) {
832 c->argv[2] = arg2;
835 assert(s->result == NULL);
836 s->result = c;
839 /* ----------------------------------------------------------------------- */
841 static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
843 static const uint16_t ops[] = {
844 CMD_GET_DEVICE_INFO,
845 CMD_OPEN_SESSION,
846 CMD_CLOSE_SESSION,
847 CMD_GET_STORAGE_IDS,
848 CMD_GET_STORAGE_INFO,
849 CMD_GET_NUM_OBJECTS,
850 CMD_GET_OBJECT_HANDLES,
851 CMD_GET_OBJECT_INFO,
852 CMD_DELETE_OBJECT,
853 CMD_SEND_OBJECT_INFO,
854 CMD_SEND_OBJECT,
855 CMD_GET_OBJECT,
856 CMD_GET_PARTIAL_OBJECT,
857 CMD_GET_OBJECT_PROPS_SUPPORTED,
858 CMD_GET_OBJECT_PROP_DESC,
859 CMD_GET_OBJECT_PROP_VALUE,
861 static const uint16_t fmt[] = {
862 FMT_UNDEFINED_OBJECT,
863 FMT_ASSOCIATION,
865 MTPData *d = usb_mtp_data_alloc(c);
867 trace_usb_mtp_op_get_device_info(s->dev.addr);
869 usb_mtp_add_u16(d, 100);
870 usb_mtp_add_u32(d, 0x00000006);
871 usb_mtp_add_u16(d, 0x0064);
872 usb_mtp_add_wstr(d, L"");
873 usb_mtp_add_u16(d, 0x0000);
875 usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops);
876 usb_mtp_add_u16_array(d, 0, NULL);
877 usb_mtp_add_u16_array(d, 0, NULL);
878 usb_mtp_add_u16_array(d, 0, NULL);
879 usb_mtp_add_u16_array(d, ARRAY_SIZE(fmt), fmt);
881 usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER);
882 usb_mtp_add_wstr(d, L"" MTP_PRODUCT);
883 usb_mtp_add_wstr(d, L"0.1");
884 usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef");
886 return d;
889 static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
891 static const uint32_t ids[] = {
892 QEMU_STORAGE_ID,
894 MTPData *d = usb_mtp_data_alloc(c);
896 trace_usb_mtp_op_get_storage_ids(s->dev.addr);
898 usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
900 return d;
903 static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
905 MTPData *d = usb_mtp_data_alloc(c);
906 struct statvfs buf;
907 int rc;
909 trace_usb_mtp_op_get_storage_info(s->dev.addr);
911 if (FLAG_SET(s, MTP_FLAG_WRITABLE)) {
912 usb_mtp_add_u16(d, 0x0003);
913 usb_mtp_add_u16(d, 0x0002);
914 usb_mtp_add_u16(d, 0x0000);
915 } else {
916 usb_mtp_add_u16(d, 0x0001);
917 usb_mtp_add_u16(d, 0x0002);
918 usb_mtp_add_u16(d, 0x0001);
921 rc = statvfs(s->root, &buf);
922 if (rc == 0) {
923 usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks);
924 usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks);
925 usb_mtp_add_u32(d, buf.f_ffree);
926 } else {
927 usb_mtp_add_u64(d, 0xffffffff);
928 usb_mtp_add_u64(d, 0xffffffff);
929 usb_mtp_add_u32(d, 0xffffffff);
932 usb_mtp_add_str(d, s->desc);
933 usb_mtp_add_wstr(d, L"123456789abcdef");
934 return d;
937 static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
938 MTPObject *o)
940 MTPData *d = usb_mtp_data_alloc(c);
941 uint32_t i = 0, handles[o->nchildren];
942 MTPObject *iter;
944 trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
946 QLIST_FOREACH(iter, &o->children, list) {
947 handles[i++] = iter->handle;
949 assert(i == o->nchildren);
950 usb_mtp_add_u32_array(d, o->nchildren, handles);
952 return d;
955 static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
956 MTPObject *o)
958 MTPData *d = usb_mtp_data_alloc(c);
960 trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
962 usb_mtp_add_u32(d, QEMU_STORAGE_ID);
963 usb_mtp_add_u16(d, o->format);
964 usb_mtp_add_u16(d, 0);
966 if (o->stat.st_size > 0xFFFFFFFF) {
967 usb_mtp_add_u32(d, 0xFFFFFFFF);
968 } else {
969 usb_mtp_add_u32(d, o->stat.st_size);
972 usb_mtp_add_u16(d, 0);
973 usb_mtp_add_u32(d, 0);
974 usb_mtp_add_u32(d, 0);
975 usb_mtp_add_u32(d, 0);
976 usb_mtp_add_u32(d, 0);
977 usb_mtp_add_u32(d, 0);
978 usb_mtp_add_u32(d, 0);
980 if (o->parent) {
981 usb_mtp_add_u32(d, o->parent->handle);
982 } else {
983 usb_mtp_add_u32(d, 0);
985 if (o->format == FMT_ASSOCIATION) {
986 usb_mtp_add_u16(d, 0x0001);
987 usb_mtp_add_u32(d, 0x00000001);
988 usb_mtp_add_u32(d, 0);
989 } else {
990 usb_mtp_add_u16(d, 0);
991 usb_mtp_add_u32(d, 0);
992 usb_mtp_add_u32(d, 0);
995 usb_mtp_add_str(d, o->name);
996 usb_mtp_add_time(d, o->stat.st_ctime);
997 usb_mtp_add_time(d, o->stat.st_mtime);
998 usb_mtp_add_wstr(d, L"");
1000 return d;
1003 static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
1004 MTPObject *o)
1006 MTPData *d = usb_mtp_data_alloc(c);
1008 trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
1010 d->fd = open(o->path, O_RDONLY);
1011 if (d->fd == -1) {
1012 usb_mtp_data_free(d);
1013 return NULL;
1015 d->length = o->stat.st_size;
1016 d->alloc = 512;
1017 d->data = g_malloc(d->alloc);
1018 return d;
1021 static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
1022 MTPObject *o)
1024 MTPData *d;
1025 off_t offset;
1027 if (c->argc <= 2) {
1028 return NULL;
1030 trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
1031 c->argv[1], c->argv[2]);
1033 d = usb_mtp_data_alloc(c);
1034 d->fd = open(o->path, O_RDONLY);
1035 if (d->fd == -1) {
1036 usb_mtp_data_free(d);
1037 return NULL;
1040 offset = c->argv[1];
1041 if (offset > o->stat.st_size) {
1042 offset = o->stat.st_size;
1044 if (lseek(d->fd, offset, SEEK_SET) < 0) {
1045 usb_mtp_data_free(d);
1046 return NULL;
1049 d->length = c->argv[2];
1050 if (d->length > o->stat.st_size - offset) {
1051 d->length = o->stat.st_size - offset;
1054 return d;
1057 static MTPData *usb_mtp_get_object_props_supported(MTPState *s, MTPControl *c)
1059 static const uint16_t props[] = {
1060 PROP_STORAGE_ID,
1061 PROP_OBJECT_FORMAT,
1062 PROP_OBJECT_COMPRESSED_SIZE,
1063 PROP_PARENT_OBJECT,
1064 PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER,
1065 PROP_NAME,
1067 MTPData *d = usb_mtp_data_alloc(c);
1068 usb_mtp_add_u16_array(d, ARRAY_SIZE(props), props);
1070 return d;
1073 static MTPData *usb_mtp_get_object_prop_desc(MTPState *s, MTPControl *c)
1075 MTPData *d = usb_mtp_data_alloc(c);
1076 switch (c->argv[0]) {
1077 case PROP_STORAGE_ID:
1078 usb_mtp_add_u16(d, PROP_STORAGE_ID);
1079 usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1080 usb_mtp_add_u8(d, 0x00);
1081 usb_mtp_add_u32(d, 0x00000000);
1082 usb_mtp_add_u32(d, 0x00000000);
1083 usb_mtp_add_u8(d, 0x00);
1084 break;
1085 case PROP_OBJECT_FORMAT:
1086 usb_mtp_add_u16(d, PROP_OBJECT_FORMAT);
1087 usb_mtp_add_u16(d, DATA_TYPE_UINT16);
1088 usb_mtp_add_u8(d, 0x00);
1089 usb_mtp_add_u16(d, 0x0000);
1090 usb_mtp_add_u32(d, 0x00000000);
1091 usb_mtp_add_u8(d, 0x00);
1092 break;
1093 case PROP_OBJECT_COMPRESSED_SIZE:
1094 usb_mtp_add_u16(d, PROP_OBJECT_COMPRESSED_SIZE);
1095 usb_mtp_add_u16(d, DATA_TYPE_UINT64);
1096 usb_mtp_add_u8(d, 0x00);
1097 usb_mtp_add_u64(d, 0x0000000000000000);
1098 usb_mtp_add_u32(d, 0x00000000);
1099 usb_mtp_add_u8(d, 0x00);
1100 break;
1101 case PROP_PARENT_OBJECT:
1102 usb_mtp_add_u16(d, PROP_PARENT_OBJECT);
1103 usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1104 usb_mtp_add_u8(d, 0x00);
1105 usb_mtp_add_u32(d, 0x00000000);
1106 usb_mtp_add_u32(d, 0x00000000);
1107 usb_mtp_add_u8(d, 0x00);
1108 break;
1109 case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1110 usb_mtp_add_u16(d, PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER);
1111 usb_mtp_add_u16(d, DATA_TYPE_UINT128);
1112 usb_mtp_add_u8(d, 0x00);
1113 usb_mtp_add_u64(d, 0x0000000000000000);
1114 usb_mtp_add_u64(d, 0x0000000000000000);
1115 usb_mtp_add_u32(d, 0x00000000);
1116 usb_mtp_add_u8(d, 0x00);
1117 break;
1118 case PROP_NAME:
1119 usb_mtp_add_u16(d, PROP_NAME);
1120 usb_mtp_add_u16(d, DATA_TYPE_STRING);
1121 usb_mtp_add_u8(d, 0x00);
1122 usb_mtp_add_u8(d, 0x00);
1123 usb_mtp_add_u32(d, 0x00000000);
1124 usb_mtp_add_u8(d, 0x00);
1125 break;
1126 default:
1127 usb_mtp_data_free(d);
1128 return NULL;
1131 return d;
1134 static MTPData *usb_mtp_get_object_prop_value(MTPState *s, MTPControl *c,
1135 MTPObject *o)
1137 MTPData *d = usb_mtp_data_alloc(c);
1138 switch (c->argv[1]) {
1139 case PROP_STORAGE_ID:
1140 usb_mtp_add_u32(d, QEMU_STORAGE_ID);
1141 break;
1142 case PROP_OBJECT_FORMAT:
1143 usb_mtp_add_u16(d, o->format);
1144 break;
1145 case PROP_OBJECT_COMPRESSED_SIZE:
1146 usb_mtp_add_u64(d, o->stat.st_size);
1147 break;
1148 case PROP_PARENT_OBJECT:
1149 if (o->parent == NULL) {
1150 usb_mtp_add_u32(d, 0x00000000);
1151 } else {
1152 usb_mtp_add_u32(d, o->parent->handle);
1154 break;
1155 case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1156 /* Should be persistent between sessions,
1157 * but using our objedt ID is "good enough"
1158 * for now */
1159 usb_mtp_add_u64(d, 0x0000000000000000);
1160 usb_mtp_add_u64(d, o->handle);
1161 break;
1162 case PROP_NAME:
1163 usb_mtp_add_str(d, o->name);
1164 break;
1165 default:
1166 usb_mtp_data_free(d);
1167 return NULL;
1170 return d;
1173 /* Return correct return code for a delete event */
1174 enum {
1175 ALL_DELETE,
1176 PARTIAL_DELETE,
1177 READ_ONLY,
1180 /* Assumes that children, if any, have been already freed */
1181 static void usb_mtp_object_free_one(MTPState *s, MTPObject *o)
1183 #ifndef CONFIG_INOTIFY1
1184 assert(o->nchildren == 0);
1185 QTAILQ_REMOVE(&s->objects, o, next);
1186 g_free(o->name);
1187 g_free(o->path);
1188 g_free(o);
1189 #endif
1192 static int usb_mtp_deletefn(MTPState *s, MTPObject *o, uint32_t trans)
1194 MTPObject *iter, *iter2;
1195 bool partial_delete = false;
1196 bool success = false;
1199 * TODO: Add support for Protection Status
1202 QLIST_FOREACH(iter, &o->children, list) {
1203 if (iter->format == FMT_ASSOCIATION) {
1204 QLIST_FOREACH(iter2, &iter->children, list) {
1205 usb_mtp_deletefn(s, iter2, trans);
1210 if (o->format == FMT_UNDEFINED_OBJECT) {
1211 if (remove(o->path)) {
1212 partial_delete = true;
1213 } else {
1214 usb_mtp_object_free_one(s, o);
1215 success = true;
1219 if (o->format == FMT_ASSOCIATION) {
1220 if (rmdir(o->path)) {
1221 partial_delete = true;
1222 } else {
1223 usb_mtp_object_free_one(s, o);
1224 success = true;
1228 if (success && partial_delete) {
1229 return PARTIAL_DELETE;
1231 if (!success && partial_delete) {
1232 return READ_ONLY;
1234 return ALL_DELETE;
1237 static void usb_mtp_object_delete(MTPState *s, uint32_t handle,
1238 uint32_t format_code, uint32_t trans)
1240 MTPObject *o;
1241 int ret;
1243 /* Return error if store is read-only */
1244 if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1245 usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1246 trans, 0, 0, 0, 0);
1247 return;
1250 if (format_code != 0) {
1251 usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1252 trans, 0, 0, 0, 0);
1253 return;
1256 if (handle == 0xFFFFFFF) {
1257 o = QTAILQ_FIRST(&s->objects);
1258 } else {
1259 o = usb_mtp_object_lookup(s, handle);
1261 if (o == NULL) {
1262 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1263 trans, 0, 0, 0, 0);
1264 return;
1267 ret = usb_mtp_deletefn(s, o, trans);
1268 if (ret == PARTIAL_DELETE) {
1269 usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1270 trans, 0, 0, 0, 0);
1271 return;
1272 } else if (ret == READ_ONLY) {
1273 usb_mtp_queue_result(s, RES_STORE_READ_ONLY, trans,
1274 0, 0, 0, 0);
1275 return;
1276 } else {
1277 usb_mtp_queue_result(s, RES_OK, trans,
1278 0, 0, 0, 0);
1279 return;
1283 static void usb_mtp_command(MTPState *s, MTPControl *c)
1285 MTPData *data_in = NULL;
1286 MTPObject *o = NULL;
1287 uint32_t nres = 0, res0 = 0;
1289 /* sanity checks */
1290 if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
1291 usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
1292 c->trans, 0, 0, 0, 0);
1293 return;
1296 /* process commands */
1297 switch (c->code) {
1298 case CMD_GET_DEVICE_INFO:
1299 data_in = usb_mtp_get_device_info(s, c);
1300 break;
1301 case CMD_OPEN_SESSION:
1302 if (s->session) {
1303 usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
1304 c->trans, 1, s->session, 0, 0);
1305 return;
1307 if (c->argv[0] == 0) {
1308 usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
1309 c->trans, 0, 0, 0, 0);
1310 return;
1312 trace_usb_mtp_op_open_session(s->dev.addr);
1313 s->session = c->argv[0];
1314 usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
1315 #ifdef CONFIG_INOTIFY1
1316 if (usb_mtp_inotify_init(s)) {
1317 fprintf(stderr, "usb-mtp: file monitoring init failed\n");
1319 #endif
1320 break;
1321 case CMD_CLOSE_SESSION:
1322 trace_usb_mtp_op_close_session(s->dev.addr);
1323 s->session = 0;
1324 s->next_handle = 0;
1325 #ifdef CONFIG_INOTIFY1
1326 usb_mtp_inotify_cleanup(s);
1327 #endif
1328 usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1329 assert(QTAILQ_EMPTY(&s->objects));
1330 break;
1331 case CMD_GET_STORAGE_IDS:
1332 data_in = usb_mtp_get_storage_ids(s, c);
1333 break;
1334 case CMD_GET_STORAGE_INFO:
1335 if (c->argv[0] != QEMU_STORAGE_ID &&
1336 c->argv[0] != 0xffffffff) {
1337 usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1338 c->trans, 0, 0, 0, 0);
1339 return;
1341 data_in = usb_mtp_get_storage_info(s, c);
1342 break;
1343 case CMD_GET_NUM_OBJECTS:
1344 case CMD_GET_OBJECT_HANDLES:
1345 if (c->argv[0] != QEMU_STORAGE_ID &&
1346 c->argv[0] != 0xffffffff) {
1347 usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1348 c->trans, 0, 0, 0, 0);
1349 return;
1351 if (c->argv[1] != 0x00000000) {
1352 usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1353 c->trans, 0, 0, 0, 0);
1354 return;
1356 if (c->argv[2] == 0x00000000 ||
1357 c->argv[2] == 0xffffffff) {
1358 o = QTAILQ_FIRST(&s->objects);
1359 } else {
1360 o = usb_mtp_object_lookup(s, c->argv[2]);
1362 if (o == NULL) {
1363 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1364 c->trans, 0, 0, 0, 0);
1365 return;
1367 if (o->format != FMT_ASSOCIATION) {
1368 usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
1369 c->trans, 0, 0, 0, 0);
1370 return;
1372 usb_mtp_object_readdir(s, o);
1373 if (c->code == CMD_GET_NUM_OBJECTS) {
1374 trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
1375 nres = 1;
1376 res0 = o->nchildren;
1377 } else {
1378 data_in = usb_mtp_get_object_handles(s, c, o);
1380 break;
1381 case CMD_GET_OBJECT_INFO:
1382 o = usb_mtp_object_lookup(s, c->argv[0]);
1383 if (o == NULL) {
1384 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1385 c->trans, 0, 0, 0, 0);
1386 return;
1388 data_in = usb_mtp_get_object_info(s, c, o);
1389 break;
1390 case CMD_GET_OBJECT:
1391 o = usb_mtp_object_lookup(s, c->argv[0]);
1392 if (o == NULL) {
1393 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1394 c->trans, 0, 0, 0, 0);
1395 return;
1397 if (o->format == FMT_ASSOCIATION) {
1398 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1399 c->trans, 0, 0, 0, 0);
1400 return;
1402 data_in = usb_mtp_get_object(s, c, o);
1403 if (data_in == NULL) {
1404 usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1405 c->trans, 0, 0, 0, 0);
1406 return;
1408 break;
1409 case CMD_DELETE_OBJECT:
1410 usb_mtp_object_delete(s, c->argv[0], c->argv[1], c->trans);
1411 return;
1412 case CMD_GET_PARTIAL_OBJECT:
1413 o = usb_mtp_object_lookup(s, c->argv[0]);
1414 if (o == NULL) {
1415 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1416 c->trans, 0, 0, 0, 0);
1417 return;
1419 if (o->format == FMT_ASSOCIATION) {
1420 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1421 c->trans, 0, 0, 0, 0);
1422 return;
1424 data_in = usb_mtp_get_partial_object(s, c, o);
1425 if (data_in == NULL) {
1426 usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1427 c->trans, 0, 0, 0, 0);
1428 return;
1430 nres = 1;
1431 res0 = data_in->length;
1432 break;
1433 case CMD_SEND_OBJECT_INFO:
1434 /* Return error if store is read-only */
1435 if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1436 usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1437 c->trans, 0, 0, 0, 0);
1438 } else if (c->argv[0] && (c->argv[0] != QEMU_STORAGE_ID)) {
1439 /* First parameter points to storage id or is 0 */
1440 usb_mtp_queue_result(s, RES_STORE_NOT_AVAILABLE, c->trans,
1441 0, 0, 0, 0);
1442 } else if (c->argv[1] && !c->argv[0]) {
1443 /* If second parameter is specified, first must also be specified */
1444 usb_mtp_queue_result(s, RES_DESTINATION_UNSUPPORTED, c->trans,
1445 0, 0, 0, 0);
1446 } else {
1447 uint32_t handle = c->argv[1];
1448 if (handle == 0xFFFFFFFF || handle == 0) {
1449 /* root object */
1450 o = QTAILQ_FIRST(&s->objects);
1451 } else {
1452 o = usb_mtp_object_lookup(s, handle);
1454 if (o == NULL) {
1455 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, c->trans,
1456 0, 0, 0, 0);
1457 } else if (o->format != FMT_ASSOCIATION) {
1458 usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT, c->trans,
1459 0, 0, 0, 0);
1462 if (o) {
1463 s->dataset.parent_handle = o->handle;
1465 s->data_out = usb_mtp_data_alloc(c);
1466 return;
1467 case CMD_SEND_OBJECT:
1468 if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1469 usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1470 c->trans, 0, 0, 0, 0);
1471 return;
1473 if (!s->write_pending) {
1474 usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO,
1475 c->trans, 0, 0, 0, 0);
1476 return;
1478 s->data_out = usb_mtp_data_alloc(c);
1479 return;
1480 case CMD_GET_OBJECT_PROPS_SUPPORTED:
1481 if (c->argv[0] != FMT_UNDEFINED_OBJECT &&
1482 c->argv[0] != FMT_ASSOCIATION) {
1483 usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1484 c->trans, 0, 0, 0, 0);
1485 return;
1487 data_in = usb_mtp_get_object_props_supported(s, c);
1488 break;
1489 case CMD_GET_OBJECT_PROP_DESC:
1490 if (c->argv[1] != FMT_UNDEFINED_OBJECT &&
1491 c->argv[1] != FMT_ASSOCIATION) {
1492 usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1493 c->trans, 0, 0, 0, 0);
1494 return;
1496 data_in = usb_mtp_get_object_prop_desc(s, c);
1497 if (data_in == NULL) {
1498 usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1499 c->trans, 0, 0, 0, 0);
1500 return;
1502 break;
1503 case CMD_GET_OBJECT_PROP_VALUE:
1504 o = usb_mtp_object_lookup(s, c->argv[0]);
1505 if (o == NULL) {
1506 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1507 c->trans, 0, 0, 0, 0);
1508 return;
1510 data_in = usb_mtp_get_object_prop_value(s, c, o);
1511 if (data_in == NULL) {
1512 usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1513 c->trans, 0, 0, 0, 0);
1514 return;
1516 break;
1517 default:
1518 trace_usb_mtp_op_unknown(s->dev.addr, c->code);
1519 usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
1520 c->trans, 0, 0, 0, 0);
1521 return;
1524 /* return results on success */
1525 if (data_in) {
1526 assert(s->data_in == NULL);
1527 s->data_in = data_in;
1529 usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0, 0);
1532 /* ----------------------------------------------------------------------- */
1534 static void usb_mtp_handle_reset(USBDevice *dev)
1536 MTPState *s = USB_MTP(dev);
1538 trace_usb_mtp_reset(s->dev.addr);
1540 #ifdef CONFIG_INOTIFY1
1541 usb_mtp_inotify_cleanup(s);
1542 #endif
1543 usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1544 s->session = 0;
1545 usb_mtp_data_free(s->data_in);
1546 s->data_in = NULL;
1547 usb_mtp_data_free(s->data_out);
1548 s->data_out = NULL;
1549 g_free(s->result);
1550 s->result = NULL;
1553 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
1554 int request, int value, int index,
1555 int length, uint8_t *data)
1557 int ret;
1558 MTPState *s = USB_MTP(dev);
1559 uint16_t *event = (uint16_t *)data;
1561 switch (request) {
1562 case ClassInterfaceOutRequest | 0x64:
1563 if (*event == EVT_CANCEL_TRANSACTION) {
1564 g_free(s->result);
1565 s->result = NULL;
1566 usb_mtp_data_free(s->data_in);
1567 s->data_in = NULL;
1568 if (s->write_pending) {
1569 g_free(s->dataset.filename);
1570 s->write_pending = false;
1572 usb_mtp_data_free(s->data_out);
1573 s->data_out = NULL;
1574 } else {
1575 p->status = USB_RET_STALL;
1577 break;
1578 default:
1579 ret = usb_desc_handle_control(dev, p, request,
1580 value, index, length, data);
1581 if (ret >= 0) {
1582 return;
1586 trace_usb_mtp_stall(dev->addr, "unknown control request");
1589 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
1591 /* we don't use async packets, so this should never be called */
1592 fprintf(stderr, "%s\n", __func__);
1595 static void utf16_to_str(uint8_t len, uint16_t *arr, char *name)
1597 int count;
1598 wchar_t *wstr = g_new0(wchar_t, len);
1600 for (count = 0; count < len; count++) {
1601 wstr[count] = (wchar_t)arr[count];
1604 wcstombs(name, wstr, len);
1605 g_free(wstr);
1608 /* Wrapper around write, returns 0 on failure */
1609 static uint64_t write_retry(int fd, void *buf, uint64_t size)
1611 uint64_t bytes_left = size, ret;
1613 while (bytes_left > 0) {
1614 ret = write(fd, buf, bytes_left);
1615 if ((ret == -1) && (errno != EINTR || errno != EAGAIN ||
1616 errno != EWOULDBLOCK)) {
1617 break;
1619 bytes_left -= ret;
1620 buf += ret;
1623 return size - bytes_left;
1626 static void usb_mtp_write_data(MTPState *s)
1628 MTPData *d = s->data_out;
1629 MTPObject *parent =
1630 usb_mtp_object_lookup(s, s->dataset.parent_handle);
1631 char *path = NULL;
1632 uint64_t rc;
1633 mode_t mask = 0644;
1635 assert(d != NULL);
1637 if (parent == NULL || !s->write_pending) {
1638 usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, d->trans,
1639 0, 0, 0, 0);
1640 return;
1643 if (s->dataset.filename) {
1644 path = g_strdup_printf("%s/%s", parent->path, s->dataset.filename);
1645 if (s->dataset.format == FMT_ASSOCIATION) {
1646 d->fd = mkdir(path, mask);
1647 goto free;
1649 if ((s->dataset.size != 0xFFFFFFFF) && (s->dataset.size < d->length)) {
1650 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1651 0, 0, 0, 0);
1652 goto done;
1654 d->fd = open(path, O_CREAT | O_WRONLY, mask);
1655 if (d->fd == -1) {
1656 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1657 0, 0, 0, 0);
1658 goto done;
1662 * Return success if initiator sent 0 sized data
1664 if (!s->dataset.size) {
1665 goto success;
1668 rc = write_retry(d->fd, d->data, s->dataset.size);
1669 if (!rc) {
1670 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1671 0, 0, 0, 0);
1672 goto done;
1674 if (rc != s->dataset.size) {
1675 usb_mtp_queue_result(s, RES_INCOMPLETE_TRANSFER, d->trans,
1676 0, 0, 0, 0);
1677 goto done;
1681 success:
1682 usb_mtp_queue_result(s, RES_OK, d->trans,
1683 0, 0, 0, 0);
1685 done:
1687 * The write dataset is kept around and freed only
1688 * on success or if another write request comes in
1690 if (d->fd != -1) {
1691 close(d->fd);
1693 free:
1694 g_free(s->dataset.filename);
1695 g_free(path);
1696 s->write_pending = false;
1699 static void usb_mtp_write_metadata(MTPState *s)
1701 MTPData *d = s->data_out;
1702 ObjectInfo *dataset = (ObjectInfo *)d->data;
1703 char *filename = g_new0(char, dataset->length);
1704 MTPObject *o;
1705 MTPObject *p = usb_mtp_object_lookup(s, s->dataset.parent_handle);
1706 uint32_t next_handle = s->next_handle;
1708 assert(!s->write_pending);
1709 assert(p != NULL);
1711 utf16_to_str(dataset->length, dataset->filename, filename);
1713 o = usb_mtp_object_lookup_name(p, filename, dataset->length);
1714 if (o != NULL) {
1715 next_handle = o->handle;
1718 s->dataset.filename = filename;
1719 s->dataset.format = dataset->format;
1720 s->dataset.size = dataset->size;
1721 s->dataset.filename = filename;
1722 s->write_pending = true;
1724 if (s->dataset.format == FMT_ASSOCIATION) {
1725 usb_mtp_write_data(s);
1726 /* next_handle will be allocated to the newly created dir */
1727 if (d->fd == -1) {
1728 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1729 0, 0, 0, 0);
1730 return;
1732 d->fd = -1;
1735 usb_mtp_queue_result(s, RES_OK, d->trans, 3, QEMU_STORAGE_ID,
1736 s->dataset.parent_handle, next_handle);
1739 static void usb_mtp_get_data(MTPState *s, mtp_container *container,
1740 USBPacket *p)
1742 MTPData *d = s->data_out;
1743 uint64_t dlen;
1744 uint32_t data_len = p->iov.size;
1745 uint64_t total_len;
1747 if (!d) {
1748 usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, 0,
1749 0, 0, 0, 0);
1750 return;
1752 if (d->first) {
1753 /* Total length of incoming data */
1754 total_len = cpu_to_le32(container->length) - sizeof(mtp_container);
1755 /* Length of data in this packet */
1756 data_len -= sizeof(mtp_container);
1757 usb_mtp_realloc(d, total_len);
1758 d->length += total_len;
1759 d->offset = 0;
1760 d->cached_length = total_len;
1761 d->first = false;
1762 d->pending = false;
1765 if (d->pending) {
1766 usb_mtp_realloc(d, d->cached_length);
1767 d->length += d->cached_length;
1768 d->pending = false;
1771 if (d->length - d->offset > data_len) {
1772 dlen = data_len;
1773 } else {
1774 dlen = d->length - d->offset;
1775 /* Check for cached data for large files */
1776 if ((s->dataset.size == 0xFFFFFFFF) && (dlen < p->iov.size)) {
1777 usb_mtp_realloc(d, p->iov.size - dlen);
1778 d->length += p->iov.size - dlen;
1779 dlen = p->iov.size;
1783 switch (d->code) {
1784 case CMD_SEND_OBJECT_INFO:
1785 usb_packet_copy(p, d->data + d->offset, dlen);
1786 d->offset += dlen;
1787 if (d->offset == d->length) {
1788 /* The operation might have already failed */
1789 if (!s->result) {
1790 usb_mtp_write_metadata(s);
1792 usb_mtp_data_free(s->data_out);
1793 s->data_out = NULL;
1794 return;
1796 break;
1797 case CMD_SEND_OBJECT:
1798 usb_packet_copy(p, d->data + d->offset, dlen);
1799 d->offset += dlen;
1800 if ((p->iov.size % 64) || !p->iov.size) {
1801 assert((s->dataset.size == 0xFFFFFFFF) ||
1802 (s->dataset.size == d->length));
1804 usb_mtp_write_data(s);
1805 usb_mtp_data_free(s->data_out);
1806 s->data_out = NULL;
1807 return;
1809 if (d->offset == d->length) {
1810 d->pending = true;
1812 break;
1813 default:
1814 p->status = USB_RET_STALL;
1815 return;
1819 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
1821 MTPState *s = USB_MTP(dev);
1822 MTPControl cmd;
1823 mtp_container container;
1824 uint32_t params[5];
1825 uint16_t container_type;
1826 int i, rc;
1828 switch (p->ep->nr) {
1829 case EP_DATA_IN:
1830 if (s->data_out != NULL) {
1831 /* guest bug */
1832 trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
1833 p->status = USB_RET_STALL;
1834 return;
1836 if (p->iov.size < sizeof(container)) {
1837 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1838 p->status = USB_RET_STALL;
1839 return;
1841 if (s->data_in != NULL) {
1842 MTPData *d = s->data_in;
1843 uint64_t dlen = d->length - d->offset;
1844 if (d->first) {
1845 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
1846 if (d->length + sizeof(container) > 0xFFFFFFFF) {
1847 container.length = cpu_to_le32(0xFFFFFFFF);
1848 } else {
1849 container.length =
1850 cpu_to_le32(d->length + sizeof(container));
1852 container.type = cpu_to_le16(TYPE_DATA);
1853 container.code = cpu_to_le16(d->code);
1854 container.trans = cpu_to_le32(d->trans);
1855 usb_packet_copy(p, &container, sizeof(container));
1856 d->first = false;
1857 if (dlen > p->iov.size - sizeof(container)) {
1858 dlen = p->iov.size - sizeof(container);
1860 } else {
1861 if (dlen > p->iov.size) {
1862 dlen = p->iov.size;
1865 if (d->fd == -1) {
1866 usb_packet_copy(p, d->data + d->offset, dlen);
1867 } else {
1868 if (d->alloc < p->iov.size) {
1869 d->alloc = p->iov.size;
1870 d->data = g_realloc(d->data, d->alloc);
1872 rc = read(d->fd, d->data, dlen);
1873 if (rc != dlen) {
1874 memset(d->data, 0, dlen);
1875 s->result->code = RES_INCOMPLETE_TRANSFER;
1877 usb_packet_copy(p, d->data, dlen);
1879 d->offset += dlen;
1880 if (d->offset == d->length) {
1881 usb_mtp_data_free(s->data_in);
1882 s->data_in = NULL;
1884 } else if (s->result != NULL) {
1885 MTPControl *r = s->result;
1886 int length = sizeof(container) + r->argc * sizeof(uint32_t);
1887 if (r->code == RES_OK) {
1888 trace_usb_mtp_success(s->dev.addr, r->trans,
1889 (r->argc > 0) ? r->argv[0] : 0,
1890 (r->argc > 1) ? r->argv[1] : 0);
1891 } else {
1892 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
1893 (r->argc > 0) ? r->argv[0] : 0,
1894 (r->argc > 1) ? r->argv[1] : 0);
1896 container.length = cpu_to_le32(length);
1897 container.type = cpu_to_le16(TYPE_RESPONSE);
1898 container.code = cpu_to_le16(r->code);
1899 container.trans = cpu_to_le32(r->trans);
1900 for (i = 0; i < r->argc; i++) {
1901 params[i] = cpu_to_le32(r->argv[i]);
1903 usb_packet_copy(p, &container, sizeof(container));
1904 usb_packet_copy(p, &params, length - sizeof(container));
1905 g_free(s->result);
1906 s->result = NULL;
1908 break;
1909 case EP_DATA_OUT:
1910 if (p->iov.size < sizeof(container)) {
1911 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1912 p->status = USB_RET_STALL;
1913 return;
1915 if ((s->data_out != NULL) && !s->data_out->first) {
1916 container_type = TYPE_DATA;
1917 } else {
1918 usb_packet_copy(p, &container, sizeof(container));
1919 container_type = le16_to_cpu(container.type);
1921 switch (container_type) {
1922 case TYPE_COMMAND:
1923 if (s->data_in || s->data_out || s->result) {
1924 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1925 p->status = USB_RET_STALL;
1926 return;
1928 cmd.code = le16_to_cpu(container.code);
1929 cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1930 / sizeof(uint32_t);
1931 cmd.trans = le32_to_cpu(container.trans);
1932 if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1933 cmd.argc = ARRAY_SIZE(cmd.argv);
1935 if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1936 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1937 p->status = USB_RET_STALL;
1938 return;
1940 usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1941 for (i = 0; i < cmd.argc; i++) {
1942 cmd.argv[i] = le32_to_cpu(params[i]);
1944 trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1945 (cmd.argc > 0) ? cmd.argv[0] : 0,
1946 (cmd.argc > 1) ? cmd.argv[1] : 0,
1947 (cmd.argc > 2) ? cmd.argv[2] : 0,
1948 (cmd.argc > 3) ? cmd.argv[3] : 0,
1949 (cmd.argc > 4) ? cmd.argv[4] : 0);
1950 usb_mtp_command(s, &cmd);
1951 break;
1952 case TYPE_DATA:
1953 /* One of the previous transfers has already errored but the
1954 * responder is still sending data associated with it
1956 if (s->result != NULL) {
1957 return;
1959 usb_mtp_get_data(s, &container, p);
1960 break;
1961 default:
1962 /* not needed as long as the mtp device is read-only */
1963 p->status = USB_RET_STALL;
1964 return;
1966 break;
1967 case EP_EVENT:
1968 #ifdef CONFIG_INOTIFY1
1969 if (!QTAILQ_EMPTY(&s->events)) {
1970 struct MTPMonEntry *e = QTAILQ_LAST(&s->events, events);
1971 uint32_t handle;
1972 int len = sizeof(container) + sizeof(uint32_t);
1974 if (p->iov.size < len) {
1975 trace_usb_mtp_stall(s->dev.addr,
1976 "packet too small to send event");
1977 p->status = USB_RET_STALL;
1978 return;
1981 QTAILQ_REMOVE(&s->events, e, next);
1982 container.length = cpu_to_le32(len);
1983 container.type = cpu_to_le32(TYPE_EVENT);
1984 container.code = cpu_to_le16(e->event);
1985 container.trans = 0; /* no trans specific events */
1986 handle = cpu_to_le32(e->handle);
1987 usb_packet_copy(p, &container, sizeof(container));
1988 usb_packet_copy(p, &handle, sizeof(uint32_t));
1989 g_free(e);
1990 return;
1992 #endif
1993 p->status = USB_RET_NAK;
1994 return;
1995 default:
1996 trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
1997 p->status = USB_RET_STALL;
1998 return;
2001 if (p->actual_length == 0) {
2002 trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
2003 p->status = USB_RET_NAK;
2004 return;
2005 } else {
2006 trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
2007 p->iov.size);
2008 return;
2012 static void usb_mtp_realize(USBDevice *dev, Error **errp)
2014 MTPState *s = USB_MTP(dev);
2016 usb_desc_create_serial(dev);
2017 usb_desc_init(dev);
2018 QTAILQ_INIT(&s->objects);
2019 if (s->desc == NULL) {
2020 if (s->root == NULL) {
2021 error_setg(errp, "usb-mtp: rootdir property must be configured");
2022 return;
2024 s->desc = strrchr(s->root, '/');
2025 if (s->desc && s->desc[0]) {
2026 s->desc = g_strdup(s->desc + 1);
2027 } else {
2028 s->desc = g_strdup("none");
2031 /* Mark store as RW */
2032 if (!s->readonly) {
2033 s->flags |= (1 << MTP_FLAG_WRITABLE);
2038 static const VMStateDescription vmstate_usb_mtp = {
2039 .name = "usb-mtp",
2040 .unmigratable = 1,
2041 .version_id = 1,
2042 .minimum_version_id = 1,
2043 .fields = (VMStateField[]) {
2044 VMSTATE_USB_DEVICE(dev, MTPState),
2045 VMSTATE_END_OF_LIST()
2049 static Property mtp_properties[] = {
2050 DEFINE_PROP_STRING("rootdir", MTPState, root),
2051 DEFINE_PROP_STRING("desc", MTPState, desc),
2052 DEFINE_PROP_BOOL("readonly", MTPState, readonly, true),
2053 DEFINE_PROP_END_OF_LIST(),
2056 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
2058 DeviceClass *dc = DEVICE_CLASS(klass);
2059 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2061 uc->realize = usb_mtp_realize;
2062 uc->product_desc = "QEMU USB MTP";
2063 uc->usb_desc = &desc;
2064 uc->cancel_packet = usb_mtp_cancel_packet;
2065 uc->handle_attach = usb_desc_attach;
2066 uc->handle_reset = usb_mtp_handle_reset;
2067 uc->handle_control = usb_mtp_handle_control;
2068 uc->handle_data = usb_mtp_handle_data;
2069 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2070 dc->desc = "USB Media Transfer Protocol device";
2071 dc->fw_name = "mtp";
2072 dc->vmsd = &vmstate_usb_mtp;
2073 dc->props = mtp_properties;
2076 static TypeInfo mtp_info = {
2077 .name = TYPE_USB_MTP,
2078 .parent = TYPE_USB_DEVICE,
2079 .instance_size = sizeof(MTPState),
2080 .class_init = usb_mtp_class_initfn,
2083 static void usb_mtp_register_types(void)
2085 type_register_static(&mtp_info);
2088 type_init(usb_mtp_register_types)