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