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