qemu/hw/usb/dev-mtp.c
<<
>>
Prefs
   1/*
   2 * Media Transfer Protocol implementation, backed by host filesystem.
   3 *
   4 * Copyright Red Hat, Inc 2014
   5 *
   6 * Author:
   7 *   Gerd Hoffmann <kraxel@redhat.com>
   8 *
   9 * This code is licensed under the GPL v2 or later.
  10 */
  11
  12#include "qemu/osdep.h"
  13#include "qapi/error.h"
  14#include "qemu/error-report.h"
  15#include <wchar.h>
  16#include <dirent.h>
  17#include <glib/gstdio.h>
  18#include <sys/statvfs.h>
  19
  20
  21#include "qemu/iov.h"
  22#include "qemu/module.h"
  23#include "qemu/filemonitor.h"
  24#include "trace.h"
  25#include "hw/qdev-properties.h"
  26#include "hw/usb.h"
  27#include "migration/vmstate.h"
  28#include "desc.h"
  29#include "qemu/units.h"
  30#include "qom/object.h"
  31
  32/* ----------------------------------------------------------------------- */
  33
  34enum mtp_container_type {
  35    TYPE_COMMAND  = 1,
  36    TYPE_DATA     = 2,
  37    TYPE_RESPONSE = 3,
  38    TYPE_EVENT    = 4,
  39};
  40
  41/* MTP write stage, for internal use only */
  42enum mtp_write_status {
  43    WRITE_START    = 1,
  44    WRITE_CONTINUE = 2,
  45    WRITE_END      = 3,
  46};
  47
  48enum mtp_code {
  49    /* command codes */
  50    CMD_GET_DEVICE_INFO            = 0x1001,
  51    CMD_OPEN_SESSION               = 0x1002,
  52    CMD_CLOSE_SESSION              = 0x1003,
  53    CMD_GET_STORAGE_IDS            = 0x1004,
  54    CMD_GET_STORAGE_INFO           = 0x1005,
  55    CMD_GET_NUM_OBJECTS            = 0x1006,
  56    CMD_GET_OBJECT_HANDLES         = 0x1007,
  57    CMD_GET_OBJECT_INFO            = 0x1008,
  58    CMD_GET_OBJECT                 = 0x1009,
  59    CMD_DELETE_OBJECT              = 0x100b,
  60    CMD_SEND_OBJECT_INFO           = 0x100c,
  61    CMD_SEND_OBJECT                = 0x100d,
  62    CMD_GET_PARTIAL_OBJECT         = 0x101b,
  63    CMD_GET_OBJECT_PROPS_SUPPORTED = 0x9801,
  64    CMD_GET_OBJECT_PROP_DESC       = 0x9802,
  65    CMD_GET_OBJECT_PROP_VALUE      = 0x9803,
  66
  67    /* response codes */
  68    RES_OK                         = 0x2001,
  69    RES_GENERAL_ERROR              = 0x2002,
  70    RES_SESSION_NOT_OPEN           = 0x2003,
  71    RES_INVALID_TRANSACTION_ID     = 0x2004,
  72    RES_OPERATION_NOT_SUPPORTED    = 0x2005,
  73    RES_PARAMETER_NOT_SUPPORTED    = 0x2006,
  74    RES_INCOMPLETE_TRANSFER        = 0x2007,
  75    RES_INVALID_STORAGE_ID         = 0x2008,
  76    RES_INVALID_OBJECT_HANDLE      = 0x2009,
  77    RES_INVALID_OBJECT_FORMAT_CODE = 0x200b,
  78    RES_STORE_FULL                 = 0x200c,
  79    RES_STORE_READ_ONLY            = 0x200e,
  80    RES_PARTIAL_DELETE             = 0x2012,
  81    RES_STORE_NOT_AVAILABLE        = 0x2013,
  82    RES_SPEC_BY_FORMAT_UNSUPPORTED = 0x2014,
  83    RES_INVALID_OBJECTINFO         = 0x2015,
  84    RES_DESTINATION_UNSUPPORTED    = 0x2020,
  85    RES_INVALID_PARENT_OBJECT      = 0x201a,
  86    RES_INVALID_PARAMETER          = 0x201d,
  87    RES_SESSION_ALREADY_OPEN       = 0x201e,
  88    RES_INVALID_OBJECT_PROP_CODE   = 0xA801,
  89
  90    /* format codes */
  91    FMT_UNDEFINED_OBJECT           = 0x3000,
  92    FMT_ASSOCIATION                = 0x3001,
  93
  94    /* event codes */
  95    EVT_CANCEL_TRANSACTION         = 0x4001,
  96    EVT_OBJ_ADDED                  = 0x4002,
  97    EVT_OBJ_REMOVED                = 0x4003,
  98    EVT_OBJ_INFO_CHANGED           = 0x4007,
  99
 100    /* object properties */
 101    PROP_STORAGE_ID                = 0xDC01,
 102    PROP_OBJECT_FORMAT             = 0xDC02,
 103    PROP_OBJECT_COMPRESSED_SIZE    = 0xDC04,
 104    PROP_PARENT_OBJECT             = 0xDC0B,
 105    PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER = 0xDC41,
 106    PROP_NAME                      = 0xDC44,
 107};
 108
 109enum mtp_data_type {
 110    DATA_TYPE_UINT16  = 0x0004,
 111    DATA_TYPE_UINT32  = 0x0006,
 112    DATA_TYPE_UINT64  = 0x0008,
 113    DATA_TYPE_UINT128 = 0x000a,
 114    DATA_TYPE_STRING  = 0xffff,
 115};
 116
 117typedef struct {
 118    uint32_t length;
 119    uint16_t type;
 120    uint16_t code;
 121    uint32_t trans;
 122} QEMU_PACKED mtp_container;
 123
 124/* ----------------------------------------------------------------------- */
 125
 126typedef struct MTPState MTPState;
 127typedef struct MTPControl MTPControl;
 128typedef struct MTPData MTPData;
 129typedef struct MTPObject MTPObject;
 130
 131enum {
 132    EP_DATA_IN = 1,
 133    EP_DATA_OUT,
 134    EP_EVENT,
 135};
 136
 137typedef struct MTPMonEntry MTPMonEntry;
 138
 139struct MTPMonEntry {
 140    uint32_t event;
 141    uint32_t handle;
 142
 143    QTAILQ_ENTRY(MTPMonEntry) next;
 144};
 145
 146struct MTPControl {
 147    uint16_t     code;
 148    uint32_t     trans;
 149    int          argc;
 150    uint32_t     argv[5];
 151};
 152
 153struct MTPData {
 154    uint16_t     code;
 155    uint32_t     trans;
 156    uint64_t     offset;
 157    uint64_t     length;
 158    uint64_t     alloc;
 159    uint8_t      *data;
 160    bool         first;
 161    /* Used for >4G file sizes */
 162    bool         pending;
 163    int          fd;
 164    uint8_t      write_status;
 165    /* Internal pointer per every MTP_WRITE_BUF_SZ */
 166    uint64_t     data_offset;
 167};
 168
 169struct MTPObject {
 170    uint32_t     handle;
 171    uint16_t     format;
 172    char         *name;
 173    char         *path;
 174    struct stat  stat;
 175    /* file monitor watch id */
 176    int64_t      watchid;
 177    MTPObject    *parent;
 178    uint32_t     nchildren;
 179    QLIST_HEAD(, MTPObject) children;
 180    QLIST_ENTRY(MTPObject) list;
 181    bool         have_children;
 182    QTAILQ_ENTRY(MTPObject) next;
 183};
 184
 185struct MTPState {
 186    USBDevice    dev;
 187    char         *root;
 188    char         *desc;
 189    uint32_t     flags;
 190
 191    MTPData      *data_in;
 192    MTPData      *data_out;
 193    MTPControl   *result;
 194    uint32_t     session;
 195    uint32_t     next_handle;
 196    bool         readonly;
 197
 198    QTAILQ_HEAD(, MTPObject) objects;
 199    QFileMonitor *file_monitor;
 200    QTAILQ_HEAD(, MTPMonEntry) events;
 201    /* Responder is expecting a write operation */
 202    bool write_pending;
 203    struct {
 204        uint32_t parent_handle;
 205        uint16_t format;
 206        uint32_t size;
 207        char *filename;
 208    } dataset;
 209};
 210
 211/*
 212 * ObjectInfo dataset received from initiator
 213 * Fields we don't care about are ignored
 214 */
 215typedef struct {
 216    uint32_t storage_id; /*unused*/
 217    uint16_t format;
 218    uint16_t protection_status; /*unused*/
 219    uint32_t size;
 220    uint16_t thumb_format; /*unused*/
 221    uint32_t thumb_comp_sz; /*unused*/
 222    uint32_t thumb_pix_width; /*unused*/
 223    uint32_t thumb_pix_height; /*unused*/
 224    uint32_t image_pix_width; /*unused*/
 225    uint32_t image_pix_height; /*unused*/
 226    uint32_t image_bit_depth; /*unused*/
 227    uint32_t parent; /*unused*/
 228    uint16_t assoc_type;
 229    uint32_t assoc_desc;
 230    uint32_t seq_no; /*unused*/
 231    uint8_t length; /*part of filename field*/
 232    uint8_t filename[0]; /* UTF-16 encoded */
 233    char date_created[0]; /*unused*/
 234    char date_modified[0]; /*unused*/
 235    char keywords[0]; /*unused*/
 236    /* string and other data follows */
 237} QEMU_PACKED ObjectInfo;
 238
 239#define TYPE_USB_MTP "usb-mtp"
 240OBJECT_DECLARE_SIMPLE_TYPE(MTPState, USB_MTP)
 241
 242#define QEMU_STORAGE_ID 0x00010001
 243
 244#define MTP_FLAG_WRITABLE 0
 245
 246#define FLAG_SET(_mtp, _flag)  ((_mtp)->flags & (1 << (_flag)))
 247
 248/* ----------------------------------------------------------------------- */
 249
 250#define MTP_MANUFACTURER  "QEMU"
 251#define MTP_PRODUCT       "QEMU filesharing"
 252#define MTP_WRITE_BUF_SZ  (512 * KiB)
 253
 254enum {
 255    STR_MANUFACTURER = 1,
 256    STR_PRODUCT,
 257    STR_SERIALNUMBER,
 258    STR_MTP,
 259    STR_CONFIG_FULL,
 260    STR_CONFIG_HIGH,
 261    STR_CONFIG_SUPER,
 262};
 263
 264static const USBDescStrings desc_strings = {
 265    [STR_MANUFACTURER] = MTP_MANUFACTURER,
 266    [STR_PRODUCT]      = MTP_PRODUCT,
 267    [STR_SERIALNUMBER] = "34617",
 268    [STR_MTP]          = "MTP",
 269    [STR_CONFIG_FULL]  = "Full speed config (usb 1.1)",
 270    [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
 271    [STR_CONFIG_SUPER] = "Super speed config (usb 3.0)",
 272};
 273
 274static const USBDescIface desc_iface_full = {
 275    .bInterfaceNumber              = 0,
 276    .bNumEndpoints                 = 3,
 277    .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
 278    .bInterfaceSubClass            = 0x01,
 279    .bInterfaceProtocol            = 0x01,
 280    .iInterface                    = STR_MTP,
 281    .eps = (USBDescEndpoint[]) {
 282        {
 283            .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
 284            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
 285            .wMaxPacketSize        = 64,
 286        },{
 287            .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
 288            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
 289            .wMaxPacketSize        = 64,
 290        },{
 291            .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
 292            .bmAttributes          = USB_ENDPOINT_XFER_INT,
 293            .wMaxPacketSize        = 64,
 294            .bInterval             = 0x0a,
 295        },
 296    }
 297};
 298
 299static const USBDescDevice desc_device_full = {
 300    .bcdUSB                        = 0x0200,
 301    .bMaxPacketSize0               = 8,
 302    .bNumConfigurations            = 1,
 303    .confs = (USBDescConfig[]) {
 304        {
 305            .bNumInterfaces        = 1,
 306            .bConfigurationValue   = 1,
 307            .iConfiguration        = STR_CONFIG_FULL,
 308            .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
 309            .bMaxPower             = 2,
 310            .nif = 1,
 311            .ifs = &desc_iface_full,
 312        },
 313    },
 314};
 315
 316static const USBDescIface desc_iface_high = {
 317    .bInterfaceNumber              = 0,
 318    .bNumEndpoints                 = 3,
 319    .bInterfaceClass               = USB_CLASS_STILL_IMAGE,
 320    .bInterfaceSubClass            = 0x01,
 321    .bInterfaceProtocol            = 0x01,
 322    .iInterface                    = STR_MTP,
 323    .eps = (USBDescEndpoint[]) {
 324        {
 325            .bEndpointAddress      = USB_DIR_IN | EP_DATA_IN,
 326            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
 327            .wMaxPacketSize        = 512,
 328        },{
 329            .bEndpointAddress      = USB_DIR_OUT | EP_DATA_OUT,
 330            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
 331            .wMaxPacketSize        = 512,
 332        },{
 333            .bEndpointAddress      = USB_DIR_IN | EP_EVENT,
 334            .bmAttributes          = USB_ENDPOINT_XFER_INT,
 335            .wMaxPacketSize        = 64,
 336            .bInterval             = 0x0a,
 337        },
 338    }
 339};
 340
 341static const USBDescDevice desc_device_high = {
 342    .bcdUSB                        = 0x0200,
 343    .bMaxPacketSize0               = 64,
 344    .bNumConfigurations            = 1,
 345    .confs = (USBDescConfig[]) {
 346        {
 347            .bNumInterfaces        = 1,
 348            .bConfigurationValue   = 1,
 349            .iConfiguration        = STR_CONFIG_HIGH,
 350            .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
 351            .bMaxPower             = 2,
 352            .nif = 1,
 353            .ifs = &desc_iface_high,
 354        },
 355    },
 356};
 357
 358static const USBDescMSOS desc_msos = {
 359    .CompatibleID = "MTP",
 360    .SelectiveSuspendEnabled = true,
 361};
 362
 363static const USBDesc desc = {
 364    .id = {
 365        .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
 366        .idProduct         = 0x0004,
 367        .bcdDevice         = 0,
 368        .iManufacturer     = STR_MANUFACTURER,
 369        .iProduct          = STR_PRODUCT,
 370        .iSerialNumber     = STR_SERIALNUMBER,
 371    },
 372    .full  = &desc_device_full,
 373    .high  = &desc_device_high,
 374    .str   = desc_strings,
 375    .msos  = &desc_msos,
 376};
 377
 378/* ----------------------------------------------------------------------- */
 379
 380static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle,
 381                                       MTPObject *parent, const char *name)
 382{
 383    MTPObject *o = g_new0(MTPObject, 1);
 384
 385    if (name[0] == '.') {
 386        goto ignore;
 387    }
 388
 389    o->watchid = -1;
 390    o->handle = handle;
 391    o->parent = parent;
 392    o->name = g_strdup(name);
 393    if (parent == NULL) {
 394        o->path = g_strdup(name);
 395    } else {
 396        o->path = g_strdup_printf("%s/%s", parent->path, name);
 397    }
 398
 399    if (lstat(o->path, &o->stat) != 0) {
 400        goto ignore;
 401    }
 402    if (S_ISREG(o->stat.st_mode)) {
 403        o->format = FMT_UNDEFINED_OBJECT;
 404    } else if (S_ISDIR(o->stat.st_mode)) {
 405        o->format = FMT_ASSOCIATION;
 406    } else {
 407        goto ignore;
 408    }
 409
 410    if (access(o->path, R_OK) != 0) {
 411        goto ignore;
 412    }
 413
 414    trace_usb_mtp_object_alloc(s->dev.addr, o->handle, o->path);
 415
 416    QTAILQ_INSERT_TAIL(&s->objects, o, next);
 417    return o;
 418
 419ignore:
 420    g_free(o->name);
 421    g_free(o->path);
 422    g_free(o);
 423    return NULL;
 424}
 425
 426static void usb_mtp_object_free(MTPState *s, MTPObject *o)
 427{
 428    MTPObject *iter;
 429
 430    if (!o) {
 431        return;
 432    }
 433
 434    trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path);
 435
 436    if (o->watchid != -1 && s->file_monitor) {
 437        qemu_file_monitor_remove_watch(s->file_monitor, o->path, o->watchid);
 438    }
 439
 440    QTAILQ_REMOVE(&s->objects, o, next);
 441    if (o->parent) {
 442        QLIST_REMOVE(o, list);
 443        o->parent->nchildren--;
 444    }
 445
 446    while (!QLIST_EMPTY(&o->children)) {
 447        iter = QLIST_FIRST(&o->children);
 448        usb_mtp_object_free(s, iter);
 449    }
 450    g_free(o->name);
 451    g_free(o->path);
 452    g_free(o);
 453}
 454
 455static MTPObject *usb_mtp_object_lookup(MTPState *s, uint32_t handle)
 456{
 457    MTPObject *o;
 458
 459    QTAILQ_FOREACH(o, &s->objects, next) {
 460        if (o->handle == handle) {
 461            return o;
 462        }
 463    }
 464    return NULL;
 465}
 466
 467static MTPObject *usb_mtp_add_child(MTPState *s, MTPObject *o,
 468                                    const char *name)
 469{
 470    MTPObject *child =
 471        usb_mtp_object_alloc(s, s->next_handle++, o, name);
 472
 473    if (child) {
 474        trace_usb_mtp_add_child(s->dev.addr, child->handle, child->path);
 475        QLIST_INSERT_HEAD(&o->children, child, list);
 476        o->nchildren++;
 477
 478        if (child->format == FMT_ASSOCIATION) {
 479            QLIST_INIT(&child->children);
 480        }
 481    }
 482
 483    return child;
 484}
 485
 486static MTPObject *usb_mtp_object_lookup_name(MTPObject *parent,
 487                                             const char *name, int len)
 488{
 489    MTPObject *iter;
 490
 491    if (len == -1) {
 492        len = strlen(name);
 493    }
 494
 495    QLIST_FOREACH(iter, &parent->children, list) {
 496        if (strncmp(iter->name, name, len) == 0) {
 497            return iter;
 498        }
 499    }
 500
 501    return NULL;
 502}
 503
 504static MTPObject *usb_mtp_object_lookup_id(MTPState *s, int64_t id)
 505{
 506    MTPObject *iter;
 507
 508    QTAILQ_FOREACH(iter, &s->objects, next) {
 509        if (iter->watchid == id) {
 510            return iter;
 511        }
 512    }
 513
 514    return NULL;
 515}
 516
 517static void file_monitor_event(int64_t id,
 518                               QFileMonitorEvent ev,
 519                               const char *name,
 520                               void *opaque)
 521{
 522    MTPState *s = opaque;
 523    MTPObject *parent = usb_mtp_object_lookup_id(s, id);
 524    MTPMonEntry *entry = NULL;
 525    MTPObject *o;
 526
 527    if (!parent) {
 528        return;
 529    }
 530
 531    switch (ev) {
 532    case QFILE_MONITOR_EVENT_CREATED:
 533        if (usb_mtp_object_lookup_name(parent, name, -1)) {
 534            /* Duplicate create event */
 535            return;
 536        }
 537        entry = g_new0(MTPMonEntry, 1);
 538        entry->handle = s->next_handle;
 539        entry->event = EVT_OBJ_ADDED;
 540        o = usb_mtp_add_child(s, parent, name);
 541        if (!o) {
 542            g_free(entry);
 543            return;
 544        }
 545        trace_usb_mtp_file_monitor_event(s->dev.addr, name, "Obj Added");
 546        break;
 547
 548    case QFILE_MONITOR_EVENT_DELETED:
 549        /*
 550         * The kernel issues a IN_IGNORED event
 551         * when a dir containing a watchpoint is
 552         * deleted, so we don't have to delete the
 553         * watchpoint
 554         */
 555        o = usb_mtp_object_lookup_name(parent, name, -1);
 556        if (!o) {
 557            return;
 558        }
 559        entry = g_new0(MTPMonEntry, 1);
 560        entry->handle = o->handle;
 561        entry->event = EVT_OBJ_REMOVED;
 562        trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, "Obj Deleted");
 563        usb_mtp_object_free(s, o);
 564        break;
 565
 566    case QFILE_MONITOR_EVENT_MODIFIED:
 567        o = usb_mtp_object_lookup_name(parent, name, -1);
 568        if (!o) {
 569            return;
 570        }
 571        entry = g_new0(MTPMonEntry, 1);
 572        entry->handle = o->handle;
 573        entry->event = EVT_OBJ_INFO_CHANGED;
 574        trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, "Obj Modified");
 575        break;
 576
 577    case QFILE_MONITOR_EVENT_IGNORED:
 578        trace_usb_mtp_file_monitor_event(s->dev.addr, parent->path,
 579                                    "Obj parent dir ignored");
 580        break;
 581
 582    case QFILE_MONITOR_EVENT_ATTRIBUTES:
 583        break;
 584
 585    default:
 586        g_assert_not_reached();
 587    }
 588
 589    if (entry) {
 590        QTAILQ_INSERT_HEAD(&s->events, entry, next);
 591    }
 592}
 593
 594static void usb_mtp_file_monitor_cleanup(MTPState *s)
 595{
 596    MTPMonEntry *e, *p;
 597
 598    QTAILQ_FOREACH_SAFE(e, &s->events, next, p) {
 599        QTAILQ_REMOVE(&s->events, e, next);
 600        g_free(e);
 601    }
 602
 603    qemu_file_monitor_free(s->file_monitor);
 604    s->file_monitor = NULL;
 605}
 606
 607
 608static void usb_mtp_object_readdir(MTPState *s, MTPObject *o)
 609{
 610    struct dirent *entry;
 611    DIR *dir;
 612    int fd;
 613    Error *err = NULL;
 614
 615    if (o->have_children) {
 616        return;
 617    }
 618    o->have_children = true;
 619
 620    fd = open(o->path, O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
 621    if (fd < 0) {
 622        return;
 623    }
 624    dir = fdopendir(fd);
 625    if (!dir) {
 626        close(fd);
 627        return;
 628    }
 629
 630    if (s->file_monitor) {
 631        int64_t id = qemu_file_monitor_add_watch(s->file_monitor, o->path, NULL,
 632                                                 file_monitor_event, s, &err);
 633        if (id == -1) {
 634            error_reportf_err(err,
 635                              "usb-mtp: failed to add watch for %s: ",
 636                              o->path);
 637        } else {
 638            trace_usb_mtp_file_monitor_event(s->dev.addr, o->path,
 639                                             "Watch Added");
 640            o->watchid = id;
 641        }
 642    }
 643
 644    while ((entry = readdir(dir)) != NULL) {
 645        usb_mtp_add_child(s, o, entry->d_name);
 646    }
 647    closedir(dir);
 648}
 649
 650/* ----------------------------------------------------------------------- */
 651
 652static MTPData *usb_mtp_data_alloc(MTPControl *c)
 653{
 654    MTPData *data = g_new0(MTPData, 1);
 655
 656    data->code  = c->code;
 657    data->trans = c->trans;
 658    data->fd    = -1;
 659    data->first = true;
 660    return data;
 661}
 662
 663static void usb_mtp_data_free(MTPData *data)
 664{
 665    if (data == NULL) {
 666        return;
 667    }
 668    if (data->fd != -1) {
 669        close(data->fd);
 670    }
 671    g_free(data->data);
 672    g_free(data);
 673}
 674
 675static void usb_mtp_realloc(MTPData *data, uint32_t bytes)
 676{
 677    if (data->length + bytes <= data->alloc) {
 678        return;
 679    }
 680    data->alloc = (data->length + bytes + 0xff) & ~0xff;
 681    data->data  = g_realloc(data->data, data->alloc);
 682}
 683
 684static void usb_mtp_add_u8(MTPData *data, uint8_t val)
 685{
 686    usb_mtp_realloc(data, 1);
 687    data->data[data->length++] = val;
 688}
 689
 690static void usb_mtp_add_u16(MTPData *data, uint16_t val)
 691{
 692    usb_mtp_realloc(data, 2);
 693    data->data[data->length++] = (val >> 0) & 0xff;
 694    data->data[data->length++] = (val >> 8) & 0xff;
 695}
 696
 697static void usb_mtp_add_u32(MTPData *data, uint32_t val)
 698{
 699    usb_mtp_realloc(data, 4);
 700    data->data[data->length++] = (val >>  0) & 0xff;
 701    data->data[data->length++] = (val >>  8) & 0xff;
 702    data->data[data->length++] = (val >> 16) & 0xff;
 703    data->data[data->length++] = (val >> 24) & 0xff;
 704}
 705
 706static void usb_mtp_add_u64(MTPData *data, uint64_t val)
 707{
 708    usb_mtp_realloc(data, 8);
 709    data->data[data->length++] = (val >>  0) & 0xff;
 710    data->data[data->length++] = (val >>  8) & 0xff;
 711    data->data[data->length++] = (val >> 16) & 0xff;
 712    data->data[data->length++] = (val >> 24) & 0xff;
 713    data->data[data->length++] = (val >> 32) & 0xff;
 714    data->data[data->length++] = (val >> 40) & 0xff;
 715    data->data[data->length++] = (val >> 48) & 0xff;
 716    data->data[data->length++] = (val >> 56) & 0xff;
 717}
 718
 719static void usb_mtp_add_u16_array(MTPData *data, uint32_t len,
 720                                  const uint16_t *vals)
 721{
 722    int i;
 723
 724    usb_mtp_add_u32(data, len);
 725    for (i = 0; i < len; i++) {
 726        usb_mtp_add_u16(data, vals[i]);
 727    }
 728}
 729
 730static void usb_mtp_add_u32_array(MTPData *data, uint32_t len,
 731                                  const uint32_t *vals)
 732{
 733    int i;
 734
 735    usb_mtp_add_u32(data, len);
 736    for (i = 0; i < len; i++) {
 737        usb_mtp_add_u32(data, vals[i]);
 738    }
 739}
 740
 741static void usb_mtp_add_wstr(MTPData *data, const wchar_t *str)
 742{
 743    uint32_t len = wcslen(str);
 744    int i;
 745
 746    if (len > 0) {
 747        len++; /* include terminating L'\0' */
 748    }
 749
 750    usb_mtp_add_u8(data, len);
 751    for (i = 0; i < len; i++) {
 752        usb_mtp_add_u16(data, str[i]);
 753    }
 754}
 755
 756static void usb_mtp_add_str(MTPData *data, const char *str)
 757{
 758    uint32_t len = strlen(str)+1;
 759    wchar_t *wstr = g_new(wchar_t, len);
 760    size_t ret;
 761
 762    ret = mbstowcs(wstr, str, len);
 763    if (ret == -1) {
 764        usb_mtp_add_wstr(data, L"Oops");
 765    } else {
 766        usb_mtp_add_wstr(data, wstr);
 767    }
 768
 769    g_free(wstr);
 770}
 771
 772static void usb_mtp_add_time(MTPData *data, time_t time)
 773{
 774    g_autoptr(GDateTime) then = g_date_time_new_from_unix_utc(time);
 775    g_autofree char *thenstr = g_date_time_format(then, "%Y%m%dT%H%M%S");
 776    usb_mtp_add_str(data, thenstr);
 777}
 778
 779/* ----------------------------------------------------------------------- */
 780
 781static 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)
 784{
 785    MTPControl *c = g_new0(MTPControl, 1);
 786
 787    c->code  = code;
 788    c->trans = trans;
 789    c->argc  = argc;
 790    if (argc > 0) {
 791        c->argv[0] = arg0;
 792    }
 793    if (argc > 1) {
 794        c->argv[1] = arg1;
 795    }
 796    if (argc > 2) {
 797        c->argv[2] = arg2;
 798    }
 799
 800    assert(s->result == NULL);
 801    s->result = c;
 802}
 803
 804/* ----------------------------------------------------------------------- */
 805
 806static MTPData *usb_mtp_get_device_info(MTPState *s, MTPControl *c)
 807{
 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,
 825    };
 826    static const uint16_t fmt[] = {
 827        FMT_UNDEFINED_OBJECT,
 828        FMT_ASSOCIATION,
 829    };
 830    MTPData *d = usb_mtp_data_alloc(c);
 831
 832    trace_usb_mtp_op_get_device_info(s->dev.addr);
 833
 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);
 839
 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);
 845
 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");
 850
 851    return d;
 852}
 853
 854static MTPData *usb_mtp_get_storage_ids(MTPState *s, MTPControl *c)
 855{
 856    static const uint32_t ids[] = {
 857        QEMU_STORAGE_ID,
 858    };
 859    MTPData *d = usb_mtp_data_alloc(c);
 860
 861    trace_usb_mtp_op_get_storage_ids(s->dev.addr);
 862
 863    usb_mtp_add_u32_array(d, ARRAY_SIZE(ids), ids);
 864
 865    return d;
 866}
 867
 868static MTPData *usb_mtp_get_storage_info(MTPState *s, MTPControl *c)
 869{
 870    MTPData *d = usb_mtp_data_alloc(c);
 871    struct statvfs buf;
 872    int rc;
 873
 874    trace_usb_mtp_op_get_storage_info(s->dev.addr);
 875
 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);
 884    }
 885
 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);
 895    }
 896
 897    usb_mtp_add_str(d, s->desc);
 898    usb_mtp_add_wstr(d, L"123456789abcdef");
 899    return d;
 900}
 901
 902static MTPData *usb_mtp_get_object_handles(MTPState *s, MTPControl *c,
 903                                           MTPObject *o)
 904{
 905    MTPData *d = usb_mtp_data_alloc(c);
 906    uint32_t i = 0;
 907    g_autofree uint32_t *handles = g_new(uint32_t, o->nchildren);
 908    MTPObject *iter;
 909
 910    trace_usb_mtp_op_get_object_handles(s->dev.addr, o->handle, o->path);
 911
 912    QLIST_FOREACH(iter, &o->children, list) {
 913        handles[i++] = iter->handle;
 914    }
 915    assert(i == o->nchildren);
 916    usb_mtp_add_u32_array(d, o->nchildren, handles);
 917
 918    return d;
 919}
 920
 921static MTPData *usb_mtp_get_object_info(MTPState *s, MTPControl *c,
 922                                        MTPObject *o)
 923{
 924    MTPData *d = usb_mtp_data_alloc(c);
 925
 926    trace_usb_mtp_op_get_object_info(s->dev.addr, o->handle, o->path);
 927
 928    usb_mtp_add_u32(d, QEMU_STORAGE_ID);
 929    usb_mtp_add_u16(d, o->format);
 930    usb_mtp_add_u16(d, 0);
 931
 932    if (o->stat.st_size > 0xFFFFFFFF) {
 933        usb_mtp_add_u32(d, 0xFFFFFFFF);
 934    } else {
 935        usb_mtp_add_u32(d, o->stat.st_size);
 936    }
 937
 938    usb_mtp_add_u16(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);
 944    usb_mtp_add_u32(d, 0);
 945
 946    if (o->parent) {
 947        usb_mtp_add_u32(d, o->parent->handle);
 948    } else {
 949        usb_mtp_add_u32(d, 0);
 950    }
 951    if (o->format == FMT_ASSOCIATION) {
 952        usb_mtp_add_u16(d, 0x0001);
 953        usb_mtp_add_u32(d, 0x00000001);
 954        usb_mtp_add_u32(d, 0);
 955    } else {
 956        usb_mtp_add_u16(d, 0);
 957        usb_mtp_add_u32(d, 0);
 958        usb_mtp_add_u32(d, 0);
 959    }
 960
 961    usb_mtp_add_str(d, o->name);
 962    usb_mtp_add_time(d, o->stat.st_ctime);
 963    usb_mtp_add_time(d, o->stat.st_mtime);
 964    usb_mtp_add_wstr(d, L"");
 965
 966    return d;
 967}
 968
 969static MTPData *usb_mtp_get_object(MTPState *s, MTPControl *c,
 970                                   MTPObject *o)
 971{
 972    MTPData *d = usb_mtp_data_alloc(c);
 973
 974    trace_usb_mtp_op_get_object(s->dev.addr, o->handle, o->path);
 975
 976    d->fd = open(o->path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
 977    if (d->fd == -1) {
 978        usb_mtp_data_free(d);
 979        return NULL;
 980    }
 981    d->length = o->stat.st_size;
 982    d->alloc  = 512;
 983    d->data   = g_malloc(d->alloc);
 984    return d;
 985}
 986
 987static MTPData *usb_mtp_get_partial_object(MTPState *s, MTPControl *c,
 988                                           MTPObject *o)
 989{
 990    MTPData *d;
 991    off_t offset;
 992
 993    if (c->argc <= 2) {
 994        return NULL;
 995    }
 996    trace_usb_mtp_op_get_partial_object(s->dev.addr, o->handle, o->path,
 997                                        c->argv[1], c->argv[2]);
 998
 999    d = usb_mtp_data_alloc(c);
1000    d->fd = open(o->path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
1001    if (d->fd == -1) {
1002        usb_mtp_data_free(d);
1003        return NULL;
1004    }
1005
1006    offset = c->argv[1];
1007    if (offset > o->stat.st_size) {
1008        offset = o->stat.st_size;
1009    }
1010    if (lseek(d->fd, offset, SEEK_SET) < 0) {
1011        usb_mtp_data_free(d);
1012        return NULL;
1013    }
1014
1015    d->length = c->argv[2];
1016    if (d->length > o->stat.st_size - offset) {
1017        d->length = o->stat.st_size - offset;
1018    }
1019
1020    return d;
1021}
1022
1023static MTPData *usb_mtp_get_object_props_supported(MTPState *s, MTPControl *c)
1024{
1025    static const uint16_t props[] = {
1026        PROP_STORAGE_ID,
1027        PROP_OBJECT_FORMAT,
1028        PROP_OBJECT_COMPRESSED_SIZE,
1029        PROP_PARENT_OBJECT,
1030        PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER,
1031        PROP_NAME,
1032    };
1033    MTPData *d = usb_mtp_data_alloc(c);
1034    usb_mtp_add_u16_array(d, ARRAY_SIZE(props), props);
1035
1036    return d;
1037}
1038
1039static MTPData *usb_mtp_get_object_prop_desc(MTPState *s, MTPControl *c)
1040{
1041    MTPData *d = usb_mtp_data_alloc(c);
1042    switch (c->argv[0]) {
1043    case PROP_STORAGE_ID:
1044        usb_mtp_add_u16(d, PROP_STORAGE_ID);
1045        usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1046        usb_mtp_add_u8(d, 0x00);
1047        usb_mtp_add_u32(d, 0x00000000);
1048        usb_mtp_add_u32(d, 0x00000000);
1049        usb_mtp_add_u8(d, 0x00);
1050        break;
1051    case PROP_OBJECT_FORMAT:
1052        usb_mtp_add_u16(d, PROP_OBJECT_FORMAT);
1053        usb_mtp_add_u16(d, DATA_TYPE_UINT16);
1054        usb_mtp_add_u8(d, 0x00);
1055        usb_mtp_add_u16(d, 0x0000);
1056        usb_mtp_add_u32(d, 0x00000000);
1057        usb_mtp_add_u8(d, 0x00);
1058        break;
1059    case PROP_OBJECT_COMPRESSED_SIZE:
1060        usb_mtp_add_u16(d, PROP_OBJECT_COMPRESSED_SIZE);
1061        usb_mtp_add_u16(d, DATA_TYPE_UINT64);
1062        usb_mtp_add_u8(d, 0x00);
1063        usb_mtp_add_u64(d, 0x0000000000000000);
1064        usb_mtp_add_u32(d, 0x00000000);
1065        usb_mtp_add_u8(d, 0x00);
1066        break;
1067    case PROP_PARENT_OBJECT:
1068        usb_mtp_add_u16(d, PROP_PARENT_OBJECT);
1069        usb_mtp_add_u16(d, DATA_TYPE_UINT32);
1070        usb_mtp_add_u8(d, 0x00);
1071        usb_mtp_add_u32(d, 0x00000000);
1072        usb_mtp_add_u32(d, 0x00000000);
1073        usb_mtp_add_u8(d, 0x00);
1074        break;
1075    case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1076        usb_mtp_add_u16(d, PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER);
1077        usb_mtp_add_u16(d, DATA_TYPE_UINT128);
1078        usb_mtp_add_u8(d, 0x00);
1079        usb_mtp_add_u64(d, 0x0000000000000000);
1080        usb_mtp_add_u64(d, 0x0000000000000000);
1081        usb_mtp_add_u32(d, 0x00000000);
1082        usb_mtp_add_u8(d, 0x00);
1083        break;
1084    case PROP_NAME:
1085        usb_mtp_add_u16(d, PROP_NAME);
1086        usb_mtp_add_u16(d, DATA_TYPE_STRING);
1087        usb_mtp_add_u8(d, 0x00);
1088        usb_mtp_add_u8(d, 0x00);
1089        usb_mtp_add_u32(d, 0x00000000);
1090        usb_mtp_add_u8(d, 0x00);
1091        break;
1092    default:
1093        usb_mtp_data_free(d);
1094        return NULL;
1095    }
1096
1097    return d;
1098}
1099
1100static MTPData *usb_mtp_get_object_prop_value(MTPState *s, MTPControl *c,
1101                                              MTPObject *o)
1102{
1103    MTPData *d = usb_mtp_data_alloc(c);
1104    switch (c->argv[1]) {
1105    case PROP_STORAGE_ID:
1106        usb_mtp_add_u32(d, QEMU_STORAGE_ID);
1107        break;
1108    case PROP_OBJECT_FORMAT:
1109        usb_mtp_add_u16(d, o->format);
1110        break;
1111    case PROP_OBJECT_COMPRESSED_SIZE:
1112        usb_mtp_add_u64(d, o->stat.st_size);
1113        break;
1114    case PROP_PARENT_OBJECT:
1115        if (o->parent == NULL) {
1116            usb_mtp_add_u32(d, 0x00000000);
1117        } else {
1118            usb_mtp_add_u32(d, o->parent->handle);
1119        }
1120        break;
1121    case PROP_PERSISTENT_UNIQUE_OBJECT_IDENTIFIER:
1122        /* Should be persistent between sessions,
1123         * but using our objedt ID is "good enough"
1124         * for now */
1125        usb_mtp_add_u64(d, 0x0000000000000000);
1126        usb_mtp_add_u64(d, o->handle);
1127        break;
1128    case PROP_NAME:
1129        usb_mtp_add_str(d, o->name);
1130        break;
1131    default:
1132        usb_mtp_data_free(d);
1133        return NULL;
1134    }
1135
1136    return d;
1137}
1138
1139/*
1140 * Return values when object @o is deleted.
1141 * If at least one of the deletions succeeded,
1142 * DELETE_SUCCESS is set and if at least one
1143 * of the deletions failed, DELETE_FAILURE is
1144 * set. Both bits being set (DELETE_PARTIAL)
1145 * signifies a  RES_PARTIAL_DELETE being sent
1146 * back to the initiator.
1147 */
1148enum {
1149    DELETE_SUCCESS = (1 << 0),
1150    DELETE_FAILURE = (1 << 1),
1151    DELETE_PARTIAL = (DELETE_FAILURE | DELETE_SUCCESS),
1152};
1153
1154static int usb_mtp_deletefn(MTPState *s, MTPObject *o, uint32_t trans)
1155{
1156    MTPObject *iter, *iter2;
1157    int ret = 0;
1158
1159    /*
1160     * TODO: Add support for Protection Status
1161     */
1162
1163    QLIST_FOREACH(iter, &o->children, list) {
1164        if (iter->format == FMT_ASSOCIATION) {
1165            QLIST_FOREACH(iter2, &iter->children, list) {
1166                ret |= usb_mtp_deletefn(s, iter2, trans);
1167            }
1168        }
1169    }
1170
1171    if (o->format == FMT_UNDEFINED_OBJECT) {
1172        if (remove(o->path)) {
1173            ret |= DELETE_FAILURE;
1174        } else {
1175            usb_mtp_object_free(s, o);
1176            ret |= DELETE_SUCCESS;
1177        }
1178    } else if (o->format == FMT_ASSOCIATION) {
1179        if (rmdir(o->path)) {
1180            ret |= DELETE_FAILURE;
1181        } else {
1182            usb_mtp_object_free(s, o);
1183            ret |= DELETE_SUCCESS;
1184        }
1185    }
1186
1187    return ret;
1188}
1189
1190static void usb_mtp_object_delete(MTPState *s, uint32_t handle,
1191                                  uint32_t format_code, uint32_t trans)
1192{
1193    MTPObject *o;
1194    int ret;
1195
1196    /* Return error if store is read-only */
1197    if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1198        usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1199                             trans, 0, 0, 0, 0);
1200        return;
1201    }
1202
1203    if (format_code != 0) {
1204        usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1205                             trans, 0, 0, 0, 0);
1206        return;
1207    }
1208
1209    if (handle == 0xFFFFFFF) {
1210        o = QTAILQ_FIRST(&s->objects);
1211    } else {
1212        o = usb_mtp_object_lookup(s, handle);
1213    }
1214    if (o == NULL) {
1215        usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1216                             trans, 0, 0, 0, 0);
1217        return;
1218    }
1219
1220    ret = usb_mtp_deletefn(s, o, trans);
1221    switch (ret) {
1222    case DELETE_SUCCESS:
1223        usb_mtp_queue_result(s, RES_OK, trans,
1224                             0, 0, 0, 0);
1225        break;
1226    case DELETE_FAILURE:
1227        usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1228                             trans, 0, 0, 0, 0);
1229        break;
1230    case DELETE_PARTIAL:
1231        usb_mtp_queue_result(s, RES_PARTIAL_DELETE,
1232                             trans, 0, 0, 0, 0);
1233        break;
1234    default:
1235        g_assert_not_reached();
1236    }
1237
1238    return;
1239}
1240
1241static void usb_mtp_command(MTPState *s, MTPControl *c)
1242{
1243    MTPData *data_in = NULL;
1244    MTPObject *o = NULL;
1245    uint32_t nres = 0, res0 = 0;
1246    Error *err = NULL;
1247
1248    /* sanity checks */
1249    if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {
1250        usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,
1251                             c->trans, 0, 0, 0, 0);
1252        return;
1253    }
1254
1255    /* process commands */
1256    switch (c->code) {
1257    case CMD_GET_DEVICE_INFO:
1258        data_in = usb_mtp_get_device_info(s, c);
1259        break;
1260    case CMD_OPEN_SESSION:
1261        if (s->session) {
1262            usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,
1263                                 c->trans, 1, s->session, 0, 0);
1264            return;
1265        }
1266        if (c->argv[0] == 0) {
1267            usb_mtp_queue_result(s, RES_INVALID_PARAMETER,
1268                                 c->trans, 0, 0, 0, 0);
1269            return;
1270        }
1271        trace_usb_mtp_op_open_session(s->dev.addr);
1272        s->session = c->argv[0];
1273        usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);
1274
1275        s->file_monitor = qemu_file_monitor_new(&err);
1276        if (err) {
1277            error_reportf_err(err,
1278                              "usb-mtp: file monitoring init failed: ");
1279        } else {
1280            QTAILQ_INIT(&s->events);
1281        }
1282        break;
1283    case CMD_CLOSE_SESSION:
1284        trace_usb_mtp_op_close_session(s->dev.addr);
1285        s->session = 0;
1286        s->next_handle = 0;
1287        usb_mtp_file_monitor_cleanup(s);
1288        usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1289        assert(QTAILQ_EMPTY(&s->objects));
1290        break;
1291    case CMD_GET_STORAGE_IDS:
1292        data_in = usb_mtp_get_storage_ids(s, c);
1293        break;
1294    case CMD_GET_STORAGE_INFO:
1295        if (c->argv[0] != QEMU_STORAGE_ID &&
1296            c->argv[0] != 0xffffffff) {
1297            usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1298                                 c->trans, 0, 0, 0, 0);
1299            return;
1300        }
1301        data_in = usb_mtp_get_storage_info(s, c);
1302        break;
1303    case CMD_GET_NUM_OBJECTS:
1304    case CMD_GET_OBJECT_HANDLES:
1305        if (c->argv[0] != QEMU_STORAGE_ID &&
1306            c->argv[0] != 0xffffffff) {
1307            usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,
1308                                 c->trans, 0, 0, 0, 0);
1309            return;
1310        }
1311        if (c->argv[1] != 0x00000000) {
1312            usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,
1313                                 c->trans, 0, 0, 0, 0);
1314            return;
1315        }
1316        if (c->argv[2] == 0x00000000 ||
1317            c->argv[2] == 0xffffffff) {
1318            o = QTAILQ_FIRST(&s->objects);
1319        } else {
1320            o = usb_mtp_object_lookup(s, c->argv[2]);
1321        }
1322        if (o == NULL) {
1323            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1324                                 c->trans, 0, 0, 0, 0);
1325            return;
1326        }
1327        if (o->format != FMT_ASSOCIATION) {
1328            usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,
1329                                 c->trans, 0, 0, 0, 0);
1330            return;
1331        }
1332        usb_mtp_object_readdir(s, o);
1333        if (c->code == CMD_GET_NUM_OBJECTS) {
1334            trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);
1335            nres = 1;
1336            res0 = o->nchildren;
1337        } else {
1338            data_in = usb_mtp_get_object_handles(s, c, o);
1339        }
1340        break;
1341    case CMD_GET_OBJECT_INFO:
1342        o = usb_mtp_object_lookup(s, c->argv[0]);
1343        if (o == NULL) {
1344            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1345                                 c->trans, 0, 0, 0, 0);
1346            return;
1347        }
1348        data_in = usb_mtp_get_object_info(s, c, o);
1349        break;
1350    case CMD_GET_OBJECT:
1351        o = usb_mtp_object_lookup(s, c->argv[0]);
1352        if (o == NULL) {
1353            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1354                                 c->trans, 0, 0, 0, 0);
1355            return;
1356        }
1357        if (o->format == FMT_ASSOCIATION) {
1358            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1359                                 c->trans, 0, 0, 0, 0);
1360            return;
1361        }
1362        data_in = usb_mtp_get_object(s, c, o);
1363        if (data_in == NULL) {
1364            usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1365                                 c->trans, 0, 0, 0, 0);
1366            return;
1367        }
1368        break;
1369    case CMD_DELETE_OBJECT:
1370        usb_mtp_object_delete(s, c->argv[0], c->argv[1], c->trans);
1371        return;
1372    case CMD_GET_PARTIAL_OBJECT:
1373        o = usb_mtp_object_lookup(s, c->argv[0]);
1374        if (o == NULL) {
1375            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1376                                 c->trans, 0, 0, 0, 0);
1377            return;
1378        }
1379        if (o->format == FMT_ASSOCIATION) {
1380            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1381                                 c->trans, 0, 0, 0, 0);
1382            return;
1383        }
1384        data_in = usb_mtp_get_partial_object(s, c, o);
1385        if (data_in == NULL) {
1386            usb_mtp_queue_result(s, RES_GENERAL_ERROR,
1387                                 c->trans, 0, 0, 0, 0);
1388            return;
1389        }
1390        nres = 1;
1391        res0 = data_in->length;
1392        break;
1393    case CMD_SEND_OBJECT_INFO:
1394        /* Return error if store is read-only */
1395        if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1396            usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1397                                 c->trans, 0, 0, 0, 0);
1398        } else if (c->argv[0] && (c->argv[0] != QEMU_STORAGE_ID)) {
1399            /* First parameter points to storage id or is 0 */
1400            usb_mtp_queue_result(s, RES_STORE_NOT_AVAILABLE, c->trans,
1401                                 0, 0, 0, 0);
1402        } else if (c->argv[1] && !c->argv[0]) {
1403            /* If second parameter is specified, first must also be specified */
1404            usb_mtp_queue_result(s, RES_DESTINATION_UNSUPPORTED, c->trans,
1405                                 0, 0, 0, 0);
1406        } else {
1407            uint32_t handle = c->argv[1];
1408            if (handle == 0xFFFFFFFF || handle == 0) {
1409                /* root object */
1410                o = QTAILQ_FIRST(&s->objects);
1411            } else {
1412                o = usb_mtp_object_lookup(s, handle);
1413            }
1414            if (o == NULL) {
1415                usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE, c->trans,
1416                                     0, 0, 0, 0);
1417            } else if (o->format != FMT_ASSOCIATION) {
1418                usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT, c->trans,
1419                                     0, 0, 0, 0);
1420            }
1421        }
1422        if (o) {
1423            s->dataset.parent_handle = o->handle;
1424        }
1425        s->data_out = usb_mtp_data_alloc(c);
1426        return;
1427    case CMD_SEND_OBJECT:
1428        if (!FLAG_SET(s, MTP_FLAG_WRITABLE)) {
1429            usb_mtp_queue_result(s, RES_STORE_READ_ONLY,
1430                                 c->trans, 0, 0, 0, 0);
1431            return;
1432        }
1433        if (!s->write_pending) {
1434            usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO,
1435                                 c->trans, 0, 0, 0, 0);
1436            return;
1437        }
1438        s->data_out = usb_mtp_data_alloc(c);
1439        return;
1440    case CMD_GET_OBJECT_PROPS_SUPPORTED:
1441        if (c->argv[0] != FMT_UNDEFINED_OBJECT &&
1442            c->argv[0] != FMT_ASSOCIATION) {
1443            usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1444                                 c->trans, 0, 0, 0, 0);
1445            return;
1446        }
1447        data_in = usb_mtp_get_object_props_supported(s, c);
1448        break;
1449    case CMD_GET_OBJECT_PROP_DESC:
1450        if (c->argv[1] != FMT_UNDEFINED_OBJECT &&
1451            c->argv[1] != FMT_ASSOCIATION) {
1452            usb_mtp_queue_result(s, RES_INVALID_OBJECT_FORMAT_CODE,
1453                                 c->trans, 0, 0, 0, 0);
1454            return;
1455        }
1456        data_in = usb_mtp_get_object_prop_desc(s, c);
1457        if (data_in == NULL) {
1458            usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1459                                 c->trans, 0, 0, 0, 0);
1460            return;
1461        }
1462        break;
1463    case CMD_GET_OBJECT_PROP_VALUE:
1464        o = usb_mtp_object_lookup(s, c->argv[0]);
1465        if (o == NULL) {
1466            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,
1467                                 c->trans, 0, 0, 0, 0);
1468            return;
1469        }
1470        data_in = usb_mtp_get_object_prop_value(s, c, o);
1471        if (data_in == NULL) {
1472            usb_mtp_queue_result(s, RES_INVALID_OBJECT_PROP_CODE,
1473                                 c->trans, 0, 0, 0, 0);
1474            return;
1475        }
1476        break;
1477    default:
1478        trace_usb_mtp_op_unknown(s->dev.addr, c->code);
1479        usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,
1480                             c->trans, 0, 0, 0, 0);
1481        return;
1482    }
1483
1484    /* return results on success */
1485    if (data_in) {
1486        assert(s->data_in == NULL);
1487        s->data_in = data_in;
1488    }
1489    usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0, 0);
1490}
1491
1492/* ----------------------------------------------------------------------- */
1493
1494static void usb_mtp_handle_reset(USBDevice *dev)
1495{
1496    MTPState *s = USB_MTP(dev);
1497
1498    trace_usb_mtp_reset(s->dev.addr);
1499
1500    usb_mtp_file_monitor_cleanup(s);
1501    usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));
1502    s->session = 0;
1503    usb_mtp_data_free(s->data_in);
1504    s->data_in = NULL;
1505    usb_mtp_data_free(s->data_out);
1506    s->data_out = NULL;
1507    g_free(s->result);
1508    s->result = NULL;
1509}
1510
1511static void usb_mtp_handle_control(USBDevice *dev, USBPacket *p,
1512                                   int request, int value, int index,
1513                                   int length, uint8_t *data)
1514{
1515    int ret;
1516    MTPState *s = USB_MTP(dev);
1517    uint16_t *event = (uint16_t *)data;
1518
1519    switch (request) {
1520    case ClassInterfaceOutRequest | 0x64:
1521        if (*event == EVT_CANCEL_TRANSACTION) {
1522            g_free(s->result);
1523            s->result = NULL;
1524            usb_mtp_data_free(s->data_in);
1525            s->data_in = NULL;
1526            if (s->write_pending) {
1527                g_free(s->dataset.filename);
1528                s->write_pending = false;
1529                s->dataset.size = 0;
1530            }
1531            usb_mtp_data_free(s->data_out);
1532            s->data_out = NULL;
1533        } else {
1534            p->status = USB_RET_STALL;
1535        }
1536        break;
1537    default:
1538        ret = usb_desc_handle_control(dev, p, request,
1539                                      value, index, length, data);
1540        if (ret >= 0) {
1541            return;
1542        }
1543    }
1544
1545    trace_usb_mtp_stall(dev->addr, "unknown control request");
1546}
1547
1548static void usb_mtp_cancel_packet(USBDevice *dev, USBPacket *p)
1549{
1550    /* we don't use async packets, so this should never be called */
1551    fprintf(stderr, "%s\n", __func__);
1552}
1553
1554static char *utf16_to_str(uint8_t len, uint8_t *str16)
1555{
1556    wchar_t *wstr = g_new0(wchar_t, len + 1);
1557    int count, dlen;
1558    char *dest;
1559
1560    for (count = 0; count < len; count++) {
1561        /* FIXME: not working for surrogate pairs */
1562        wstr[count] = lduw_le_p(str16 + (count * 2));
1563    }
1564    wstr[count] = 0;
1565
1566    dlen = wcstombs(NULL, wstr, 0) + 1;
1567    dest = g_malloc(dlen);
1568    wcstombs(dest, wstr, dlen);
1569    g_free(wstr);
1570    return dest;
1571}
1572
1573/* Wrapper around write, returns 0 on failure */
1574static uint64_t write_retry(int fd, void *buf, uint64_t size, off_t offset)
1575{
1576        uint64_t ret = 0;
1577
1578        if (lseek(fd, offset, SEEK_SET) < 0) {
1579            goto done;
1580        }
1581
1582        ret = qemu_write_full(fd, buf, size);
1583
1584done:
1585        return ret;
1586}
1587
1588static int usb_mtp_update_object(MTPObject *parent, char *name)
1589{
1590    int ret = 0;
1591
1592    MTPObject *o =
1593        usb_mtp_object_lookup_name(parent, name, strlen(name));
1594
1595    if (o) {
1596        ret = lstat(o->path, &o->stat);
1597    }
1598
1599    return ret;
1600}
1601
1602static void usb_mtp_write_data(MTPState *s, uint32_t handle)
1603{
1604    MTPData *d = s->data_out;
1605    MTPObject *parent =
1606        usb_mtp_object_lookup(s, s->dataset.parent_handle);
1607    char *path = NULL;
1608    uint64_t rc;
1609    mode_t mask = 0755;
1610    int ret = 0;
1611
1612    assert(d != NULL);
1613
1614    switch (d->write_status) {
1615    case WRITE_START:
1616        if (!parent || !s->write_pending) {
1617            usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, d->trans,
1618                0, 0, 0, 0);
1619            return;
1620        }
1621
1622        if (s->dataset.filename) {
1623            path = g_strdup_printf("%s/%s", parent->path, s->dataset.filename);
1624            if (s->dataset.format == FMT_ASSOCIATION) {
1625                ret = g_mkdir(path, mask);
1626                if (!ret) {
1627                    usb_mtp_queue_result(s, RES_OK, d->trans, 3,
1628                                         QEMU_STORAGE_ID,
1629                                         s->dataset.parent_handle,
1630                                         handle);
1631                    goto close;
1632                }
1633                goto done;
1634            }
1635
1636            d->fd = open(path, O_CREAT | O_WRONLY |
1637                         O_CLOEXEC | O_NOFOLLOW, mask & 0666);
1638            if (d->fd == -1) {
1639                ret = 1;
1640                goto done;
1641            }
1642
1643            /* Return success if initiator sent 0 sized data */
1644            if (!s->dataset.size) {
1645                goto done;
1646            }
1647            if (d->length != MTP_WRITE_BUF_SZ && !d->pending) {
1648                d->write_status = WRITE_END;
1649            }
1650        }
1651        /* fall through */
1652    case WRITE_CONTINUE:
1653    case WRITE_END:
1654        rc = write_retry(d->fd, d->data, d->data_offset,
1655                         d->offset - d->data_offset);
1656        if (rc != d->data_offset) {
1657            ret = 1;
1658            goto done;
1659        }
1660        if (d->write_status != WRITE_END) {
1661            g_free(path);
1662            return;
1663        } else {
1664            /*
1665             * Return an incomplete transfer if file size doesn't match
1666             * for < 4G file or if lstat fails which will result in an incorrect
1667             * file size
1668             */
1669            if ((s->dataset.size != 0xFFFFFFFF &&
1670                 d->offset != s->dataset.size) ||
1671                usb_mtp_update_object(parent, s->dataset.filename)) {
1672                usb_mtp_queue_result(s, RES_INCOMPLETE_TRANSFER, d->trans,
1673                                     0, 0, 0, 0);
1674                goto close;
1675            }
1676        }
1677    }
1678
1679done:
1680    if (ret) {
1681        usb_mtp_queue_result(s, RES_STORE_FULL, d->trans,
1682                             0, 0, 0, 0);
1683    } else {
1684        usb_mtp_queue_result(s, RES_OK, d->trans,
1685                             0, 0, 0, 0);
1686    }
1687close:
1688    /*
1689     * The write dataset is kept around and freed only
1690     * on success or if another write request comes in
1691     */
1692    if (d->fd != -1) {
1693        close(d->fd);
1694        d->fd = -1;
1695    }
1696    g_free(s->dataset.filename);
1697    s->dataset.size = 0;
1698    g_free(path);
1699    s->write_pending = false;
1700}
1701
1702static void usb_mtp_write_metadata(MTPState *s, uint64_t dlen)
1703{
1704    MTPData *d = s->data_out;
1705    ObjectInfo *dataset = (ObjectInfo *)d->data;
1706    char *filename;
1707    MTPObject *o;
1708    MTPObject *p = usb_mtp_object_lookup(s, s->dataset.parent_handle);
1709    uint32_t next_handle = s->next_handle;
1710    size_t filename_chars = dlen - offsetof(ObjectInfo, filename);
1711
1712    /*
1713     * filename is utf-16. We're intentionally doing
1714     * integer division to truncate if malicious guest
1715     * sent an odd number of bytes.
1716     */
1717    filename_chars /= 2;
1718
1719    assert(!s->write_pending);
1720    assert(p != NULL);
1721
1722    filename = utf16_to_str(MIN(dataset->length, filename_chars),
1723                            dataset->filename);
1724
1725    if (strchr(filename, '/')) {
1726        usb_mtp_queue_result(s, RES_PARAMETER_NOT_SUPPORTED, d->trans,
1727                             0, 0, 0, 0);
1728        g_free(filename);
1729        return;
1730    }
1731
1732    o = usb_mtp_object_lookup_name(p, filename, -1);
1733    if (o != NULL) {
1734        next_handle = o->handle;
1735    }
1736
1737    s->dataset.filename = filename;
1738    s->dataset.format = dataset->format;
1739    s->dataset.size = dataset->size;
1740    s->write_pending = true;
1741
1742    if (s->dataset.format == FMT_ASSOCIATION) {
1743        usb_mtp_write_data(s, next_handle);
1744    } else {
1745        usb_mtp_queue_result(s, RES_OK, d->trans, 3, QEMU_STORAGE_ID,
1746                             s->dataset.parent_handle, next_handle);
1747    }
1748}
1749
1750static void usb_mtp_get_data(MTPState *s, mtp_container *container,
1751                             USBPacket *p)
1752{
1753    MTPData *d = s->data_out;
1754    uint64_t dlen;
1755    uint32_t data_len = p->iov.size;
1756    uint64_t total_len;
1757
1758    if (!d) {
1759            usb_mtp_queue_result(s, RES_INVALID_OBJECTINFO, 0,
1760                                 0, 0, 0, 0);
1761            return;
1762    }
1763    if (d->first) {
1764        /* Total length of incoming data */
1765        total_len = cpu_to_le32(container->length) - sizeof(mtp_container);
1766        /* Length of data in this packet */
1767        data_len -= sizeof(mtp_container);
1768        if (total_len < MTP_WRITE_BUF_SZ) {
1769                usb_mtp_realloc(d, total_len);
1770                d->length += total_len;
1771        } else {
1772                usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - sizeof(mtp_container));
1773                d->length += MTP_WRITE_BUF_SZ - sizeof(mtp_container);
1774        }
1775        d->offset = 0;
1776        d->first = false;
1777        d->pending = false;
1778        d->data_offset = 0;
1779        d->write_status = WRITE_START;
1780    }
1781
1782    if (d->pending) {
1783        memset(d->data, 0, d->length);
1784        if (d->length != MTP_WRITE_BUF_SZ) {
1785            usb_mtp_realloc(d, MTP_WRITE_BUF_SZ - d->length);
1786            d->length += (MTP_WRITE_BUF_SZ - d->length);
1787        }
1788        d->pending = false;
1789        d->write_status = WRITE_CONTINUE;
1790        d->data_offset = 0;
1791    }
1792
1793    if (d->length - d->data_offset > data_len) {
1794        dlen = data_len;
1795    } else {
1796        dlen = d->length - d->data_offset;
1797    }
1798
1799    switch (d->code) {
1800    case CMD_SEND_OBJECT_INFO:
1801        usb_packet_copy(p, d->data + d->data_offset, dlen);
1802        d->offset += dlen;
1803        d->data_offset += dlen;
1804        if (d->data_offset == d->length) {
1805            /* The operation might have already failed */
1806            if (!s->result) {
1807                usb_mtp_write_metadata(s, dlen);
1808            }
1809            usb_mtp_data_free(s->data_out);
1810            s->data_out = NULL;
1811            return;
1812        }
1813        break;
1814    case CMD_SEND_OBJECT:
1815        usb_packet_copy(p, d->data + d->data_offset, dlen);
1816        d->offset += dlen;
1817        d->data_offset += dlen;
1818        if ((p->iov.size % 64) || !p->iov.size) {
1819            assert((s->dataset.size == 0xFFFFFFFF) ||
1820                   (s->dataset.size == d->offset));
1821
1822            if (d->length == MTP_WRITE_BUF_SZ) {
1823                d->write_status = WRITE_END;
1824            } else {
1825                d->write_status = WRITE_START;
1826            }
1827            usb_mtp_write_data(s, 0);
1828            usb_mtp_data_free(s->data_out);
1829            s->data_out = NULL;
1830            return;
1831        }
1832        if (d->data_offset == d->length) {
1833            d->pending = true;
1834            usb_mtp_write_data(s, 0);
1835        }
1836        break;
1837    default:
1838        p->status = USB_RET_STALL;
1839        return;
1840    }
1841}
1842
1843static void usb_mtp_handle_data(USBDevice *dev, USBPacket *p)
1844{
1845    MTPState *s = USB_MTP(dev);
1846    MTPControl cmd;
1847    mtp_container container;
1848    uint32_t params[5];
1849    uint16_t container_type;
1850    int i, rc;
1851
1852    switch (p->ep->nr) {
1853    case EP_DATA_IN:
1854        if (s->data_out != NULL) {
1855            /* guest bug */
1856            trace_usb_mtp_stall(s->dev.addr, "awaiting data-out");
1857            p->status = USB_RET_STALL;
1858            return;
1859        }
1860        if (p->iov.size < sizeof(container)) {
1861            trace_usb_mtp_stall(s->dev.addr, "packet too small");
1862            p->status = USB_RET_STALL;
1863            return;
1864        }
1865        if (s->data_in !=  NULL) {
1866            MTPData *d = s->data_in;
1867            uint64_t dlen = d->length - d->offset;
1868            if (d->first) {
1869                trace_usb_mtp_data_in(s->dev.addr, d->trans, d->length);
1870                if (d->length + sizeof(container) > 0xFFFFFFFF) {
1871                    container.length = cpu_to_le32(0xFFFFFFFF);
1872                } else {
1873                    container.length =
1874                        cpu_to_le32(d->length + sizeof(container));
1875                }
1876                container.type   = cpu_to_le16(TYPE_DATA);
1877                container.code   = cpu_to_le16(d->code);
1878                container.trans  = cpu_to_le32(d->trans);
1879                usb_packet_copy(p, &container, sizeof(container));
1880                d->first = false;
1881                if (dlen > p->iov.size - sizeof(container)) {
1882                    dlen = p->iov.size - sizeof(container);
1883                }
1884            } else {
1885                if (dlen > p->iov.size) {
1886                    dlen = p->iov.size;
1887                }
1888            }
1889            if (d->fd == -1) {
1890                usb_packet_copy(p, d->data + d->offset, dlen);
1891            } else {
1892                if (d->alloc < p->iov.size) {
1893                    d->alloc = p->iov.size;
1894                    d->data = g_realloc(d->data, d->alloc);
1895                }
1896                rc = read(d->fd, d->data, dlen);
1897                if (rc != dlen) {
1898                    memset(d->data, 0, dlen);
1899                    s->result->code = RES_INCOMPLETE_TRANSFER;
1900                }
1901                usb_packet_copy(p, d->data, dlen);
1902            }
1903            d->offset += dlen;
1904            if (d->offset == d->length) {
1905                usb_mtp_data_free(s->data_in);
1906                s->data_in = NULL;
1907            }
1908        } else if (s->result != NULL) {
1909            MTPControl *r = s->result;
1910            int length = sizeof(container) + r->argc * sizeof(uint32_t);
1911            if (r->code == RES_OK) {
1912                trace_usb_mtp_success(s->dev.addr, r->trans,
1913                                      (r->argc > 0) ? r->argv[0] : 0,
1914                                      (r->argc > 1) ? r->argv[1] : 0);
1915            } else {
1916                trace_usb_mtp_error(s->dev.addr, r->code, r->trans,
1917                                    (r->argc > 0) ? r->argv[0] : 0,
1918                                    (r->argc > 1) ? r->argv[1] : 0);
1919            }
1920            container.length = cpu_to_le32(length);
1921            container.type   = cpu_to_le16(TYPE_RESPONSE);
1922            container.code   = cpu_to_le16(r->code);
1923            container.trans  = cpu_to_le32(r->trans);
1924            for (i = 0; i < r->argc; i++) {
1925                params[i] = cpu_to_le32(r->argv[i]);
1926            }
1927            usb_packet_copy(p, &container, sizeof(container));
1928            usb_packet_copy(p, &params, length - sizeof(container));
1929            g_free(s->result);
1930            s->result = NULL;
1931        }
1932        break;
1933    case EP_DATA_OUT:
1934        if (p->iov.size < sizeof(container)) {
1935            trace_usb_mtp_stall(s->dev.addr, "packet too small");
1936            p->status = USB_RET_STALL;
1937            return;
1938        }
1939        if ((s->data_out != NULL) && !s->data_out->first) {
1940            container_type = TYPE_DATA;
1941        } else {
1942            usb_packet_copy(p, &container, sizeof(container));
1943            container_type = le16_to_cpu(container.type);
1944        }
1945        switch (container_type) {
1946        case TYPE_COMMAND:
1947            if (s->data_in || s->data_out || s->result) {
1948                trace_usb_mtp_stall(s->dev.addr, "transaction inflight");
1949                p->status = USB_RET_STALL;
1950                return;
1951            }
1952            cmd.code = le16_to_cpu(container.code);
1953            cmd.argc = (le32_to_cpu(container.length) - sizeof(container))
1954                / sizeof(uint32_t);
1955            cmd.trans = le32_to_cpu(container.trans);
1956            if (cmd.argc > ARRAY_SIZE(cmd.argv)) {
1957                cmd.argc = ARRAY_SIZE(cmd.argv);
1958            }
1959            if (p->iov.size < sizeof(container) + cmd.argc * sizeof(uint32_t)) {
1960                trace_usb_mtp_stall(s->dev.addr, "packet too small");
1961                p->status = USB_RET_STALL;
1962                return;
1963            }
1964            usb_packet_copy(p, &params, cmd.argc * sizeof(uint32_t));
1965            for (i = 0; i < cmd.argc; i++) {
1966                cmd.argv[i] = le32_to_cpu(params[i]);
1967            }
1968            trace_usb_mtp_command(s->dev.addr, cmd.code, cmd.trans,
1969                                  (cmd.argc > 0) ? cmd.argv[0] : 0,
1970                                  (cmd.argc > 1) ? cmd.argv[1] : 0,
1971                                  (cmd.argc > 2) ? cmd.argv[2] : 0,
1972                                  (cmd.argc > 3) ? cmd.argv[3] : 0,
1973                                  (cmd.argc > 4) ? cmd.argv[4] : 0);
1974            usb_mtp_command(s, &cmd);
1975            break;
1976        case TYPE_DATA:
1977            /* One of the previous transfers has already errored but the
1978             * responder is still sending data associated with it
1979             */
1980            if (s->result != NULL) {
1981                return;
1982            }
1983            usb_mtp_get_data(s, &container, p);
1984            break;
1985        default:
1986            /* not needed as long as the mtp device is read-only */
1987            p->status = USB_RET_STALL;
1988            return;
1989        }
1990        break;
1991    case EP_EVENT:
1992        if (!QTAILQ_EMPTY(&s->events)) {
1993            struct MTPMonEntry *e = QTAILQ_LAST(&s->events);
1994            uint32_t handle;
1995            int len = sizeof(container) + sizeof(uint32_t);
1996
1997            if (p->iov.size < len) {
1998                trace_usb_mtp_stall(s->dev.addr,
1999                                    "packet too small to send event");
2000                p->status = USB_RET_STALL;
2001                return;
2002            }
2003
2004            QTAILQ_REMOVE(&s->events, e, next);
2005            container.length = cpu_to_le32(len);
2006            container.type = cpu_to_le32(TYPE_EVENT);
2007            container.code = cpu_to_le16(e->event);
2008            container.trans = 0; /* no trans specific events */
2009            handle = cpu_to_le32(e->handle);
2010            usb_packet_copy(p, &container, sizeof(container));
2011            usb_packet_copy(p, &handle, sizeof(uint32_t));
2012            g_free(e);
2013            return;
2014        }
2015        p->status = USB_RET_NAK;
2016        return;
2017    default:
2018        trace_usb_mtp_stall(s->dev.addr, "invalid endpoint");
2019        p->status = USB_RET_STALL;
2020        return;
2021    }
2022
2023    if (p->actual_length == 0) {
2024        trace_usb_mtp_nak(s->dev.addr, p->ep->nr);
2025        p->status = USB_RET_NAK;
2026        return;
2027    } else {
2028        trace_usb_mtp_xfer(s->dev.addr, p->ep->nr, p->actual_length,
2029                           p->iov.size);
2030        return;
2031    }
2032}
2033
2034static void usb_mtp_realize(USBDevice *dev, Error **errp)
2035{
2036    MTPState *s = USB_MTP(dev);
2037
2038    if ((s->root == NULL) || !g_path_is_absolute(s->root)) {
2039        error_setg(errp, "usb-mtp: rootdir must be configured and be an absolute path");
2040        return;
2041    }
2042
2043    if (access(s->root, R_OK) != 0) {
2044        error_setg(errp, "usb-mtp: rootdir does not exist/not readable");
2045        return;
2046    } else if (!s->readonly && access(s->root, W_OK) != 0) {
2047        error_setg(errp, "usb-mtp: rootdir does not have write permissions");
2048        return;
2049    }
2050
2051    /* Mark store as RW */
2052    if (!s->readonly) {
2053        s->flags |= (1 << MTP_FLAG_WRITABLE);
2054    }
2055
2056    if (s->desc == NULL) {
2057        /*
2058         * This does not check if path exists
2059         * but we have the checks above
2060         */
2061        s->desc = g_path_get_basename(s->root);
2062    }
2063
2064    usb_desc_create_serial(dev);
2065    usb_desc_init(dev);
2066    QTAILQ_INIT(&s->objects);
2067
2068}
2069
2070static const VMStateDescription vmstate_usb_mtp = {
2071    .name = "usb-mtp",
2072    .unmigratable = 1,
2073    .version_id = 1,
2074    .minimum_version_id = 1,
2075    .fields = (VMStateField[]) {
2076        VMSTATE_USB_DEVICE(dev, MTPState),
2077        VMSTATE_END_OF_LIST()
2078    }
2079};
2080
2081static Property mtp_properties[] = {
2082    DEFINE_PROP_STRING("rootdir", MTPState, root),
2083    DEFINE_PROP_STRING("desc", MTPState, desc),
2084    DEFINE_PROP_BOOL("readonly", MTPState, readonly, true),
2085    DEFINE_PROP_END_OF_LIST(),
2086};
2087
2088static void usb_mtp_class_initfn(ObjectClass *klass, void *data)
2089{
2090    DeviceClass *dc = DEVICE_CLASS(klass);
2091    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
2092
2093    uc->realize        = usb_mtp_realize;
2094    uc->product_desc   = "QEMU USB MTP";
2095    uc->usb_desc       = &desc;
2096    uc->cancel_packet  = usb_mtp_cancel_packet;
2097    uc->handle_attach  = usb_desc_attach;
2098    uc->handle_reset   = usb_mtp_handle_reset;
2099    uc->handle_control = usb_mtp_handle_control;
2100    uc->handle_data    = usb_mtp_handle_data;
2101    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2102    dc->desc = "USB Media Transfer Protocol device";
2103    dc->fw_name = "mtp";
2104    dc->vmsd = &vmstate_usb_mtp;
2105    device_class_set_props(dc, mtp_properties);
2106}
2107
2108static const TypeInfo mtp_info = {
2109    .name          = TYPE_USB_MTP,
2110    .parent        = TYPE_USB_DEVICE,
2111    .instance_size = sizeof(MTPState),
2112    .class_init    = usb_mtp_class_initfn,
2113};
2114
2115static void usb_mtp_register_types(void)
2116{
2117    type_register_static(&mtp_info);
2118}
2119
2120type_init(usb_mtp_register_types)
2121