xref: /openbmc/qemu/qga/commands-win32.c (revision 7c08eefc)
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, QERR_UNSUPPORTED);
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, QERR_UNSUPPORTED);
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, QERR_UNSUPPORTED);
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 void qmp_guest_suspend_hybrid(Error **errp)
1498 {
1499     error_setg(errp, QERR_UNSUPPORTED);
1500 }
1501 
1502 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1503 {
1504     IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1505     ULONG adptr_addrs_len = 0;
1506     DWORD ret;
1507 
1508     /* Call the first time to get the adptr_addrs_len. */
1509     GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1510                          NULL, adptr_addrs, &adptr_addrs_len);
1511 
1512     adptr_addrs = g_malloc(adptr_addrs_len);
1513     ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1514                                NULL, adptr_addrs, &adptr_addrs_len);
1515     if (ret != ERROR_SUCCESS) {
1516         error_setg_win32(errp, ret, "failed to get adapters addresses");
1517         g_free(adptr_addrs);
1518         adptr_addrs = NULL;
1519     }
1520     return adptr_addrs;
1521 }
1522 
1523 static char *guest_wctomb_dup(WCHAR *wstr)
1524 {
1525     char *str;
1526     size_t str_size;
1527 
1528     str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
1529     /* add 1 to str_size for NULL terminator */
1530     str = g_malloc(str_size + 1);
1531     WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
1532     return str;
1533 }
1534 
1535 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1536                                Error **errp)
1537 {
1538     char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1539     DWORD len;
1540     int ret;
1541 
1542     if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1543             ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1544         len = sizeof(addr_str);
1545         ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1546                                  ip_addr->Address.iSockaddrLength,
1547                                  NULL,
1548                                  addr_str,
1549                                  &len);
1550         if (ret != 0) {
1551             error_setg_win32(errp, WSAGetLastError(),
1552                 "failed address presentation form conversion");
1553             return NULL;
1554         }
1555         return g_strdup(addr_str);
1556     }
1557     return NULL;
1558 }
1559 
1560 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1561 {
1562     /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1563      * field to obtain the prefix.
1564      */
1565     return ip_addr->OnLinkPrefixLength;
1566 }
1567 
1568 #define INTERFACE_PATH_BUF_SZ 512
1569 
1570 static DWORD get_interface_index(const char *guid)
1571 {
1572     ULONG index;
1573     DWORD status;
1574     wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1575     snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1576     wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1577     status = GetAdapterIndex (wbuf, &index);
1578     if (status != NO_ERROR) {
1579         return (DWORD)~0;
1580     } else {
1581         return index;
1582     }
1583 }
1584 
1585 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1586 
1587 static int guest_get_network_stats(const char *name,
1588                                    GuestNetworkInterfaceStat *stats)
1589 {
1590     OSVERSIONINFO os_ver;
1591 
1592     os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1593     GetVersionEx(&os_ver);
1594     if (os_ver.dwMajorVersion >= 6) {
1595         MIB_IF_ROW2 a_mid_ifrow;
1596         GetIfEntry2Func getifentry2_ex;
1597         DWORD if_index = 0;
1598         HMODULE module = GetModuleHandle("iphlpapi");
1599         PVOID func = GetProcAddress(module, "GetIfEntry2");
1600 
1601         if (func == NULL) {
1602             return -1;
1603         }
1604 
1605         getifentry2_ex = (GetIfEntry2Func)func;
1606         if_index = get_interface_index(name);
1607         if (if_index == (DWORD)~0) {
1608             return -1;
1609         }
1610 
1611         memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1612         a_mid_ifrow.InterfaceIndex = if_index;
1613         if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1614             stats->rx_bytes = a_mid_ifrow.InOctets;
1615             stats->rx_packets = a_mid_ifrow.InUcastPkts;
1616             stats->rx_errs = a_mid_ifrow.InErrors;
1617             stats->rx_dropped = a_mid_ifrow.InDiscards;
1618             stats->tx_bytes = a_mid_ifrow.OutOctets;
1619             stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1620             stats->tx_errs = a_mid_ifrow.OutErrors;
1621             stats->tx_dropped = a_mid_ifrow.OutDiscards;
1622             return 0;
1623         }
1624     }
1625     return -1;
1626 }
1627 
1628 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1629 {
1630     IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1631     IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1632     GuestNetworkInterfaceList *head = NULL, **tail = &head;
1633     GuestIpAddressList *head_addr, **tail_addr;
1634     GuestNetworkInterface *info;
1635     GuestNetworkInterfaceStat *interface_stat = NULL;
1636     GuestIpAddress *address_item = NULL;
1637     unsigned char *mac_addr;
1638     char *addr_str;
1639     WORD wsa_version;
1640     WSADATA wsa_data;
1641     int ret;
1642 
1643     adptr_addrs = guest_get_adapters_addresses(errp);
1644     if (adptr_addrs == NULL) {
1645         return NULL;
1646     }
1647 
1648     /* Make WSA APIs available. */
1649     wsa_version = MAKEWORD(2, 2);
1650     ret = WSAStartup(wsa_version, &wsa_data);
1651     if (ret != 0) {
1652         error_setg_win32(errp, ret, "failed socket startup");
1653         goto out;
1654     }
1655 
1656     for (addr = adptr_addrs; addr; addr = addr->Next) {
1657         info = g_malloc0(sizeof(*info));
1658 
1659         QAPI_LIST_APPEND(tail, info);
1660 
1661         info->name = guest_wctomb_dup(addr->FriendlyName);
1662 
1663         if (addr->PhysicalAddressLength != 0) {
1664             mac_addr = addr->PhysicalAddress;
1665 
1666             info->hardware_address =
1667                 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1668                                 (int) mac_addr[0], (int) mac_addr[1],
1669                                 (int) mac_addr[2], (int) mac_addr[3],
1670                                 (int) mac_addr[4], (int) mac_addr[5]);
1671         }
1672 
1673         head_addr = NULL;
1674         tail_addr = &head_addr;
1675         for (ip_addr = addr->FirstUnicastAddress;
1676                 ip_addr;
1677                 ip_addr = ip_addr->Next) {
1678             addr_str = guest_addr_to_str(ip_addr, errp);
1679             if (addr_str == NULL) {
1680                 continue;
1681             }
1682 
1683             address_item = g_malloc0(sizeof(*address_item));
1684 
1685             QAPI_LIST_APPEND(tail_addr, address_item);
1686 
1687             address_item->ip_address = addr_str;
1688             address_item->prefix = guest_ip_prefix(ip_addr);
1689             if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1690                 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1691             } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1692                 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1693             }
1694         }
1695         if (head_addr) {
1696             info->has_ip_addresses = true;
1697             info->ip_addresses = head_addr;
1698         }
1699         if (!info->statistics) {
1700             interface_stat = g_malloc0(sizeof(*interface_stat));
1701             if (guest_get_network_stats(addr->AdapterName, interface_stat)
1702                 == -1) {
1703                 g_free(interface_stat);
1704             } else {
1705                 info->statistics = interface_stat;
1706             }
1707         }
1708     }
1709     WSACleanup();
1710 out:
1711     g_free(adptr_addrs);
1712     return head;
1713 }
1714 
1715 static int64_t filetime_to_ns(const FILETIME *tf)
1716 {
1717     return ((((int64_t)tf->dwHighDateTime << 32) | tf->dwLowDateTime)
1718             - W32_FT_OFFSET) * 100;
1719 }
1720 
1721 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1722 {
1723     Error *local_err = NULL;
1724     SYSTEMTIME ts;
1725     FILETIME tf;
1726     LONGLONG time;
1727 
1728     if (!has_time) {
1729         /* Unfortunately, Windows libraries don't provide an easy way to access
1730          * RTC yet:
1731          *
1732          * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1733          *
1734          * Instead, a workaround is to use the Windows win32tm command to
1735          * resync the time using the Windows Time service.
1736          */
1737         LPVOID msg_buffer;
1738         DWORD ret_flags;
1739 
1740         HRESULT hr = system("w32tm /resync /nowait");
1741 
1742         if (GetLastError() != 0) {
1743             strerror_s((LPTSTR) & msg_buffer, 0, errno);
1744             error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1745         } else if (hr != 0) {
1746             if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1747                 error_setg(errp, "Windows Time service not running on the "
1748                                  "guest");
1749             } else {
1750                 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1751                                    FORMAT_MESSAGE_FROM_SYSTEM |
1752                                    FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1753                                    (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1754                                    SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1755                                    NULL)) {
1756                     error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1757                                      "t retrieve error message", hr);
1758                 } else {
1759                     error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1760                                (LPCTSTR)msg_buffer);
1761                     LocalFree(msg_buffer);
1762                 }
1763             }
1764         } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1765             error_setg(errp, "No internet connection on guest, sync not "
1766                              "accurate");
1767         }
1768         return;
1769     }
1770 
1771     /* Validate time passed by user. */
1772     if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1773         error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1774         return;
1775     }
1776 
1777     time = time_ns / 100 + W32_FT_OFFSET;
1778 
1779     tf.dwLowDateTime = (DWORD) time;
1780     tf.dwHighDateTime = (DWORD) (time >> 32);
1781 
1782     if (!FileTimeToSystemTime(&tf, &ts)) {
1783         error_setg(errp, "Failed to convert system time %d",
1784                    (int)GetLastError());
1785         return;
1786     }
1787 
1788     acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1789     if (local_err) {
1790         error_propagate(errp, local_err);
1791         return;
1792     }
1793 
1794     if (!SetSystemTime(&ts)) {
1795         error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1796         return;
1797     }
1798 }
1799 
1800 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1801 {
1802     PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1803     DWORD length;
1804     GuestLogicalProcessorList *head, **tail;
1805     Error *local_err = NULL;
1806     int64_t current;
1807 
1808     ptr = pslpi = NULL;
1809     length = 0;
1810     current = 0;
1811     head = NULL;
1812     tail = &head;
1813 
1814     if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1815         (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1816         (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1817         ptr = pslpi = g_malloc0(length);
1818         if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1819             error_setg(&local_err, "Failed to get processor information: %d",
1820                        (int)GetLastError());
1821         }
1822     } else {
1823         error_setg(&local_err,
1824                    "Failed to get processor information buffer length: %d",
1825                    (int)GetLastError());
1826     }
1827 
1828     while ((local_err == NULL) && (length > 0)) {
1829         if (pslpi->Relationship == RelationProcessorCore) {
1830             ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1831 
1832             while (cpu_bits > 0) {
1833                 if (!!(cpu_bits & 1)) {
1834                     GuestLogicalProcessor *vcpu;
1835 
1836                     vcpu = g_malloc0(sizeof *vcpu);
1837                     vcpu->logical_id = current++;
1838                     vcpu->online = true;
1839                     vcpu->has_can_offline = true;
1840 
1841                     QAPI_LIST_APPEND(tail, vcpu);
1842                 }
1843                 cpu_bits >>= 1;
1844             }
1845         }
1846         length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1847         pslpi++; /* next entry */
1848     }
1849 
1850     g_free(ptr);
1851 
1852     if (local_err == NULL) {
1853         if (head != NULL) {
1854             return head;
1855         }
1856         /* there's no guest with zero VCPUs */
1857         error_setg(&local_err, "Guest reported zero VCPUs");
1858     }
1859 
1860     qapi_free_GuestLogicalProcessorList(head);
1861     error_propagate(errp, local_err);
1862     return NULL;
1863 }
1864 
1865 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1866 {
1867     error_setg(errp, QERR_UNSUPPORTED);
1868     return -1;
1869 }
1870 
1871 static gchar *
1872 get_net_error_message(gint error)
1873 {
1874     HMODULE module = NULL;
1875     gchar *retval = NULL;
1876     wchar_t *msg = NULL;
1877     int flags;
1878     size_t nchars;
1879 
1880     flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1881         FORMAT_MESSAGE_IGNORE_INSERTS |
1882         FORMAT_MESSAGE_FROM_SYSTEM;
1883 
1884     if (error >= NERR_BASE && error <= MAX_NERR) {
1885         module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1886 
1887         if (module != NULL) {
1888             flags |= FORMAT_MESSAGE_FROM_HMODULE;
1889         }
1890     }
1891 
1892     FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1893 
1894     if (msg != NULL) {
1895         nchars = wcslen(msg);
1896 
1897         if (nchars >= 2 &&
1898             msg[nchars - 1] == L'\n' &&
1899             msg[nchars - 2] == L'\r') {
1900             msg[nchars - 2] = L'\0';
1901         }
1902 
1903         retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1904 
1905         LocalFree(msg);
1906     }
1907 
1908     if (module != NULL) {
1909         FreeLibrary(module);
1910     }
1911 
1912     return retval;
1913 }
1914 
1915 void qmp_guest_set_user_password(const char *username,
1916                                  const char *password,
1917                                  bool crypted,
1918                                  Error **errp)
1919 {
1920     NET_API_STATUS nas;
1921     char *rawpasswddata = NULL;
1922     size_t rawpasswdlen;
1923     wchar_t *user = NULL, *wpass = NULL;
1924     USER_INFO_1003 pi1003 = { 0, };
1925     GError *gerr = NULL;
1926 
1927     if (crypted) {
1928         error_setg(errp, QERR_UNSUPPORTED);
1929         return;
1930     }
1931 
1932     rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1933     if (!rawpasswddata) {
1934         return;
1935     }
1936     rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1937     rawpasswddata[rawpasswdlen] = '\0';
1938 
1939     user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1940     if (!user) {
1941         error_setg(errp, "can't convert 'username' to UTF-16: %s",
1942                    gerr->message);
1943         g_error_free(gerr);
1944         goto done;
1945     }
1946 
1947     wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1948     if (!wpass) {
1949         error_setg(errp, "can't convert 'password' to UTF-16: %s",
1950                    gerr->message);
1951         g_error_free(gerr);
1952         goto done;
1953     }
1954 
1955     pi1003.usri1003_password = wpass;
1956     nas = NetUserSetInfo(NULL, user,
1957                          1003, (LPBYTE)&pi1003,
1958                          NULL);
1959 
1960     if (nas != NERR_Success) {
1961         gchar *msg = get_net_error_message(nas);
1962         error_setg(errp, "failed to set password: %s", msg);
1963         g_free(msg);
1964     }
1965 
1966 done:
1967     g_free(user);
1968     g_free(wpass);
1969     g_free(rawpasswddata);
1970 }
1971 
1972 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1973 {
1974     error_setg(errp, QERR_UNSUPPORTED);
1975     return NULL;
1976 }
1977 
1978 GuestMemoryBlockResponseList *
1979 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1980 {
1981     error_setg(errp, QERR_UNSUPPORTED);
1982     return NULL;
1983 }
1984 
1985 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1986 {
1987     error_setg(errp, QERR_UNSUPPORTED);
1988     return NULL;
1989 }
1990 
1991 /* add unsupported commands to the list of blocked RPCs */
1992 GList *ga_command_init_blockedrpcs(GList *blockedrpcs)
1993 {
1994     const char *list_unsupported[] = {
1995         "guest-suspend-hybrid",
1996         "guest-set-vcpus",
1997         "guest-get-memory-blocks", "guest-set-memory-blocks",
1998         "guest-get-memory-block-size", "guest-get-memory-block-info",
1999         NULL};
2000     char **p = (char **)list_unsupported;
2001 
2002     while (*p) {
2003         blockedrpcs = g_list_append(blockedrpcs, g_strdup(*p++));
2004     }
2005 
2006     if (!vss_init(true)) {
2007         g_debug("vss_init failed, vss commands are going to be disabled");
2008         const char *list[] = {
2009             "guest-get-fsinfo", "guest-fsfreeze-status",
2010             "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
2011         p = (char **)list;
2012 
2013         while (*p) {
2014             blockedrpcs = g_list_append(blockedrpcs, g_strdup(*p++));
2015         }
2016     }
2017 
2018     return blockedrpcs;
2019 }
2020 
2021 /* register init/cleanup routines for stateful command groups */
2022 void ga_command_state_init(GAState *s, GACommandState *cs)
2023 {
2024     if (!vss_initialized()) {
2025         ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2026     }
2027 }
2028 
2029 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
2030 typedef struct _GA_WTSINFOA {
2031     WTS_CONNECTSTATE_CLASS State;
2032     DWORD SessionId;
2033     DWORD IncomingBytes;
2034     DWORD OutgoingBytes;
2035     DWORD IncomingFrames;
2036     DWORD OutgoingFrames;
2037     DWORD IncomingCompressedBytes;
2038     DWORD OutgoingCompressedBy;
2039     CHAR WinStationName[WINSTATIONNAME_LENGTH];
2040     CHAR Domain[DOMAIN_LENGTH];
2041     CHAR UserName[USERNAME_LENGTH + 1];
2042     LARGE_INTEGER ConnectTime;
2043     LARGE_INTEGER DisconnectTime;
2044     LARGE_INTEGER LastInputTime;
2045     LARGE_INTEGER LogonTime;
2046     LARGE_INTEGER CurrentTime;
2047 
2048 } GA_WTSINFOA;
2049 
2050 GuestUserList *qmp_guest_get_users(Error **errp)
2051 {
2052 #define QGA_NANOSECONDS 10000000
2053 
2054     GHashTable *cache = NULL;
2055     GuestUserList *head = NULL, **tail = &head;
2056 
2057     DWORD buffer_size = 0, count = 0, i = 0;
2058     GA_WTSINFOA *info = NULL;
2059     WTS_SESSION_INFOA *entries = NULL;
2060     GuestUser *user = NULL;
2061     gpointer value = NULL;
2062     INT64 login = 0;
2063     double login_time = 0;
2064 
2065     cache = g_hash_table_new(g_str_hash, g_str_equal);
2066 
2067     if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
2068         for (i = 0; i < count; ++i) {
2069             buffer_size = 0;
2070             info = NULL;
2071             if (WTSQuerySessionInformationA(
2072                 NULL,
2073                 entries[i].SessionId,
2074                 WTSSessionInfo,
2075                 (LPSTR *)&info,
2076                 &buffer_size
2077             )) {
2078 
2079                 if (strlen(info->UserName) == 0) {
2080                     WTSFreeMemory(info);
2081                     continue;
2082                 }
2083 
2084                 login = info->LogonTime.QuadPart;
2085                 login -= W32_FT_OFFSET;
2086                 login_time = ((double)login) / QGA_NANOSECONDS;
2087 
2088                 if (g_hash_table_contains(cache, info->UserName)) {
2089                     value = g_hash_table_lookup(cache, info->UserName);
2090                     user = (GuestUser *)value;
2091                     if (user->login_time > login_time) {
2092                         user->login_time = login_time;
2093                     }
2094                 } else {
2095                     user = g_new0(GuestUser, 1);
2096 
2097                     user->user = g_strdup(info->UserName);
2098                     user->domain = g_strdup(info->Domain);
2099 
2100                     user->login_time = login_time;
2101 
2102                     g_hash_table_add(cache, user->user);
2103 
2104                     QAPI_LIST_APPEND(tail, user);
2105                 }
2106             }
2107             WTSFreeMemory(info);
2108         }
2109         WTSFreeMemory(entries);
2110     }
2111     g_hash_table_destroy(cache);
2112     return head;
2113 }
2114 
2115 typedef struct _ga_matrix_lookup_t {
2116     int major;
2117     int minor;
2118     const char *version;
2119     const char *version_id;
2120 } ga_matrix_lookup_t;
2121 
2122 static const ga_matrix_lookup_t WIN_CLIENT_VERSION_MATRIX[] = {
2123     { 5, 0, "Microsoft Windows 2000",   "2000"},
2124     { 5, 1, "Microsoft Windows XP",     "xp"},
2125     { 6, 0, "Microsoft Windows Vista",  "vista"},
2126     { 6, 1, "Microsoft Windows 7"       "7"},
2127     { 6, 2, "Microsoft Windows 8",      "8"},
2128     { 6, 3, "Microsoft Windows 8.1",    "8.1"},
2129     { }
2130 };
2131 
2132 static const ga_matrix_lookup_t WIN_SERVER_VERSION_MATRIX[] = {
2133     { 5, 2, "Microsoft Windows Server 2003",        "2003"},
2134     { 6, 0, "Microsoft Windows Server 2008",        "2008"},
2135     { 6, 1, "Microsoft Windows Server 2008 R2",     "2008r2"},
2136     { 6, 2, "Microsoft Windows Server 2012",        "2012"},
2137     { 6, 3, "Microsoft Windows Server 2012 R2",     "2012r2"},
2138     { },
2139 };
2140 
2141 typedef struct _ga_win_10_0_t {
2142     int first_build;
2143     const char *version;
2144     const char *version_id;
2145 } ga_win_10_0_t;
2146 
2147 static const ga_win_10_0_t WIN_10_0_SERVER_VERSION_MATRIX[] = {
2148     {14393, "Microsoft Windows Server 2016",    "2016"},
2149     {17763, "Microsoft Windows Server 2019",    "2019"},
2150     {20344, "Microsoft Windows Server 2022",    "2022"},
2151     {26040, "MIcrosoft Windows Server 2025",    "2025"},
2152     { }
2153 };
2154 
2155 static const ga_win_10_0_t WIN_10_0_CLIENT_VERSION_MATRIX[] = {
2156     {10240, "Microsoft Windows 10",    "10"},
2157     {22000, "Microsoft Windows 11",    "11"},
2158     { }
2159 };
2160 
2161 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2162 {
2163     typedef NTSTATUS(WINAPI *rtl_get_version_t)(
2164         RTL_OSVERSIONINFOEXW *os_version_info_ex);
2165 
2166     info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2167 
2168     HMODULE module = GetModuleHandle("ntdll");
2169     PVOID fun = GetProcAddress(module, "RtlGetVersion");
2170     if (fun == NULL) {
2171         error_setg(errp, "Failed to get address of RtlGetVersion");
2172         return;
2173     }
2174 
2175     rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2176     rtl_get_version(info);
2177     return;
2178 }
2179 
2180 static char *ga_get_win_name(const OSVERSIONINFOEXW *os_version, bool id)
2181 {
2182     DWORD major = os_version->dwMajorVersion;
2183     DWORD minor = os_version->dwMinorVersion;
2184     DWORD build = os_version->dwBuildNumber;
2185     int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2186     const ga_matrix_lookup_t *table = tbl_idx ?
2187         WIN_SERVER_VERSION_MATRIX : WIN_CLIENT_VERSION_MATRIX;
2188     const ga_win_10_0_t *win_10_0_table = tbl_idx ?
2189         WIN_10_0_SERVER_VERSION_MATRIX : WIN_10_0_CLIENT_VERSION_MATRIX;
2190     const ga_win_10_0_t *win_10_0_version = NULL;
2191     while (table->version != NULL) {
2192         if (major == 10 && minor == 0) {
2193             while (win_10_0_table->version != NULL) {
2194                 if (build >= win_10_0_table->first_build) {
2195                     win_10_0_version = win_10_0_table;
2196                 }
2197                 win_10_0_table++;
2198             }
2199             if (win_10_0_table) {
2200                 if (id) {
2201                     return g_strdup(win_10_0_version->version_id);
2202                 } else {
2203                     return g_strdup(win_10_0_version->version);
2204                 }
2205             }
2206         } else if (major == table->major && minor == table->minor) {
2207             if (id) {
2208                 return g_strdup(table->version_id);
2209             } else {
2210                 return g_strdup(table->version);
2211             }
2212         }
2213         ++table;
2214     }
2215     slog("failed to lookup Windows version: major=%lu, minor=%lu",
2216         major, minor);
2217     return g_strdup("N/A");
2218 }
2219 
2220 static char *ga_get_win_product_name(Error **errp)
2221 {
2222     HKEY key = INVALID_HANDLE_VALUE;
2223     DWORD size = 128;
2224     char *result = g_malloc0(size);
2225     LONG err = ERROR_SUCCESS;
2226 
2227     err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2228                       "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2229                       &key);
2230     if (err != ERROR_SUCCESS) {
2231         error_setg_win32(errp, err, "failed to open registry key");
2232         g_free(result);
2233         return NULL;
2234     }
2235 
2236     err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2237                             (LPBYTE)result, &size);
2238     if (err == ERROR_MORE_DATA) {
2239         slog("ProductName longer than expected (%lu bytes), retrying",
2240                 size);
2241         g_free(result);
2242         result = NULL;
2243         if (size > 0) {
2244             result = g_malloc0(size);
2245             err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2246                                     (LPBYTE)result, &size);
2247         }
2248     }
2249     if (err != ERROR_SUCCESS) {
2250         error_setg_win32(errp, err, "failed to retrieve ProductName");
2251         goto fail;
2252     }
2253 
2254     RegCloseKey(key);
2255     return result;
2256 
2257 fail:
2258     if (key != INVALID_HANDLE_VALUE) {
2259         RegCloseKey(key);
2260     }
2261     g_free(result);
2262     return NULL;
2263 }
2264 
2265 static char *ga_get_current_arch(void)
2266 {
2267     SYSTEM_INFO info;
2268     GetNativeSystemInfo(&info);
2269     char *result = NULL;
2270     switch (info.wProcessorArchitecture) {
2271     case PROCESSOR_ARCHITECTURE_AMD64:
2272         result = g_strdup("x86_64");
2273         break;
2274     case PROCESSOR_ARCHITECTURE_ARM:
2275         result = g_strdup("arm");
2276         break;
2277     case PROCESSOR_ARCHITECTURE_IA64:
2278         result = g_strdup("ia64");
2279         break;
2280     case PROCESSOR_ARCHITECTURE_INTEL:
2281         result = g_strdup("x86");
2282         break;
2283     case PROCESSOR_ARCHITECTURE_UNKNOWN:
2284     default:
2285         slog("unknown processor architecture 0x%0x",
2286             info.wProcessorArchitecture);
2287         result = g_strdup("unknown");
2288         break;
2289     }
2290     return result;
2291 }
2292 
2293 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2294 {
2295     Error *local_err = NULL;
2296     OSVERSIONINFOEXW os_version = {0};
2297     bool server;
2298     char *product_name;
2299     GuestOSInfo *info;
2300 
2301     ga_get_win_version(&os_version, &local_err);
2302     if (local_err) {
2303         error_propagate(errp, local_err);
2304         return NULL;
2305     }
2306 
2307     server = os_version.wProductType != VER_NT_WORKSTATION;
2308     product_name = ga_get_win_product_name(errp);
2309     if (product_name == NULL) {
2310         return NULL;
2311     }
2312 
2313     info = g_new0(GuestOSInfo, 1);
2314 
2315     info->kernel_version = g_strdup_printf("%lu.%lu",
2316         os_version.dwMajorVersion,
2317         os_version.dwMinorVersion);
2318     info->kernel_release = g_strdup_printf("%lu",
2319         os_version.dwBuildNumber);
2320     info->machine = ga_get_current_arch();
2321 
2322     info->id = g_strdup("mswindows");
2323     info->name = g_strdup("Microsoft Windows");
2324     info->pretty_name = product_name;
2325     info->version = ga_get_win_name(&os_version, false);
2326     info->version_id = ga_get_win_name(&os_version, true);
2327     info->variant = g_strdup(server ? "server" : "client");
2328     info->variant_id = g_strdup(server ? "server" : "client");
2329 
2330     return info;
2331 }
2332 
2333 /*
2334  * Safely get device property. Returned strings are using wide characters.
2335  * Caller is responsible for freeing the buffer.
2336  */
2337 static LPBYTE cm_get_property(DEVINST devInst, const DEVPROPKEY *propName,
2338     PDEVPROPTYPE propType)
2339 {
2340     CONFIGRET cr;
2341     g_autofree LPBYTE buffer = NULL;
2342     ULONG buffer_len = 0;
2343 
2344     /* First query for needed space */
2345     cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2346         buffer, &buffer_len, 0);
2347     if (cr != CR_SUCCESS && cr != CR_BUFFER_SMALL) {
2348 
2349         slog("failed to get property size, error=0x%lx", cr);
2350         return NULL;
2351     }
2352     buffer = g_new0(BYTE, buffer_len + 1);
2353     cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2354         buffer, &buffer_len, 0);
2355     if (cr != CR_SUCCESS) {
2356         slog("failed to get device property, error=0x%lx", cr);
2357         return NULL;
2358     }
2359     return g_steal_pointer(&buffer);
2360 }
2361 
2362 static GStrv ga_get_hardware_ids(DEVINST devInstance)
2363 {
2364     GArray *values = NULL;
2365     DEVPROPTYPE cm_type;
2366     LPWSTR id;
2367     g_autofree LPWSTR property = (LPWSTR)cm_get_property(devInstance,
2368         &qga_DEVPKEY_Device_HardwareIds, &cm_type);
2369     if (property == NULL) {
2370         slog("failed to get hardware IDs");
2371         return NULL;
2372     }
2373     if (*property == '\0') {
2374         /* empty list */
2375         return NULL;
2376     }
2377     values = g_array_new(TRUE, TRUE, sizeof(gchar *));
2378     for (id = property; '\0' != *id; id += lstrlenW(id) + 1) {
2379         gchar *id8 = g_utf16_to_utf8(id, -1, NULL, NULL, NULL);
2380         g_array_append_val(values, id8);
2381     }
2382     return (GStrv)g_array_free(values, FALSE);
2383 }
2384 
2385 /*
2386  * https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
2387  */
2388 #define DEVICE_PCI_RE "PCI\\\\VEN_(1AF4|1B36)&DEV_([0-9A-B]{4})(&|$)"
2389 
2390 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
2391 {
2392     GuestDeviceInfoList *head = NULL, **tail = &head;
2393     HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2394     SP_DEVINFO_DATA dev_info_data;
2395     int i, j;
2396     GError *gerr = NULL;
2397     g_autoptr(GRegex) device_pci_re = NULL;
2398     DEVPROPTYPE cm_type;
2399 
2400     device_pci_re = g_regex_new(DEVICE_PCI_RE,
2401         G_REGEX_ANCHORED | G_REGEX_OPTIMIZE, 0,
2402         &gerr);
2403     g_assert(device_pci_re != NULL);
2404 
2405     dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
2406     dev_info = SetupDiGetClassDevs(0, 0, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES);
2407     if (dev_info == INVALID_HANDLE_VALUE) {
2408         error_setg(errp, "failed to get device tree");
2409         return NULL;
2410     }
2411 
2412     slog("enumerating devices");
2413     for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
2414         bool skip = true;
2415         g_autofree LPWSTR name = NULL;
2416         g_autofree LPFILETIME date = NULL;
2417         g_autofree LPWSTR version = NULL;
2418         g_auto(GStrv) hw_ids = NULL;
2419         g_autoptr(GuestDeviceInfo) device = g_new0(GuestDeviceInfo, 1);
2420         g_autofree char *vendor_id = NULL;
2421         g_autofree char *device_id = NULL;
2422 
2423         name = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2424             &qga_DEVPKEY_NAME, &cm_type);
2425         if (name == NULL) {
2426             slog("failed to get device description");
2427             continue;
2428         }
2429         device->driver_name = g_utf16_to_utf8(name, -1, NULL, NULL, NULL);
2430         if (device->driver_name == NULL) {
2431             error_setg(errp, "conversion to utf8 failed (driver name)");
2432             return NULL;
2433         }
2434         slog("querying device: %s", device->driver_name);
2435         hw_ids = ga_get_hardware_ids(dev_info_data.DevInst);
2436         if (hw_ids == NULL) {
2437             continue;
2438         }
2439         for (j = 0; hw_ids[j] != NULL; j++) {
2440             g_autoptr(GMatchInfo) match_info;
2441             GuestDeviceIdPCI *id;
2442             if (!g_regex_match(device_pci_re, hw_ids[j], 0, &match_info)) {
2443                 continue;
2444             }
2445             skip = false;
2446 
2447             vendor_id = g_match_info_fetch(match_info, 1);
2448             device_id = g_match_info_fetch(match_info, 2);
2449 
2450             device->id = g_new0(GuestDeviceId, 1);
2451             device->id->type = GUEST_DEVICE_TYPE_PCI;
2452             id = &device->id->u.pci;
2453             id->vendor_id = g_ascii_strtoull(vendor_id, NULL, 16);
2454             id->device_id = g_ascii_strtoull(device_id, NULL, 16);
2455 
2456             break;
2457         }
2458         if (skip) {
2459             continue;
2460         }
2461 
2462         version = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2463             &qga_DEVPKEY_Device_DriverVersion, &cm_type);
2464         if (version == NULL) {
2465             slog("failed to get driver version");
2466             continue;
2467         }
2468         device->driver_version = g_utf16_to_utf8(version, -1, NULL,
2469             NULL, NULL);
2470         if (device->driver_version == NULL) {
2471             error_setg(errp, "conversion to utf8 failed (driver version)");
2472             return NULL;
2473         }
2474 
2475         date = (LPFILETIME)cm_get_property(dev_info_data.DevInst,
2476             &qga_DEVPKEY_Device_DriverDate, &cm_type);
2477         if (date == NULL) {
2478             slog("failed to get driver date");
2479             continue;
2480         }
2481         device->driver_date = filetime_to_ns(date);
2482         device->has_driver_date = true;
2483 
2484         slog("driver: %s\ndriver version: %" PRId64 ",%s\n",
2485              device->driver_name, device->driver_date,
2486              device->driver_version);
2487         QAPI_LIST_APPEND(tail, g_steal_pointer(&device));
2488     }
2489 
2490     if (dev_info != INVALID_HANDLE_VALUE) {
2491         SetupDiDestroyDeviceInfoList(dev_info);
2492     }
2493     return head;
2494 }
2495 
2496 char *qga_get_host_name(Error **errp)
2497 {
2498     wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
2499     DWORD size = G_N_ELEMENTS(tmp);
2500 
2501     if (GetComputerNameW(tmp, &size) == 0) {
2502         error_setg_win32(errp, GetLastError(), "failed close handle");
2503         return NULL;
2504     }
2505 
2506     return g_utf16_to_utf8(tmp, size, NULL, NULL, NULL);
2507 }
2508 
2509 GuestDiskStatsInfoList *qmp_guest_get_diskstats(Error **errp)
2510 {
2511     error_setg(errp, QERR_UNSUPPORTED);
2512     return NULL;
2513 }
2514 
2515 GuestCpuStatsList *qmp_guest_get_cpustats(Error **errp)
2516 {
2517     error_setg(errp, QERR_UNSUPPORTED);
2518     return NULL;
2519 }
2520