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