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