qemu/qga/commands-win32.c
<<
>>
Prefs
   1/*
   2 * QEMU Guest Agent win32-specific command implementations
   3 *
   4 * Copyright IBM Corp. 2012
   5 *
   6 * Authors:
   7 *  Michael Roth      <mdroth@linux.vnet.ibm.com>
   8 *  Gal Hammer        <ghammer@redhat.com>
   9 *
  10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
  11 * See the COPYING file in the top-level directory.
  12 */
  13#include "qemu/osdep.h"
  14
  15#include <wtypes.h>
  16#include <powrprof.h>
  17#include <winsock2.h>
  18#include <ws2tcpip.h>
  19#include <iptypes.h>
  20#include <iphlpapi.h>
  21#ifdef CONFIG_QGA_NTDDSCSI
  22#include <winioctl.h>
  23#include <ntddscsi.h>
  24#include <setupapi.h>
  25#include <cfgmgr32.h>
  26#include <initguid.h>
  27#endif
  28#include <lm.h>
  29#include <wtsapi32.h>
  30#include <wininet.h>
  31
  32#include "guest-agent-core.h"
  33#include "vss-win32.h"
  34#include "qga-qapi-commands.h"
  35#include "qapi/error.h"
  36#include "qapi/qmp/qerror.h"
  37#include "qemu/queue.h"
  38#include "qemu/host-utils.h"
  39#include "qemu/base64.h"
  40
  41#ifndef SHTDN_REASON_FLAG_PLANNED
  42#define SHTDN_REASON_FLAG_PLANNED 0x80000000
  43#endif
  44
  45/* multiple of 100 nanoseconds elapsed between windows baseline
  46 *    (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
  47#define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
  48                       (365 * (1970 - 1601) +       \
  49                        (1970 - 1601) / 4 - 3))
  50
  51#define INVALID_SET_FILE_POINTER ((DWORD)-1)
  52
  53typedef struct GuestFileHandle {
  54    int64_t id;
  55    HANDLE fh;
  56    QTAILQ_ENTRY(GuestFileHandle) next;
  57} GuestFileHandle;
  58
  59static struct {
  60    QTAILQ_HEAD(, GuestFileHandle) filehandles;
  61} guest_file_state = {
  62    .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
  63};
  64
  65#define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
  66
  67typedef struct OpenFlags {
  68    const char *forms;
  69    DWORD desired_access;
  70    DWORD creation_disposition;
  71} OpenFlags;
  72static OpenFlags guest_file_open_modes[] = {
  73    {"r",   GENERIC_READ,                     OPEN_EXISTING},
  74    {"rb",  GENERIC_READ,                     OPEN_EXISTING},
  75    {"w",   GENERIC_WRITE,                    CREATE_ALWAYS},
  76    {"wb",  GENERIC_WRITE,                    CREATE_ALWAYS},
  77    {"a",   FILE_GENERIC_APPEND,              OPEN_ALWAYS  },
  78    {"r+",  GENERIC_WRITE|GENERIC_READ,       OPEN_EXISTING},
  79    {"rb+", GENERIC_WRITE|GENERIC_READ,       OPEN_EXISTING},
  80    {"r+b", GENERIC_WRITE|GENERIC_READ,       OPEN_EXISTING},
  81    {"w+",  GENERIC_WRITE|GENERIC_READ,       CREATE_ALWAYS},
  82    {"wb+", GENERIC_WRITE|GENERIC_READ,       CREATE_ALWAYS},
  83    {"w+b", GENERIC_WRITE|GENERIC_READ,       CREATE_ALWAYS},
  84    {"a+",  FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS  },
  85    {"ab+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS  },
  86    {"a+b", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS  }
  87};
  88
  89#define debug_error(msg) do { \
  90    char *suffix = g_win32_error_message(GetLastError()); \
  91    g_debug("%s: %s", (msg), suffix); \
  92    g_free(suffix); \
  93} while (0)
  94
  95static OpenFlags *find_open_flag(const char *mode_str)
  96{
  97    int mode;
  98    Error **errp = NULL;
  99
 100    for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
 101        OpenFlags *flags = guest_file_open_modes + mode;
 102
 103        if (strcmp(flags->forms, mode_str) == 0) {
 104            return flags;
 105        }
 106    }
 107
 108    error_setg(errp, "invalid file open mode '%s'", mode_str);
 109    return NULL;
 110}
 111
 112static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
 113{
 114    GuestFileHandle *gfh;
 115    int64_t handle;
 116
 117    handle = ga_get_fd_handle(ga_state, errp);
 118    if (handle < 0) {
 119        return -1;
 120    }
 121    gfh = g_new0(GuestFileHandle, 1);
 122    gfh->id = handle;
 123    gfh->fh = fh;
 124    QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
 125
 126    return handle;
 127}
 128
 129static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
 130{
 131    GuestFileHandle *gfh;
 132    QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
 133        if (gfh->id == id) {
 134            return gfh;
 135        }
 136    }
 137    error_setg(errp, "handle '%" PRId64 "' has not been found", id);
 138    return NULL;
 139}
 140
 141static void handle_set_nonblocking(HANDLE fh)
 142{
 143    DWORD file_type, pipe_state;
 144    file_type = GetFileType(fh);
 145    if (file_type != FILE_TYPE_PIPE) {
 146        return;
 147    }
 148    /* If file_type == FILE_TYPE_PIPE, according to MSDN
 149     * the specified file is socket or named pipe */
 150    if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
 151                                 NULL, NULL, NULL, 0)) {
 152        return;
 153    }
 154    /* The fd is named pipe fd */
 155    if (pipe_state & PIPE_NOWAIT) {
 156        return;
 157    }
 158
 159    pipe_state |= PIPE_NOWAIT;
 160    SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
 161}
 162
 163int64_t qmp_guest_file_open(const char *path, bool has_mode,
 164                            const char *mode, Error **errp)
 165{
 166    int64_t fd = -1;
 167    HANDLE fh;
 168    HANDLE templ_file = NULL;
 169    DWORD share_mode = FILE_SHARE_READ;
 170    DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
 171    LPSECURITY_ATTRIBUTES sa_attr = NULL;
 172    OpenFlags *guest_flags;
 173    GError *gerr = NULL;
 174    wchar_t *w_path = NULL;
 175
 176    if (!has_mode) {
 177        mode = "r";
 178    }
 179    slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
 180    guest_flags = find_open_flag(mode);
 181    if (guest_flags == NULL) {
 182        error_setg(errp, "invalid file open mode");
 183        goto done;
 184    }
 185
 186    w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
 187    if (!w_path) {
 188        goto done;
 189    }
 190
 191    fh = CreateFileW(w_path, guest_flags->desired_access, share_mode, sa_attr,
 192                    guest_flags->creation_disposition, flags_and_attr,
 193                    templ_file);
 194    if (fh == INVALID_HANDLE_VALUE) {
 195        error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
 196                         path);
 197        goto done;
 198    }
 199
 200    /* set fd non-blocking to avoid common use cases (like reading from a
 201     * named pipe) from hanging the agent
 202     */
 203    handle_set_nonblocking(fh);
 204
 205    fd = guest_file_handle_add(fh, errp);
 206    if (fd < 0) {
 207        CloseHandle(fh);
 208        error_setg(errp, "failed to add handle to qmp handle table");
 209        goto done;
 210    }
 211
 212    slog("guest-file-open, handle: % " PRId64, fd);
 213
 214done:
 215    if (gerr) {
 216        error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
 217        g_error_free(gerr);
 218    }
 219    g_free(w_path);
 220    return fd;
 221}
 222
 223void qmp_guest_file_close(int64_t handle, Error **errp)
 224{
 225    bool ret;
 226    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
 227    slog("guest-file-close called, handle: %" PRId64, handle);
 228    if (gfh == NULL) {
 229        return;
 230    }
 231    ret = CloseHandle(gfh->fh);
 232    if (!ret) {
 233        error_setg_win32(errp, GetLastError(), "failed close handle");
 234        return;
 235    }
 236
 237    QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
 238    g_free(gfh);
 239}
 240
 241static void acquire_privilege(const char *name, Error **errp)
 242{
 243    HANDLE token = NULL;
 244    TOKEN_PRIVILEGES priv;
 245    Error *local_err = NULL;
 246
 247    if (OpenProcessToken(GetCurrentProcess(),
 248        TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
 249    {
 250        if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
 251            error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
 252                       "no luid for requested privilege");
 253            goto out;
 254        }
 255
 256        priv.PrivilegeCount = 1;
 257        priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
 258
 259        if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
 260            error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
 261                       "unable to acquire requested privilege");
 262            goto out;
 263        }
 264
 265    } else {
 266        error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
 267                   "failed to open privilege token");
 268    }
 269
 270out:
 271    if (token) {
 272        CloseHandle(token);
 273    }
 274    error_propagate(errp, local_err);
 275}
 276
 277static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
 278                          Error **errp)
 279{
 280    Error *local_err = NULL;
 281
 282    HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
 283    if (!thread) {
 284        error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
 285                   "failed to dispatch asynchronous command");
 286        error_propagate(errp, local_err);
 287    }
 288}
 289
 290void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
 291{
 292    Error *local_err = NULL;
 293    UINT shutdown_flag = EWX_FORCE;
 294
 295    slog("guest-shutdown called, mode: %s", mode);
 296
 297    if (!has_mode || strcmp(mode, "powerdown") == 0) {
 298        shutdown_flag |= EWX_POWEROFF;
 299    } else if (strcmp(mode, "halt") == 0) {
 300        shutdown_flag |= EWX_SHUTDOWN;
 301    } else if (strcmp(mode, "reboot") == 0) {
 302        shutdown_flag |= EWX_REBOOT;
 303    } else {
 304        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
 305                   "halt|powerdown|reboot");
 306        return;
 307    }
 308
 309    /* Request a shutdown privilege, but try to shut down the system
 310       anyway. */
 311    acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
 312    if (local_err) {
 313        error_propagate(errp, local_err);
 314        return;
 315    }
 316
 317    if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
 318        slog("guest-shutdown failed: %lu", GetLastError());
 319        error_setg(errp, QERR_UNDEFINED_ERROR);
 320    }
 321}
 322
 323GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
 324                                   int64_t count, Error **errp)
 325{
 326    GuestFileRead *read_data = NULL;
 327    guchar *buf;
 328    HANDLE fh;
 329    bool is_ok;
 330    DWORD read_count;
 331    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
 332
 333    if (!gfh) {
 334        return NULL;
 335    }
 336    if (!has_count) {
 337        count = QGA_READ_COUNT_DEFAULT;
 338    } else if (count < 0 || count >= UINT32_MAX) {
 339        error_setg(errp, "value '%" PRId64
 340                   "' is invalid for argument count", count);
 341        return NULL;
 342    }
 343
 344    fh = gfh->fh;
 345    buf = g_malloc0(count+1);
 346    is_ok = ReadFile(fh, buf, count, &read_count, NULL);
 347    if (!is_ok) {
 348        error_setg_win32(errp, GetLastError(), "failed to read file");
 349        slog("guest-file-read failed, handle %" PRId64, handle);
 350    } else {
 351        buf[read_count] = 0;
 352        read_data = g_new0(GuestFileRead, 1);
 353        read_data->count = (size_t)read_count;
 354        read_data->eof = read_count == 0;
 355
 356        if (read_count != 0) {
 357            read_data->buf_b64 = g_base64_encode(buf, read_count);
 358        }
 359    }
 360    g_free(buf);
 361
 362    return read_data;
 363}
 364
 365GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
 366                                     bool has_count, int64_t count,
 367                                     Error **errp)
 368{
 369    GuestFileWrite *write_data = NULL;
 370    guchar *buf;
 371    gsize buf_len;
 372    bool is_ok;
 373    DWORD write_count;
 374    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
 375    HANDLE fh;
 376
 377    if (!gfh) {
 378        return NULL;
 379    }
 380    fh = gfh->fh;
 381    buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
 382    if (!buf) {
 383        return NULL;
 384    }
 385
 386    if (!has_count) {
 387        count = buf_len;
 388    } else if (count < 0 || count > buf_len) {
 389        error_setg(errp, "value '%" PRId64
 390                   "' is invalid for argument count", count);
 391        goto done;
 392    }
 393
 394    is_ok = WriteFile(fh, buf, count, &write_count, NULL);
 395    if (!is_ok) {
 396        error_setg_win32(errp, GetLastError(), "failed to write to file");
 397        slog("guest-file-write-failed, handle: %" PRId64, handle);
 398    } else {
 399        write_data = g_new0(GuestFileWrite, 1);
 400        write_data->count = (size_t) write_count;
 401    }
 402
 403done:
 404    g_free(buf);
 405    return write_data;
 406}
 407
 408GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
 409                                   GuestFileWhence *whence_code,
 410                                   Error **errp)
 411{
 412    GuestFileHandle *gfh;
 413    GuestFileSeek *seek_data;
 414    HANDLE fh;
 415    LARGE_INTEGER new_pos, off_pos;
 416    off_pos.QuadPart = offset;
 417    BOOL res;
 418    int whence;
 419    Error *err = NULL;
 420
 421    gfh = guest_file_handle_find(handle, errp);
 422    if (!gfh) {
 423        return NULL;
 424    }
 425
 426    /* We stupidly exposed 'whence':'int' in our qapi */
 427    whence = ga_parse_whence(whence_code, &err);
 428    if (err) {
 429        error_propagate(errp, err);
 430        return NULL;
 431    }
 432
 433    fh = gfh->fh;
 434    res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
 435    if (!res) {
 436        error_setg_win32(errp, GetLastError(), "failed to seek file");
 437        return NULL;
 438    }
 439    seek_data = g_new0(GuestFileSeek, 1);
 440    seek_data->position = new_pos.QuadPart;
 441    return seek_data;
 442}
 443
 444void qmp_guest_file_flush(int64_t handle, Error **errp)
 445{
 446    HANDLE fh;
 447    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
 448    if (!gfh) {
 449        return;
 450    }
 451
 452    fh = gfh->fh;
 453    if (!FlushFileBuffers(fh)) {
 454        error_setg_win32(errp, GetLastError(), "failed to flush file");
 455    }
 456}
 457
 458#ifdef CONFIG_QGA_NTDDSCSI
 459
 460static GuestDiskBusType win2qemu[] = {
 461    [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
 462    [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
 463    [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
 464    [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
 465    [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
 466    [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
 467    [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
 468    [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
 469    [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
 470    [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
 471    [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
 472    [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
 473    [BusTypeSd] =  GUEST_DISK_BUS_TYPE_SD,
 474    [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
 475#if (_WIN32_WINNT >= 0x0601)
 476    [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
 477    [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
 478#endif
 479};
 480
 481static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
 482{
 483    if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
 484        return GUEST_DISK_BUS_TYPE_UNKNOWN;
 485    }
 486    return win2qemu[(int)bus];
 487}
 488
 489DEFINE_GUID(GUID_DEVINTERFACE_DISK,
 490        0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2,
 491        0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
 492DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT,
 493        0x2accfe60L, 0xc130, 0x11d2, 0xb0, 0x82,
 494        0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
 495
 496static GuestPCIAddress *get_pci_info(int number, Error **errp)
 497{
 498    HDEVINFO dev_info;
 499    SP_DEVINFO_DATA dev_info_data;
 500    SP_DEVICE_INTERFACE_DATA dev_iface_data;
 501    HANDLE dev_file;
 502    int i;
 503    GuestPCIAddress *pci = NULL;
 504    bool partial_pci = false;
 505
 506    pci = g_malloc0(sizeof(*pci));
 507    pci->domain = -1;
 508    pci->slot = -1;
 509    pci->function = -1;
 510    pci->bus = -1;
 511
 512    dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
 513                                   DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
 514    if (dev_info == INVALID_HANDLE_VALUE) {
 515        error_setg_win32(errp, GetLastError(), "failed to get devices tree");
 516        goto out;
 517    }
 518
 519    g_debug("enumerating devices");
 520    dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
 521    dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
 522    for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
 523        PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
 524        STORAGE_DEVICE_NUMBER sdn;
 525        char *parent_dev_id = NULL;
 526        HDEVINFO parent_dev_info;
 527        SP_DEVINFO_DATA parent_dev_info_data;
 528        DWORD j;
 529        DWORD size = 0;
 530
 531        g_debug("getting device path");
 532        if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
 533                                        &GUID_DEVINTERFACE_DISK, 0,
 534                                        &dev_iface_data)) {
 535            while (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
 536                                                    pdev_iface_detail_data,
 537                                                    size, &size,
 538                                                    &dev_info_data)) {
 539                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
 540                    pdev_iface_detail_data = g_malloc(size);
 541                    pdev_iface_detail_data->cbSize =
 542                        sizeof(*pdev_iface_detail_data);
 543                } else {
 544                    error_setg_win32(errp, GetLastError(),
 545                                     "failed to get device interfaces");
 546                    goto free_dev_info;
 547                }
 548            }
 549
 550            dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
 551                                  FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
 552                                  NULL);
 553            g_free(pdev_iface_detail_data);
 554
 555            if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
 556                                 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
 557                CloseHandle(dev_file);
 558                error_setg_win32(errp, GetLastError(),
 559                                 "failed to get device slot number");
 560                goto free_dev_info;
 561            }
 562
 563            CloseHandle(dev_file);
 564            if (sdn.DeviceNumber != number) {
 565                continue;
 566            }
 567        } else {
 568            error_setg_win32(errp, GetLastError(),
 569                             "failed to get device interfaces");
 570            goto free_dev_info;
 571        }
 572
 573        g_debug("found device slot %d. Getting storage controller", number);
 574        {
 575            CONFIGRET cr;
 576            DEVINST dev_inst, parent_dev_inst;
 577            ULONG dev_id_size = 0;
 578
 579            size = 0;
 580            while (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
 581                                               parent_dev_id, size, &size)) {
 582                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
 583                    parent_dev_id = g_malloc(size);
 584                } else {
 585                    error_setg_win32(errp, GetLastError(),
 586                                     "failed to get device instance ID");
 587                    goto out;
 588                }
 589            }
 590
 591            /*
 592             * CM API used here as opposed to
 593             * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
 594             * which exports are only available in mingw-w64 6+
 595             */
 596            cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
 597            if (cr != CR_SUCCESS) {
 598                g_error("CM_Locate_DevInst failed with code %lx", cr);
 599                error_setg_win32(errp, GetLastError(),
 600                                 "failed to get device instance");
 601                goto out;
 602            }
 603            cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
 604            if (cr != CR_SUCCESS) {
 605                g_error("CM_Get_Parent failed with code %lx", cr);
 606                error_setg_win32(errp, GetLastError(),
 607                                 "failed to get parent device instance");
 608                goto out;
 609            }
 610
 611            cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
 612            if (cr != CR_SUCCESS) {
 613                g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
 614                error_setg_win32(errp, GetLastError(),
 615                                 "failed to get parent device ID length");
 616                goto out;
 617            }
 618
 619            ++dev_id_size;
 620            if (dev_id_size > size) {
 621                g_free(parent_dev_id);
 622                parent_dev_id = g_malloc(dev_id_size);
 623            }
 624
 625            cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
 626                                  0);
 627            if (cr != CR_SUCCESS) {
 628                g_error("CM_Get_Device_ID failed with code %lx", cr);
 629                error_setg_win32(errp, GetLastError(),
 630                                 "failed to get parent device ID");
 631                goto out;
 632            }
 633        }
 634
 635        g_debug("querying storage controller %s for PCI information",
 636                parent_dev_id);
 637        parent_dev_info =
 638            SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
 639                                NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
 640        g_free(parent_dev_id);
 641
 642        if (parent_dev_info == INVALID_HANDLE_VALUE) {
 643            error_setg_win32(errp, GetLastError(),
 644                             "failed to get parent device");
 645            goto out;
 646        }
 647
 648        parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
 649        if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
 650            error_setg_win32(errp, GetLastError(),
 651                           "failed to get parent device data");
 652            goto out;
 653        }
 654
 655        for (j = 0;
 656             SetupDiEnumDeviceInfo(parent_dev_info, j, &parent_dev_info_data);
 657             j++) {
 658            DWORD addr, bus, ui_slot, type;
 659            int func, slot;
 660
 661            /*
 662             * There is no need to allocate buffer in the next functions. The
 663             * size is known and ULONG according to
 664             * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
 665             */
 666            if (!SetupDiGetDeviceRegistryProperty(
 667                  parent_dev_info, &parent_dev_info_data, SPDRP_BUSNUMBER,
 668                  &type, (PBYTE)&bus, size, NULL)) {
 669                debug_error("failed to get PCI bus");
 670                bus = -1;
 671                partial_pci = true;
 672            }
 673
 674            /*
 675             * The function retrieves the device's address. This value will be
 676             * transformed into device function and number
 677             */
 678            if (!SetupDiGetDeviceRegistryProperty(
 679                    parent_dev_info, &parent_dev_info_data, SPDRP_ADDRESS,
 680                    &type, (PBYTE)&addr, size, NULL)) {
 681                debug_error("failed to get PCI address");
 682                addr = -1;
 683                partial_pci = true;
 684            }
 685
 686            /*
 687             * This call returns UINumber of DEVICE_CAPABILITIES structure.
 688             * This number is typically a user-perceived slot number.
 689             */
 690            if (!SetupDiGetDeviceRegistryProperty(
 691                    parent_dev_info, &parent_dev_info_data, SPDRP_UI_NUMBER,
 692                    &type, (PBYTE)&ui_slot, size, NULL)) {
 693                debug_error("failed to get PCI slot");
 694                ui_slot = -1;
 695                partial_pci = true;
 696            }
 697
 698            /*
 699             * SetupApi gives us the same information as driver with
 700             * IoGetDeviceProperty. According to Microsoft:
 701             *
 702             *   FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
 703             *   DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
 704             *   SPDRP_ADDRESS is propertyAddress, so we do the same.
 705             *
 706             * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
 707             */
 708            if (partial_pci) {
 709                pci->domain = -1;
 710                pci->slot = -1;
 711                pci->function = -1;
 712                pci->bus = -1;
 713                continue;
 714            } else {
 715                func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
 716                slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
 717                if ((int)ui_slot != slot) {
 718                    g_debug("mismatch with reported slot values: %d vs %d",
 719                            (int)ui_slot, slot);
 720                }
 721                pci->domain = 0;
 722                pci->slot = (int)ui_slot;
 723                pci->function = func;
 724                pci->bus = (int)bus;
 725                break;
 726            }
 727        }
 728        SetupDiDestroyDeviceInfoList(parent_dev_info);
 729        break;
 730    }
 731
 732free_dev_info:
 733    SetupDiDestroyDeviceInfoList(dev_info);
 734out:
 735    return pci;
 736}
 737
 738static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
 739    Error **errp)
 740{
 741    STORAGE_PROPERTY_QUERY query;
 742    STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
 743    DWORD received;
 744    ULONG size = sizeof(buf);
 745
 746    dev_desc = &buf;
 747    query.PropertyId = StorageDeviceProperty;
 748    query.QueryType = PropertyStandardQuery;
 749
 750    if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
 751                         sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
 752                         size, &received, NULL)) {
 753        error_setg_win32(errp, GetLastError(), "failed to get bus type");
 754        return;
 755    }
 756    disk->bus_type = find_bus_type(dev_desc->BusType);
 757    g_debug("bus type %d", disk->bus_type);
 758
 759    /* Query once more. Now with long enough buffer. */
 760    size = dev_desc->Size;
 761    dev_desc = g_malloc0(size);
 762    if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
 763                         sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
 764                         size, &received, NULL)) {
 765        error_setg_win32(errp, GetLastError(), "failed to get serial number");
 766        g_debug("failed to get serial number");
 767        goto out_free;
 768    }
 769    if (dev_desc->SerialNumberOffset > 0) {
 770        const char *serial;
 771        size_t len;
 772
 773        if (dev_desc->SerialNumberOffset >= received) {
 774            error_setg(errp, "failed to get serial number: offset outside the buffer");
 775            g_debug("serial number offset outside the buffer");
 776            goto out_free;
 777        }
 778        serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
 779        len = received - dev_desc->SerialNumberOffset;
 780        g_debug("serial number \"%s\"", serial);
 781        if (*serial != 0) {
 782            disk->serial = g_strndup(serial, len);
 783            disk->has_serial = true;
 784        }
 785    }
 786out_free:
 787    g_free(dev_desc);
 788
 789    return;
 790}
 791
 792static void get_single_disk_info(int disk_number,
 793                                 GuestDiskAddress *disk, Error **errp)
 794{
 795    SCSI_ADDRESS addr, *scsi_ad;
 796    DWORD len;
 797    HANDLE disk_h;
 798    Error *local_err = NULL;
 799
 800    scsi_ad = &addr;
 801
 802    g_debug("getting disk info for: %s", disk->dev);
 803    disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
 804                       0, NULL);
 805    if (disk_h == INVALID_HANDLE_VALUE) {
 806        error_setg_win32(errp, GetLastError(), "failed to open disk");
 807        return;
 808    }
 809
 810    get_disk_properties(disk_h, disk, &local_err);
 811    if (local_err) {
 812        error_propagate(errp, local_err);
 813        goto err_close;
 814    }
 815
 816    g_debug("bus type %d", disk->bus_type);
 817    /* always set pci_controller as required by schema. get_pci_info() should
 818     * report -1 values for non-PCI buses rather than fail. fail the command
 819     * if that doesn't hold since that suggests some other unexpected
 820     * breakage
 821     */
 822    disk->pci_controller = get_pci_info(disk_number, &local_err);
 823    if (local_err) {
 824        error_propagate(errp, local_err);
 825        goto err_close;
 826    }
 827    if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
 828            || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
 829            || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
 830            /* This bus type is not supported before Windows Server 2003 SP1 */
 831            || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
 832        ) {
 833        /* We are able to use the same ioctls for different bus types
 834         * according to Microsoft docs
 835         * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
 836        g_debug("getting SCSI info");
 837        if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
 838                            sizeof(SCSI_ADDRESS), &len, NULL)) {
 839            disk->unit = addr.Lun;
 840            disk->target = addr.TargetId;
 841            disk->bus = addr.PathId;
 842        }
 843        /* We do not set error in this case, because we still have enough
 844         * information about volume. */
 845    }
 846
 847err_close:
 848    CloseHandle(disk_h);
 849    return;
 850}
 851
 852/* VSS provider works with volumes, thus there is no difference if
 853 * the volume consist of spanned disks. Info about the first disk in the
 854 * volume is returned for the spanned disk group (LVM) */
 855static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
 856{
 857    Error *local_err = NULL;
 858    GuestDiskAddressList *list = NULL, *cur_item = NULL;
 859    GuestDiskAddress *disk = NULL;
 860    int i;
 861    HANDLE vol_h;
 862    DWORD size;
 863    PVOLUME_DISK_EXTENTS extents = NULL;
 864
 865    /* strip final backslash */
 866    char *name = g_strdup(guid);
 867    if (g_str_has_suffix(name, "\\")) {
 868        name[strlen(name) - 1] = 0;
 869    }
 870
 871    g_debug("opening %s", name);
 872    vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
 873                       0, NULL);
 874    if (vol_h == INVALID_HANDLE_VALUE) {
 875        error_setg_win32(errp, GetLastError(), "failed to open volume");
 876        goto out;
 877    }
 878
 879    /* Get list of extents */
 880    g_debug("getting disk extents");
 881    size = sizeof(VOLUME_DISK_EXTENTS);
 882    extents = g_malloc0(size);
 883    if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
 884                         0, extents, size, &size, NULL)) {
 885        DWORD last_err = GetLastError();
 886        if (last_err == ERROR_MORE_DATA) {
 887            /* Try once more with big enough buffer */
 888            g_free(extents);
 889            extents = g_malloc0(size);
 890            if (!DeviceIoControl(
 891                    vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
 892                    0, extents, size, NULL, NULL)) {
 893                error_setg_win32(errp, GetLastError(),
 894                    "failed to get disk extents");
 895                goto out;
 896            }
 897        } else if (last_err == ERROR_INVALID_FUNCTION) {
 898            /* Possibly CD-ROM or a shared drive. Try to pass the volume */
 899            g_debug("volume not on disk");
 900            disk = g_malloc0(sizeof(GuestDiskAddress));
 901            disk->has_dev = true;
 902            disk->dev = g_strdup(name);
 903            get_single_disk_info(0xffffffff, disk, &local_err);
 904            if (local_err) {
 905                g_debug("failed to get disk info, ignoring error: %s",
 906                    error_get_pretty(local_err));
 907                error_free(local_err);
 908                goto out;
 909            }
 910            list = g_malloc0(sizeof(*list));
 911            list->value = disk;
 912            disk = NULL;
 913            list->next = NULL;
 914            goto out;
 915        } else {
 916            error_setg_win32(errp, GetLastError(),
 917                "failed to get disk extents");
 918            goto out;
 919        }
 920    }
 921    g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
 922
 923    /* Go through each extent */
 924    for (i = 0; i < extents->NumberOfDiskExtents; i++) {
 925        disk = g_malloc0(sizeof(GuestDiskAddress));
 926
 927        /* Disk numbers directly correspond to numbers used in UNCs
 928         *
 929         * See documentation for DISK_EXTENT:
 930         * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
 931         *
 932         * See also Naming Files, Paths and Namespaces:
 933         * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
 934         */
 935        disk->has_dev = true;
 936        disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
 937                                    extents->Extents[i].DiskNumber);
 938
 939        get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
 940        if (local_err) {
 941            error_propagate(errp, local_err);
 942            goto out;
 943        }
 944        cur_item = g_malloc0(sizeof(*list));
 945        cur_item->value = disk;
 946        disk = NULL;
 947        cur_item->next = list;
 948        list = cur_item;
 949    }
 950
 951
 952out:
 953    if (vol_h != INVALID_HANDLE_VALUE) {
 954        CloseHandle(vol_h);
 955    }
 956    qapi_free_GuestDiskAddress(disk);
 957    g_free(extents);
 958    g_free(name);
 959
 960    return list;
 961}
 962
 963#else
 964
 965static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
 966{
 967    return NULL;
 968}
 969
 970#endif /* CONFIG_QGA_NTDDSCSI */
 971
 972static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
 973{
 974    DWORD info_size;
 975    char mnt, *mnt_point;
 976    char fs_name[32];
 977    char vol_info[MAX_PATH+1];
 978    size_t len;
 979    uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
 980    GuestFilesystemInfo *fs = NULL;
 981
 982    GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
 983    if (GetLastError() != ERROR_MORE_DATA) {
 984        error_setg_win32(errp, GetLastError(), "failed to get volume name");
 985        return NULL;
 986    }
 987
 988    mnt_point = g_malloc(info_size + 1);
 989    if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
 990                                         &info_size)) {
 991        error_setg_win32(errp, GetLastError(), "failed to get volume name");
 992        goto free;
 993    }
 994
 995    len = strlen(mnt_point);
 996    mnt_point[len] = '\\';
 997    mnt_point[len+1] = 0;
 998    if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
 999                              NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
