migration: use bitmap_mutex in migration_bitmap_clear_dirty
[qemu.git] / hw / usb / dev-mtp.c
blob4ee4fc5a893a219a5279c3463be48af00e3be05b
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 "qemu/error-report.h"
15 #include <wchar.h>
16 #include <dirent.h>
18 #include <sys/statvfs.h>
21 #include "qemu-common.h"
22 #include "qemu/iov.h"
23 #include "qemu/filemonitor.h"
24 #include "trace.h"
25 #include "hw/usb.h"
26 #include "desc.h"
27 #include "qemu/units.h"
29 /* ----------------------------------------------------------------------- */
31 enum mtp_container_type {
32 TYPE_COMMAND = 1,
33 TYPE_DATA = 2,
34 TYPE_RESPONSE = 3,
35 TYPE_EVENT = 4,
38 /* MTP write stage, for internal use only */
39 enum mtp_write_status {
40 WRITE_START = 1,
41 WRITE_CONTINUE = 2,
42 WRITE_END = 3,
45 enum mtp_code {
46 /* command codes */
47 CMD_GET_DEVICE_INFO = 0x1001,
48 CMD_OPEN_SESSION = 0x1002,
49 CMD_CLOSE_SESSION = 0x1003,
50 CMD_GET_STORAGE_IDS = 0x1004,
51 CMD_GET_STORAGE_INFO = 0x1005,
52 CMD_GET_NUM_OBJECTS = 0x1006,
53 CMD_GET_OBJECT_HANDLES = 0x1007,
54 CMD_GET_OBJECT_INFO = 0x1008,
55 CMD_GET_OBJECT = 0x1009,
56 CMD_DELETE_OBJECT = 0x100b,
57 CMD_SEND_OBJECT_INFO = 0x100c,
58 CMD_SEND_OBJECT = 0x100d,
59 CMD_GET_PARTIAL_OBJECT = 0x101b,
60 CMD_GET_OBJECT_PROPS_SUPPORTED = 0x9801,
61 CMD_GET_OBJECT_PROP_DESC = 0x9802,
62 CMD_GET_OBJECT_PROP_VALUE = 0x9803,
64 /* response codes */
65 RES_OK = 0x2001,
66 RES_GENERAL_ERROR = 0x2002,
67 RES_SESSION_NOT_OPEN = 0x2003,
68 RES_INVALID_TRANSACTION_ID = 0x2004,
69 RES_OPERATION_NOT_SUPPORTED = 0x2005,
70 RES_PARAMETER_NOT_SUPPORTED = 0x2006,
71 RES_INCOMPLETE_TRANSFER = 0x2007,
72 RES_INVALID_STORAGE_ID = 0x2008,
73 RES_INVALID_OBJECT_HANDLE = 0x2009,
74 RES_INVALID_OBJECT_FORMAT_CODE = 0x200b,
75 RES_STORE_FULL = 0x200c,
76 RES_STORE_READ_ONLY = 0x200e,
77 RES_PARTIAL_DELETE = 0x2012,
78 RES_STORE_NOT_AVAILABLE = 0x2013,
79 RES_SPEC_BY_FORMAT_UNSUPPORTED = 0x2014,
80 RES_INVALID_OBJECTINFO = 0x2015,
81 RES_DESTINATION_UNSUPPORTED = 0x2020,
82 RES_INVALID_PARENT_OBJECT = 0x201a,
83 RES_INVALID_PARAMETER = 0x201d,
84 RES_SESSION_ALREADY_OPEN = 0x201e,
85 RES_INVALID_OBJECT_PROP_CODE = 0xA801,
87 /* format codes */
88 FMT_UNDEFINED_OBJECT = 0x3000,
89 FMT_ASSOCIATION = 0x3001,
91 /* event codes */
92 EVT_CANCEL_TRANSACTION = 0x4001,
93 EVT_OBJ_ADDED = 0x4002,
94 EVT_OBJ_REMOVED = 0x4003,
95 EVT_OBJ_INFO_CHANGED = 0x4007,
97 /* object properties */
98 PROP_STORAGE_ID = 0xDC01,
99 PROP_OBJECT_FORMAT = 0xDC02,
100 PROP_OBJECT_COMPRESSED_SIZE = 0xDC04,
101 PROP_PARENT_OBJECT = 0xDC0B,
102 PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER = 0xDC41,
103 PROP_NAME = 0xDC44,
106 enum mtp_data_type {
107 DATA_TYPE_UINT16 = 0x0004,
108 DATA_TYPE_UINT32 = 0x0006,
109 DATA_TYPE_UINT64 = 0x0008,
110 DATA_TYPE_UINT128 = 0x000a,
111 DATA_TYPE_STRING = 0xffff,
114 typedef struct {
115 uint32_t length;
116 uint16_t type;
117 uint16_t code;
118 uint32_t trans;
119 } QEMU_PACKED mtp_container;
121 /* ----------------------------------------------------------------------- */
123 typedef struct MTPState MTPState;
124 typedef struct MTPControl MTPControl;
125 typedef struct MTPData MTPData;
126 typedef struct MTPObject MTPObject;
128 enum {
129 EP_DATA_IN = 1,
130 EP_DATA_OUT,
131 EP_EVENT,
134 typedef struct MTPMonEntry MTPMonEntry;
136 struct MTPMonEntry {
137 uint32_t event;
138 uint32_t handle;
140 QTAILQ_ENTRY(MTPMonEntry) next;
143 struct MTPControl {
144 uint16_t code;
145 uint32_t trans;
146 int argc;
147 uint32_t argv[5];
150 struct MTPData {
151 uint16_t code;
152 uint32_t trans;
153 uint64_t offset;
154 uint64_t length;
155 uint64_t alloc;
156 uint8_t *data;
157 bool first;
158 /* Used for >4G file sizes */
159 bool pending;
160 int fd;
161 uint8_t write_status;
162 /* Internal pointer per every MTP_WRITE_BUF_SZ */
163 uint64_t data_offset;
166 struct MTPObject {
167 uint32_t handle;
168 uint16_t format;
169 char *name;
170 char *path;
171 struct stat stat;
172 /* file monitor watch id */
173 int watchid;
174 MTPObject *parent;
175 uint32_t nchildren;
176 QLIST_HEAD(, MTPObject) children;
177 QLIST_ENTRY(MTPObject) list;
178 bool have_children;
179 QTAILQ_ENTRY(MTPObject) next;
182 struct MTPState {
183 USBDevice dev;
184 char *root;
185 char *desc;
186 uint32_t flags;
188 MTPData *data_in;
189 MTPData *data_out;
190 MTPControl *result;
191 uint32_t session;
192 uint32_t next_handle;
193 bool readonly;
195 QTAILQ_HEAD(, MTPObject) objects;
196 QFileMonitor *file_monitor;
197 QTAILQ_HEAD(, MTPMonEntry) events;
198 /* Responder is expecting a write operation */
199 bool write_pending;
200 struct {
201 uint32_t parent_handle;
202 uint16_t format;
203 uint32_t size;
204 char *filename;
205 } dataset;
209 * ObjectInfo dataset received from initiator
210 * Fields we don't care about are ignored
212 typedef struct {
213 uint32_t storage_id; /*unused*/
214 uint16_t format;
215 uint16_t protection_status; /*unused*/
216 uint32_t size;
217 uint16_t thumb_format; /*unused*/
218 uint32_t thumb_comp_sz; /*unused*/
219 uint32_t thumb_pix_width; /*unused*/
220 uint32_t thumb_pix_height; /*unused*/
221 uint32_t image_pix_width; /*unused*/
222 uint32_t image_pix_height; /*unused*/
223 uint32_t image_bit_depth; /*unused*/
224 uint32_t parent; /*unused*/
225 uint16_t assoc_type;
226 uint32_t assoc_desc;
227 uint32_t seq_no; /*unused*/
228 uint8_t length; /*part of filename field*/
229 uint16_t filename[0];
230 char date_created[0]; /*unused*/
231 char date_modified[0]; /*unused*/
232 char keywords[0]; /*unused*/
233 /* string and other data follows */
234 } QEMU_PACKED ObjectInfo;
236 #define TYPE_USB_MTP "usb-mtp"
237 #define USB_MTP(obj) OBJECT_CHECK(MTPState, (obj), TYPE_USB_MTP)
239 #define QEMU_STORAGE_ID 0x00010001
241 #define MTP_FLAG_WRITABLE 0
243 #define FLAG_SET(_mtp, _flag) ((_mtp)->flags & (1 << (_flag)))
245 /* ----------------------------------------------------------------------- */
247 #define MTP_MANUFACTURER "QEMU"
248 #define MTP_PRODUCT "QEMU filesharing"
249 #define MTP_WRITE_BUF_SZ (512 * KiB)
251 enum {
252 STR_MANUFACTURER = 1,
253 STR_PRODUCT,
254 STR_SERIALNUMBER,
255 STR_MTP,
256 STR_CONFIG_FULL,
257 STR_CONFIG_HIGH,
258 STR_CONFIG_SUPER,
261 static const USBDescStrings desc_strings = {
262 [STR_MANUFACTURER] = MTP_MANUFACTURER,
263 [STR_PRODUCT] = MTP_PRODUCT,
264 [STR_SERIALNUMBER] = "34617",
265 [STR_MTP] = "MTP",
266 [STR_CONFIG_FULL] = "Full speed config (usb 1.1)",
267 [STR_CONFIG_HIGH] = "High speed config (usb 2.0)",
268 [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
271 static const USBDescIface desc_iface_full = {
272 .bInterfaceNumber = 0,
273 .bNumEndpoints = 3,
274 .bInterfaceClass = USB_CLASS_STILL_IMAGE,
275 .bInterfaceSubClass = 0x01,
276 .bInterfaceProtocol = 0x01,
277 .iInterface = STR_MTP,
278 .eps = (USBDescEndpoint[]) {
280 .bEndpointAddress = USB_DIR_IN | EP_DATA_IN,
281 .bmAttributes = USB_ENDPOINT_XFER_BULK,
282 .wMaxPacketSize = 64,
284 .bEndpointAddress = USB_DIR_OUT | EP_DATA_OUT,
285 .bmAttributes = USB_ENDPOINT_XFER_BULK,
286 .wMaxPacketSize = 64,
288 .bEndpointAddress = USB_DIR_IN | EP_EVENT,
289 .bmAttributes = USB_ENDPOINT_XFER_INT,
290 .wMaxPacketSize = 64,
291 .bInterval = 0x0a,
296 static const USBDescDevice desc_device_full = {
297 .bcdUSB = 0x0200,
298 .bMaxPacketSize0 = 8,
299 .bNumConfigurations = 1,
300 .confs = (USBDescConfig[]) {
302 .bNumInterfaces = 1,
303 .bConfigurationValue = 1,
304 .iConfiguration = STR_CONFIG_FULL,
305 .bmAttributes = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
306 .bMaxPower = 2,
307 .nif = 1,
308 .ifs = &desc_iface_full,
313 static const USBDescIface desc_iface_high = {
314 .bInterfaceNumber = 0,
315 .bNumEndpoints = 3,
316 .bInterfaceClass = USB_CLASS_STILL_IMAGE,
317 .bInterfaceSubClass = 0x01,
318 .bInterfaceProtocol = 0x01,
319 .iInterface = STR_MTP,
320 .eps = (USBDescEndpoint[]) {
322 .bEndpointAddress = USB_DIR_IN | EP_DATA_IN,
323 .bmAttributes = USB_ENDPOINT_XFER_BULK,
324 .wMaxPacketSize = 512,
326 .bEndpointAddress = USB_DIR_OUT | EP_DATA_OUT,
327 .bmAttributes = USB_ENDPOINT_XFER_BULK,
328 .wMaxPacketSize = 512,
330 .bEndpointAddress = USB_DIR_IN | EP_EVENT,
331 .bmAttributes = USB_ENDPOINT_XFER_INT,
332 .wMaxPacketSize = 64,
333 .bInterval = 0x0a,
338 static const USBDescDevice desc_device_high = {
339 .bcdUSB = 0x0200,
340 .bMaxPacketSize0 = 64,
341 .bNumConfigurations = 1,
342 .confs = (USBDescConfig[]) {
344 .bNumInterfaces = 1,
345 .bConfigurationValue = 1,
346 .iConfiguration = STR_CONFIG_HIGH,
347 .bmAttributes = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
348 .bMaxPower = 2,
349 .nif = 1,
350 .ifs = &desc_iface_high,
355 static const USBDescMSOS desc_msos = {
356 .CompatibleID = "MTP",
357 .SelectiveSuspendEnabled = true,
360 static const USBDesc desc = {
361 .id = {
362 .idVendor = 0x46f4, /* CRC16() of "QEMU" */
363 .idProduct = 0x0004,
364 .bcdDevice = 0,
365 .iManufacturer = STR_MANUFACTURER,
366 .iProduct = STR_PRODUCT,
367 .iSerialNumber = STR_SERIALNUMBER,
369 .full = &desc_device_full,
370 .high = &desc_device_high,
371 .str = desc_strings,
372 .msos = &desc_msos,
375 /* ----------------------------------------------------------------------- */
377 static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle,
378 MTPObject *parent, const char *name)
380 MTPObject *o = g_new0(MTPObject, 1);
382 if (name[0] == '.') {
383 goto ignore;
386 o->watchid = -1;
387 o->handle = handle;
388 o->parent = parent;
389 o->name = g_strdup(name);
390 if (parent == NULL) {
391 o->path = g_strdup(name);
392 } else {
393 o->path = g_strdup_printf("%s/%s", parent->path, name);
396 if (lstat(o->path, &o->stat) != 0) {
397 goto ignore;
399 if (S_ISREG(o->stat.st_mode)) {
400 o->format = FMT_UNDEFINED_OBJECT;
401 } else if (S_ISDIR(o->stat.st_mode)) {
402 o->format = FMT_ASSOCIATION;
403 } else {
404 goto ignore;
407 if (access(o->path, R_OK) != 0) {
408 goto ignore;
411 trace_usb_mtp_object_alloc(s->dev.addr, o->handle, o->path);
413 QTAILQ_INSERT_TAIL(&s->objects, o, next);
414 return o;
416 ignore:
417 g_free(o->name);
418 g_free(o->path);
419 g_free(o);
420 return NULL;
423 static void usb_mtp_object_free(MTPState *s, MTPObject *o)
425 MTPObject *iter;
427 if (!o) {
428 return;
431 trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path);
433 if (o->watchid != -1 && s->file_monitor) {
434 qemu_file_monitor_remove_watch(s->file_monitor, o->path, o->watchid);
437 QTAILQ_REMOVE(&s->objects, o, next);
438 if (o->parent) {
439 QLIST_REMOVE(o, list);
440 o->parent->nchildren--;
443 while (!QLIST_EMPTY(&o->children)) {
444 iter = QLIST_FIRST(&o->children);
445 usb_mtp_object_free(s, iter);
447 g_free(o->name);
448 g_free(o->path);
449 g_free(o);
452 static MTPObject *usb_mtp_object_lookup(MTPState *s, uint32_t handle)
454 MTPObject *o;
456 QTAILQ_FOREACH(o, &s->objects, next) {
457 if (o->handle == handle) {
458 return o;
461 return NULL;
464 static MTPObject *usb_mtp_add_child(MTPState *s, MTPObject *o,
465 const char *name)
467 MTPObject *child =
468 usb_mtp_object_alloc(s, s->next_handle++, o, name);
470 if (child) {
471 trace_usb_mtp_add_child(s->dev.addr, child->handle, child->path);
472 QLIST_INSERT_HEAD(&o->children, child, list);
473 o->nchildren++;
475 if (child->format == FMT_ASSOCIATION) {
476 QLIST_INIT(&child->children);
480 return child;
483 static MTPObject *usb_mtp_object_lookup_name(MTPObject *parent,
484 const char *name, int len)
486 MTPObject *iter;
488 if (len == -1) {
489 len = strlen(name);
492 QLIST_FOREACH(iter, &parent->children, list) {
493 if (strncmp(iter->name, name, len) == 0) {
494 return iter;
498 return NULL;
501 static MTPObject *usb_mtp_object_lookup_id(MTPState *s, int id)
503 MTPObject *iter;
505 QTAILQ_FOREACH(iter, &s->objects, next) {
506 if (iter->watchid == id) {
507 return iter;
511 return NULL;
514 static void file_monitor_event(int id,
515 QFileMonitorEvent ev,
516 const char *name,
517 void *opaque)
519 MTPState *s = opaque;
520 MTPObject *parent = usb_mtp_object_lookup_id(s, id);
521 MTPMonEntry *entry = NULL;
522 MTPObject *o;
524 if (!parent) {
525 return;
528 switch (ev) {
529 case QFILE_MONITOR_EVENT_CREATED:
530 if (usb_mtp_object_lookup_name(parent, name, -1)) {
531 /* Duplicate create event */
532 return;
534 entry = g_new0(MTPMonEntry, 1);
535 entry->handle = s->next_handle;
536 entry->event = EVT_OBJ_ADDED;
537 o = usb_mtp_add_child(s, parent, name);
538 if (!o) {
539 g_free(entry);
540 return;
542 trace_usb_mtp_file_monitor_event(s->dev.addr, name, "Obj Added");
543 break;
545 case QFILE_MONITOR_EVENT_DELETED:
547 * The kernel issues a IN_IGNORED event
548 * when a dir containing a watchpoint is
549 * deleted, so we don't have to delete the
550 * watchpoint
552 o = usb_mtp_object_lookup_name(parent, name, -1);
553 if (!o) {
554 return;
556 entry = g_new0(MTPMonEntry, 1);
557 entry->handle = o->handle;
558 entry->event = EVT_OBJ_REMOVED;
559 trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, "Obj Deleted");
560 usb_mtp_object_free(s, o);
561 break;
563 case QFILE_MONITOR_EVENT_MODIFIED:
564 o = usb_mtp_object_lookup_name(parent, name, -1);
565 if (!o) {
566 return;
568 entry = g_new0(MTPMonEntry, 1);
569 entry->handle = o->handle;
570 entry->event = EVT_OBJ_INFO_CHANGED;
571 trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, "Obj Modified");
572 break;
574 case QFILE_MONITOR_EVENT_IGNORED:
575 trace_usb_mtp_file_monitor_event(s->dev.addr, parent->path,
576 "Obj parent dir ignored");
577 break;
579 case QFILE_MONITOR_EVENT_ATTRIBUTES:
580 break;
582 default:
583 g_assert_not_reached();
586 if (entry) {
587 QTAILQ_INSERT_HEAD(&s->events, entry, next);
591 static void usb_mtp_file_monitor_cleanup(MTPState *s)
593 MTPMonEntry *e, *p;
595 QTAILQ_FOREACH_SAFE(e, &s->events, next, p) {
596 QTAILQ_REMOVE(&s->events, e, next);
597 g_free(e);
600 qemu_file_monitor_free(s->file_monitor);
601 s->file_monitor = NULL;
605 static void usb_mtp_object_readdir(MTPState *s, MTPObject *o)
607 struct dirent *entry;
608 DIR *dir;
609 int fd;
610 Error *err = NULL;
612 if (o->have_children) {
613 return;
615 o->have_children = true;
617 fd = open(o->path, O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
618 if (fd < 0) {
619 return;
621 dir = fdopendir(fd);
622 if (!dir) {
623 close(fd);
624 return;
627 if (s->file_monitor) {
628 int id = qemu_file_monitor_add_watch(s->file_monitor, o->path, NULL,
629 file_monitor_event, s, &err);
630 if (id == -1) {
631 error_report("usb-mtp: failed to add watch for %s: %s", o->path,
632 error_get_pretty(err));
633 error_free(err);
634 } else {
635 trace_usb_mtp_file_monitor_event(s->dev.addr, o->path,
636 "Watch Added");
637 o->watchid = id;
641 while ((entry = readdir(dir)) != NULL) {
642 usb_mtp_add_child(s, o, entry->d_name);
644 closedir(dir);
647 /* ----------------------------------------------------------------------- */
649 static MTPData *usb_mtp_data_alloc(MTPControl *c)
651 MTPData *data = g_new0(MTPData, 1);
653 data->code = c->code;
654 data->trans = c->trans;
655 data->fd = -1;
656 data->first = true;
657 return data;
660 static void usb_mtp_data_free(MTPData *data)
662 if (data == NULL) {
663 return;
665 if (data->fd != -1) {
666 close(data->fd);
668 g_free(data->data);
669 g_free(data);
672 static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
674 if (data->length + bytes <= data->alloc) {
675 return;
677 data->alloc = (data->length + bytes + 0xff) & ~0xff;
678 data->data = g_realloc(data->data, data->alloc);
681 static void usb_mtp_add_u8(MTPData *data, uint8_t val)
683 usb_mtp_realloc(data, 1);
684 data->data[data->length++] = val;
687 static void usb_mtp_add_u16(MTPData *data, uint16_t val)
689 usb_mtp_realloc(data, 2);
690 data->data[data->length++] = (val >> 0) & 0xff;
691 data->data[data->length++] = (val >> 8) & 0xff;
694 static void usb_mtp_add_u32(MTPData *data, uint32_t val)
696 usb_mtp_realloc(data, 4);
697 data->data[data->length++] = (val >> 0) & 0xff;
698 data->data[data->length++] = (val >> 8) & 0xff;
699 data->data[data->length++] = (val >> 16) & 0xff;
700 data->data[data->length++] = (val >> 24) & 0xff;
703 static void usb_mtp_add_u64(MTPData *data, uint64_t val)
705 usb_mtp_realloc(data, 8);
706 data->data[data->length++] = (val >> 0) & 0xff;
707 data->data[data->length++] = (val >> 8) & 0xff;
708 data->data[data->length++] = (val >> 16) & 0xff;
709 data->data[data->length++] = (val >> 24) & 0xff;
710 data->data[data->length++] = (val >> 32) & 0xff;
711 data->data[data->length++] = (val >> 40) & 0xff;
712 data->data[data->length++] = (val >> 48) & 0xff;
713 data->data[data->length++] = (val >> 56) & 0xff;
716 static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
717 const uint16_t *vals)
719 int i;
721 usb_mtp_add_u32(data, len);
722 for (i = 0; i < len; i++) {
723 usb_mtp_add_u16(data, vals[i]);
727 static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
728 const uint32_t *vals)
730 int i;
732 usb_mtp_add_u32(data, len);
733 for (i = 0; i < len; i++) {
734 usb_mtp_add_u32(data, vals[i]);
738 static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
740 uint32_t len = wcslen(str);
741 int i;
743 if (len > 0) {
744 len++; /* include terminating L'\0' */
747 usb_mtp_add_u8(data, len);
748 for (i = 0; i < len; i++) {
749 usb_mtp_add_u16(data, str[i]);
753 static void usb_mtp_add_str(MTPData *data, const char *str)
755 uint32_t len = strlen(str)+1;
756 wchar_t *wstr = g_new(wchar_t, len);
757 size_t ret;
759 ret = mbstowcs(wstr, str, len);
760 if (ret == -1) {
761 usb_mtp_add_wstr(data, L"Oops");
762 } else {
763 usb_mtp_add_wstr(data, wstr);
766 g_free(wstr);
769 static void usb_mtp_add_time(MTPData *data, time_t time)
771 char buf[16];
772 struct tm tm;
774 gmtime_r(&time, &tm);
775 strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", &tm);
776 usb_mtp_add_str(data, buf);
779 /* ----------------------------------------------------------------------- */
781 static void usb_mtp_queue_result(MTPState *s, uint16_t code, uint32_t trans,
782 int argc, uint32_t arg0, uint32_t arg1,
783 uint32_t arg2)
785 MTPControl *c = g_new0(MTPControl, 1);
787 c->code = code;
788 c->trans = trans;
789 c->argc = argc;
790 if (argc > 0) {
791 c->argv[0] = arg0;
793 if (argc > 1) {
794 c->argv[1] = arg1;
796 if (argc > 2) {
797 c->argv[2] = arg2;
800 assert(s->result == NULL);
801 s->result = c;
804 /* ----------------------------------------------------------------------- */
806 static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
808 static const uint16_t ops[] = {
809 CMD_GET_DEVICE_INFO,
810 CMD_OPEN_SESSION,
811 CMD_CLOSE_SESSION,
812 CMD_GET_STORAGE_IDS,
813 CMD_GET_STORAGE_INFO,
814 CMD_GET_NUM_OBJECTS,
815 CMD_GET_OBJECT_HANDLES,
816 CMD_GET_OBJECT_INFO,
817 CMD_DELETE_OBJECT,
818 CMD_SEND_OBJECT_INFO,
819 CMD_SEND_OBJECT,
820 CMD_GET_OBJECT,
821 CMD_GET_PARTIAL_OBJECT,
822 CMD_GET_OBJECT_PROPS_SUPPORTED,
823 CMD_GET_OBJECT_PROP_DESC,
824 CMD_GET_OBJECT_PROP_VALUE,
826 static const uint16_t fmt[] = {
827 FMT_UNDEFINED_OBJECT,
828 FMT_ASSOCIATION,
830 MTPData *d = usb_mtp_data_alloc(c);
832 trace_usb_mtp_op_get_device_info(s->dev.addr);
834 usb_mtp_add_u16(d, 100);
835 usb_mtp_add_u32(d, 0x00000006);
836 usb_mtp_add_u16(d, 0x0064);
837 usb_mtp_add_wstr(d, L"");
838 usb_mtp_add_u16(d, 0x0000);
840 usb_mtp_add_u16_array(d, ARRAY_SIZE(ops), ops);
841 usb_mtp_add_u16_array(d, 0, NULL);
842 usb_mtp_add_u16_array(d, 0, NULL);
843 usb_mtp_add_u16_array(d, 0, NULL);
844 usb_mtp_add_u16_array(d, ARRAY_SIZE(fmt), fmt);
846 usb_mtp_add_wstr(d, L"" MTP_MANUFACTURER);
847 usb_mtp_add_wstr(d, L"" MTP_PRODUCT);
848 usb_mtp_add_wstr(d, L"0.1");
849 usb_mtp_add_wstr(d, L"0123456789abcdef0123456789abcdef");
851 return d;
854 static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
856 static const uint32_t ids[] = {
857 QEMU_STORAGE_ID,
859 MTPData *d = usb_mtp_data_alloc(c);
861 trace_usb_mtp_op_get_storage_ids(s->dev.addr);
863 usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
865 return d;
868 static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
870 MTPData *d = usb_mtp_data_alloc(c);
871 struct statvfs buf;
872 int rc;
874 trace_usb_mtp_op_get_storage_info(s->dev.addr);
876 if (FLAG_SET(s, MTP_FLAG_WRITABLE)) {
877 usb_mtp_add_u16(d, 0x0003);
878 usb_mtp_add_u16(d, 0x0002);
879 usb_mtp_add_u16(d, 0x0000);
880 } else {
881 usb_mtp_add_u16(d, 0x0001);
882 usb_mtp_add_u16(d, 0x0002);
883 usb_mtp_add_u16(d, 0x0001);
886 rc = statvfs(s->root, &buf);
887 if (rc == 0) {
888 usb_mtp_add_u64(d, (uint64_t)buf.f_frsize * buf.f_blocks);
889 usb_mtp_add_u64(d, (uint64_t)buf.f_bavail * buf.f_blocks);
890 usb_mtp_add_u32(d, buf.f_ffree);
891 } else {
892 usb_mtp_add_u64(d, 0xffffffff);
893 usb_mtp_add_u64(d, 0xffffffff);
894 usb_mtp_add_u32(d, 0xffffffff);
897 usb_mtp_add_str(d, s->desc);
898 usb_mtp_add_wstr(d, L"123456789abcdef");
899 return d;
902 static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
903 MTPObject *o)
905 MTPData *d = usb_mtp_data_alloc(c);
906 uint32_t i = 0, handles[o->nchildren];
907 MTPObject *iter;
909 trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
911 QLIST_FOREACH(iter, &o->children, list) {
912 handles[i++] = iter->handle;
914 assert(i == o->nchildren);
915 usb_mtp_add_u32_array(d, o->nchildren, handles);
917 return d;
920 static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
921 MTPObject *o)
923 MTPData *d = usb_mtp_data_alloc(c);
925 trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
927 usb_mtp_add_u32(d, QEMU_STORAGE_ID);
928 usb_mtp_add_u16(d, o->format);
929 usb_mtp_add_u16(d, 0);
931 if (o->stat.st_size > 0xFFFFFFFF) {
932 usb_mtp_add_u32(d, 0xFFFFFFFF);
933 } else {
934 usb_mtp_add_u32(d, o->stat.st_size);
937 usb_mtp_add_u16(d, 0);
938 usb_mtp_add_u32(d, 0);
939 usb_mtp_add_u32(d, 0);
940 usb_mtp_add_u32(d, 0);
941 usb_mtp_add_u32(d, 0);
942 usb_mtp_add_u32(d, 0);
943 usb_mtp_add_u32(d, 0);
945 if (o->parent) {
946 usb_mtp_add_u32(d, o->parent->handle);
947 } else {
948 usb_mtp_add_u32(d, 0);
950 if (o->format == FMT_ASSOCIATION) {
951 usb_mtp_add_u16(d, 0x0001);
952 usb_mtp_add_u32(d, 0x00000001);
953 usb_mtp_add_u32(d, 0);
954 } else {
955 usb_mtp_add_u16(d, 0);
956 usb_mtp_add_u32(d, 0);
957 usb_mtp_add_u32(d, 0);
960 usb_mtp_add_str(d, o->name);
961 usb_mtp_add_time(d, o->stat.st_ctime);
962 usb_mtp_add_time(d, o->stat.st_mtime);
963 usb_mtp_add_wstr(d, L"");
965 return d;
968 static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
969 MTPObject *o)
971 MTPData *d = usb_mtp_data_alloc(c);
973 trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
975 d->fd = open(o->path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
976 if (d->fd == -1) {
977 usb_mtp_data_free(d);
978 return NULL;
980 d->length = o->stat.st_size;
981 d->alloc = 512;
982 d->data = g_malloc(d->alloc);
983 return d;
986 static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
987 MTPObject *o)
989 MTPData *d;
990 off_t offset;
992 if (c->argc <= 2) {
993 return NULL;
995 trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
996 c->argv[1], c->argv[2]);
998 d = usb_mtp_data_alloc(c);
999 d->fd = open(o->path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
1000 if (d->fd == -1) {
1001 usb_mtp_data_free(d);
1002 return NULL;
1005 offset = c->argv[1];
1006 if (offset > o->stat.st_size) {
1007 offset = o->stat.st_size;
1009 if (lseek(d->fd, offset, SEEK_SET) < 0) {
1010 usb_mtp_data_free(d);
1011 return NULL;
1014 d->length = c->argv[2];
1015 if (d->length > o->stat.st_size - offset) {
1016 d->length = o->stat.st_size - offset;
1019 return d;
1022 static MTPData *usb_mtp_get_object_props_supported(MTPState *s, MTPControl *c)
1024 static const uint16_t props[] = {
1025 PROP_STORAGE_ID,
1026 PROP_OBJECT_FORMAT,
1027 PROP_OBJECT_COMPRESSED_SIZE,
1028 PROP_PARENT_OBJECT,
1029 PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER,
1030 PROP_NAME,
1032 MTPData *d = usb_mtp_data_alloc(c);
1033 usb_mtp_add_u16_array(d, ARRAY_SIZE(props), props);
1035 return d;
1038 static MTPData *usb_mtp_get_object_prop_desc(MTPState *s, MTPControl *c)
1040 MTPData *d = usb_mtp_data_alloc(c);
1041 switch (c->argv[0]) {
1042 case PROP_STORAGE_ID:
1043 usb_mtp_add_u16(d, PROP_STORAGE_ID);
1044 usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1045 usb_mtp_add_u8(d, 0x00);
1046 usb_mtp_add_u32(d, 0x00000000);
1047 usb_mtp_add_u32(d, 0x00000000);
1048 usb_mtp_add_u8(d, 0x00);
1049 break;
1050 case PROP_OBJECT_FORMAT:
1051 usb_mtp_add_u16(d, PROP_OBJECT_FORMAT);
1052 usb_mtp_add_u16(d, DATA_TYPE_UINT16);
1053 usb_mtp_add_u8(d, 0x00);
1054 usb_mtp_add_u16(d, 0x0000);
1055 usb_mtp_add_u32(d, 0x00000000);
1056 usb_mtp_add_u8(d, 0x00);
1057 break;
1058 case PROP_OBJECT_COMPRESSED_SIZE:
1059 usb_mtp_add_u16(d, PROP_OBJECT_COMPRESSED_SIZE);
1060 usb_mtp_add_u16(d, DATA_TYPE_UINT64);
1061 usb_mtp_add_u8(d, 0x00);
1062 usb_mtp_add_u64(d, 0x0000000000000000);
1063 usb_mtp_add_u32(d, 0x00000000);
1064 usb_mtp_add_u8(d, 0x00);
1065 break;
1066 case PROP_PARENT_OBJECT:
1067 usb_mtp_add_u16(d, PROP_PARENT_OBJECT);
1068 usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1069 usb_mtp_add_u8(d, 0x00);
1070 usb_mtp_add_u32(d, 0x00000000);
1071 usb_mtp_add_u32(d, 0x00000000);
1072 usb_mtp_add_u8(d, 0x00);
1073 break;
1074 case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1075 usb_mtp_add_u16(d, PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER);
1076 usb_mtp_add_u16(d, DATA_TYPE_UINT128);
1077 usb_mtp_add_u8(d, 0x00);
1078 usb_mtp_add_u64(d, 0x0000000000000000);
1079 usb_mtp_add_u64(d, 0x0000000000000000);
1080 usb_mtp_add_u32(d, 0x00000000);
1081 usb_mtp_add_u8(d, 0x00);
1082 break;
1083 case PROP_NAME:
1084 usb_mtp_add_u16(d, PROP_NAME);
1085 usb_mtp_add_u16(d, DATA_TYPE_STRING);
1086 usb_mtp_add_u8(d, 0x00);
1087 usb_mtp_add_u8(d, 0x00);
1088 usb_mtp_add_u32(d, 0x00000000);
1089 usb_mtp_add_u8(d, 0x00);
1090 break;
1091 default:
1092 usb_mtp_data_free(d);
1093 return NULL;
1096 return d;
1099 static MTPData *usb_mtp_get_object_prop_value(MTPState *s, MTPControl *c,
1100 MTPObject *o)
1102 MTPData *d = usb_mtp_data_alloc(c);
1103 switch (c->argv[1]) {
1104 case PROP_STORAGE_ID:
1105 usb_mtp_add_u32(d, QEMU_STORAGE_ID);
1106 break;
1107 case PROP_OBJECT_FORMAT:
1108 usb_mtp_add_u16(d, o->format);
1109 break;
1110 case PROP_OBJECT_COMPRESSED_SIZE:
1111 usb_mtp_add_u64(d, o->stat.st_size);
1112 break;
1113 case PROP_PARENT_OBJECT:
1114 if (o->parent == NULL) {
1115 usb_mtp_add_u32(d, 0x00000000);
1116 } else {
1117 usb_mtp_add_u32(d, o->parent->handle);
1119 break;
1120 case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1121 /* Should be persistent between sessions,
1122 * but using our objedt ID is "good enough"
1123 * for now */
1124 usb_mtp_add_u64(d, 0x0000000000000000);
1125 usb_mtp_add_u64(d, o->handle);
1126 break;
1127 case PROP_NAME:
1128 usb_mtp_add_str(d, o->name);
1129 break;
1130 default:
1131 usb_mtp_data_free(d);
1132 return NULL;
1135 return d;
1138 /* Return correct return code for a delete event */
1139 enum {
1140 ALL_DELETE,
1141 PARTIAL_DELETE,
1142 READ_ONLY,
1145 /* Assumes that children, if any, have been already freed */
1146 static void usb_mtp_object_free_one(MTPState *s, MTPObject *o)
1148 assert(o->nchildren == 0);
1149 QTAILQ_REMOVE(&s->objects, o, next);
1150 g_free(o->name);
1151 g_free(o->path);
1152 g_free(o);
1155 static int usb_mtp_deletefn(MTPState *s, MTPObject *o, uint32_t trans)
1157 MTPObject *iter, *iter2;
1158 bool partial_delete = false;
1159 bool success = false;
1162 * TODO: Add support for Protection Status
1165 QLIST_FOREACH(iter, &o->children, list) {
1166 if (iter->format == FMT_ASSOCIATION) {
1167 QLIST_FOREACH(iter2, &iter->children, list) {
1168 usb_mtp_deletefn(s, iter2, trans);
1173 if (o->format == FMT_UNDEFINED_OBJECT) {
1174 if (remove(o->path)) {
1175 partial_delete = true;
1176 } else {
1177 usb_mtp_object_free_one(s, o);
1178 success = true;
1182 if (o->format == FMT_ASSOCIATION) {
1183 if (rmdir(o->path)) {
1184 partial_delete = true;
1185 } else {
1186 usb_mtp_object_free_one(s, o);
1187 success = true;
1191 if (success && partial_delete) {
1192 return PARTIAL_DELETE;
1194 if (!success && partial_delete) {
1195 return READ_ONLY;
1197 return ALL_DELETE;
1200 static void usb_mtp_object_delete(MTPState *s, uint32_t handle,
1201 uint32_t format_code, uint32_t trans)
1203 MTPObject *o;
1204 int ret;
1206 /* Return error if store is read-only */
1207 if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1208 usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1209 trans, 0, 0, 0, 0);
1210 return;
1213 if (format_code != 0) {
1214 usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1215 trans, 0, 0, 0, 0);
1216 return;
1219 if (handle == 0xFFFFFFF) {
1220 o = QTAILQ_FIRST(&s->objects);
1221 } else {
1222 o = usb_mtp_object_lookup(s, handle);
1224 if (o == NULL) {
1225 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1226 trans, 0, 0, 0, 0);
1227 return;
1230 ret = usb_mtp_deletefn(s, o, trans);
1231 if (ret == PARTIAL_DELETE) {
1232 usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1233 trans, 0, 0, 0, 0);
1234 return;
1235 } else if (ret == READ_ONLY) {
1236 usb_mtp_queue_result(s, RES_STORE_READ_ONLY, trans,
1237 0, 0, 0, 0);
1238 return;
1239 } else {
1240 usb_mtp_queue_result(s, RES_OK, trans,
1241 0, 0, 0, 0);
1242 return;
1246 static void usb_mtp_command(MTPState *s, MTPControl *c)
1248 MTPData *data_in = NULL;
1249 MTPObject *o = NULL;
1250 uint32_t nres = 0, res0 = 0;
1251 Error *err = NULL;
1253 /* sanity checks */
1254 if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
1255 usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
1256 c->trans, 0, 0, 0, 0);
1257 return;
1260 /* process commands */
1261 switch (c->code) {
1262 case CMD_GET_DEVICE_INFO:
1263 data_in = usb_mtp_get_device_info(s, c);
1264 break;
1265 case CMD_OPEN_SESSION:
1266 if (s->session) {
1267 usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
1268 c->trans, 1, s->session, 0, 0);
1269 return;
1271 if (c->argv[0] == 0) {
1272 usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
1273 c->trans, 0, 0, 0, 0);
1274 return;
1276 trace_usb_mtp_op_open_session(s->dev.addr);
1277 s->session = c->argv[0];
1278 usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
1280 s->file_monitor = qemu_file_monitor_new(&err);
1281 if (err) {
1282 error_report("usb-mtp: file monitoring init failed: %s",
1283 error_get_pretty(err));
1284 error_free(err);
1285 } else {
1286 QTAILQ_INIT(&s->events);
1288 break;
1289 case CMD_CLOSE_SESSION:
1290 trace_usb_mtp_op_close_session(s->dev.addr);
1291 s->session = 0;
1292 s->next_handle = 0;
1293 usb_mtp_file_monitor_cleanup(s);
1294 usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1295 assert(QTAILQ_EMPTY(&s->objects));
1296 break;
1297 case CMD_GET_STORAGE_IDS:
1298 data_in = usb_mtp_get_storage_ids(s, c);
1299 break;
1300 case CMD_GET_STORAGE_INFO:
1301 if (c->argv[0] != QEMU_STORAGE_ID &&
1302 c->argv[0] != 0xffffffff) {
1303 usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1304 c->trans, 0, 0, 0, 0);
1305 return;
1307 data_in = usb_mtp_get_storage_info(s, c);
1308 break;
1309 case CMD_GET_NUM_OBJECTS:
1310 case CMD_GET_OBJECT_HANDLES:
1311 if (c->argv[0] != QEMU_STORAGE_ID &&
1312 c->argv[0] != 0xffffffff) {
1313 usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1314 c->trans, 0, 0, 0, 0);
1315 return;
1317 if (c->argv[1] != 0x00000000) {
1318 usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1319 c->trans, 0, 0, 0, 0);
1320 return;
1322 if (c->argv[2] == 0x00000000 ||
1323 c->argv[2] == 0xffffffff) {
1324 o = QTAILQ_FIRST(&s->objects);
1325 } else {
1326 o = usb_mtp_object_lookup(s, c->argv[2]);
1328 if (o == NULL) {
1329 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1330 c->trans, 0, 0, 0, 0);
1331 return;
1333 if (o->format != FMT_ASSOCIATION) {
1334 usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
1335 c->trans, 0, 0, 0, 0);
1336 return;
1338 usb_mtp_object_readdir(s, o);
1339 if (c->code == CMD_GET_NUM_OBJECTS) {
1340 trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
1341 nres = 1;
1342 res0 = o->nchildren;
1343 } else {
1344 data_in = usb_mtp_get_object_handles(s, c, o);
1346 break;
1347 case CMD_GET_OBJECT_INFO:
1348 o = usb_mtp_object_lookup(s, c->argv[0]);
1349 if (o == NULL) {
1350 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1351 c->trans, 0, 0, 0, 0);
1352 return;
1354 data_in = usb_mtp_get_object_info(s, c, o);
1355 break;
1356 case CMD_GET_OBJECT:
1357 o = usb_mtp_object_lookup(s, c->argv[0]);
1358 if (o == NULL) {
1359 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1360 c->trans, 0, 0, 0, 0);
1361 return;
1363 if (o->format == FMT_ASSOCIATION) {
1364 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1365 c->trans, 0, 0, 0, 0);
1366 return;
1368 data_in = usb_mtp_get_object(s, c, o);
1369 if (data_in == NULL) {
1370 usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1371 c->trans, 0, 0, 0, 0);
1372 return;
1374 break;
1375 case CMD_DELETE_OBJECT:
1376 usb_mtp_object_delete(s, c->argv[0], c->argv[1], c->trans);
1377 return;
1378 case CMD_GET_PARTIAL_OBJECT:
1379 o = usb_mtp_object_lookup(s, c->argv[0]);
1380 if (o == NULL) {
1381 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1382 c->trans, 0, 0, 0, 0);
1383 return;
1385 if (o->format == FMT_ASSOCIATION) {
1386 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1387 c->trans, 0, 0, 0, 0);
1388 return;
1390 data_in = usb_mtp_get_partial_object(s, c, o);
1391 if (data_in == NULL) {
1392 usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1393 c->trans, 0, 0, 0, 0);
1394 return;
1396 nres = 1;
1397 res0 = data_in->length;
1398 break;
1399 case CMD_SEND_OBJECT_INFO:
1400 /* Return error if store is read-only */
1401 if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1402 usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1403 c->trans, 0, 0, 0, 0);
1404 } else if (c->argv[0] && (c->argv[0] != QEMU_STORAGE_ID)) {
1405 /* First parameter points to storage id or is 0 */
1406 usb_mtp_queue_result(s, RES_STORE_NOT_AVAILABLE, c->trans,
1407 0, 0, 0, 0);
1408 } else if (c->argv[1] && !c->argv[0]) {
1409 /* If second parameter is specified, first must also be specified */
1410 usb_mtp_queue_result(s, RES_DESTINATION_UNSUPPORTED, c->trans,
1411 0, 0, 0, 0);
1412 } else {
1413 uint32_t handle = c->argv[1];
1414 if (handle == 0xFFFFFFFF || handle == 0) {
1415 /* root object */
1416 o = QTAILQ_FIRST(&s->objects);
1417 } else {
1418 o = usb_mtp_object_lookup(s, handle);
1420 if (o == NULL) {
1421 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, c->trans,
1422 0, 0, 0, 0);
1423 } else if (o->format != FMT_ASSOCIATION) {
1424 usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT, c->trans,
1425 0, 0, 0, 0);
1428 if (o) {
1429 s->dataset.parent_handle = o->handle;
1431 s->data_out = usb_mtp_data_alloc(c);
1432 return;
1433 case CMD_SEND_OBJECT:
1434 if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1435 usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1436 c->trans, 0, 0, 0, 0);
1437 return;
1439 if (!s->write_pending) {
1440 usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO,
1441 c->trans, 0, 0, 0, 0);
1442 return;
1444 s->data_out = usb_mtp_data_alloc(c);
1445 return;
1446 case CMD_GET_OBJECT_PROPS_SUPPORTED:
1447 if (c->argv[0] != FMT_UNDEFINED_OBJECT &&
1448 c->argv[0] != FMT_ASSOCIATION) {
1449 usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1450 c->trans, 0, 0, 0, 0);
1451 return;
1453 data_in = usb_mtp_get_object_props_supported(s, c);
1454 break;
1455 case CMD_GET_OBJECT_PROP_DESC:
1456 if (c->argv[1] != FMT_UNDEFINED_OBJECT &&
1457 c->argv[1] != FMT_ASSOCIATION) {
1458 usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1459 c->trans, 0, 0, 0, 0);
1460 return;
1462 data_in = usb_mtp_get_object_prop_desc(s, c);
1463 if (data_in == NULL) {
1464 usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1465 c->trans, 0, 0, 0, 0);
1466 return;
1468 break;
1469 case CMD_GET_OBJECT_PROP_VALUE:
1470 o = usb_mtp_object_lookup(s, c->argv[0]);
1471 if (o == NULL) {
1472 usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1473 c->trans, 0, 0, 0, 0);
1474 return;
1476 data_in = usb_mtp_get_object_prop_value(s, c, o);
1477 if (data_in == NULL) {
1478 usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1479 c->trans, 0, 0, 0, 0);
1480 return;
1482 break;
1483 default:
1484 trace_usb_mtp_op_unknown(s->dev.addr, c->code);
1485 usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
1486 c->trans, 0, 0, 0, 0);
1487 return;
1490 /* return results on success */
1491 if (data_in) {
1492 assert(s->data_in == NULL);
1493 s->data_in = data_in;
1495 usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0, 0);
1498 /* ----------------------------------------------------------------------- */
1500 static void usb_mtp_handle_reset(USBDevice *dev)
1502 MTPState *s = USB_MTP(dev);
1504 trace_usb_mtp_reset(s->dev.addr);
1506 usb_mtp_file_monitor_cleanup(s);
1507 usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1508 s->session = 0;
1509 usb_mtp_data_free(s->data_in);
1510 s->data_in = NULL;
1511 usb_mtp_data_free(s->data_out);
1512 s->data_out = NULL;
1513 g_free(s->result);
1514 s->result = NULL;
1517 static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
1518 int request, int value, int index,
1519 int length, uint8_t *data)
1521 int ret;
1522 MTPState *s = USB_MTP(dev);
1523 uint16_t *event = (uint16_t *)data;
1525 switch (request) {
1526 case ClassInterfaceOutRequest | 0x64:
1527 if (*event == EVT_CANCEL_TRANSACTION) {
1528 g_free(s->result);
1529 s->result = NULL;
1530 usb_mtp_data_free(s->data_in);
1531 s->data_in = NULL;
1532 if (s->write_pending) {
1533 g_free(s->dataset.filename);
1534 s->write_pending = false;
1535 s->dataset.size = 0;
1537 usb_mtp_data_free(s->data_out);
1538 s->data_out = NULL;
1539 } else {
1540 p->status = USB_RET_STALL;
1542 break;
1543 default:
1544 ret = usb_desc_handle_control(dev, p, request,
1545 value, index, length, data);
1546 if (ret >= 0) {
1547 return;
1551 trace_usb_mtp_stall(dev->addr, "unknown control request");
1554 static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
1556 /* we don't use async packets, so this should never be called */
1557 fprintf(stderr, "%s\n", __func__);
1560 static char *utf16_to_str(uint8_t len, uint16_t *arr)
1562 wchar_t *wstr = g_new0(wchar_t, len + 1);
1563 int count, dlen;
1564 char *dest;
1566 for (count = 0; count < len; count++) {
1567 /* FIXME: not working for surrogate pairs */
1568 wstr[count] = (wchar_t)arr[count];
1570 wstr[count] = 0;
1572 dlen = wcstombs(NULL, wstr, 0) + 1;
1573 dest = g_malloc(dlen);
1574 wcstombs(dest, wstr, dlen);
1575 g_free(wstr);
1576 return dest;
1579 /* Wrapper around write, returns 0 on failure */
1580 static uint64_t write_retry(int fd, void *buf, uint64_t size, off_t offset)
1582 uint64_t ret = 0;
1584 if (lseek(fd, offset, SEEK_SET) < 0) {
1585 goto done;
1588 ret = qemu_write_full(fd, buf, size);
1590 done:
1591 return ret;
1594 static void usb_mtp_update_object(MTPObject *parent, char *name)
1596 MTPObject *o =
1597 usb_mtp_object_lookup_name(parent, name, strlen(name));
1599 if (o) {
1600 lstat(o->path, &o->stat);
1604 static void usb_mtp_write_data(MTPState *s)
1606 MTPData *d = s->data_out;
1607 MTPObject *parent =
1608 usb_mtp_object_lookup(s, s->dataset.parent_handle);
1609 char *path = NULL;
1610 uint64_t rc;
1611 mode_t mask = 0644;
1613 assert(d != NULL);
1615 switch (d->write_status) {
1616 case WRITE_START:
1617 if (!parent || !s->write_pending) {
1618 usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, d->trans,
1619 0, 0, 0, 0);
1620 return;
1623 if (s->dataset.filename) {
1624 path = g_strdup_printf("%s/%s", parent->path, s->dataset.filename);
1625 if (s->dataset.format == FMT_ASSOCIATION) {
1626 d->fd = mkdir(path, mask);
1627 goto free;
1629 d->fd = open(path, O_CREAT | O_WRONLY |
1630 O_CLOEXEC | O_NOFOLLOW, mask);
1631 if (d->fd == -1) {
1632 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1633 0, 0, 0, 0);
1634 goto done;
1637 /* Return success if initiator sent 0 sized data */
1638 if (!s->dataset.size) {
1639 goto success;
1641 if (d->length != MTP_WRITE_BUF_SZ && !d->pending) {
1642 d->write_status = WRITE_END;
1645 /* fall through */
1646 case WRITE_CONTINUE:
1647 case WRITE_END:
1648 rc = write_retry(d->fd, d->data, d->data_offset,
1649 d->offset - d->data_offset);
1650 if (rc != d->data_offset) {
1651 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1652 0, 0, 0, 0);
1653 goto done;
1655 if (d->write_status != WRITE_END) {
1656 return;
1657 } else {
1658 /* Only for < 4G file sizes */
1659 if (s->dataset.size != 0xFFFFFFFF && d->offset != s->dataset.size) {
1660 usb_mtp_queue_result(s, RES_INCOMPLETE_TRANSFER, d->trans,
1661 0, 0, 0, 0);
1662 goto done;
1664 usb_mtp_update_object(parent, s->dataset.filename);
1668 success:
1669 usb_mtp_queue_result(s, RES_OK, d->trans,
1670 0, 0, 0, 0);
1672 done:
1674 * The write dataset is kept around and freed only
1675 * on success or if another write request comes in
1677 if (d->fd != -1) {
1678 close(d->fd);
1680 free:
1681 g_free(s->dataset.filename);
1682 s->dataset.size = 0;
1683 g_free(path);
1684 s->write_pending = false;
1687 static void usb_mtp_write_metadata(MTPState *s, uint64_t dlen)
1689 MTPData *d = s->data_out;
1690 ObjectInfo *dataset = (ObjectInfo *)d->data;
1691 char *filename;
1692 MTPObject *o;
1693 MTPObject *p = usb_mtp_object_lookup(s, s->dataset.parent_handle);
1694 uint32_t next_handle = s->next_handle;
1696 assert(!s->write_pending);
1697 assert(p != NULL);
1699 filename = utf16_to_str(MIN(dataset->length,
1700 dlen - offsetof(ObjectInfo, filename)),
1701 dataset->filename);
1703 if (strchr(filename, '/')) {
1704 usb_mtp_queue_result(s, RES_PARAMETER_NOT_SUPPORTED, d->trans,
1705 0, 0, 0, 0);
1706 g_free(filename);
1707 return;
1710 o = usb_mtp_object_lookup_name(p, filename, dataset->length);
1711 if (o != NULL) {
1712 next_handle = o->handle;
1715 s->dataset.filename = filename;
1716 s->dataset.format = dataset->format;
1717 s->dataset.size = dataset->size;
1718 s->write_pending = true;
1720 if (s->dataset.format == FMT_ASSOCIATION) {
1721 usb_mtp_write_data(s);
1722 /* next_handle will be allocated to the newly created dir */
1723 if (d->fd == -1) {
1724 usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1725 0, 0, 0, 0);
1726 return;
1728 d->fd = -1;
1731 usb_mtp_queue_result(s, RES_OK, d->trans, 3, QEMU_STORAGE_ID,
1732 s->dataset.parent_handle, next_handle);
1735 static void usb_mtp_get_data(MTPState *s, mtp_container *container,
1736 USBPacket *p)
1738 MTPData *d = s->data_out;
1739 uint64_t dlen;
1740 uint32_t data_len = p->iov.size;
1741 uint64_t total_len;
1743 if (!d) {
1744 usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, 0,
1745 0, 0, 0, 0);
1746 return;
1748 if (d->first) {
1749 /* Total length of incoming data */
1750 total_len = cpu_to_le32(container->length) - sizeof(mtp_container);
1751 /* Length of data in this packet */
1752 data_len -= sizeof(mtp_container);
1753 if (total_len < MTP_WRITE_BUF_SZ) {
1754 usb_mtp_realloc(d, total_len);
1755 d->length += total_len;
1756 } else {
1757 usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - sizeof(mtp_container));
1758 d->length += MTP_WRITE_BUF_SZ - sizeof(mtp_container);
1760 d->offset = 0;
1761 d->first = false;
1762 d->pending = false;
1763 d->data_offset = 0;
1764 d->write_status = WRITE_START;
1767 if (d->pending) {
1768 memset(d->data, 0, d->length);
1769 if (d->length != MTP_WRITE_BUF_SZ) {
1770 usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - d->length);
1771 d->length += (MTP_WRITE_BUF_SZ - d->length);
1773 d->pending = false;
1774 d->write_status = WRITE_CONTINUE;
1775 d->data_offset = 0;
1778 if (d->length - d->data_offset > data_len) {
1779 dlen = data_len;
1780 } else {
1781 dlen = d->length - d->data_offset;
1784 switch (d->code) {
1785 case CMD_SEND_OBJECT_INFO:
1786 usb_packet_copy(p, d->data + d->data_offset, dlen);
1787 d->offset += dlen;
1788 d->data_offset += dlen;
1789 if (d->data_offset == d->length) {
1790 /* The operation might have already failed */
1791 if (!s->result) {
1792 usb_mtp_write_metadata(s, dlen);
1794 usb_mtp_data_free(s->data_out);
1795 s->data_out = NULL;
1796 return;
1798 break;
1799 case CMD_SEND_OBJECT:
1800 usb_packet_copy(p, d->data + d->data_offset, dlen);
1801 d->offset += dlen;
1802 d->data_offset += dlen;
1803 if ((p->iov.size % 64) || !p->iov.size) {
1804 assert((s->dataset.size == 0xFFFFFFFF) ||
1805 (s->dataset.size == d->offset));
1807 if (d->length == MTP_WRITE_BUF_SZ) {
1808 d->write_status = WRITE_END;
1809 } else {
1810 d->write_status = WRITE_START;
1812 usb_mtp_write_data(s);
1813 usb_mtp_data_free(s->data_out);
1814 s->data_out = NULL;
1815 return;
1817 if (d->data_offset == d->length) {
1818 d->pending = true;
1819 usb_mtp_write_data(s);
1821 break;
1822 default:
1823 p->status = USB_RET_STALL;
1824 return;
1828 static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
1830 MTPState *s = USB_MTP(dev);
1831 MTPControl cmd;
1832 mtp_container container;
1833 uint32_t params[5];
1834 uint16_t container_type;
1835 int i, rc;
1837 switch (p->ep->nr) {
1838 case EP_DATA_IN:
1839 if (s->data_out != NULL) {
1840 /* guest bug */
1841 trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
1842 p->status = USB_RET_STALL;
1843 return;
1845 if (p->iov.size < sizeof(container)) {
1846 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1847 p->status = USB_RET_STALL;
1848 return;
1850 if (s->data_in != NULL) {
1851 MTPData *d = s->data_in;
1852 uint64_t dlen = d->length - d->offset;
1853 if (d->first) {
1854 trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
1855 if (d->length + sizeof(container) > 0xFFFFFFFF) {
1856 container.length = cpu_to_le32(0xFFFFFFFF);
1857 } else {
1858 container.length =
1859 cpu_to_le32(d->length + sizeof(container));
1861 container.type = cpu_to_le16(TYPE_DATA);
1862 container.code = cpu_to_le16(d->code);
1863 container.trans = cpu_to_le32(d->trans);
1864 usb_packet_copy(p, &container, sizeof(container));
1865 d->first = false;
1866 if (dlen > p->iov.size - sizeof(container)) {
1867 dlen = p->iov.size - sizeof(container);
1869 } else {
1870 if (dlen > p->iov.size) {
1871 dlen = p->iov.size;
1874 if (d->fd == -1) {
1875 usb_packet_copy(p, d->data + d->offset, dlen);
1876 } else {
1877 if (d->alloc < p->iov.size) {
1878 d->alloc = p->iov.size;
1879 d->data = g_realloc(d->data, d->alloc);
1881 rc = read(d->fd, d->data, dlen);
1882 if (rc != dlen) {
1883 memset(d->data, 0, dlen);
1884 s->result->code = RES_INCOMPLETE_TRANSFER;
1886 usb_packet_copy(p, d->data, dlen);
1888 d->offset += dlen;
1889 if (d->offset == d->length) {
1890 usb_mtp_data_free(s->data_in);
1891 s->data_in = NULL;
1893 } else if (s->result != NULL) {
1894 MTPControl *r = s->result;
1895 int length = sizeof(container) + r->argc * sizeof(uint32_t);
1896 if (r->code == RES_OK) {
1897 trace_usb_mtp_success(s->dev.addr, r->trans,
1898 (r->argc > 0) ? r->argv[0] : 0,
1899 (r->argc > 1) ? r->argv[1] : 0);
1900 } else {
1901 trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
1902 (r->argc > 0) ? r->argv[0] : 0,
1903 (r->argc > 1) ? r->argv[1] : 0);
1905 container.length = cpu_to_le32(length);
1906 container.type = cpu_to_le16(TYPE_RESPONSE);
1907 container.code = cpu_to_le16(r->code);
1908 container.trans = cpu_to_le32(r->trans);
1909 for (i = 0; i < r->argc; i++) {
1910 params[i] = cpu_to_le32(r->argv[i]);
1912 usb_packet_copy(p, &container, sizeof(container));
1913 usb_packet_copy(p, &params, length - sizeof(container));
1914 g_free(s->result);
1915 s->result = NULL;
1917 break;
1918 case EP_DATA_OUT:
1919 if (p->iov.size < sizeof(container)) {
1920 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1921 p->status = USB_RET_STALL;
1922 return;
1924 if ((s->data_out != NULL) && !s->data_out->first) {
1925 container_type = TYPE_DATA;
1926 } else {
1927 usb_packet_copy(p, &container, sizeof(container));
1928 container_type = le16_to_cpu(container.type);
1930 switch (container_type) {
1931 case TYPE_COMMAND:
1932 if (s->data_in || s->data_out || s->result) {
1933 trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1934 p->status = USB_RET_STALL;
1935 return;
1937 cmd.code = le16_to_cpu(container.code);
1938 cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1939 / sizeof(uint32_t);
1940 cmd.trans = le32_to_cpu(container.trans);
1941 if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1942 cmd.argc = ARRAY_SIZE(cmd.argv);
1944 if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1945 trace_usb_mtp_stall(s->dev.addr, "packet too small");
1946 p->status = USB_RET_STALL;
1947 return;
1949 usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1950 for (i = 0; i < cmd.argc; i++) {
1951 cmd.argv[i] = le32_to_cpu(params[i]);
1953 trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1954 (cmd.argc > 0) ? cmd.argv[0] : 0,
1955 (cmd.argc > 1) ? cmd.argv[1] : 0,
1956 (cmd.argc > 2) ? cmd.argv[2] : 0,
1957 (cmd.argc > 3) ? cmd.argv[3] : 0,
1958 (cmd.argc > 4) ? cmd.argv[4] : 0);
1959 usb_mtp_command(s, &cmd);
1960 break;
1961 case TYPE_DATA:
1962 /* One of the previous transfers has already errored but the
1963 * responder is still sending data associated with it
1965 if (s->result != NULL) {
1966 return;
1968 usb_mtp_get_data(s, &container, p);
1969 break;
1970 default:
1971 /* not needed as long as the mtp device is read-only */
1972 p->status = USB_RET_STALL;
1973 return;
1975 break;
1976 case EP_EVENT:
1977 if (!QTAILQ_EMPTY(&s->events)) {
1978 struct MTPMonEntry *e = QTAILQ_LAST(&s->events);
1979 uint32_t handle;
1980 int len = sizeof(container) + sizeof(uint32_t);
1982 if (p->iov.size < len) {
1983 trace_usb_mtp_stall(s->dev.addr,
1984 "packet too small to send event");
1985 p->status = USB_RET_STALL;
1986 return;
1989 QTAILQ_REMOVE(&s->events, e, next);
1990 container.length = cpu_to_le32(len);
1991 container.type = cpu_to_le32(TYPE_EVENT);
1992 container.code = cpu_to_le16(e->event);
1993 container.trans = 0; /* no trans specific events */
1994 handle = cpu_to_le32(e->handle);
1995 usb_packet_copy(p, &container, sizeof(container));
1996 usb_packet_copy(p, &handle, sizeof(uint32_t));
1997 g_free(e);
1998 return;
2000 p->status = USB_RET_NAK;
2001 return;
2002 default:
2003 trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
2004 p->status = USB_RET_STALL;
2005 return;
2008 if (p->actual_length == 0) {
2009 trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
2010 p->status = USB_RET_NAK;
2011 return;
2012 } else {
2013 trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
2014 p->iov.size);
2015 return;
2019 static void usb_mtp_realize(USBDevice *dev, Error **errp)
2021 MTPState *s = USB_MTP(dev);
2023 usb_desc_create_serial(dev);
2024 usb_desc_init(dev);
2025 QTAILQ_INIT(&s->objects);
2026 if (s->desc == NULL) {
2027 if (s->root == NULL) {
2028 error_setg(errp, "usb-mtp: rootdir property must be configured");
2029 return;
2031 s->desc = strrchr(s->root, '/');
2032 if (s->desc && s->desc[0]) {
2033 s->desc = g_strdup(s->desc + 1);
2034 } else {
2035 s->desc = g_strdup("none");
2038 /* Mark store as RW */
2039 if (!s->readonly) {
2040 s->flags |= (1 << MTP_FLAG_WRITABLE);
2045 static const VMStateDescription vmstate_usb_mtp = {
2046 .name = "usb-mtp",
2047 .unmigratable = 1,
2048 .version_id = 1,
2049 .minimum_version_id = 1,
2050 .fields = (VMStateField[]) {
2051 VMSTATE_USB_DEVICE(dev, MTPState),
2052 VMSTATE_END_OF_LIST()
2056 static Property mtp_properties[] = {
2057 DEFINE_PROP_STRING("rootdir", MTPState, root),
2058 DEFINE_PROP_STRING("desc", MTPState, desc),
2059 DEFINE_PROP_BOOL("readonly", MTPState, readonly, true),
2060 DEFINE_PROP_END_OF_LIST(),
2063 static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
2065 DeviceClass *dc = DEVICE_CLASS(klass);
2066 USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2068 uc->realize = usb_mtp_realize;
2069 uc->product_desc = "QEMU USB MTP";
2070 uc->usb_desc = &desc;
2071 uc->cancel_packet = usb_mtp_cancel_packet;
2072 uc->handle_attach = usb_desc_attach;
2073 uc->handle_reset = usb_mtp_handle_reset;
2074 uc->handle_control = usb_mtp_handle_control;
2075 uc->handle_data = usb_mtp_handle_data;
2076 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2077 dc->desc = "USB Media Transfer Protocol device";
2078 dc->fw_name = "mtp";
2079 dc->vmsd = &vmstate_usb_mtp;
2080 dc->props = mtp_properties;
2083 static TypeInfo mtp_info = {
2084 .name = TYPE_USB_MTP,
2085 .parent = TYPE_USB_DEVICE,
2086 .instance_size = sizeof(MTPState),
2087 .class_init = usb_mtp_class_initfn,
2090 static void usb_mtp_register_types(void)
2092 type_register_static(&mtp_info);
2095 type_init(usb_mtp_register_types)