qcow2: Fix corruption on write_zeroes with MAY_UNMAP
[qemu/ar7.git] / qga / commands-win32.c
blob300b87c859af3155cf84136b925e1cbd2fb5fc8c
1 /*
2 * QEMU Guest Agent win32-specific command implementations
4 * Copyright IBM Corp. 2012
6 * Authors:
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Gal Hammer <ghammer@redhat.com>
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.
13 #include "qemu/osdep.h"
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>
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"
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.
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
72 #define CM_Get_DevNode_Property CM_Get_DevNode_PropertyW
73 #pragma GCC diagnostic pop
74 #endif
76 #ifndef SHTDN_REASON_FLAG_PLANNED
77 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
78 #endif
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))
86 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
88 struct GuestFileHandle {
89 int64_t id;
90 HANDLE fh;
91 QTAILQ_ENTRY(GuestFileHandle) next;
94 static struct {
95 QTAILQ_HEAD(, GuestFileHandle) filehandles;
96 } guest_file_state = {
97 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
100 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
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 }
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)
130 static OpenFlags *find_open_flag(const char *mode_str)
132 int mode;
133 Error **errp = NULL;
135 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
136 OpenFlags *flags = guest_file_open_modes + mode;
138 if (strcmp(flags->forms, mode_str) == 0) {
139 return flags;
143 error_setg(errp, "invalid file open mode '%s'", mode_str);
144 return NULL;
147 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
149 GuestFileHandle *gfh;
150 int64_t handle;
152 handle = ga_get_fd_handle(ga_state, errp);
153 if (handle < 0) {
154 return -1;
156 gfh = g_new0(GuestFileHandle, 1);
157 gfh->id = handle;
158 gfh->fh = fh;
159 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
161 return handle;
164 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
166 GuestFileHandle *gfh;
167 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
168 if (gfh->id == id) {
169 return gfh;
172 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
173 return NULL;
176 static void handle_set_nonblocking(HANDLE fh)
178 DWORD file_type, pipe_state;
179 file_type = GetFileType(fh);
180 if (file_type != FILE_TYPE_PIPE) {
181 return;
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;
189 /* The fd is named pipe fd */
190 if (pipe_state & PIPE_NOWAIT) {
191 return;
194 pipe_state |= PIPE_NOWAIT;
195 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
198 int64_t qmp_guest_file_open(const char *path, bool has_mode,
199 const char *mode, Error **errp)
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;
211 if (!has_mode) {
212 mode = "r";
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;
221 w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
222 if (!w_path) {
223 goto done;
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;
235 /* set fd non-blocking to avoid common use cases (like reading from a
236 * named pipe) from hanging the agent
238 handle_set_nonblocking(fh);
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;
247 slog("guest-file-open, handle: % " PRId64, fd);
249 done:
250 if (gerr) {
251 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
252 g_error_free(gerr);
254 g_free(w_path);
255 return fd;
258 void qmp_guest_file_close(int64_t handle, Error **errp)
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;
266 ret = CloseHandle(gfh->fh);
267 if (!ret) {
268 error_setg_win32(errp, GetLastError(), "failed close handle");
269 return;
272 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
273 g_free(gfh);
276 static void acquire_privilege(const char *name, Error **errp)
278 HANDLE token = NULL;
279 TOKEN_PRIVILEGES priv;
280 Error *local_err = NULL;
282 if (OpenProcessToken(GetCurrentProcess(),
283 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
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;
291 priv.PrivilegeCount = 1;
292 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
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;
300 } else {
301 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
302 "failed to open privilege token");
305 out:
306 if (token) {
307 CloseHandle(token);
309 error_propagate(errp, local_err);
312 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
313 Error **errp)
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");
322 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
324 Error *local_err = NULL;
325 UINT shutdown_flag = EWX_FORCE;
327 slog("guest-shutdown called, mode: %s", mode);
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|reboot");
338 return;
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;
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");
356 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
357 int64_t count, Error **errp)
359 GuestFileRead *read_data = NULL;
360 guchar *buf;
361 HANDLE fh = gfh->fh;
362 bool is_ok;
363 DWORD read_count;
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;
375 if (read_count != 0) {
376 read_data->buf_b64 = g_base64_encode(buf, read_count);
379 g_free(buf);
381 return read_data;
384 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
385 bool has_count, int64_t count,
386 Error **errp)
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;
396 if (!gfh) {
397 return NULL;
399 fh = gfh->fh;
400 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
401 if (!buf) {
402 return NULL;
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;
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;
422 done:
423 g_free(buf);
424 return write_data;
427 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
428 GuestFileWhence *whence_code,
429 Error **errp)
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;
440 gfh = guest_file_handle_find(handle, errp);
441 if (!gfh) {
442 return NULL;
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;
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;
458 seek_data = g_new0(GuestFileSeek, 1);
459 seek_data->position = new_pos.QuadPart;
460 return seek_data;
463 void qmp_guest_file_flush(int64_t handle, Error **errp)
465 HANDLE fh;
466 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
467 if (!gfh) {
468 return;
471 fh = gfh->fh;
472 if (!FlushFileBuffers(fh)) {
473 error_setg_win32(errp, GetLastError(), "failed to flush file");
477 #ifdef CONFIG_QGA_NTDDSCSI
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
500 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
502 if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
503 return GUEST_DISK_BUS_TYPE_UNKNOWN;
505 return win2qemu[(int)bus];
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);
515 static GuestPCIAddress *get_pci_info(int number, Error **errp)
517 HDEVINFO dev_info;
518 SP_DEVINFO_DATA dev_info_data;
519 SP_DEVICE_INTERFACE_DATA dev_iface_data;
520 HANDLE dev_file;
521 int i;
522 GuestPCIAddress *pci = NULL;
523 bool partial_pci = false;
525 pci = g_malloc0(sizeof(*pci));
526 pci->domain = -1;
527 pci->slot = -1;
528 pci->function = -1;
529 pci->bus = -1;
531 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
532 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
533 if (dev_info == INVALID_HANDLE_VALUE) {
534 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
535 goto out;
538 g_debug("enumerating devices");
539 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
540 dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
541 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
542 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
543 STORAGE_DEVICE_NUMBER sdn;
544 char *parent_dev_id = NULL;
545 HDEVINFO parent_dev_info;
546 SP_DEVINFO_DATA parent_dev_info_data;
547 DWORD j;
548 DWORD size = 0;
550 g_debug("getting device path");
551 if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
552 &GUID_DEVINTERFACE_DISK, 0,
553 &dev_iface_data)) {
554 while (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
555 pdev_iface_detail_data,
556 size, &size,
557 &dev_info_data)) {
558 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
559 pdev_iface_detail_data = g_malloc(size);
560 pdev_iface_detail_data->cbSize =
561 sizeof(*pdev_iface_detail_data);
562 } else {
563 error_setg_win32(errp, GetLastError(),
564 "failed to get device interfaces");
565 goto free_dev_info;
569 dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
570 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
571 NULL);
572 g_free(pdev_iface_detail_data);
574 if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
575 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
576 CloseHandle(dev_file);
577 error_setg_win32(errp, GetLastError(),
578 "failed to get device slot number");
579 goto free_dev_info;
582 CloseHandle(dev_file);
583 if (sdn.DeviceNumber != number) {
584 continue;
586 } else {
587 error_setg_win32(errp, GetLastError(),
588 "failed to get device interfaces");
589 goto free_dev_info;
592 g_debug("found device slot %d. Getting storage controller", number);
594 CONFIGRET cr;
595 DEVINST dev_inst, parent_dev_inst;
596 ULONG dev_id_size = 0;
598 size = 0;
599 while (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
600 parent_dev_id, size, &size)) {
601 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
602 parent_dev_id = g_malloc(size);
603 } else {
604 error_setg_win32(errp, GetLastError(),
605 "failed to get device instance ID");
606 goto out;
611 * CM API used here as opposed to
612 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
613 * which exports are only available in mingw-w64 6+
615 cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
616 if (cr != CR_SUCCESS) {
617 g_error("CM_Locate_DevInst failed with code %lx", cr);
618 error_setg_win32(errp, GetLastError(),
619 "failed to get device instance");
620 goto out;
622 cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
623 if (cr != CR_SUCCESS) {
624 g_error("CM_Get_Parent failed with code %lx", cr);
625 error_setg_win32(errp, GetLastError(),
626 "failed to get parent device instance");
627 goto out;
630 cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
631 if (cr != CR_SUCCESS) {
632 g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
633 error_setg_win32(errp, GetLastError(),
634 "failed to get parent device ID length");
635 goto out;
638 ++dev_id_size;
639 if (dev_id_size > size) {
640 g_free(parent_dev_id);
641 parent_dev_id = g_malloc(dev_id_size);
644 cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
646 if (cr != CR_SUCCESS) {
647 g_error("CM_Get_Device_ID failed with code %lx", cr);
648 error_setg_win32(errp, GetLastError(),
649 "failed to get parent device ID");
650 goto out;
654 g_debug("querying storage controller %s for PCI information",
655 parent_dev_id);
656 parent_dev_info =
657 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
658 NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
659 g_free(parent_dev_id);
661 if (parent_dev_info == INVALID_HANDLE_VALUE) {
662 error_setg_win32(errp, GetLastError(),
663 "failed to get parent device");
664 goto out;
667 parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
668 if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
669 error_setg_win32(errp, GetLastError(),
670 "failed to get parent device data");
671 goto out;
674 for (j = 0;
675 SetupDiEnumDeviceInfo(parent_dev_info, j, &parent_dev_info_data);
676 j++) {
677 DWORD addr, bus, ui_slot, type;
678 int func, slot;
681 * There is no need to allocate buffer in the next functions. The
682 * size is known and ULONG according to
683 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
685 if (!SetupDiGetDeviceRegistryProperty(
686 parent_dev_info, &parent_dev_info_data, SPDRP_BUSNUMBER,
687 &type, (PBYTE)&bus, size, NULL)) {
688 debug_error("failed to get PCI bus");
689 bus = -1;
690 partial_pci = true;
694 * The function retrieves the device's address. This value will be
695 * transformed into device function and number
697 if (!SetupDiGetDeviceRegistryProperty(
698 parent_dev_info, &parent_dev_info_data, SPDRP_ADDRESS,
699 &type, (PBYTE)&addr, size, NULL)) {
700 debug_error("failed to get PCI address");
701 addr = -1;
702 partial_pci = true;
706 * This call returns UINumber of DEVICE_CAPABILITIES structure.
707 * This number is typically a user-perceived slot number.
709 if (!SetupDiGetDeviceRegistryProperty(
710 parent_dev_info, &parent_dev_info_data, SPDRP_UI_NUMBER,
711 &type, (PBYTE)&ui_slot, size, NULL)) {
712 debug_error("failed to get PCI slot");
713 ui_slot = -1;
714 partial_pci = true;
718 * SetupApi gives us the same information as driver with
719 * IoGetDeviceProperty. According to Microsoft:
721 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
722 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
723 * SPDRP_ADDRESS is propertyAddress, so we do the same.
725 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
727 if (partial_pci) {
728 pci->domain = -1;
729 pci->slot = -1;
730 pci->function = -1;
731 pci->bus = -1;
732 continue;
733 } else {
734 func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
735 slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
736 if ((int)ui_slot != slot) {
737 g_debug("mismatch with reported slot values: %d vs %d",
738 (int)ui_slot, slot);
740 pci->domain = 0;
741 pci->slot = (int)ui_slot;
742 pci->function = func;
743 pci->bus = (int)bus;
744 break;
747 SetupDiDestroyDeviceInfoList(parent_dev_info);
748 break;
751 free_dev_info:
752 SetupDiDestroyDeviceInfoList(dev_info);
753 out:
754 return pci;
757 static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
758 Error **errp)
760 STORAGE_PROPERTY_QUERY query;
761 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
762 DWORD received;
763 ULONG size = sizeof(buf);
765 dev_desc = &buf;
766 query.PropertyId = StorageDeviceProperty;
767 query.QueryType = PropertyStandardQuery;
769 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
770 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
771 size, &received, NULL)) {
772 error_setg_win32(errp, GetLastError(), "failed to get bus type");
773 return;
775 disk->bus_type = find_bus_type(dev_desc->BusType);
776 g_debug("bus type %d", disk->bus_type);
778 /* Query once more. Now with long enough buffer. */
779 size = dev_desc->Size;
780 dev_desc = g_malloc0(size);
781 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
782 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
783 size, &received, NULL)) {
784 error_setg_win32(errp, GetLastError(), "failed to get serial number");
785 g_debug("failed to get serial number");
786 goto out_free;
788 if (dev_desc->SerialNumberOffset > 0) {
789 const char *serial;
790 size_t len;
792 if (dev_desc->SerialNumberOffset >= received) {
793 error_setg(errp, "failed to get serial number: offset outside the buffer");
794 g_debug("serial number offset outside the buffer");
795 goto out_free;
797 serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
798 len = received - dev_desc->SerialNumberOffset;
799 g_debug("serial number \"%s\"", serial);
800 if (*serial != 0) {
801 disk->serial = g_strndup(serial, len);
802 disk->has_serial = true;
805 out_free:
806 g_free(dev_desc);
808 return;
811 static void get_single_disk_info(int disk_number,
812 GuestDiskAddress *disk, Error **errp)
814 SCSI_ADDRESS addr, *scsi_ad;
815 DWORD len;
816 HANDLE disk_h;
817 Error *local_err = NULL;
819 scsi_ad = &addr;
821 g_debug("getting disk info for: %s", disk->dev);
822 disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
823 0, NULL);
824 if (disk_h == INVALID_HANDLE_VALUE) {
825 error_setg_win32(errp, GetLastError(), "failed to open disk");
826 return;
829 get_disk_properties(disk_h, disk, &local_err);
830 if (local_err) {
831 error_propagate(errp, local_err);
832 goto err_close;
835 g_debug("bus type %d", disk->bus_type);
836 /* always set pci_controller as required by schema. get_pci_info() should
837 * report -1 values for non-PCI buses rather than fail. fail the command
838 * if that doesn't hold since that suggests some other unexpected
839 * breakage
841 disk->pci_controller = get_pci_info(disk_number, &local_err);
842 if (local_err) {
843 error_propagate(errp, local_err);
844 goto err_close;
846 if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
847 || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
848 || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
849 /* This bus type is not supported before Windows Server 2003 SP1 */
850 || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
852 /* We are able to use the same ioctls for different bus types
853 * according to Microsoft docs
854 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
855 g_debug("getting SCSI info");
856 if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
857 sizeof(SCSI_ADDRESS), &len, NULL)) {
858 disk->unit = addr.Lun;
859 disk->target = addr.TargetId;
860 disk->bus = addr.PathId;
862 /* We do not set error in this case, because we still have enough
863 * information about volume. */
866 err_close:
867 CloseHandle(disk_h);
868 return;
871 /* VSS provider works with volumes, thus there is no difference if
872 * the volume consist of spanned disks. Info about the first disk in the
873 * volume is returned for the spanned disk group (LVM) */
874 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
876 Error *local_err = NULL;
877 GuestDiskAddressList *list = NULL, *cur_item = NULL;
878 GuestDiskAddress *disk = NULL;
879 int i;
880 HANDLE vol_h;
881 DWORD size;
882 PVOLUME_DISK_EXTENTS extents = NULL;
884 /* strip final backslash */
885 char *name = g_strdup(guid);
886 if (g_str_has_suffix(name, "\\")) {
887 name[strlen(name) - 1] = 0;
890 g_debug("opening %s", name);
891 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
892 0, NULL);
893 if (vol_h == INVALID_HANDLE_VALUE) {
894 error_setg_win32(errp, GetLastError(), "failed to open volume");
895 goto out;
898 /* Get list of extents */
899 g_debug("getting disk extents");
900 size = sizeof(VOLUME_DISK_EXTENTS);
901 extents = g_malloc0(size);
902 if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
903 0, extents, size, &size, NULL)) {
904 DWORD last_err = GetLastError();
905 if (last_err == ERROR_MORE_DATA) {
906 /* Try once more with big enough buffer */
907 g_free(extents);
908 extents = g_malloc0(size);
909 if (!DeviceIoControl(
910 vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
911 0, extents, size, NULL, NULL)) {
912 error_setg_win32(errp, GetLastError(),
913 "failed to get disk extents");
914 goto out;
916 } else if (last_err == ERROR_INVALID_FUNCTION) {
917 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
918 g_debug("volume not on disk");
919 disk = g_malloc0(sizeof(GuestDiskAddress));
920 disk->has_dev = true;
921 disk->dev = g_strdup(name);
922 get_single_disk_info(0xffffffff, disk, &local_err);
923 if (local_err) {
924 g_debug("failed to get disk info, ignoring error: %s",
925 error_get_pretty(local_err));
926 error_free(local_err);
927 goto out;
929 list = g_malloc0(sizeof(*list));
930 list->value = disk;
931 disk = NULL;
932 list->next = NULL;
933 goto out;
934 } else {
935 error_setg_win32(errp, GetLastError(),
936 "failed to get disk extents");
937 goto out;
940 g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
942 /* Go through each extent */
943 for (i = 0; i < extents->NumberOfDiskExtents; i++) {
944 disk = g_malloc0(sizeof(GuestDiskAddress));
946 /* Disk numbers directly correspond to numbers used in UNCs
948 * See documentation for DISK_EXTENT:
949 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
951 * See also Naming Files, Paths and Namespaces:
952 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
954 disk->has_dev = true;
955 disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
956 extents->Extents[i].DiskNumber);
958 get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
959 if (local_err) {
960 error_propagate(errp, local_err);
961 goto out;
963 cur_item = g_malloc0(sizeof(*list));
964 cur_item->value = disk;
965 disk = NULL;
966 cur_item->next = list;
967 list = cur_item;
971 out:
972 if (vol_h != INVALID_HANDLE_VALUE) {
973 CloseHandle(vol_h);
975 qapi_free_GuestDiskAddress(disk);
976 g_free(extents);
977 g_free(name);
979 return list;
982 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
984 ERRP_GUARD();
985 GuestDiskInfoList *new = NULL, *ret = NULL;
986 HDEVINFO dev_info;
987 SP_DEVICE_INTERFACE_DATA dev_iface_data;
988 int i;
990 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
991 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
992 if (dev_info == INVALID_HANDLE_VALUE) {
993 error_setg_win32(errp, GetLastError(), "failed to get device tree");
994 return NULL;
997 g_debug("enumerating devices");
998 dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
999 for (i = 0;
1000 SetupDiEnumDeviceInterfaces(dev_info, NULL, &GUID_DEVINTERFACE_DISK,
1001 i, &dev_iface_data);
1002 i++) {
1003 GuestDiskAddress *address = NULL;
1004 GuestDiskInfo *disk = NULL;
1005 Error *local_err = NULL;
1006 g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA
1007 pdev_iface_detail_data = NULL;
1008 STORAGE_DEVICE_NUMBER sdn;
1009 HANDLE dev_file;
1010 DWORD size = 0;
1011 BOOL result;
1012 int attempt;
1014 g_debug(" getting device path");
1015 for (attempt = 0, result = FALSE; attempt < 2 && !result; attempt++) {
1016 result = SetupDiGetDeviceInterfaceDetail(dev_info,
1017 &dev_iface_data, pdev_iface_detail_data, size, &size, NULL);
1018 if (result) {
1019 break;
1021 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1022 pdev_iface_detail_data = g_realloc(pdev_iface_detail_data,
1023 size);
1024 pdev_iface_detail_data->cbSize =
1025 sizeof(*pdev_iface_detail_data);
1026 } else {
1027 g_debug("failed to get device interface details");
1028 break;
1031 if (!result) {
1032 g_debug("skipping device");
1033 continue;
1036 g_debug(" device: %s", pdev_iface_detail_data->DevicePath);
1037 dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
1038 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
1039 if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
1040 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
1041 CloseHandle(dev_file);
1042 debug_error("failed to get storage device number");
1043 continue;
1045 CloseHandle(dev_file);
1047 disk = g_new0(GuestDiskInfo, 1);
1048 disk->name = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
1049 sdn.DeviceNumber);
1051 g_debug(" number: %lu", sdn.DeviceNumber);
1052 address = g_malloc0(sizeof(GuestDiskAddress));
1053 address->has_dev = true;
1054 address->dev = g_strdup(disk->name);
1055 get_single_disk_info(sdn.DeviceNumber, address, &local_err);
1056 if (local_err) {
1057 g_debug("failed to get disk info: %s",
1058 error_get_pretty(local_err));
1059 error_free(local_err);
1060 qapi_free_GuestDiskAddress(address);
1061 address = NULL;
1062 } else {
1063 disk->address = address;
1064 disk->has_address = true;
1067 new = g_malloc0(sizeof(GuestDiskInfoList));
1068 new->value = disk;
1069 new->next = ret;
1070 ret = new;
1073 SetupDiDestroyDeviceInfoList(dev_info);
1074 return ret;
1077 #else
1079 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
1081 return NULL;
1084 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1086 error_setg(errp, QERR_UNSUPPORTED);
1087 return NULL;
1090 #endif /* CONFIG_QGA_NTDDSCSI */
1092 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
1094 DWORD info_size;
1095 char mnt, *mnt_point;
1096 wchar_t wfs_name[32];
1097 char fs_name[32];
1098 wchar_t vol_info[MAX_PATH + 1];
1099 size_t len;
1100 uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
1101 GuestFilesystemInfo *fs = NULL;
1102 HANDLE hLocalDiskHandle = NULL;
1104 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
1105 if (GetLastError() != ERROR_MORE_DATA) {
1106 error_setg_win32(errp, GetLastError(), "failed to get volume name");
1107 return NULL;
1110 mnt_point = g_malloc(info_size + 1);
1111 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
1112 &info_size)) {
1113 error_setg_win32(errp, GetLastError(), "failed to get volume name");
1114 goto free;
1117 hLocalDiskHandle = CreateFile(guid, 0 , 0, NULL, OPEN_EXISTING,
1118 FILE_ATTRIBUTE_NORMAL |
1119 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1120 if (INVALID_HANDLE_VALUE == hLocalDiskHandle) {
1121 error_setg_win32(errp, GetLastError(), "failed to get handle for volume");
1122 goto free;
1125 len = strlen(mnt_point);
1126 mnt_point[len] = '\\';
1127 mnt_point[len+1] = 0;
1129 if (!GetVolumeInformationByHandleW(hLocalDiskHandle, vol_info,
1130 sizeof(vol_info), NULL, NULL, NULL,
1131 (LPWSTR) & wfs_name, sizeof(wfs_name))) {
1132 if (GetLastError() != ERROR_NOT_READY) {
1133 error_setg_win32(errp, GetLastError(), "failed to get volume info");
1135 goto free;
1138 fs = g_malloc(sizeof(*fs));
1139 fs->name = g_strdup(guid);
1140 fs->has_total_bytes = false;
1141 fs->has_used_bytes = false;
1142 if (len == 0) {
1143 fs->mountpoint = g_strdup("System Reserved");
1144 } else {
1145 fs->mountpoint = g_strndup(mnt_point, len);
1146 if (GetDiskFreeSpaceEx(fs->mountpoint,
1147 (PULARGE_INTEGER) & i64FreeBytesToCaller,
1148 (PULARGE_INTEGER) & i64TotalBytes,
1149 (PULARGE_INTEGER) & i64FreeBytes)) {
1150 fs->used_bytes = i64TotalBytes - i64FreeBytes;
1151 fs->total_bytes = i64TotalBytes;
1152 fs->has_total_bytes = true;
1153 fs->has_used_bytes = true;
1156 wcstombs(fs_name, wfs_name, sizeof(wfs_name));
1157 fs->type = g_strdup(fs_name);
1158 fs->disk = build_guest_disk_info(guid, errp);
1159 free:
1160 CloseHandle(hLocalDiskHandle);
1161 g_free(mnt_point);
1162 return fs;
1165 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1167 HANDLE vol_h;
1168 GuestFilesystemInfoList *new, *ret = NULL;
1169 char guid[256];
1171 vol_h = FindFirstVolume(guid, sizeof(guid));
1172 if (vol_h == INVALID_HANDLE_VALUE) {
1173 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1174 return NULL;
1177 do {
1178 Error *local_err = NULL;
1179 GuestFilesystemInfo *info = build_guest_fsinfo(guid, &local_err);
1180 if (local_err) {
1181 g_debug("failed to get filesystem info, ignoring error: %s",
1182 error_get_pretty(local_err));
1183 error_free(local_err);
1184 continue;
1186 new = g_malloc(sizeof(*ret));
1187 new->value = info;
1188 new->next = ret;
1189 ret = new;
1190 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
1192 if (GetLastError() != ERROR_NO_MORE_FILES) {
1193 error_setg_win32(errp, GetLastError(), "failed to find next volume");
1196 FindVolumeClose(vol_h);
1197 return ret;
1201 * Return status of freeze/thaw
1203 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1205 if (!vss_initialized()) {
1206 error_setg(errp, QERR_UNSUPPORTED);
1207 return 0;
1210 if (ga_is_frozen(ga_state)) {
1211 return GUEST_FSFREEZE_STATUS_FROZEN;
1214 return GUEST_FSFREEZE_STATUS_THAWED;
1218 * Freeze local file systems using Volume Shadow-copy Service.
1219 * The frozen state is limited for up to 10 seconds by VSS.
1221 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1223 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1226 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1227 strList *mountpoints,
1228 Error **errp)
1230 int i;
1231 Error *local_err = NULL;
1233 if (!vss_initialized()) {
1234 error_setg(errp, QERR_UNSUPPORTED);
1235 return 0;
1238 slog("guest-fsfreeze called");
1240 /* cannot risk guest agent blocking itself on a write in this state */
1241 ga_set_frozen(ga_state);
1243 qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
1244 if (local_err) {
1245 error_propagate(errp, local_err);
1246 goto error;
1249 return i;
1251 error:
1252 local_err = NULL;
1253 qmp_guest_fsfreeze_thaw(&local_err);
1254 if (local_err) {
1255 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
1256 error_free(local_err);
1258 return 0;
1262 * Thaw local file systems using Volume Shadow-copy Service.
1264 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1266 int i;
1268 if (!vss_initialized()) {
1269 error_setg(errp, QERR_UNSUPPORTED);
1270 return 0;
1273 qga_vss_fsfreeze(&i, false, NULL, errp);
1275 ga_unset_frozen(ga_state);
1276 return i;
1279 static void guest_fsfreeze_cleanup(void)
1281 Error *err = NULL;
1283 if (!vss_initialized()) {
1284 return;
1287 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1288 qmp_guest_fsfreeze_thaw(&err);
1289 if (err) {
1290 slog("failed to clean up frozen filesystems: %s",
1291 error_get_pretty(err));
1292 error_free(err);
1296 vss_deinit(true);
1300 * Walk list of mounted file systems in the guest, and discard unused
1301 * areas.
1303 GuestFilesystemTrimResponse *
1304 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1306 GuestFilesystemTrimResponse *resp;
1307 HANDLE handle;
1308 WCHAR guid[MAX_PATH] = L"";
1309 OSVERSIONINFO osvi;
1310 BOOL win8_or_later;
1312 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
1313 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1314 GetVersionEx(&osvi);
1315 win8_or_later = (osvi.dwMajorVersion > 6 ||
1316 ((osvi.dwMajorVersion == 6) &&
1317 (osvi.dwMinorVersion >= 2)));
1318 if (!win8_or_later) {
1319 error_setg(errp, "fstrim is only supported for Win8+");
1320 return NULL;
1323 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
1324 if (handle == INVALID_HANDLE_VALUE) {
1325 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1326 return NULL;
1329 resp = g_new0(GuestFilesystemTrimResponse, 1);
1331 do {
1332 GuestFilesystemTrimResult *res;
1333 GuestFilesystemTrimResultList *list;
1334 PWCHAR uc_path;
1335 DWORD char_count = 0;
1336 char *path, *out;
1337 GError *gerr = NULL;
1338 gchar * argv[4];
1340 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1342 if (GetLastError() != ERROR_MORE_DATA) {
1343 continue;
1345 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1346 continue;
1349 uc_path = g_malloc(sizeof(WCHAR) * char_count);
1350 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1351 &char_count) || !*uc_path) {
1352 /* strange, but this condition could be faced even with size == 2 */
1353 g_free(uc_path);
1354 continue;
1357 res = g_new0(GuestFilesystemTrimResult, 1);
1359 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1361 g_free(uc_path);
1363 if (!path) {
1364 res->has_error = true;
1365 res->error = g_strdup(gerr->message);
1366 g_error_free(gerr);
1367 break;
1370 res->path = path;
1372 list = g_new0(GuestFilesystemTrimResultList, 1);
1373 list->value = res;
1374 list->next = resp->paths;
1376 resp->paths = list;
1378 memset(argv, 0, sizeof(argv));
1379 argv[0] = (gchar *)"defrag.exe";
1380 argv[1] = (gchar *)"/L";
1381 argv[2] = path;
1383 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1384 &out /* stdout */, NULL /* stdin */,
1385 NULL, &gerr)) {
1386 res->has_error = true;
1387 res->error = g_strdup(gerr->message);
1388 g_error_free(gerr);
1389 } else {
1390 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1391 Error is reported in the output with something like
1392 (x89000020) etc code in the stdout */
1394 int i;
1395 gchar **lines = g_strsplit(out, "\r\n", 0);
1396 g_free(out);
1398 for (i = 0; lines[i] != NULL; i++) {
1399 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1400 continue;
1402 res->has_error = true;
1403 res->error = g_strdup(lines[i]);
1404 break;
1406 g_strfreev(lines);
1408 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1410 FindVolumeClose(handle);
1411 return resp;
1414 typedef enum {
1415 GUEST_SUSPEND_MODE_DISK,
1416 GUEST_SUSPEND_MODE_RAM
1417 } GuestSuspendMode;
1419 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
1421 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1423 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1424 if (!GetPwrCapabilities(&sys_pwr_caps)) {
1425 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1426 "failed to determine guest suspend capabilities");
1427 return;
1430 switch (mode) {
1431 case GUEST_SUSPEND_MODE_DISK:
1432 if (!sys_pwr_caps.SystemS4) {
1433 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1434 "suspend-to-disk not supported by OS");
1436 break;
1437 case GUEST_SUSPEND_MODE_RAM:
1438 if (!sys_pwr_caps.SystemS3) {
1439 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1440 "suspend-to-ram not supported by OS");
1442 break;
1443 default:
1444 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
1445 "GuestSuspendMode");
1449 static DWORD WINAPI do_suspend(LPVOID opaque)
1451 GuestSuspendMode *mode = opaque;
1452 DWORD ret = 0;
1454 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1455 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
1456 slog("failed to suspend guest: %s", emsg);
1457 ret = -1;
1459 g_free(mode);
1460 return ret;
1463 void qmp_guest_suspend_disk(Error **errp)
1465 Error *local_err = NULL;
1466 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1468 *mode = GUEST_SUSPEND_MODE_DISK;
1469 check_suspend_mode(*mode, &local_err);
1470 if (local_err) {
1471 goto out;
1473 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1474 if (local_err) {
1475 goto out;
1477 execute_async(do_suspend, mode, &local_err);
1479 out:
1480 if (local_err) {
1481 error_propagate(errp, local_err);
1482 g_free(mode);
1486 void qmp_guest_suspend_ram(Error **errp)
1488 Error *local_err = NULL;
1489 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1491 *mode = GUEST_SUSPEND_MODE_RAM;
1492 check_suspend_mode(*mode, &local_err);
1493 if (local_err) {
1494 goto out;
1496 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1497 if (local_err) {
1498 goto out;
1500 execute_async(do_suspend, mode, &local_err);
1502 out:
1503 if (local_err) {
1504 error_propagate(errp, local_err);
1505 g_free(mode);
1509 void qmp_guest_suspend_hybrid(Error **errp)
1511 error_setg(errp, QERR_UNSUPPORTED);
1514 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1516 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1517 ULONG adptr_addrs_len = 0;
1518 DWORD ret;
1520 /* Call the first time to get the adptr_addrs_len. */
1521 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1522 NULL, adptr_addrs, &adptr_addrs_len);
1524 adptr_addrs = g_malloc(adptr_addrs_len);
1525 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1526 NULL, adptr_addrs, &adptr_addrs_len);
1527 if (ret != ERROR_SUCCESS) {
1528 error_setg_win32(errp, ret, "failed to get adapters addresses");
1529 g_free(adptr_addrs);
1530 adptr_addrs = NULL;
1532 return adptr_addrs;
1535 static char *guest_wctomb_dup(WCHAR *wstr)
1537 char *str;
1538 size_t str_size;
1540 str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
1541 /* add 1 to str_size for NULL terminator */
1542 str = g_malloc(str_size + 1);
1543 WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
1544 return str;
1547 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1548 Error **errp)
1550 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1551 DWORD len;
1552 int ret;
1554 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1555 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1556 len = sizeof(addr_str);
1557 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1558 ip_addr->Address.iSockaddrLength,
1559 NULL,
1560 addr_str,
1561 &len);
1562 if (ret != 0) {
1563 error_setg_win32(errp, WSAGetLastError(),
1564 "failed address presentation form conversion");
1565 return NULL;
1567 return g_strdup(addr_str);
1569 return NULL;
1572 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1574 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1575 * field to obtain the prefix.
1577 return ip_addr->OnLinkPrefixLength;
1580 #define INTERFACE_PATH_BUF_SZ 512
1582 static DWORD get_interface_index(const char *guid)
1584 ULONG index;
1585 DWORD status;
1586 wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1587 snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1588 wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1589 status = GetAdapterIndex (wbuf, &index);
1590 if (status != NO_ERROR) {
1591 return (DWORD)~0;
1592 } else {
1593 return index;
1597 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1599 static int guest_get_network_stats(const char *name,
1600 GuestNetworkInterfaceStat *stats)
1602 OSVERSIONINFO os_ver;
1604 os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1605 GetVersionEx(&os_ver);
1606 if (os_ver.dwMajorVersion >= 6) {
1607 MIB_IF_ROW2 a_mid_ifrow;
1608 GetIfEntry2Func getifentry2_ex;
1609 DWORD if_index = 0;
1610 HMODULE module = GetModuleHandle("iphlpapi");
1611 PVOID func = GetProcAddress(module, "GetIfEntry2");
1613 if (func == NULL) {
1614 return -1;
1617 getifentry2_ex = (GetIfEntry2Func)func;
1618 if_index = get_interface_index(name);
1619 if (if_index == (DWORD)~0) {
1620 return -1;
1623 memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1624 a_mid_ifrow.InterfaceIndex = if_index;
1625 if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1626 stats->rx_bytes = a_mid_ifrow.InOctets;
1627 stats->rx_packets = a_mid_ifrow.InUcastPkts;
1628 stats->rx_errs = a_mid_ifrow.InErrors;
1629 stats->rx_dropped = a_mid_ifrow.InDiscards;
1630 stats->tx_bytes = a_mid_ifrow.OutOctets;
1631 stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1632 stats->tx_errs = a_mid_ifrow.OutErrors;
1633 stats->tx_dropped = a_mid_ifrow.OutDiscards;
1634 return 0;
1637 return -1;
1640 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1642 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1643 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1644 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1645 GuestIpAddressList *head_addr, *cur_addr;
1646 GuestNetworkInterfaceList *info;
1647 GuestNetworkInterfaceStat *interface_stat = NULL;
1648 GuestIpAddressList *address_item = NULL;
1649 unsigned char *mac_addr;
1650 char *addr_str;
1651 WORD wsa_version;
1652 WSADATA wsa_data;
1653 int ret;
1655 adptr_addrs = guest_get_adapters_addresses(errp);
1656 if (adptr_addrs == NULL) {
1657 return NULL;
1660 /* Make WSA APIs available. */
1661 wsa_version = MAKEWORD(2, 2);
1662 ret = WSAStartup(wsa_version, &wsa_data);
1663 if (ret != 0) {
1664 error_setg_win32(errp, ret, "failed socket startup");
1665 goto out;
1668 for (addr = adptr_addrs; addr; addr = addr->Next) {
1669 info = g_malloc0(sizeof(*info));
1671 if (cur_item == NULL) {
1672 head = cur_item = info;
1673 } else {
1674 cur_item->next = info;
1675 cur_item = info;
1678 info->value = g_malloc0(sizeof(*info->value));
1679 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1681 if (addr->PhysicalAddressLength != 0) {
1682 mac_addr = addr->PhysicalAddress;
1684 info->value->hardware_address =
1685 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1686 (int) mac_addr[0], (int) mac_addr[1],
1687 (int) mac_addr[2], (int) mac_addr[3],
1688 (int) mac_addr[4], (int) mac_addr[5]);
1690 info->value->has_hardware_address = true;
1693 head_addr = NULL;
1694 cur_addr = NULL;
1695 for (ip_addr = addr->FirstUnicastAddress;
1696 ip_addr;
1697 ip_addr = ip_addr->Next) {
1698 addr_str = guest_addr_to_str(ip_addr, errp);
1699 if (addr_str == NULL) {
1700 continue;
1703 address_item = g_malloc0(sizeof(*address_item));
1705 if (!cur_addr) {
1706 head_addr = cur_addr = address_item;
1707 } else {
1708 cur_addr->next = address_item;
1709 cur_addr = address_item;
1712 address_item->value = g_malloc0(sizeof(*address_item->value));
1713 address_item->value->ip_address = addr_str;
1714 address_item->value->prefix = guest_ip_prefix(ip_addr);
1715 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1716 address_item->value->ip_address_type =
1717 GUEST_IP_ADDRESS_TYPE_IPV4;
1718 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1719 address_item->value->ip_address_type =
1720 GUEST_IP_ADDRESS_TYPE_IPV6;
1723 if (head_addr) {
1724 info->value->has_ip_addresses = true;
1725 info->value->ip_addresses = head_addr;
1727 if (!info->value->has_statistics) {
1728 interface_stat = g_malloc0(sizeof(*interface_stat));
1729 if (guest_get_network_stats(addr->AdapterName,
1730 interface_stat) == -1) {
1731 info->value->has_statistics = false;
1732 g_free(interface_stat);
1733 } else {
1734 info->value->statistics = interface_stat;
1735 info->value->has_statistics = true;
1739 WSACleanup();
1740 out:
1741 g_free(adptr_addrs);
1742 return head;
1745 static int64_t filetime_to_ns(const FILETIME *tf)
1747 return ((((int64_t)tf->dwHighDateTime << 32) | tf->dwLowDateTime)
1748 - W32_FT_OFFSET) * 100;
1751 int64_t qmp_guest_get_time(Error **errp)
1753 SYSTEMTIME ts = {0};
1754 FILETIME tf;
1756 GetSystemTime(&ts);
1757 if (ts.wYear < 1601 || ts.wYear > 30827) {
1758 error_setg(errp, "Failed to get time");
1759 return -1;
1762 if (!SystemTimeToFileTime(&ts, &tf)) {
1763 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1764 return -1;
1767 return filetime_to_ns(&tf);
1770 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1772 Error *local_err = NULL;
1773 SYSTEMTIME ts;
1774 FILETIME tf;
1775 LONGLONG time;
1777 if (!has_time) {
1778 /* Unfortunately, Windows libraries don't provide an easy way to access
1779 * RTC yet:
1781 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1783 * Instead, a workaround is to use the Windows win32tm command to
1784 * resync the time using the Windows Time service.
1786 LPVOID msg_buffer;
1787 DWORD ret_flags;
1789 HRESULT hr = system("w32tm /resync /nowait");
1791 if (GetLastError() != 0) {
1792 strerror_s((LPTSTR) & msg_buffer, 0, errno);
1793 error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1794 } else if (hr != 0) {
1795 if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1796 error_setg(errp, "Windows Time service not running on the "
1797 "guest");
1798 } else {
1799 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1800 FORMAT_MESSAGE_FROM_SYSTEM |
1801 FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1802 (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1803 SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1804 NULL)) {
1805 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1806 "t retrieve error message", hr);
1807 } else {
1808 error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1809 (LPCTSTR)msg_buffer);
1810 LocalFree(msg_buffer);
1813 } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1814 error_setg(errp, "No internet connection on guest, sync not "
1815 "accurate");
1817 return;
1820 /* Validate time passed by user. */
1821 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1822 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1823 return;
1826 time = time_ns / 100 + W32_FT_OFFSET;
1828 tf.dwLowDateTime = (DWORD) time;
1829 tf.dwHighDateTime = (DWORD) (time >> 32);
1831 if (!FileTimeToSystemTime(&tf, &ts)) {
1832 error_setg(errp, "Failed to convert system time %d",
1833 (int)GetLastError());
1834 return;
1837 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1838 if (local_err) {
1839 error_propagate(errp, local_err);
1840 return;
1843 if (!SetSystemTime(&ts)) {
1844 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1845 return;
1849 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1851 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1852 DWORD length;
1853 GuestLogicalProcessorList *head, **link;
1854 Error *local_err = NULL;
1855 int64_t current;
1857 ptr = pslpi = NULL;
1858 length = 0;
1859 current = 0;
1860 head = NULL;
1861 link = &head;
1863 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1864 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1865 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1866 ptr = pslpi = g_malloc0(length);
1867 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1868 error_setg(&local_err, "Failed to get processor information: %d",
1869 (int)GetLastError());
1871 } else {
1872 error_setg(&local_err,
1873 "Failed to get processor information buffer length: %d",
1874 (int)GetLastError());
1877 while ((local_err == NULL) && (length > 0)) {
1878 if (pslpi->Relationship == RelationProcessorCore) {
1879 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1881 while (cpu_bits > 0) {
1882 if (!!(cpu_bits & 1)) {
1883 GuestLogicalProcessor *vcpu;
1884 GuestLogicalProcessorList *entry;
1886 vcpu = g_malloc0(sizeof *vcpu);
1887 vcpu->logical_id = current++;
1888 vcpu->online = true;
1889 vcpu->has_can_offline = true;
1891 entry = g_malloc0(sizeof *entry);
1892 entry->value = vcpu;
1894 *link = entry;
1895 link = &entry->next;
1897 cpu_bits >>= 1;
1900 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1901 pslpi++; /* next entry */
1904 g_free(ptr);
1906 if (local_err == NULL) {
1907 if (head != NULL) {
1908 return head;
1910 /* there's no guest with zero VCPUs */
1911 error_setg(&local_err, "Guest reported zero VCPUs");
1914 qapi_free_GuestLogicalProcessorList(head);
1915 error_propagate(errp, local_err);
1916 return NULL;
1919 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1921 error_setg(errp, QERR_UNSUPPORTED);
1922 return -1;
1925 static gchar *
1926 get_net_error_message(gint error)
1928 HMODULE module = NULL;
1929 gchar *retval = NULL;
1930 wchar_t *msg = NULL;
1931 int flags;
1932 size_t nchars;
1934 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1935 FORMAT_MESSAGE_IGNORE_INSERTS |
1936 FORMAT_MESSAGE_FROM_SYSTEM;
1938 if (error >= NERR_BASE && error <= MAX_NERR) {
1939 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1941 if (module != NULL) {
1942 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1946 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1948 if (msg != NULL) {
1949 nchars = wcslen(msg);
1951 if (nchars >= 2 &&
1952 msg[nchars - 1] == L'\n' &&
1953 msg[nchars - 2] == L'\r') {
1954 msg[nchars - 2] = L'\0';
1957 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1959 LocalFree(msg);
1962 if (module != NULL) {
1963 FreeLibrary(module);
1966 return retval;
1969 void qmp_guest_set_user_password(const char *username,
1970 const char *password,
1971 bool crypted,
1972 Error **errp)
1974 NET_API_STATUS nas;
1975 char *rawpasswddata = NULL;
1976 size_t rawpasswdlen;
1977 wchar_t *user = NULL, *wpass = NULL;
1978 USER_INFO_1003 pi1003 = { 0, };
1979 GError *gerr = NULL;
1981 if (crypted) {
1982 error_setg(errp, QERR_UNSUPPORTED);
1983 return;
1986 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1987 if (!rawpasswddata) {
1988 return;
1990 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1991 rawpasswddata[rawpasswdlen] = '\0';
1993 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1994 if (!user) {
1995 goto done;
1998 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1999 if (!wpass) {
2000 goto done;
2003 pi1003.usri1003_password = wpass;
2004 nas = NetUserSetInfo(NULL, user,
2005 1003, (LPBYTE)&pi1003,
2006 NULL);
2008 if (nas != NERR_Success) {
2009 gchar *msg = get_net_error_message(nas);
2010 error_setg(errp, "failed to set password: %s", msg);
2011 g_free(msg);
2014 done:
2015 if (gerr) {
2016 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
2017 g_error_free(gerr);
2019 g_free(user);
2020 g_free(wpass);
2021 g_free(rawpasswddata);
2024 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2026 error_setg(errp, QERR_UNSUPPORTED);
2027 return NULL;
2030 GuestMemoryBlockResponseList *
2031 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2033 error_setg(errp, QERR_UNSUPPORTED);
2034 return NULL;
2037 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2039 error_setg(errp, QERR_UNSUPPORTED);
2040 return NULL;
2043 /* add unsupported commands to the blacklist */
2044 GList *ga_command_blacklist_init(GList *blacklist)
2046 const char *list_unsupported[] = {
2047 "guest-suspend-hybrid",
2048 "guest-set-vcpus",
2049 "guest-get-memory-blocks", "guest-set-memory-blocks",
2050 "guest-get-memory-block-size", "guest-get-memory-block-info",
2051 NULL};
2052 char **p = (char **)list_unsupported;
2054 while (*p) {
2055 blacklist = g_list_append(blacklist, g_strdup(*p++));
2058 if (!vss_init(true)) {
2059 g_debug("vss_init failed, vss commands are going to be disabled");
2060 const char *list[] = {
2061 "guest-get-fsinfo", "guest-fsfreeze-status",
2062 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
2063 p = (char **)list;
2065 while (*p) {
2066 blacklist = g_list_append(blacklist, g_strdup(*p++));
2070 return blacklist;
2073 /* register init/cleanup routines for stateful command groups */
2074 void ga_command_state_init(GAState *s, GACommandState *cs)
2076 if (!vss_initialized()) {
2077 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2081 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
2082 typedef struct _GA_WTSINFOA {
2083 WTS_CONNECTSTATE_CLASS State;
2084 DWORD SessionId;
2085 DWORD IncomingBytes;
2086 DWORD OutgoingBytes;
2087 DWORD IncomingFrames;
2088 DWORD OutgoingFrames;
2089 DWORD IncomingCompressedBytes;
2090 DWORD OutgoingCompressedBy;
2091 CHAR WinStationName[WINSTATIONNAME_LENGTH];
2092 CHAR Domain[DOMAIN_LENGTH];
2093 CHAR UserName[USERNAME_LENGTH + 1];
2094 LARGE_INTEGER ConnectTime;
2095 LARGE_INTEGER DisconnectTime;
2096 LARGE_INTEGER LastInputTime;
2097 LARGE_INTEGER LogonTime;
2098 LARGE_INTEGER CurrentTime;
2100 } GA_WTSINFOA;
2102 GuestUserList *qmp_guest_get_users(Error **errp)
2104 #define QGA_NANOSECONDS 10000000
2106 GHashTable *cache = NULL;
2107 GuestUserList *head = NULL, *cur_item = NULL;
2109 DWORD buffer_size = 0, count = 0, i = 0;
2110 GA_WTSINFOA *info = NULL;
2111 WTS_SESSION_INFOA *entries = NULL;
2112 GuestUserList *item = NULL;
2113 GuestUser *user = NULL;
2114 gpointer value = NULL;
2115 INT64 login = 0;
2116 double login_time = 0;
2118 cache = g_hash_table_new(g_str_hash, g_str_equal);
2120 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
2121 for (i = 0; i < count; ++i) {
2122 buffer_size = 0;
2123 info = NULL;
2124 if (WTSQuerySessionInformationA(
2125 NULL,
2126 entries[i].SessionId,
2127 WTSSessionInfo,
2128 (LPSTR *)&info,
2129 &buffer_size
2130 )) {
2132 if (strlen(info->UserName) == 0) {
2133 WTSFreeMemory(info);
2134 continue;
2137 login = info->LogonTime.QuadPart;
2138 login -= W32_FT_OFFSET;
2139 login_time = ((double)login) / QGA_NANOSECONDS;
2141 if (g_hash_table_contains(cache, info->UserName)) {
2142 value = g_hash_table_lookup(cache, info->UserName);
2143 user = (GuestUser *)value;
2144 if (user->login_time > login_time) {
2145 user->login_time = login_time;
2147 } else {
2148 item = g_new0(GuestUserList, 1);
2149 item->value = g_new0(GuestUser, 1);
2151 item->value->user = g_strdup(info->UserName);
2152 item->value->domain = g_strdup(info->Domain);
2153 item->value->has_domain = true;
2155 item->value->login_time = login_time;
2157 g_hash_table_add(cache, item->value->user);
2159 if (!cur_item) {
2160 head = cur_item = item;
2161 } else {
2162 cur_item->next = item;
2163 cur_item = item;
2167 WTSFreeMemory(info);
2169 WTSFreeMemory(entries);
2171 g_hash_table_destroy(cache);
2172 return head;
2175 typedef struct _ga_matrix_lookup_t {
2176 int major;
2177 int minor;
2178 char const *version;
2179 char const *version_id;
2180 } ga_matrix_lookup_t;
2182 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
2184 /* Desktop editions */
2185 { 5, 0, "Microsoft Windows 2000", "2000"},
2186 { 5, 1, "Microsoft Windows XP", "xp"},
2187 { 6, 0, "Microsoft Windows Vista", "vista"},
2188 { 6, 1, "Microsoft Windows 7" "7"},
2189 { 6, 2, "Microsoft Windows 8", "8"},
2190 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2191 {10, 0, "Microsoft Windows 10", "10"},
2192 { 0, 0, 0}
2194 /* Server editions */
2195 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2196 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2197 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2198 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2199 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2200 { 0, 0, 0},
2201 { 0, 0, 0},
2202 { 0, 0, 0}
2206 typedef struct _ga_win_10_0_server_t {
2207 int final_build;
2208 char const *version;
2209 char const *version_id;
2210 } ga_win_10_0_server_t;
2212 static ga_win_10_0_server_t const WIN_10_0_SERVER_VERSION_MATRIX[3] = {
2213 {14393, "Microsoft Windows Server 2016", "2016"},
2214 {17763, "Microsoft Windows Server 2019", "2019"},
2215 {0, 0}
2218 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2220 typedef NTSTATUS(WINAPI * rtl_get_version_t)(
2221 RTL_OSVERSIONINFOEXW *os_version_info_ex);
2223 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2225 HMODULE module = GetModuleHandle("ntdll");
2226 PVOID fun = GetProcAddress(module, "RtlGetVersion");
2227 if (fun == NULL) {
2228 error_setg(errp, QERR_QGA_COMMAND_FAILED,
2229 "Failed to get address of RtlGetVersion");
2230 return;
2233 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2234 rtl_get_version(info);
2235 return;
2238 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
2240 DWORD major = os_version->dwMajorVersion;
2241 DWORD minor = os_version->dwMinorVersion;
2242 DWORD build = os_version->dwBuildNumber;
2243 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2244 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
2245 ga_win_10_0_server_t const *win_10_0_table = WIN_10_0_SERVER_VERSION_MATRIX;
2246 while (table->version != NULL) {
2247 if (major == 10 && minor == 0 && tbl_idx) {
2248 while (win_10_0_table->version != NULL) {
2249 if (build <= win_10_0_table->final_build) {
2250 if (id) {
2251 return g_strdup(win_10_0_table->version_id);
2252 } else {
2253 return g_strdup(win_10_0_table->version);
2256 win_10_0_table++;
2258 } else if (major == table->major && minor == table->minor) {
2259 if (id) {
2260 return g_strdup(table->version_id);
2261 } else {
2262 return g_strdup(table->version);
2265 ++table;
2267 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2268 major, minor);
2269 return g_strdup("N/A");
2272 static char *ga_get_win_product_name(Error **errp)
2274 HKEY key = NULL;
2275 DWORD size = 128;
2276 char *result = g_malloc0(size);
2277 LONG err = ERROR_SUCCESS;
2279 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2280 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2281 &key);
2282 if (err != ERROR_SUCCESS) {
2283 error_setg_win32(errp, err, "failed to open registry key");
2284 goto fail;
2287 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2288 (LPBYTE)result, &size);
2289 if (err == ERROR_MORE_DATA) {
2290 slog("ProductName longer than expected (%lu bytes), retrying",
2291 size);
2292 g_free(result);
2293 result = NULL;
2294 if (size > 0) {
2295 result = g_malloc0(size);
2296 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2297 (LPBYTE)result, &size);
2300 if (err != ERROR_SUCCESS) {
2301 error_setg_win32(errp, err, "failed to retrive ProductName");
2302 goto fail;
2305 return result;
2307 fail:
2308 g_free(result);
2309 return NULL;
2312 static char *ga_get_current_arch(void)
2314 SYSTEM_INFO info;
2315 GetNativeSystemInfo(&info);
2316 char *result = NULL;
2317 switch (info.wProcessorArchitecture) {
2318 case PROCESSOR_ARCHITECTURE_AMD64:
2319 result = g_strdup("x86_64");
2320 break;
2321 case PROCESSOR_ARCHITECTURE_ARM:
2322 result = g_strdup("arm");
2323 break;
2324 case PROCESSOR_ARCHITECTURE_IA64:
2325 result = g_strdup("ia64");
2326 break;
2327 case PROCESSOR_ARCHITECTURE_INTEL:
2328 result = g_strdup("x86");
2329 break;
2330 case PROCESSOR_ARCHITECTURE_UNKNOWN:
2331 default:
2332 slog("unknown processor architecture 0x%0x",
2333 info.wProcessorArchitecture);
2334 result = g_strdup("unknown");
2335 break;
2337 return result;
2340 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2342 Error *local_err = NULL;
2343 OSVERSIONINFOEXW os_version = {0};
2344 bool server;
2345 char *product_name;
2346 GuestOSInfo *info;
2348 ga_get_win_version(&os_version, &local_err);
2349 if (local_err) {
2350 error_propagate(errp, local_err);
2351 return NULL;
2354 server = os_version.wProductType != VER_NT_WORKSTATION;
2355 product_name = ga_get_win_product_name(errp);
2356 if (product_name == NULL) {
2357 return NULL;
2360 info = g_new0(GuestOSInfo, 1);
2362 info->has_kernel_version = true;
2363 info->kernel_version = g_strdup_printf("%lu.%lu",
2364 os_version.dwMajorVersion,
2365 os_version.dwMinorVersion);
2366 info->has_kernel_release = true;
2367 info->kernel_release = g_strdup_printf("%lu",
2368 os_version.dwBuildNumber);
2369 info->has_machine = true;
2370 info->machine = ga_get_current_arch();
2372 info->has_id = true;
2373 info->id = g_strdup("mswindows");
2374 info->has_name = true;
2375 info->name = g_strdup("Microsoft Windows");
2376 info->has_pretty_name = true;
2377 info->pretty_name = product_name;
2378 info->has_version = true;
2379 info->version = ga_get_win_name(&os_version, false);
2380 info->has_version_id = true;
2381 info->version_id = ga_get_win_name(&os_version, true);
2382 info->has_variant = true;
2383 info->variant = g_strdup(server ? "server" : "client");
2384 info->has_variant_id = true;
2385 info->variant_id = g_strdup(server ? "server" : "client");
2387 return info;
2391 * Safely get device property. Returned strings are using wide characters.
2392 * Caller is responsible for freeing the buffer.
2394 static LPBYTE cm_get_property(DEVINST devInst, const DEVPROPKEY *propName,
2395 PDEVPROPTYPE propType)
2397 CONFIGRET cr;
2398 g_autofree LPBYTE buffer = NULL;
2399 ULONG buffer_len = 0;
2401 /* First query for needed space */
2402 cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2403 buffer, &buffer_len, 0);
2404 if (cr != CR_SUCCESS && cr != CR_BUFFER_SMALL) {
2406 slog("failed to get property size, error=0x%lx", cr);
2407 return NULL;
2409 buffer = g_new0(BYTE, buffer_len + 1);
2410 cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2411 buffer, &buffer_len, 0);
2412 if (cr != CR_SUCCESS) {
2413 slog("failed to get device property, error=0x%lx", cr);
2414 return NULL;
2416 return g_steal_pointer(&buffer);
2419 static GStrv ga_get_hardware_ids(DEVINST devInstance)
2421 GArray *values = NULL;
2422 DEVPROPTYPE cm_type;
2423 LPWSTR id;
2424 g_autofree LPWSTR property = (LPWSTR)cm_get_property(devInstance,
2425 &qga_DEVPKEY_Device_HardwareIds, &cm_type);
2426 if (property == NULL) {
2427 slog("failed to get hardware IDs");
2428 return NULL;
2430 if (*property == '\0') {
2431 /* empty list */
2432 return NULL;
2434 values = g_array_new(TRUE, TRUE, sizeof(gchar *));
2435 for (id = property; '\0' != *id; id += lstrlenW(id) + 1) {
2436 gchar *id8 = g_utf16_to_utf8(id, -1, NULL, NULL, NULL);
2437 g_array_append_val(values, id8);
2439 return (GStrv)g_array_free(values, FALSE);
2443 * https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
2445 #define DEVICE_PCI_RE "PCI\\\\VEN_(1AF4|1B36)&DEV_([0-9A-B]{4})(&|$)"
2447 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
2449 GuestDeviceInfoList *head = NULL, *cur_item = NULL, *item = NULL;
2450 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2451 SP_DEVINFO_DATA dev_info_data;
2452 int i, j;
2453 GError *gerr = NULL;
2454 g_autoptr(GRegex) device_pci_re = NULL;
2455 DEVPROPTYPE cm_type;
2457 device_pci_re = g_regex_new(DEVICE_PCI_RE,
2458 G_REGEX_ANCHORED | G_REGEX_OPTIMIZE, 0,
2459 &gerr);
2460 g_assert(device_pci_re != NULL);
2462 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
2463 dev_info = SetupDiGetClassDevs(0, 0, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES);
2464 if (dev_info == INVALID_HANDLE_VALUE) {
2465 error_setg(errp, "failed to get device tree");
2466 return NULL;
2469 slog("enumerating devices");
2470 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
2471 bool skip = true;
2472 g_autofree LPWSTR name = NULL;
2473 g_autofree LPFILETIME date = NULL;
2474 g_autofree LPWSTR version = NULL;
2475 g_auto(GStrv) hw_ids = NULL;
2476 g_autoptr(GuestDeviceInfo) device = g_new0(GuestDeviceInfo, 1);
2477 g_autofree char *vendor_id = NULL;
2478 g_autofree char *device_id = NULL;
2480 name = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2481 &qga_DEVPKEY_NAME, &cm_type);
2482 if (name == NULL) {
2483 slog("failed to get device description");
2484 continue;
2486 device->driver_name = g_utf16_to_utf8(name, -1, NULL, NULL, NULL);
2487 if (device->driver_name == NULL) {
2488 error_setg(errp, "conversion to utf8 failed (driver name)");
2489 return NULL;
2491 slog("querying device: %s", device->driver_name);
2492 hw_ids = ga_get_hardware_ids(dev_info_data.DevInst);
2493 if (hw_ids == NULL) {
2494 continue;
2496 for (j = 0; hw_ids[j] != NULL; j++) {
2497 GMatchInfo *match_info;
2498 GuestDeviceIdPCI *id;
2499 if (!g_regex_match(device_pci_re, hw_ids[j], 0, &match_info)) {
2500 continue;
2502 skip = false;
2504 vendor_id = g_match_info_fetch(match_info, 1);
2505 device_id = g_match_info_fetch(match_info, 2);
2507 device->id = g_new0(GuestDeviceId, 1);
2508 device->has_id = true;
2509 device->id->type = GUEST_DEVICE_TYPE_PCI;
2510 id = &device->id->u.pci;
2511 id->vendor_id = g_ascii_strtoull(vendor_id, NULL, 16);
2512 id->device_id = g_ascii_strtoull(device_id, NULL, 16);
2514 g_match_info_free(match_info);
2515 break;
2517 if (skip) {
2518 continue;
2521 version = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2522 &qga_DEVPKEY_Device_DriverVersion, &cm_type);
2523 if (version == NULL) {
2524 slog("failed to get driver version");
2525 continue;
2527 device->driver_version = g_utf16_to_utf8(version, -1, NULL,
2528 NULL, NULL);
2529 if (device->driver_version == NULL) {
2530 error_setg(errp, "conversion to utf8 failed (driver version)");
2531 return NULL;
2533 device->has_driver_version = true;
2535 date = (LPFILETIME)cm_get_property(dev_info_data.DevInst,
2536 &qga_DEVPKEY_Device_DriverDate, &cm_type);
2537 if (date == NULL) {
2538 slog("failed to get driver date");
2539 continue;
2541 device->driver_date = filetime_to_ns(date);
2542 device->has_driver_date = true;
2544 slog("driver: %s\ndriver version: %" PRId64 ",%s\n",
2545 device->driver_name, device->driver_date,
2546 device->driver_version);
2547 item = g_new0(GuestDeviceInfoList, 1);
2548 item->value = g_steal_pointer(&device);
2549 if (!cur_item) {
2550 head = cur_item = item;
2551 } else {
2552 cur_item->next = item;
2553 cur_item = item;
2557 if (dev_info != INVALID_HANDLE_VALUE) {
2558 SetupDiDestroyDeviceInfoList(dev_info);
2560 return head;