1000        if (GetLastError() != ERROR_NOT_READY) {
1001            error_setg_win32(errp, GetLastError(), "failed to get volume info");
1002        }
1003        goto free;
1004    }
1005
1006    fs_name[sizeof(fs_name) - 1] = 0;
1007    fs = g_malloc(sizeof(*fs));
1008    fs->name = g_strdup(guid);
1009    fs->has_total_bytes = false;
1010    fs->has_used_bytes = false;
1011    if (len == 0) {
1012        fs->mountpoint = g_strdup("System Reserved");
1013    } else {
1014        fs->mountpoint = g_strndup(mnt_point, len);
1015        if (GetDiskFreeSpaceEx(fs->mountpoint,
1016                               (PULARGE_INTEGER) & i64FreeBytesToCaller,
1017                               (PULARGE_INTEGER) & i64TotalBytes,
1018                               (PULARGE_INTEGER) & i64FreeBytes)) {
1019            fs->used_bytes = i64TotalBytes - i64FreeBytes;
1020            fs->total_bytes = i64TotalBytes;
1021            fs->has_total_bytes = true;
1022            fs->has_used_bytes = true;
1023        }
1024    }
1025    fs->type = g_strdup(fs_name);
1026    fs->disk = build_guest_disk_info(guid, errp);
1027free:
1028    g_free(mnt_point);
1029    return fs;
1030}
1031
1032GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1033{
1034    HANDLE vol_h;
1035    GuestFilesystemInfoList *new, *ret = NULL;
1036    char guid[256];
1037
1038    vol_h = FindFirstVolume(guid, sizeof(guid));
1039    if (vol_h == INVALID_HANDLE_VALUE) {
1040        error_setg_win32(errp, GetLastError(), "failed to find any volume");
1041        return NULL;
1042    }
1043
1044    do {
1045        GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
1046        if (info == NULL) {
1047            continue;
1048        }
1049        new = g_malloc(sizeof(*ret));
1050        new->value = info;
1051        new->next = ret;
1052        ret = new;
1053    } while (FindNextVolume(vol_h, guid, sizeof(guid)));
1054
1055    if (GetLastError() != ERROR_NO_MORE_FILES) {
1056        error_setg_win32(errp, GetLastError(), "failed to find next volume");
1057    }
1058
1059    FindVolumeClose(vol_h);
1060    return ret;
1061}
1062
1063/*
1064 * Return status of freeze/thaw
1065 */
1066GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1067{
1068    if (!vss_initialized()) {
1069        error_setg(errp, QERR_UNSUPPORTED);
1070        return 0;
1071    }
1072
1073    if (ga_is_frozen(ga_state)) {
1074        return GUEST_FSFREEZE_STATUS_FROZEN;
1075    }
1076
1077    return GUEST_FSFREEZE_STATUS_THAWED;
1078}
1079
1080/*
1081 * Freeze local file systems using Volume Shadow-copy Service.
1082 * The frozen state is limited for up to 10 seconds by VSS.
1083 */
1084int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1085{
1086    return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1087}
1088
1089int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1090                                       strList *mountpoints,
1091                                       Error **errp)
1092{
1093    int i;
1094    Error *local_err = NULL;
1095
1096    if (!vss_initialized()) {
1097        error_setg(errp, QERR_UNSUPPORTED);
1098        return 0;
1099    }
1100
1101    slog("guest-fsfreeze called");
1102
1103    /* cannot risk guest agent blocking itself on a write in this state */
1104    ga_set_frozen(ga_state);
1105
1106    qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
1107    if (local_err) {
1108        error_propagate(errp, local_err);
1109        goto error;
1110    }
1111
1112    return i;
1113
1114error:
1115    local_err = NULL;
1116    qmp_guest_fsfreeze_thaw(&local_err);
1117    if (local_err) {
1118        g_debug("cleanup thaw: %s", error_get_pretty(local_err));
1119        error_free(local_err);
1120    }
1121    return 0;
1122}
1123
1124/*
1125 * Thaw local file systems using Volume Shadow-copy Service.
1126 */
1127int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1128{
1129    int i;
1130
1131    if (!vss_initialized()) {
1132        error_setg(errp, QERR_UNSUPPORTED);
1133        return 0;
1134    }
1135
1136    qga_vss_fsfreeze(&i, false, NULL, errp);
1137
1138    ga_unset_frozen(ga_state);
1139    return i;
1140}
1141
1142static void guest_fsfreeze_cleanup(void)
1143{
1144    Error *err = NULL;
1145
1146    if (!vss_initialized()) {
1147        return;
1148    }
1149
1150    if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1151        qmp_guest_fsfreeze_thaw(&err);
1152        if (err) {
1153            slog("failed to clean up frozen filesystems: %s",
1154                 error_get_pretty(err));
1155            error_free(err);
1156        }
1157    }
1158
1159    vss_deinit(true);
1160}
1161
1162/*
1163 * Walk list of mounted file systems in the guest, and discard unused
1164 * areas.
1165 */
1166GuestFilesystemTrimResponse *
1167qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1168{
1169    GuestFilesystemTrimResponse *resp;
1170    HANDLE handle;
1171    WCHAR guid[MAX_PATH] = L"";
1172    OSVERSIONINFO osvi;
1173    BOOL win8_or_later;
1174
1175    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
1176    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1177    GetVersionEx(&osvi);
1178    win8_or_later = (osvi.dwMajorVersion > 6 ||
1179                          ((osvi.dwMajorVersion == 6) &&
1180                           (osvi.dwMinorVersion >= 2)));
1181    if (!win8_or_later) {
1182        error_setg(errp, "fstrim is only supported for Win8+");
1183        return NULL;
1184    }
1185
1186    handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
1187    if (handle == INVALID_HANDLE_VALUE) {
1188        error_setg_win32(errp, GetLastError(), "failed to find any volume");
1189        return NULL;
1190    }
1191
1192    resp = g_new0(GuestFilesystemTrimResponse, 1);
1193
1194    do {
1195        GuestFilesystemTrimResult *res;
1196        GuestFilesystemTrimResultList *list;
1197        PWCHAR uc_path;
1198        DWORD char_count = 0;
1199        char *path, *out;
1200        GError *gerr = NULL;
1201        gchar * argv[4];
1202
1203        GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1204
1205        if (GetLastError() != ERROR_MORE_DATA) {
1206            continue;
1207        }
1208        if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1209            continue;
1210        }
1211
1212        uc_path = g_malloc(sizeof(WCHAR) * char_count);
1213        if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1214                                              &char_count) || !*uc_path) {
1215            /* strange, but this condition could be faced even with size == 2 */
1216            g_free(uc_path);
1217            continue;
1218        }
1219
1220        res = g_new0(GuestFilesystemTrimResult, 1);
1221
1222        path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1223
1224        g_free(uc_path);
1225
1226        if (!path) {
1227            res->has_error = true;
1228            res->error = g_strdup(gerr->message);
1229            g_error_free(gerr);
1230            break;
1231        }
1232
1233        res->path = path;
1234
1235        list = g_new0(GuestFilesystemTrimResultList, 1);
1236        list->value = res;
1237        list->next = resp->paths;
1238
1239        resp->paths = list;
1240
1241        memset(argv, 0, sizeof(argv));
1242        argv[0] = (gchar *)"defrag.exe";
1243        argv[1] = (gchar *)"/L";
1244        argv[2] = path;
1245
1246        if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1247                          &out /* stdout */, NULL /* stdin */,
1248                          NULL, &gerr)) {
1249            res->has_error = true;
1250            res->error = g_strdup(gerr->message);
1251            g_error_free(gerr);
1252        } else {
1253            /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1254               Error is reported in the output with something like
1255               (x89000020) etc code in the stdout */
1256
1257            int i;
1258            gchar **lines = g_strsplit(out, "\r\n", 0);
1259            g_free(out);
1260
1261            for (i = 0; lines[i] != NULL; i++) {
1262                if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1263                    continue;
1264                }
1265                res->has_error = true;
1266                res->error = g_strdup(lines[i]);
1267                break;
1268            }
1269            g_strfreev(lines);
1270        }
1271    } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1272
1273    FindVolumeClose(handle);
1274    return resp;
1275}
1276
1277typedef enum {
1278    GUEST_SUSPEND_MODE_DISK,
1279    GUEST_SUSPEND_MODE_RAM
1280} GuestSuspendMode;
1281
1282static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
1283{
1284    SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1285    Error *local_err = NULL;
1286
1287    ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1288    if (!GetPwrCapabilities(&sys_pwr_caps)) {
1289        error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1290                   "failed to determine guest suspend capabilities");
1291        goto out;
1292    }
1293
1294    switch (mode) {
1295    case GUEST_SUSPEND_MODE_DISK:
1296        if (!sys_pwr_caps.SystemS4) {
1297            error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1298                       "suspend-to-disk not supported by OS");
1299        }
1300        break;
1301    case GUEST_SUSPEND_MODE_RAM:
1302        if (!sys_pwr_caps.SystemS3) {
1303            error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1304                       "suspend-to-ram not supported by OS");
1305        }
1306        break;
1307    default:
1308        error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
1309                   "GuestSuspendMode");
1310    }
1311
1312out:
1313    error_propagate(errp, local_err);
1314}
1315
1316static DWORD WINAPI do_suspend(LPVOID opaque)
1317{
1318    GuestSuspendMode *mode = opaque;
1319    DWORD ret = 0;
1320
1321    if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1322        slog("failed to suspend guest, %lu", GetLastError());
1323        ret = -1;
1324    }
1325    g_free(mode);
1326    return ret;
1327}
1328
1329void qmp_guest_suspend_disk(Error **errp)
1330{
1331    Error *local_err = NULL;
1332    GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1333
1334    *mode = GUEST_SUSPEND_MODE_DISK;
1335    check_suspend_mode(*mode, &local_err);
1336    acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1337    execute_async(do_suspend, mode, &local_err);
1338
1339    if (local_err) {
1340        error_propagate(errp, local_err);
1341        g_free(mode);
1342    }
1343}
1344
1345void qmp_guest_suspend_ram(Error **errp)
1346{
1347    Error *local_err = NULL;
1348    GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1349
1350    *mode = GUEST_SUSPEND_MODE_RAM;
1351    check_suspend_mode(*mode, &local_err);
1352    acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1353    execute_async(do_suspend, mode, &local_err);
1354
1355    if (local_err) {
1356        error_propagate(errp, local_err);
1357        g_free(mode);
1358    }
1359}
1360
1361void qmp_guest_suspend_hybrid(Error **errp)
1362{
1363    error_setg(errp, QERR_UNSUPPORTED);
1364}
1365
1366static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1367{
1368    IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1369    ULONG adptr_addrs_len = 0;
1370    DWORD ret;
1371
1372    /* Call the first time to get the adptr_addrs_len. */
1373    GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1374                         NULL, adptr_addrs, &adptr_addrs_len);
1375
1376    adptr_addrs = g_malloc(adptr_addrs_len);
1377    ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1378                               NULL, adptr_addrs, &adptr_addrs_len);
1379    if (ret != ERROR_SUCCESS) {
1380        error_setg_win32(errp, ret, "failed to get adapters addresses");
1381        g_free(adptr_addrs);
1382        adptr_addrs = NULL;
1383    }
1384    return adptr_addrs;
1385}
1386
1387static char *guest_wctomb_dup(WCHAR *wstr)
1388{
1389    char *str;
1390    size_t i;
1391
1392    i = wcslen(wstr) + 1;
1393    str = g_malloc(i);
1394    WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
1395                        wstr, -1, str, i, NULL, NULL);
1396    return str;
1397}
1398
1399static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1400                               Error **errp)
1401{
1402    char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1403    DWORD len;
1404    int ret;
1405
1406    if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1407            ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1408        len = sizeof(addr_str);
1409        ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1410                                 ip_addr->Address.iSockaddrLength,
1411                                 NULL,
1412                                 addr_str,
1413                                 &len);
1414        if (ret != 0) {
1415            error_setg_win32(errp, WSAGetLastError(),
1416                "failed address presentation form conversion");
1417            return NULL;
1418        }
1419        return g_strdup(addr_str);
1420    }
1421    return NULL;
1422}
1423
1424static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1425{
1426    /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1427     * field to obtain the prefix.
1428     */
1429    return ip_addr->OnLinkPrefixLength;
1430}
1431
1432#define INTERFACE_PATH_BUF_SZ 512
1433
1434static DWORD get_interface_index(const char *guid)
1435{
1436    ULONG index;
1437    DWORD status;
1438    wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1439    snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1440    wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1441    status = GetAdapterIndex (wbuf, &index);
1442    if (status != NO_ERROR) {
1443        return (DWORD)~0;
1444    } else {
1445        return index;
1446    }
1447}
1448
1449typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1450
1451static int guest_get_network_stats(const char *name,
1452                                   GuestNetworkInterfaceStat *stats)
1453{
1454    OSVERSIONINFO os_ver;
1455
1456    os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1457    GetVersionEx(&os_ver);
1458    if (os_ver.dwMajorVersion >= 6) {
1459        MIB_IF_ROW2 a_mid_ifrow;
1460        GetIfEntry2Func getifentry2_ex;
1461        DWORD if_index = 0;
1462        HMODULE module = GetModuleHandle("iphlpapi");
1463        PVOID func = GetProcAddress(module, "GetIfEntry2");
1464
1465        if (func == NULL) {
1466            return -1;
1467        }
1468
1469        getifentry2_ex = (GetIfEntry2Func)func;
1470        if_index = get_interface_index(name);
1471        if (if_index == (DWORD)~0) {
1472            return -1;
1473        }
1474
1475        memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1476        a_mid_ifrow.InterfaceIndex = if_index;
1477        if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1478            stats->rx_bytes = a_mid_ifrow.InOctets;
1479            stats->rx_packets = a_mid_ifrow.InUcastPkts;
1480            stats->rx_errs = a_mid_ifrow.InErrors;
1481            stats->rx_dropped = a_mid_ifrow.InDiscards;
1482            stats->tx_bytes = a_mid_ifrow.OutOctets;
1483            stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1484            stats->tx_errs = a_mid_ifrow.OutErrors;
1485            stats->tx_dropped = a_mid_ifrow.OutDiscards;
1486            return 0;
1487        }
1488    }
1489    return -1;
1490}
1491
1492GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1493{
1494    IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1495    IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1496    GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1497    GuestIpAddressList *head_addr, *cur_addr;
1498    GuestNetworkInterfaceList *info;
1499    GuestNetworkInterfaceStat *interface_stat = NULL;
1500    GuestIpAddressList *address_item = NULL;
1501    unsigned char *mac_addr;
1502    char *addr_str;
1503    WORD wsa_version;
1504    WSADATA wsa_data;
1505    int ret;
1506
1507    adptr_addrs = guest_get_adapters_addresses(errp);
1508    if (adptr_addrs == NULL) {
1509        return NULL;
1510    }
1511
1512    /* Make WSA APIs available. */
1513    wsa_version = MAKEWORD(2, 2);
1514    ret = WSAStartup(wsa_version, &wsa_data);
1515    if (ret != 0) {
1516        error_setg_win32(errp, ret, "failed socket startup");
1517        goto out;
1518    }
1519
1520    for (addr = adptr_addrs; addr; addr = addr->Next) {
1521        info = g_malloc0(sizeof(*info));
1522
1523        if (cur_item == NULL) {
1524            head = cur_item = info;
1525        } else {
1526            cur_item->next = info;
1527            cur_item = info;
1528        }
1529
1530        info->value = g_malloc0(sizeof(*info->value));
1531        info->value->name = guest_wctomb_dup(addr->FriendlyName);
1532
1533        if (addr->PhysicalAddressLength != 0) {
1534            mac_addr = addr->PhysicalAddress;
1535
1536            info->value->hardware_address =
1537                g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1538                                (int) mac_addr[0], (int) mac_addr[1],
1539                                (int) mac_addr[2], (int) mac_addr[3],
1540                                (int) mac_addr[4], (int) mac_addr[5]);
1541
1542            info->value->has_hardware_address = true;
1543        }
1544
1545        head_addr = NULL;
1546        cur_addr = NULL;
1547        for (ip_addr = addr->FirstUnicastAddress;
1548                ip_addr;
1549                ip_addr = ip_addr->Next) {
1550            addr_str = guest_addr_to_str(ip_addr, errp);
1551            if (addr_str == NULL) {
1552                continue;
1553            }
1554
1555            address_item = g_malloc0(sizeof(*address_item));
1556
1557            if (!cur_addr) {
1558                head_addr = cur_addr = address_item;
1559            } else {
1560                cur_addr->next = address_item;
1561                cur_addr = address_item;
1562            }
1563
1564            address_item->value = g_malloc0(sizeof(*address_item->value));
1565            address_item->value->ip_address = addr_str;
1566            address_item->value->prefix = guest_ip_prefix(ip_addr);
1567            if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1568                address_item->value->ip_address_type =
1569                    GUEST_IP_ADDRESS_TYPE_IPV4;
1570            } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1571                address_item->value->ip_address_type =
1572                    GUEST_IP_ADDRESS_TYPE_IPV6;
1573            }
1574        }
1575        if (head_addr) {
1576            info->value->has_ip_addresses = true;
1577            info->value->ip_addresses = head_addr;
1578        }
1579        if (!info->value->has_statistics) {
1580            interface_stat = g_malloc0(sizeof(*interface_stat));
1581            if (guest_get_network_stats(addr->AdapterName,
1582                interface_stat) == -1) {
1583                info->value->has_statistics = false;
1584                g_free(interface_stat);
1585            } else {
1586                info->value->statistics = interface_stat;
1587                info->value->has_statistics = true;
1588            }
1589        }
1590    }
1591    WSACleanup();
1592out:
1593    g_free(adptr_addrs);
1594    return head;
1595}
1596
1597int64_t qmp_guest_get_time(Error **errp)
1598{
1599    SYSTEMTIME ts = {0};
1600    FILETIME tf;
1601
1602    GetSystemTime(&ts);
1603    if (ts.wYear < 1601 || ts.wYear > 30827) {
1604        error_setg(errp, "Failed to get time");
1605        return -1;
1606    }
1607
1608    if (!SystemTimeToFileTime(&ts, &tf)) {
1609        error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1610        return -1;
1611    }
1612
1613    return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1614                - W32_FT_OFFSET) * 100;
1615}
1616
1617void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1618{
1619    Error *local_err = NULL;
1620    SYSTEMTIME ts;
1621    FILETIME tf;
1622    LONGLONG time;
1623
1624    if (!has_time) {
1625        /* Unfortunately, Windows libraries don't provide an easy way to access
1626         * RTC yet:
1627         *
1628         * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1629         *
1630         * Instead, a workaround is to use the Windows win32tm command to
1631         * resync the time using the Windows Time service.
1632         */
1633        LPVOID msg_buffer;
1634        DWORD ret_flags;
1635
1636        HRESULT hr = system("w32tm /resync /nowait");
1637
1638        if (GetLastError() != 0) {
1639            strerror_s((LPTSTR) & msg_buffer, 0, errno);
1640            error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1641        } else if (hr != 0) {
1642            if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1643                error_setg(errp, "Windows Time service not running on the "
1644                                 "guest");
1645            } else {
1646                if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1647                                   FORMAT_MESSAGE_FROM_SYSTEM |
1648                                   FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1649                                   (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1650                                   SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1651                                   NULL)) {
1652                    error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1653                                     "t retrieve error message", hr);
1654                } else {
1655                    error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1656                               (LPCTSTR)msg_buffer);
1657                    LocalFree(msg_buffer);
1658                }
1659            }
1660        } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1661            error_setg(errp, "No internet connection on guest, sync not "
1662                             "accurate");
1663        }
1664        return;
1665    }
1666
1667    /* Validate time passed by user. */
1668    if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1669        error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1670        return;
1671    }
1672
1673    time = time_ns / 100 + W32_FT_OFFSET;
1674
1675    tf.dwLowDateTime = (DWORD) time;
1676    tf.dwHighDateTime = (DWORD) (time >> 32);
1677
1678    if (!FileTimeToSystemTime(&tf, &ts)) {
1679        error_setg(errp, "Failed to convert system time %d",
1680                   (int)GetLastError());
1681        return;
1682    }
1683
1684    acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1685    if (local_err) {
1686        error_propagate(errp, local_err);
1687        return;
1688    }
1689
1690    if (!SetSystemTime(&ts)) {
1691        error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1692        return;
1693    }
1694}
1695
1696GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1697{
1698    PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1699    DWORD length;
1700    GuestLogicalProcessorList *head, **link;
1701    Error *local_err = NULL;
1702    int64_t current;
1703
1704    ptr = pslpi = NULL;
1705    length = 0;
1706    current = 0;
1707    head = NULL;
1708    link = &head;
1709
1710    if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1711        (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1712        (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1713        ptr = pslpi = g_malloc0(length);
1714        if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1715            error_setg(&local_err, "Failed to get processor information: %d",
1716                       (int)GetLastError());
1717        }
1718    } else {
1719        error_setg(&local_err,
1720                   "Failed to get processor information buffer length: %d",
1721                   (int)GetLastError());
1722    }
1723
1724    while ((local_err == NULL) && (length > 0)) {
1725        if (pslpi->Relationship == RelationProcessorCore) {
1726            ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1727
1728            while (cpu_bits > 0) {
1729                if (!!(cpu_bits & 1)) {
1730                    GuestLogicalProcessor *vcpu;
1731                    GuestLogicalProcessorList *entry;
1732
1733                    vcpu = g_malloc0(sizeof *vcpu);
1734                    vcpu->logical_id = current++;
1735                    vcpu->online = true;
1736                    vcpu->has_can_offline = true;
1737
1738                    entry = g_malloc0(sizeof *entry);
1739                    entry->value = vcpu;
1740
1741                    *link = entry;
1742                    link = &entry->next;
1743                }
1744                cpu_bits >>= 1;
1745            }
1746        }
1747        length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1748        pslpi++; /* next entry */
1749    }
1750
1751    g_free(ptr);
1752
1753    if (local_err == NULL) {
1754        if (head != NULL) {
1755            return head;
1756        }
1757        /* there's no guest with zero VCPUs */
1758        error_setg(&local_err, "Guest reported zero VCPUs");
1759    }
1760
1761    qapi_free_GuestLogicalProcessorList(head);
1762    error_propagate(errp, local_err);
1763    return NULL;
1764}
1765
1766int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1767{
1768    error_setg(errp, QERR_UNSUPPORTED);
1769    return -1;
1770}
1771
1772static gchar *
1773get_net_error_message(gint error)
1774{
1775    HMODULE module = NULL;
1776    gchar *retval = NULL;
1777    wchar_t *msg = NULL;
1778    int flags;
1779    size_t nchars;
1780
1781    flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1782        FORMAT_MESSAGE_IGNORE_INSERTS |
1783        FORMAT_MESSAGE_FROM_SYSTEM;
1784
1785    if (error >= NERR_BASE && error <= MAX_NERR) {
1786        module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1787
1788        if (module != NULL) {
1789            flags |= FORMAT_MESSAGE_FROM_HMODULE;
1790        }
1791    }
1792
1793    FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1794
1795    if (msg != NULL) {
1796        nchars = wcslen(msg);
1797
1798        if (nchars >= 2 &&
1799            msg[nchars - 1] == L'\n' &&
1800            msg[nchars - 2] == L'\r') {
1801            msg[nchars - 2] = L'\0';
1802        }
1803
1804        retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1805
1806        LocalFree(msg);
1807    }
1808
1809    if (module != NULL) {
1810        FreeLibrary(module);
1811    }
1812
1813    return retval;
1814}
1815
1816void qmp_guest_set_user_password(const char *username,
1817                                 const char *password,
1818                                 bool crypted,
1819                                 Error **errp)
1820{
1821    NET_API_STATUS nas;
1822    char *rawpasswddata = NULL;
1823    size_t rawpasswdlen;
1824    wchar_t *user = NULL, *wpass = NULL;
1825    USER_INFO_1003 pi1003 = { 0, };
1826    GError *gerr = NULL;
1827
1828    if (crypted) {
1829        error_setg(errp, QERR_UNSUPPORTED);
1830        return;
1831    }
1832
1833    rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1834    if (!rawpasswddata) {
1835        return;
1836    }
1837    rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1838    rawpasswddata[rawpasswdlen] = '\0';
1839
1840    user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1841    if (!user) {
1842        goto done;
1843    }
1844
1845    wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1846    if (!wpass) {
1847        goto done;
1848    }
1849
1850    pi1003.usri1003_password = wpass;
1851    nas = NetUserSetInfo(NULL, user,
1852                         1003, (LPBYTE)&pi1003,
1853                         NULL);
1854
1855    if (nas != NERR_Success) {
1856        gchar *msg = get_net_error_message(nas);
1857        error_setg(errp, "failed to set password: %s", msg);
1858        g_free(msg);
1859    }
1860
1861done:
1862    if (gerr) {
1863        error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1864        g_error_free(gerr);
1865    }
1866    g_free(user);
1867    g_free(wpass);
1868    g_free(rawpasswddata);
1869}
1870
1871GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1872{
1873    error_setg(errp, QERR_UNSUPPORTED);
1874    return NULL;
1875}
1876
1877GuestMemoryBlockResponseList *
1878qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1879{
1880    error_setg(errp, QERR_UNSUPPORTED);
1881    return NULL;
1882}
1883
1884GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1885{
1886    error_setg(errp, QERR_UNSUPPORTED);
1887    return NULL;
1888}
1889
1890/* add unsupported commands to the blacklist */
1891GList *ga_command_blacklist_init(GList *blacklist)
1892{
1893    const char *list_unsupported[] = {
1894        "guest-suspend-hybrid",
1895        "guest-set-vcpus",
1896        "guest-get-memory-blocks", "guest-set-memory-blocks",
1897        "guest-get-memory-block-size",
1898        NULL};
1899    char **p = (char **)list_unsupported;
1900
1901    while (*p) {
1902        blacklist = g_list_append(blacklist, g_strdup(*p++));
1903    }
1904
1905    if (!vss_init(true)) {
1906        g_debug("vss_init failed, vss commands are going to be disabled");
1907        const char *list[] = {
1908            "guest-get-fsinfo", "guest-fsfreeze-status",
1909            "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1910        p = (char **)list;
1911
1912        while (*p) {
1913            blacklist = g_list_append(blacklist, g_strdup(*p++));
1914        }
1915    }
1916
1917    return blacklist;
1918}
1919
1920/* register init/cleanup routines for stateful command groups */
1921void ga_command_state_init(GAState *s, GACommandState *cs)
1922{
1923    if (!vss_initialized()) {
1924        ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1925    }
1926}
1927
1928/* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1929typedef struct _GA_WTSINFOA {
1930    WTS_CONNECTSTATE_CLASS State;
1931    DWORD SessionId;
1932    DWORD IncomingBytes;
1933    DWORD OutgoingBytes;
1934    DWORD IncomingFrames;
1935    DWORD OutgoingFrames;
1936    DWORD IncomingCompressedBytes;
1937    DWORD OutgoingCompressedBy;
1938    CHAR WinStationName[WINSTATIONNAME_LENGTH];
1939    CHAR Domain[DOMAIN_LENGTH];
1940    CHAR UserName[USERNAME_LENGTH + 1];
1941    LARGE_INTEGER ConnectTime;
1942    LARGE_INTEGER DisconnectTime;
1943    LARGE_INTEGER LastInputTime;
1944    LARGE_INTEGER LogonTime;
1945    LARGE_INTEGER CurrentTime;
1946
1947} GA_WTSINFOA;
1948
1949GuestUserList *qmp_guest_get_users(Error **err)
1950{
1951#define QGA_NANOSECONDS 10000000
1952
1953    GHashTable *cache = NULL;
1954    GuestUserList *head = NULL, *cur_item = NULL;
1955
1956    DWORD buffer_size = 0, count = 0, i = 0;
1957    GA_WTSINFOA *info = NULL;
1958    WTS_SESSION_INFOA *entries = NULL;
1959    GuestUserList *item = NULL;
1960    GuestUser *user = NULL;
1961    gpointer value = NULL;
1962    INT64 login = 0;
1963    double login_time = 0;
1964
1965    cache = g_hash_table_new(g_str_hash, g_str_equal);
1966
1967    if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
1968        for (i = 0; i < count; ++i) {
1969            buffer_size = 0;
1970            info = NULL;
1971            if (WTSQuerySessionInformationA(
1972                NULL,
1973                entries[i].SessionId,
1974                WTSSessionInfo,
1975                (LPSTR *)&info,
1976                &buffer_size
1977            )) {
1978
1979                if (strlen(info->UserName) == 0) {
1980                    WTSFreeMemory(info);
1981                    continue;
1982                }
1983
1984                login = info->LogonTime.QuadPart;
1985                login -= W32_FT_OFFSET;
1986                login_time = ((double)login) / QGA_NANOSECONDS;
1987
1988                if (g_hash_table_contains(cache, info->UserName)) {
1989                    value = g_hash_table_lookup(cache, info->UserName);
1990                    user = (GuestUser *)value;
1991                    if (user->login_time > login_time) {
1992                        user->login_time = login_time;
1993                    }
1994                } else {
1995                    item = g_new0(GuestUserList, 1);
1996                    item->value = g_new0(GuestUser, 1);
1997
1998                    item->value->user = g_strdup(info->UserName);
1999                    item->value->domain = g_strdup(info->Domain);
2000                    item->value->has_domain = true;
2001
2002                    item->value->login_time = login_time;
2003
2004                    g_hash_table_add(cache, item->value->user);
2005
2006                    if (!cur_item) {
2007                        head = cur_item = item;
2008                    } else {
2009                        cur_item->next = item;
2010                        cur_item = item;
2011                    }
2012                }
2013            }
2014            WTSFreeMemory(info);
2015        }
2016        WTSFreeMemory(entries);
2017    }
2018    g_hash_table_destroy(cache);
2019    return head;
2020}
2021
2022typedef struct _ga_matrix_lookup_t {
2023    int major;
2024    int minor;
2025    char const *version;
2026    char const *version_id;
2027} ga_matrix_lookup_t;
2028
2029static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
2030    {
2031        /* Desktop editions */
2032        { 5, 0, "Microsoft Windows 2000",   "2000"},
2033        { 5, 1, "Microsoft Windows XP",     "xp"},
2034        { 6, 0, "Microsoft Windows Vista",  "vista"},
2035        { 6, 1, "Microsoft Windows 7"       "7"},
2036        { 6, 2, "Microsoft Windows 8",      "8"},
2037        { 6, 3, "Microsoft Windows 8.1",    "8.1"},
2038        {10, 0, "Microsoft Windows 10",     "10"},
2039        { 0, 0, 0}
2040    },{
2041        /* Server editions */
2042        { 5, 2, "Microsoft Windows Server 2003",        "2003"},
2043        { 6, 0, "Microsoft Windows Server 2008",        "2008"},
2044        { 6, 1, "Microsoft Windows Server 2008 R2",     "2008r2"},
2045        { 6, 2, "Microsoft Windows Server 2012",        "2012"},
2046        { 6, 3, "Microsoft Windows Server 2012 R2",     "2012r2"},
2047        { 0, 0, 0},
2048        { 0, 0, 0},
2049        { 0, 0, 0}
2050    }
2051};
2052
2053typedef struct _ga_win_10_0_server_t {
2054    int final_build;
2055    char const *version;
2056    char const *version_id;
2057} ga_win_10_0_server_t;
2058
2059static ga_win_10_0_server_t const WIN_10_0_SERVER_VERSION_MATRIX[3] = {
2060    {14393, "Microsoft Windows Server 2016",    "2016"},
2061    {17763, "Microsoft Windows Server 2019",    "2019"},
2062    {0, 0}
2063};
2064
2065static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2066{
2067    typedef NTSTATUS(WINAPI * rtl_get_version_t)(
2068        RTL_OSVERSIONINFOEXW *os_version_info_ex);
2069
2070    info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2071
2072    HMODULE module = GetModuleHandle("ntdll");
2073    PVOID fun = GetProcAddress(module, "RtlGetVersion");
2074    if (fun == NULL) {
2075        error_setg(errp, QERR_QGA_COMMAND_FAILED,
2076            "Failed to get address of RtlGetVersion");
2077        return;
2078    }
2079
2080    rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2081    rtl_get_version(info);
2082    return;
2083}
2084
2085static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
2086{
2087    DWORD major = os_version->dwMajorVersion;
2088    DWORD minor = os_version->dwMinorVersion;
2089    DWORD build = os_version->dwBuildNumber;
2090    int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2091    ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
2092    ga_win_10_0_server_t const *win_10_0_table = WIN_10_0_SERVER_VERSION_MATRIX;
2093    while (table->version != NULL) {
2094        if (major == 10 && minor == 0 && tbl_idx) {
2095            while (win_10_0_table->version != NULL) {
2096                if (build <= win_10_0_table->final_build) {
2097                    if (id) {
2098                        return g_strdup(win_10_0_table->version_id);
2099                    } else {
2100                        return g_strdup(win_10_0_table->version);
2101                    }
2102                }
2103                win_10_0_table++;
2104            }
2105        } else if (major == table->major && minor == table->minor) {
2106            if (id) {
2107                return g_strdup(table->version_id);
2108            } else {
2109                return g_strdup(table->version);
2110            }
2111        }
2112        ++table;
2113    }
2114    slog("failed to lookup Windows version: major=%lu, minor=%lu",
2115        major, minor);
2116    return g_strdup("N/A");
2117}
2118
2119static char *ga_get_win_product_name(Error **errp)
2120{
2121    HKEY key = NULL;
2122    DWORD size = 128;
2123    char *result = g_malloc0(size);
2124    LONG err = ERROR_SUCCESS;
2125
2126    err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2127                      "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2128                      &key);
2129    if (err != ERROR_SUCCESS) {
2130        error_setg_win32(errp, err, "failed to open registry key");
2131        goto fail;
2132    }
2133
2134    err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2135                            (LPBYTE)result, &size);
2136    if (err == ERROR_MORE_DATA) {
2137        slog("ProductName longer than expected (%lu bytes), retrying",
2138                size);
2139        g_free(result);
2140        result = NULL;
2141        if (size > 0) {
2142            result = g_malloc0(size);
2143            err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2144                                    (LPBYTE)result, &size);
2145        }
2146    }
2147    if (err != ERROR_SUCCESS) {
2148        error_setg_win32(errp, err, "failed to retrive ProductName");
2149        goto fail;
2150    }
2151
2152    return result;
2153
2154fail:
2155    g_free(result);
2156    return NULL;
2157}
2158
2159static char *ga_get_current_arch(void)
2160{
2161    SYSTEM_INFO info;
2162    GetNativeSystemInfo(&info);
2163    char *result = NULL;
2164    switch (info.wProcessorArchitecture) {
2165    case PROCESSOR_ARCHITECTURE_AMD64:
2166        result = g_strdup("x86_64");
2167        break;
2168    case PROCESSOR_ARCHITECTURE_ARM:
2169        result = g_strdup("arm");
2170        break;
2171    case PROCESSOR_ARCHITECTURE_IA64:
2172        result = g_strdup("ia64");
2173        break;
2174    case PROCESSOR_ARCHITECTURE_INTEL:
2175        result = g_strdup("x86");
2176        break;
2177    case PROCESSOR_ARCHITECTURE_UNKNOWN:
2178    default:
2179        slog("unknown processor architecture 0x%0x",
2180            info.wProcessorArchitecture);
2181        result = g_strdup("unknown");
2182        break;
2183    }
2184    return result;
2185}
2186
2187GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2188{
2189    Error *local_err = NULL;
2190    OSVERSIONINFOEXW os_version = {0};
2191    bool server;
2192    char *product_name;
2193    GuestOSInfo *info;
2194
2195    ga_get_win_version(&os_version, &local_err);
2196    if (local_err) {
2197        error_propagate(errp, local_err);
2198        return NULL;
2199    }
2200
2201    server = os_version.wProductType != VER_NT_WORKSTATION;
2202    product_name = ga_get_win_product_name(&local_err);
2203    if (product_name == NULL) {
2204        error_propagate(errp, local_err);
2205        return NULL;
2206    }
2207
2208    info = g_new0(GuestOSInfo, 1);
2209
2210    info->has_kernel_version = true;
2211    info->kernel_version = g_strdup_printf("%lu.%lu",
2212        os_version.dwMajorVersion,
2213        os_version.dwMinorVersion);
2214    info->has_kernel_release = true;
2215    info->kernel_release = g_strdup_printf("%lu",
2216        os_version.dwBuildNumber);
2217    info->has_machine = true;
2218    info->machine = ga_get_current_arch();
2219
2220    info->has_id = true;
2221    info->id = g_strdup("mswindows");
2222    info->has_name = true;
2223    info->name = g_strdup("Microsoft Windows");
2224    info->has_pretty_name = true;
2225    info->pretty_name = product_name;
2226    info->has_version = true;
2227    info->version = ga_get_win_name(&os_version, false);
2228    info->has_version_id = true;
2229    info->version_id = ga_get_win_name(&os_version, true);
2230    info->has_variant = true;
2231    info->variant = g_strdup(server ? "server" : "client");
2232    info->has_variant_id = true;
2233    info->variant_id = g_strdup(server ? "server" : "client");
2234
2235    return info;
2236}
2237