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