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