net: tulip: check frame size and r/w data length
[qemu/ar7.git] / qga / commands-win32.c
blobb49920e201fd792b1febcb495d5d20bd91ca4c59
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 #include <setupapi.h>
25 #include <cfgmgr32.h>
26 #include <initguid.h>
27 #endif
28 #include <lm.h>
29 #include <wtsapi32.h>
30 #include <wininet.h>
32 #include "guest-agent-core.h"
33 #include "vss-win32.h"
34 #include "qga-qapi-commands.h"
35 #include "qapi/error.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qemu/queue.h"
38 #include "qemu/host-utils.h"
39 #include "qemu/base64.h"
41 #ifndef SHTDN_REASON_FLAG_PLANNED
42 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
43 #endif
45 /* multiple of 100 nanoseconds elapsed between windows baseline
46 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
47 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
48 (365 * (1970 - 1601) + \
49 (1970 - 1601) / 4 - 3))
51 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
53 typedef struct GuestFileHandle {
54 int64_t id;
55 HANDLE fh;
56 QTAILQ_ENTRY(GuestFileHandle) next;
57 } GuestFileHandle;
59 static struct {
60 QTAILQ_HEAD(, GuestFileHandle) filehandles;
61 } guest_file_state = {
62 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
65 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
67 typedef struct OpenFlags {
68 const char *forms;
69 DWORD desired_access;
70 DWORD creation_disposition;
71 } OpenFlags;
72 static OpenFlags guest_file_open_modes[] = {
73 {"r", GENERIC_READ, OPEN_EXISTING},
74 {"rb", GENERIC_READ, OPEN_EXISTING},
75 {"w", GENERIC_WRITE, CREATE_ALWAYS},
76 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
77 {"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
78 {"r+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
79 {"rb+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
80 {"r+b", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
81 {"w+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
82 {"wb+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
83 {"w+b", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
84 {"a+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
85 {"ab+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
86 {"a+b", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS }
89 #define debug_error(msg) do { \
90 char *suffix = g_win32_error_message(GetLastError()); \
91 g_debug("%s: %s", (msg), suffix); \
92 g_free(suffix); \
93 } while (0)
95 static OpenFlags *find_open_flag(const char *mode_str)
97 int mode;
98 Error **errp = NULL;
100 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
101 OpenFlags *flags = guest_file_open_modes + mode;
103 if (strcmp(flags->forms, mode_str) == 0) {
104 return flags;
108 error_setg(errp, "invalid file open mode '%s'", mode_str);
109 return NULL;
112 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
114 GuestFileHandle *gfh;
115 int64_t handle;
117 handle = ga_get_fd_handle(ga_state, errp);
118 if (handle < 0) {
119 return -1;
121 gfh = g_new0(GuestFileHandle, 1);
122 gfh->id = handle;
123 gfh->fh = fh;
124 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
126 return handle;
129 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
131 GuestFileHandle *gfh;
132 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
133 if (gfh->id == id) {
134 return gfh;
137 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
138 return NULL;
141 static void handle_set_nonblocking(HANDLE fh)
143 DWORD file_type, pipe_state;
144 file_type = GetFileType(fh);
145 if (file_type != FILE_TYPE_PIPE) {
146 return;
148 /* If file_type == FILE_TYPE_PIPE, according to MSDN
149 * the specified file is socket or named pipe */
150 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
151 NULL, NULL, NULL, 0)) {
152 return;
154 /* The fd is named pipe fd */
155 if (pipe_state & PIPE_NOWAIT) {
156 return;
159 pipe_state |= PIPE_NOWAIT;
160 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
163 int64_t qmp_guest_file_open(const char *path, bool has_mode,
164 const char *mode, Error **errp)
166 int64_t fd = -1;
167 HANDLE fh;
168 HANDLE templ_file = NULL;
169 DWORD share_mode = FILE_SHARE_READ;
170 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
171 LPSECURITY_ATTRIBUTES sa_attr = NULL;
172 OpenFlags *guest_flags;
173 GError *gerr = NULL;
174 wchar_t *w_path = NULL;
176 if (!has_mode) {
177 mode = "r";
179 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
180 guest_flags = find_open_flag(mode);
181 if (guest_flags == NULL) {
182 error_setg(errp, "invalid file open mode");
183 goto done;
186 w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
187 if (!w_path) {
188 goto done;
191 fh = CreateFileW(w_path, guest_flags->desired_access, share_mode, sa_attr,
192 guest_flags->creation_disposition, flags_and_attr,
193 templ_file);
194 if (fh == INVALID_HANDLE_VALUE) {
195 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
196 path);
197 goto done;
200 /* set fd non-blocking to avoid common use cases (like reading from a
201 * named pipe) from hanging the agent
203 handle_set_nonblocking(fh);
205 fd = guest_file_handle_add(fh, errp);
206 if (fd < 0) {
207 CloseHandle(fh);
208 error_setg(errp, "failed to add handle to qmp handle table");
209 goto done;
212 slog("guest-file-open, handle: % " PRId64, fd);
214 done:
215 if (gerr) {
216 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
217 g_error_free(gerr);
219 g_free(w_path);
220 return fd;
223 void qmp_guest_file_close(int64_t handle, Error **errp)
225 bool ret;
226 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
227 slog("guest-file-close called, handle: %" PRId64, handle);
228 if (gfh == NULL) {
229 return;
231 ret = CloseHandle(gfh->fh);
232 if (!ret) {
233 error_setg_win32(errp, GetLastError(), "failed close handle");
234 return;
237 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
238 g_free(gfh);
241 static void acquire_privilege(const char *name, Error **errp)
243 HANDLE token = NULL;
244 TOKEN_PRIVILEGES priv;
245 Error *local_err = NULL;
247 if (OpenProcessToken(GetCurrentProcess(),
248 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
250 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
251 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
252 "no luid for requested privilege");
253 goto out;
256 priv.PrivilegeCount = 1;
257 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
259 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
260 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
261 "unable to acquire requested privilege");
262 goto out;
265 } else {
266 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
267 "failed to open privilege token");
270 out:
271 if (token) {
272 CloseHandle(token);
274 error_propagate(errp, local_err);
277 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
278 Error **errp)
280 Error *local_err = NULL;
282 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
283 if (!thread) {
284 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
285 "failed to dispatch asynchronous command");
286 error_propagate(errp, local_err);
290 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
292 Error *local_err = NULL;
293 UINT shutdown_flag = EWX_FORCE;
295 slog("guest-shutdown called, mode: %s", mode);
297 if (!has_mode || strcmp(mode, "powerdown") == 0) {
298 shutdown_flag |= EWX_POWEROFF;
299 } else if (strcmp(mode, "halt") == 0) {
300 shutdown_flag |= EWX_SHUTDOWN;
301 } else if (strcmp(mode, "reboot") == 0) {
302 shutdown_flag |= EWX_REBOOT;
303 } else {
304 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
305 "halt|powerdown|reboot");
306 return;
309 /* Request a shutdown privilege, but try to shut down the system
310 anyway. */
311 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
312 if (local_err) {
313 error_propagate(errp, local_err);
314 return;
317 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
318 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
319 slog("guest-shutdown failed: %s", emsg);
320 error_setg_win32(errp, GetLastError(), "guest-shutdown failed");
324 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
325 int64_t count, Error **errp)
327 GuestFileRead *read_data = NULL;
328 guchar *buf;
329 HANDLE fh;
330 bool is_ok;
331 DWORD read_count;
332 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
334 if (!gfh) {
335 return NULL;
337 if (!has_count) {
338 count = QGA_READ_COUNT_DEFAULT;
339 } else if (count < 0 || count >= UINT32_MAX) {
340 error_setg(errp, "value '%" PRId64
341 "' is invalid for argument count", count);
342 return NULL;
345 fh = gfh->fh;
346 buf = g_try_malloc0(count + 1);
347 if (!buf) {
348 error_setg(errp,
349 "failed to allocate sufficient memory "
350 "to complete the requested service");
351 return NULL;
353 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
354 if (!is_ok) {
355 error_setg_win32(errp, GetLastError(), "failed to read file");
356 slog("guest-file-read failed, handle %" PRId64, handle);
357 } else {
358 buf[read_count] = 0;
359 read_data = g_new0(GuestFileRead, 1);
360 read_data->count = (size_t)read_count;
361 read_data->eof = read_count == 0;
363 if (read_count != 0) {
364 read_data->buf_b64 = g_base64_encode(buf, read_count);
367 g_free(buf);
369 return read_data;
372 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
373 bool has_count, int64_t count,
374 Error **errp)
376 GuestFileWrite *write_data = NULL;
377 guchar *buf;
378 gsize buf_len;
379 bool is_ok;
380 DWORD write_count;
381 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
382 HANDLE fh;
384 if (!gfh) {
385 return NULL;
387 fh = gfh->fh;
388 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
389 if (!buf) {
390 return NULL;
393 if (!has_count) {
394 count = buf_len;
395 } else if (count < 0 || count > buf_len) {
396 error_setg(errp, "value '%" PRId64
397 "' is invalid for argument count", count);
398 goto done;
401 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
402 if (!is_ok) {
403 error_setg_win32(errp, GetLastError(), "failed to write to file");
404 slog("guest-file-write-failed, handle: %" PRId64, handle);
405 } else {
406 write_data = g_new0(GuestFileWrite, 1);
407 write_data->count = (size_t) write_count;
410 done:
411 g_free(buf);
412 return write_data;
415 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
416 GuestFileWhence *whence_code,
417 Error **errp)
419 GuestFileHandle *gfh;
420 GuestFileSeek *seek_data;
421 HANDLE fh;
422 LARGE_INTEGER new_pos, off_pos;
423 off_pos.QuadPart = offset;
424 BOOL res;
425 int whence;
426 Error *err = NULL;
428 gfh = guest_file_handle_find(handle, errp);
429 if (!gfh) {
430 return NULL;
433 /* We stupidly exposed 'whence':'int' in our qapi */
434 whence = ga_parse_whence(whence_code, &err);
435 if (err) {
436 error_propagate(errp, err);
437 return NULL;
440 fh = gfh->fh;
441 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
442 if (!res) {
443 error_setg_win32(errp, GetLastError(), "failed to seek file");
444 return NULL;
446 seek_data = g_new0(GuestFileSeek, 1);
447 seek_data->position = new_pos.QuadPart;
448 return seek_data;
451 void qmp_guest_file_flush(int64_t handle, Error **errp)
453 HANDLE fh;
454 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
455 if (!gfh) {
456 return;
459 fh = gfh->fh;
460 if (!FlushFileBuffers(fh)) {
461 error_setg_win32(errp, GetLastError(), "failed to flush file");
465 #ifdef CONFIG_QGA_NTDDSCSI
467 static GuestDiskBusType win2qemu[] = {
468 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
469 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
470 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
471 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
472 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
473 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
474 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
475 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
476 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
477 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
478 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
479 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
480 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
481 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
482 #if (_WIN32_WINNT >= 0x0601)
483 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
484 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
485 #endif
488 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
490 if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
491 return GUEST_DISK_BUS_TYPE_UNKNOWN;
493 return win2qemu[(int)bus];
496 DEFINE_GUID(GUID_DEVINTERFACE_DISK,
497 0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2,
498 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
499 DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT,
500 0x2accfe60L, 0xc130, 0x11d2, 0xb0, 0x82,
501 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
503 static GuestPCIAddress *get_pci_info(int number, Error **errp)
505 HDEVINFO dev_info;
506 SP_DEVINFO_DATA dev_info_data;
507 SP_DEVICE_INTERFACE_DATA dev_iface_data;
508 HANDLE dev_file;
509 int i;
510 GuestPCIAddress *pci = NULL;
511 bool partial_pci = false;
513 pci = g_malloc0(sizeof(*pci));
514 pci->domain = -1;
515 pci->slot = -1;
516 pci->function = -1;
517 pci->bus = -1;
519 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
520 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
521 if (dev_info == INVALID_HANDLE_VALUE) {
522 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
523 goto out;
526 g_debug("enumerating devices");
527 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
528 dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
529 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
530 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
531 STORAGE_DEVICE_NUMBER sdn;
532 char *parent_dev_id = NULL;
533 HDEVINFO parent_dev_info;
534 SP_DEVINFO_DATA parent_dev_info_data;
535 DWORD j;
536 DWORD size = 0;
538 g_debug("getting device path");
539 if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
540 &GUID_DEVINTERFACE_DISK, 0,
541 &dev_iface_data)) {
542 while (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
543 pdev_iface_detail_data,
544 size, &size,
545 &dev_info_data)) {
546 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
547 pdev_iface_detail_data = g_malloc(size);
548 pdev_iface_detail_data->cbSize =
549 sizeof(*pdev_iface_detail_data);
550 } else {
551 error_setg_win32(errp, GetLastError(),
552 "failed to get device interfaces");
553 goto free_dev_info;
557 dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
558 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
559 NULL);
560 g_free(pdev_iface_detail_data);
562 if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
563 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
564 CloseHandle(dev_file);
565 error_setg_win32(errp, GetLastError(),
566 "failed to get device slot number");
567 goto free_dev_info;
570 CloseHandle(dev_file);
571 if (sdn.DeviceNumber != number) {
572 continue;
574 } else {
575 error_setg_win32(errp, GetLastError(),
576 "failed to get device interfaces");
577 goto free_dev_info;
580 g_debug("found device slot %d. Getting storage controller", number);
582 CONFIGRET cr;
583 DEVINST dev_inst, parent_dev_inst;
584 ULONG dev_id_size = 0;
586 size = 0;
587 while (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
588 parent_dev_id, size, &size)) {
589 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
590 parent_dev_id = g_malloc(size);
591 } else {
592 error_setg_win32(errp, GetLastError(),
593 "failed to get device instance ID");
594 goto out;
599 * CM API used here as opposed to
600 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
601 * which exports are only available in mingw-w64 6+
603 cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
604 if (cr != CR_SUCCESS) {
605 g_error("CM_Locate_DevInst failed with code %lx", cr);
606 error_setg_win32(errp, GetLastError(),
607 "failed to get device instance");
608 goto out;
610 cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
611 if (cr != CR_SUCCESS) {
612 g_error("CM_Get_Parent failed with code %lx", cr);
613 error_setg_win32(errp, GetLastError(),
614 "failed to get parent device instance");
615 goto out;
618 cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
619 if (cr != CR_SUCCESS) {
620 g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
621 error_setg_win32(errp, GetLastError(),
622 "failed to get parent device ID length");
623 goto out;
626 ++dev_id_size;
627 if (dev_id_size > size) {
628 g_free(parent_dev_id);
629 parent_dev_id = g_malloc(dev_id_size);
632 cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
634 if (cr != CR_SUCCESS) {
635 g_error("CM_Get_Device_ID failed with code %lx", cr);
636 error_setg_win32(errp, GetLastError(),
637 "failed to get parent device ID");
638 goto out;
642 g_debug("querying storage controller %s for PCI information",
643 parent_dev_id);
644 parent_dev_info =
645 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
646 NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
647 g_free(parent_dev_id);
649 if (parent_dev_info == INVALID_HANDLE_VALUE) {
650 error_setg_win32(errp, GetLastError(),
651 "failed to get parent device");
652 goto out;
655 parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
656 if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
657 error_setg_win32(errp, GetLastError(),
658 "failed to get parent device data");
659 goto out;
662 for (j = 0;
663 SetupDiEnumDeviceInfo(parent_dev_info, j, &parent_dev_info_data);
664 j++) {
665 DWORD addr, bus, ui_slot, type;
666 int func, slot;
669 * There is no need to allocate buffer in the next functions. The
670 * size is known and ULONG according to
671 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
673 if (!SetupDiGetDeviceRegistryProperty(
674 parent_dev_info, &parent_dev_info_data, SPDRP_BUSNUMBER,
675 &type, (PBYTE)&bus, size, NULL)) {
676 debug_error("failed to get PCI bus");
677 bus = -1;
678 partial_pci = true;
682 * The function retrieves the device's address. This value will be
683 * transformed into device function and number
685 if (!SetupDiGetDeviceRegistryProperty(
686 parent_dev_info, &parent_dev_info_data, SPDRP_ADDRESS,
687 &type, (PBYTE)&addr, size, NULL)) {
688 debug_error("failed to get PCI address");
689 addr = -1;
690 partial_pci = true;
694 * This call returns UINumber of DEVICE_CAPABILITIES structure.
695 * This number is typically a user-perceived slot number.
697 if (!SetupDiGetDeviceRegistryProperty(
698 parent_dev_info, &parent_dev_info_data, SPDRP_UI_NUMBER,
699 &type, (PBYTE)&ui_slot, size, NULL)) {
700 debug_error("failed to get PCI slot");
701 ui_slot = -1;
702 partial_pci = true;
706 * SetupApi gives us the same information as driver with
707 * IoGetDeviceProperty. According to Microsoft:
709 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
710 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
711 * SPDRP_ADDRESS is propertyAddress, so we do the same.
713 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
715 if (partial_pci) {
716 pci->domain = -1;
717 pci->slot = -1;
718 pci->function = -1;
719 pci->bus = -1;
720 continue;
721 } else {
722 func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
723 slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
724 if ((int)ui_slot != slot) {
725 g_debug("mismatch with reported slot values: %d vs %d",
726 (int)ui_slot, slot);
728 pci->domain = 0;
729 pci->slot = (int)ui_slot;
730 pci->function = func;
731 pci->bus = (int)bus;
732 break;
735 SetupDiDestroyDeviceInfoList(parent_dev_info);
736 break;
739 free_dev_info:
740 SetupDiDestroyDeviceInfoList(dev_info);
741 out:
742 return pci;
745 static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
746 Error **errp)
748 STORAGE_PROPERTY_QUERY query;
749 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
750 DWORD received;
751 ULONG size = sizeof(buf);
753 dev_desc = &buf;
754 query.PropertyId = StorageDeviceProperty;
755 query.QueryType = PropertyStandardQuery;
757 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
758 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
759 size, &received, NULL)) {
760 error_setg_win32(errp, GetLastError(), "failed to get bus type");
761 return;
763 disk->bus_type = find_bus_type(dev_desc->BusType);
764 g_debug("bus type %d", disk->bus_type);
766 /* Query once more. Now with long enough buffer. */
767 size = dev_desc->Size;
768 dev_desc = g_malloc0(size);
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 serial number");
773 g_debug("failed to get serial number");
774 goto out_free;
776 if (dev_desc->SerialNumberOffset > 0) {
777 const char *serial;
778 size_t len;
780 if (dev_desc->SerialNumberOffset >= received) {
781 error_setg(errp, "failed to get serial number: offset outside the buffer");
782 g_debug("serial number offset outside the buffer");
783 goto out_free;
785 serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
786 len = received - dev_desc->SerialNumberOffset;
787 g_debug("serial number \"%s\"", serial);
788 if (*serial != 0) {
789 disk->serial = g_strndup(serial, len);
790 disk->has_serial = true;
793 out_free:
794 g_free(dev_desc);
796 return;
799 static void get_single_disk_info(int disk_number,
800 GuestDiskAddress *disk, Error **errp)
802 SCSI_ADDRESS addr, *scsi_ad;
803 DWORD len;
804 HANDLE disk_h;
805 Error *local_err = NULL;
807 scsi_ad = &addr;
809 g_debug("getting disk info for: %s", disk->dev);
810 disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
811 0, NULL);
812 if (disk_h == INVALID_HANDLE_VALUE) {
813 error_setg_win32(errp, GetLastError(), "failed to open disk");
814 return;
817 get_disk_properties(disk_h, disk, &local_err);
818 if (local_err) {
819 error_propagate(errp, local_err);
820 goto err_close;
823 g_debug("bus type %d", disk->bus_type);
824 /* always set pci_controller as required by schema. get_pci_info() should
825 * report -1 values for non-PCI buses rather than fail. fail the command
826 * if that doesn't hold since that suggests some other unexpected
827 * breakage
829 disk->pci_controller = get_pci_info(disk_number, &local_err);
830 if (local_err) {
831 error_propagate(errp, local_err);
832 goto err_close;
834 if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
835 || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
836 || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
837 /* This bus type is not supported before Windows Server 2003 SP1 */
838 || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
840 /* We are able to use the same ioctls for different bus types
841 * according to Microsoft docs
842 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
843 g_debug("getting SCSI info");
844 if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
845 sizeof(SCSI_ADDRESS), &len, NULL)) {
846 disk->unit = addr.Lun;
847 disk->target = addr.TargetId;
848 disk->bus = addr.PathId;
850 /* We do not set error in this case, because we still have enough
851 * information about volume. */
854 err_close:
855 CloseHandle(disk_h);
856 return;
859 /* VSS provider works with volumes, thus there is no difference if
860 * the volume consist of spanned disks. Info about the first disk in the
861 * volume is returned for the spanned disk group (LVM) */
862 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
864 Error *local_err = NULL;
865 GuestDiskAddressList *list = NULL, *cur_item = NULL;
866 GuestDiskAddress *disk = NULL;
867 int i;
868 HANDLE vol_h;
869 DWORD size;
870 PVOLUME_DISK_EXTENTS extents = NULL;
872 /* strip final backslash */
873 char *name = g_strdup(guid);
874 if (g_str_has_suffix(name, "\\")) {
875 name[strlen(name) - 1] = 0;
878 g_debug("opening %s", name);
879 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
880 0, NULL);
881 if (vol_h == INVALID_HANDLE_VALUE) {
882 error_setg_win32(errp, GetLastError(), "failed to open volume");
883 goto out;
886 /* Get list of extents */
887 g_debug("getting disk extents");
888 size = sizeof(VOLUME_DISK_EXTENTS);
889 extents = g_malloc0(size);
890 if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
891 0, extents, size, &size, NULL)) {
892 DWORD last_err = GetLastError();
893 if (last_err == ERROR_MORE_DATA) {
894 /* Try once more with big enough buffer */
895 g_free(extents);
896 extents = g_malloc0(size);
897 if (!DeviceIoControl(
898 vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
899 0, extents, size, NULL, NULL)) {
900 error_setg_win32(errp, GetLastError(),
901 "failed to get disk extents");
902 goto out;
904 } else if (last_err == ERROR_INVALID_FUNCTION) {
905 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
906 g_debug("volume not on disk");
907 disk = g_malloc0(sizeof(GuestDiskAddress));
908 disk->has_dev = true;
909 disk->dev = g_strdup(name);
910 get_single_disk_info(0xffffffff, disk, &local_err);
911 if (local_err) {
912 g_debug("failed to get disk info, ignoring error: %s",
913 error_get_pretty(local_err));
914 error_free(local_err);
915 goto out;
917 list = g_malloc0(sizeof(*list));
918 list->value = disk;
919 disk = NULL;
920 list->next = NULL;
921 goto out;
922 } else {
923 error_setg_win32(errp, GetLastError(),
924 "failed to get disk extents");
925 goto out;
928 g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
930 /* Go through each extent */
931 for (i = 0; i < extents->NumberOfDiskExtents; i++) {
932 disk = g_malloc0(sizeof(GuestDiskAddress));
934 /* Disk numbers directly correspond to numbers used in UNCs
936 * See documentation for DISK_EXTENT:
937 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
939 * See also Naming Files, Paths and Namespaces:
940 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
942 disk->has_dev = true;
943 disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
944 extents->Extents[i].DiskNumber);
946 get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
947 if (local_err) {
948 error_propagate(errp, local_err);
949 goto out;
951 cur_item = g_malloc0(sizeof(*list));
952 cur_item->value = disk;
953 disk = NULL;
954 cur_item->next = list;
955 list = cur_item;
959 out:
960 if (vol_h != INVALID_HANDLE_VALUE) {
961 CloseHandle(vol_h);
963 qapi_free_GuestDiskAddress(disk);
964 g_free(extents);
965 g_free(name);
967 return list;
970 #else
972 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
974 return NULL;
977 #endif /* CONFIG_QGA_NTDDSCSI */
979 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
981 DWORD info_size;
982 char mnt, *mnt_point;
983 char fs_name[32];
984 char vol_info[MAX_PATH+1];
985 size_t len;
986 uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
987 GuestFilesystemInfo *fs = NULL;
989 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
990 if (GetLastError() != ERROR_MORE_DATA) {
991 error_setg_win32(errp, GetLastError(), "failed to get volume name");
992 return NULL;
995 mnt_point = g_malloc(info_size + 1);
996 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
997 &info_size)) {
998 error_setg_win32(errp, GetLastError(), "failed to get volume name");
999 goto free;
1002 len = strlen(mnt_point);
1003 mnt_point[len] = '\\';
1004 mnt_point[len+1] = 0;
1005 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
1006 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
1007 if (GetLastError() != ERROR_NOT_READY) {
1008 error_setg_win32(errp, GetLastError(), "failed to get volume info");
1010 goto free;
1013 fs_name[sizeof(fs_name) - 1] = 0;
1014 fs = g_malloc(sizeof(*fs));
1015 fs->name = g_strdup(guid);
1016 fs->has_total_bytes = false;
1017 fs->has_used_bytes = false;
1018 if (len == 0) {
1019 fs->mountpoint = g_strdup("System Reserved");
1020 } else {
1021 fs->mountpoint = g_strndup(mnt_point, len);
1022 if (GetDiskFreeSpaceEx(fs->mountpoint,
1023 (PULARGE_INTEGER) & i64FreeBytesToCaller,
1024 (PULARGE_INTEGER) & i64TotalBytes,
1025 (PULARGE_INTEGER) & i64FreeBytes)) {
1026 fs->used_bytes = i64TotalBytes - i64FreeBytes;
1027 fs->total_bytes = i64TotalBytes;
1028 fs->has_total_bytes = true;
1029 fs->has_used_bytes = true;
1032 fs->type = g_strdup(fs_name);
1033 fs->disk = build_guest_disk_info(guid, errp);
1034 free:
1035 g_free(mnt_point);
1036 return fs;
1039 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1041 HANDLE vol_h;
1042 GuestFilesystemInfoList *new, *ret = NULL;
1043 char guid[256];
1045 vol_h = FindFirstVolume(guid, sizeof(guid));
1046 if (vol_h == INVALID_HANDLE_VALUE) {
1047 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1048 return NULL;
1051 do {
1052 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
1053 if (info == NULL) {
1054 continue;
1056 new = g_malloc(sizeof(*ret));
1057 new->value = info;
1058 new->next = ret;
1059 ret = new;
1060 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
1062 if (GetLastError() != ERROR_NO_MORE_FILES) {
1063 error_setg_win32(errp, GetLastError(), "failed to find next volume");
1066 FindVolumeClose(vol_h);
1067 return ret;
1071 * Return status of freeze/thaw
1073 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1075 if (!vss_initialized()) {
1076 error_setg(errp, QERR_UNSUPPORTED);
1077 return 0;
1080 if (ga_is_frozen(ga_state)) {
1081 return GUEST_FSFREEZE_STATUS_FROZEN;
1084 return GUEST_FSFREEZE_STATUS_THAWED;
1088 * Freeze local file systems using Volume Shadow-copy Service.
1089 * The frozen state is limited for up to 10 seconds by VSS.
1091 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1093 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1096 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1097 strList *mountpoints,
1098 Error **errp)
1100 int i;
1101 Error *local_err = NULL;
1103 if (!vss_initialized()) {
1104 error_setg(errp, QERR_UNSUPPORTED);
1105 return 0;
1108 slog("guest-fsfreeze called");
1110 /* cannot risk guest agent blocking itself on a write in this state */
1111 ga_set_frozen(ga_state);
1113 qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
1114 if (local_err) {
1115 error_propagate(errp, local_err);
1116 goto error;
1119 return i;
1121 error:
1122 local_err = NULL;
1123 qmp_guest_fsfreeze_thaw(&local_err);
1124 if (local_err) {
1125 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
1126 error_free(local_err);
1128 return 0;
1132 * Thaw local file systems using Volume Shadow-copy Service.
1134 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1136 int i;
1138 if (!vss_initialized()) {
1139 error_setg(errp, QERR_UNSUPPORTED);
1140 return 0;
1143 qga_vss_fsfreeze(&i, false, NULL, errp);
1145 ga_unset_frozen(ga_state);
1146 return i;
1149 static void guest_fsfreeze_cleanup(void)
1151 Error *err = NULL;
1153 if (!vss_initialized()) {
1154 return;
1157 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1158 qmp_guest_fsfreeze_thaw(&err);
1159 if (err) {
1160 slog("failed to clean up frozen filesystems: %s",
1161 error_get_pretty(err));
1162 error_free(err);
1166 vss_deinit(true);
1170 * Walk list of mounted file systems in the guest, and discard unused
1171 * areas.
1173 GuestFilesystemTrimResponse *
1174 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1176 GuestFilesystemTrimResponse *resp;
1177 HANDLE handle;
1178 WCHAR guid[MAX_PATH] = L"";
1179 OSVERSIONINFO osvi;
1180 BOOL win8_or_later;
1182 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
1183 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1184 GetVersionEx(&osvi);
1185 win8_or_later = (osvi.dwMajorVersion > 6 ||
1186 ((osvi.dwMajorVersion == 6) &&
1187 (osvi.dwMinorVersion >= 2)));
1188 if (!win8_or_later) {
1189 error_setg(errp, "fstrim is only supported for Win8+");
1190 return NULL;
1193 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
1194 if (handle == INVALID_HANDLE_VALUE) {
1195 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1196 return NULL;
1199 resp = g_new0(GuestFilesystemTrimResponse, 1);
1201 do {
1202 GuestFilesystemTrimResult *res;
1203 GuestFilesystemTrimResultList *list;
1204 PWCHAR uc_path;
1205 DWORD char_count = 0;
1206 char *path, *out;
1207 GError *gerr = NULL;
1208 gchar * argv[4];
1210 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1212 if (GetLastError() != ERROR_MORE_DATA) {
1213 continue;
1215 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1216 continue;
1219 uc_path = g_malloc(sizeof(WCHAR) * char_count);
1220 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1221 &char_count) || !*uc_path) {
1222 /* strange, but this condition could be faced even with size == 2 */
1223 g_free(uc_path);
1224 continue;
1227 res = g_new0(GuestFilesystemTrimResult, 1);
1229 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1231 g_free(uc_path);
1233 if (!path) {
1234 res->has_error = true;
1235 res->error = g_strdup(gerr->message);
1236 g_error_free(gerr);
1237 break;
1240 res->path = path;
1242 list = g_new0(GuestFilesystemTrimResultList, 1);
1243 list->value = res;
1244 list->next = resp->paths;
1246 resp->paths = list;
1248 memset(argv, 0, sizeof(argv));
1249 argv[0] = (gchar *)"defrag.exe";
1250 argv[1] = (gchar *)"/L";
1251 argv[2] = path;
1253 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1254 &out /* stdout */, NULL /* stdin */,
1255 NULL, &gerr)) {
1256 res->has_error = true;
1257 res->error = g_strdup(gerr->message);
1258 g_error_free(gerr);
1259 } else {
1260 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1261 Error is reported in the output with something like
1262 (x89000020) etc code in the stdout */
1264 int i;
1265 gchar **lines = g_strsplit(out, "\r\n", 0);
1266 g_free(out);
1268 for (i = 0; lines[i] != NULL; i++) {
1269 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1270 continue;
1272 res->has_error = true;
1273 res->error = g_strdup(lines[i]);
1274 break;
1276 g_strfreev(lines);
1278 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1280 FindVolumeClose(handle);
1281 return resp;
1284 typedef enum {
1285 GUEST_SUSPEND_MODE_DISK,
1286 GUEST_SUSPEND_MODE_RAM
1287 } GuestSuspendMode;
1289 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
1291 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1292 Error *local_err = NULL;
1294 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1295 if (!GetPwrCapabilities(&sys_pwr_caps)) {
1296 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1297 "failed to determine guest suspend capabilities");
1298 goto out;
1301 switch (mode) {
1302 case GUEST_SUSPEND_MODE_DISK:
1303 if (!sys_pwr_caps.SystemS4) {
1304 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1305 "suspend-to-disk not supported by OS");
1307 break;
1308 case GUEST_SUSPEND_MODE_RAM:
1309 if (!sys_pwr_caps.SystemS3) {
1310 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1311 "suspend-to-ram not supported by OS");
1313 break;
1314 default:
1315 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
1316 "GuestSuspendMode");
1319 out:
1320 error_propagate(errp, local_err);
1323 static DWORD WINAPI do_suspend(LPVOID opaque)
1325 GuestSuspendMode *mode = opaque;
1326 DWORD ret = 0;
1328 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1329 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
1330 slog("failed to suspend guest: %s", emsg);
1331 ret = -1;
1333 g_free(mode);
1334 return ret;
1337 void qmp_guest_suspend_disk(Error **errp)
1339 Error *local_err = NULL;
1340 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1342 *mode = GUEST_SUSPEND_MODE_DISK;
1343 check_suspend_mode(*mode, &local_err);
1344 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1345 execute_async(do_suspend, mode, &local_err);
1347 if (local_err) {
1348 error_propagate(errp, local_err);
1349 g_free(mode);
1353 void qmp_guest_suspend_ram(Error **errp)
1355 Error *local_err = NULL;
1356 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1358 *mode = GUEST_SUSPEND_MODE_RAM;
1359 check_suspend_mode(*mode, &local_err);
1360 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1361 execute_async(do_suspend, mode, &local_err);
1363 if (local_err) {
1364 error_propagate(errp, local_err);
1365 g_free(mode);
1369 void qmp_guest_suspend_hybrid(Error **errp)
1371 error_setg(errp, QERR_UNSUPPORTED);
1374 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1376 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1377 ULONG adptr_addrs_len = 0;
1378 DWORD ret;
1380 /* Call the first time to get the adptr_addrs_len. */
1381 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1382 NULL, adptr_addrs, &adptr_addrs_len);
1384 adptr_addrs = g_malloc(adptr_addrs_len);
1385 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1386 NULL, adptr_addrs, &adptr_addrs_len);
1387 if (ret != ERROR_SUCCESS) {
1388 error_setg_win32(errp, ret, "failed to get adapters addresses");
1389 g_free(adptr_addrs);
1390 adptr_addrs = NULL;
1392 return adptr_addrs;
1395 static char *guest_wctomb_dup(WCHAR *wstr)
1397 char *str;
1398 size_t str_size;
1400 str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
1401 /* add 1 to str_size for NULL terminator */
1402 str = g_malloc(str_size + 1);
1403 WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
1404 return str;
1407 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1408 Error **errp)
1410 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1411 DWORD len;
1412 int ret;
1414 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1415 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1416 len = sizeof(addr_str);
1417 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1418 ip_addr->Address.iSockaddrLength,
1419 NULL,
1420 addr_str,
1421 &len);
1422 if (ret != 0) {
1423 error_setg_win32(errp, WSAGetLastError(),
1424 "failed address presentation form conversion");
1425 return NULL;
1427 return g_strdup(addr_str);
1429 return NULL;
1432 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1434 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1435 * field to obtain the prefix.
1437 return ip_addr->OnLinkPrefixLength;
1440 #define INTERFACE_PATH_BUF_SZ 512
1442 static DWORD get_interface_index(const char *guid)
1444 ULONG index;
1445 DWORD status;
1446 wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1447 snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1448 wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1449 status = GetAdapterIndex (wbuf, &index);
1450 if (status != NO_ERROR) {
1451 return (DWORD)~0;
1452 } else {
1453 return index;
1457 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1459 static int guest_get_network_stats(const char *name,
1460 GuestNetworkInterfaceStat *stats)
1462 OSVERSIONINFO os_ver;
1464 os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1465 GetVersionEx(&os_ver);
1466 if (os_ver.dwMajorVersion >= 6) {
1467 MIB_IF_ROW2 a_mid_ifrow;
1468 GetIfEntry2Func getifentry2_ex;
1469 DWORD if_index = 0;
1470 HMODULE module = GetModuleHandle("iphlpapi");
1471 PVOID func = GetProcAddress(module, "GetIfEntry2");
1473 if (func == NULL) {
1474 return -1;
1477 getifentry2_ex = (GetIfEntry2Func)func;
1478 if_index = get_interface_index(name);
1479 if (if_index == (DWORD)~0) {
1480 return -1;
1483 memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1484 a_mid_ifrow.InterfaceIndex = if_index;
1485 if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1486 stats->rx_bytes = a_mid_ifrow.InOctets;
1487 stats->rx_packets = a_mid_ifrow.InUcastPkts;
1488 stats->rx_errs = a_mid_ifrow.InErrors;
1489 stats->rx_dropped = a_mid_ifrow.InDiscards;
1490 stats->tx_bytes = a_mid_ifrow.OutOctets;
1491 stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1492 stats->tx_errs = a_mid_ifrow.OutErrors;
1493 stats->tx_dropped = a_mid_ifrow.OutDiscards;
1494 return 0;
1497 return -1;
1500 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1502 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1503 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1504 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1505 GuestIpAddressList *head_addr, *cur_addr;
1506 GuestNetworkInterfaceList *info;
1507 GuestNetworkInterfaceStat *interface_stat = NULL;
1508 GuestIpAddressList *address_item = NULL;
1509 unsigned char *mac_addr;
1510 char *addr_str;
1511 WORD wsa_version;
1512 WSADATA wsa_data;
1513 int ret;
1515 adptr_addrs = guest_get_adapters_addresses(errp);
1516 if (adptr_addrs == NULL) {
1517 return NULL;
1520 /* Make WSA APIs available. */
1521 wsa_version = MAKEWORD(2, 2);
1522 ret = WSAStartup(wsa_version, &wsa_data);
1523 if (ret != 0) {
1524 error_setg_win32(errp, ret, "failed socket startup");
1525 goto out;
1528 for (addr = adptr_addrs; addr; addr = addr->Next) {
1529 info = g_malloc0(sizeof(*info));
1531 if (cur_item == NULL) {
1532 head = cur_item = info;
1533 } else {
1534 cur_item->next = info;
1535 cur_item = info;
1538 info->value = g_malloc0(sizeof(*info->value));
1539 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1541 if (addr->PhysicalAddressLength != 0) {
1542 mac_addr = addr->PhysicalAddress;
1544 info->value->hardware_address =
1545 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1546 (int) mac_addr[0], (int) mac_addr[1],
1547 (int) mac_addr[2], (int) mac_addr[3],
1548 (int) mac_addr[4], (int) mac_addr[5]);
1550 info->value->has_hardware_address = true;
1553 head_addr = NULL;
1554 cur_addr = NULL;
1555 for (ip_addr = addr->FirstUnicastAddress;
1556 ip_addr;
1557 ip_addr = ip_addr->Next) {
1558 addr_str = guest_addr_to_str(ip_addr, errp);
1559 if (addr_str == NULL) {
1560 continue;
1563 address_item = g_malloc0(sizeof(*address_item));
1565 if (!cur_addr) {
1566 head_addr = cur_addr = address_item;
1567 } else {
1568 cur_addr->next = address_item;
1569 cur_addr = address_item;
1572 address_item->value = g_malloc0(sizeof(*address_item->value));
1573 address_item->value->ip_address = addr_str;
1574 address_item->value->prefix = guest_ip_prefix(ip_addr);
1575 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1576 address_item->value->ip_address_type =
1577 GUEST_IP_ADDRESS_TYPE_IPV4;
1578 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1579 address_item->value->ip_address_type =
1580 GUEST_IP_ADDRESS_TYPE_IPV6;
1583 if (head_addr) {
1584 info->value->has_ip_addresses = true;
1585 info->value->ip_addresses = head_addr;
1587 if (!info->value->has_statistics) {
1588 interface_stat = g_malloc0(sizeof(*interface_stat));
1589 if (guest_get_network_stats(addr->AdapterName,
1590 interface_stat) == -1) {
1591 info->value->has_statistics = false;
1592 g_free(interface_stat);
1593 } else {
1594 info->value->statistics = interface_stat;
1595 info->value->has_statistics = true;
1599 WSACleanup();
1600 out:
1601 g_free(adptr_addrs);
1602 return head;
1605 int64_t qmp_guest_get_time(Error **errp)
1607 SYSTEMTIME ts = {0};
1608 FILETIME tf;
1610 GetSystemTime(&ts);
1611 if (ts.wYear < 1601 || ts.wYear > 30827) {
1612 error_setg(errp, "Failed to get time");
1613 return -1;
1616 if (!SystemTimeToFileTime(&ts, &tf)) {
1617 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1618 return -1;
1621 return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1622 - W32_FT_OFFSET) * 100;
1625 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1627 Error *local_err = NULL;
1628 SYSTEMTIME ts;
1629 FILETIME tf;
1630 LONGLONG time;
1632 if (!has_time) {
1633 /* Unfortunately, Windows libraries don't provide an easy way to access
1634 * RTC yet:
1636 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1638 * Instead, a workaround is to use the Windows win32tm command to
1639 * resync the time using the Windows Time service.
1641 LPVOID msg_buffer;
1642 DWORD ret_flags;
1644 HRESULT hr = system("w32tm /resync /nowait");
1646 if (GetLastError() != 0) {
1647 strerror_s((LPTSTR) & msg_buffer, 0, errno);
1648 error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1649 } else if (hr != 0) {
1650 if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1651 error_setg(errp, "Windows Time service not running on the "
1652 "guest");
1653 } else {
1654 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1655 FORMAT_MESSAGE_FROM_SYSTEM |
1656 FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1657 (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1658 SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1659 NULL)) {
1660 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1661 "t retrieve error message", hr);
1662 } else {
1663 error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1664 (LPCTSTR)msg_buffer);
1665 LocalFree(msg_buffer);
1668 } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1669 error_setg(errp, "No internet connection on guest, sync not "
1670 "accurate");
1672 return;
1675 /* Validate time passed by user. */
1676 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1677 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1678 return;
1681 time = time_ns / 100 + W32_FT_OFFSET;
1683 tf.dwLowDateTime = (DWORD) time;
1684 tf.dwHighDateTime = (DWORD) (time >> 32);
1686 if (!FileTimeToSystemTime(&tf, &ts)) {
1687 error_setg(errp, "Failed to convert system time %d",
1688 (int)GetLastError());
1689 return;
1692 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1693 if (local_err) {
1694 error_propagate(errp, local_err);
1695 return;
1698 if (!SetSystemTime(&ts)) {
1699 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1700 return;
1704 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1706 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1707 DWORD length;
1708 GuestLogicalProcessorList *head, **link;
1709 Error *local_err = NULL;
1710 int64_t current;
1712 ptr = pslpi = NULL;
1713 length = 0;
1714 current = 0;
1715 head = NULL;
1716 link = &head;
1718 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1719 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1720 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1721 ptr = pslpi = g_malloc0(length);
1722 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1723 error_setg(&local_err, "Failed to get processor information: %d",
1724 (int)GetLastError());
1726 } else {
1727 error_setg(&local_err,
1728 "Failed to get processor information buffer length: %d",
1729 (int)GetLastError());
1732 while ((local_err == NULL) && (length > 0)) {
1733 if (pslpi->Relationship == RelationProcessorCore) {
1734 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1736 while (cpu_bits > 0) {
1737 if (!!(cpu_bits & 1)) {
1738 GuestLogicalProcessor *vcpu;
1739 GuestLogicalProcessorList *entry;
1741 vcpu = g_malloc0(sizeof *vcpu);
1742 vcpu->logical_id = current++;
1743 vcpu->online = true;
1744 vcpu->has_can_offline = true;
1746 entry = g_malloc0(sizeof *entry);
1747 entry->value = vcpu;
1749 *link = entry;
1750 link = &entry->next;
1752 cpu_bits >>= 1;
1755 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1756 pslpi++; /* next entry */
1759 g_free(ptr);
1761 if (local_err == NULL) {
1762 if (head != NULL) {
1763 return head;
1765 /* there's no guest with zero VCPUs */
1766 error_setg(&local_err, "Guest reported zero VCPUs");
1769 qapi_free_GuestLogicalProcessorList(head);
1770 error_propagate(errp, local_err);
1771 return NULL;
1774 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1776 error_setg(errp, QERR_UNSUPPORTED);
1777 return -1;
1780 static gchar *
1781 get_net_error_message(gint error)
1783 HMODULE module = NULL;
1784 gchar *retval = NULL;
1785 wchar_t *msg = NULL;
1786 int flags;
1787 size_t nchars;
1789 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1790 FORMAT_MESSAGE_IGNORE_INSERTS |
1791 FORMAT_MESSAGE_FROM_SYSTEM;
1793 if (error >= NERR_BASE && error <= MAX_NERR) {
1794 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1796 if (module != NULL) {
1797 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1801 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1803 if (msg != NULL) {
1804 nchars = wcslen(msg);
1806 if (nchars >= 2 &&
1807 msg[nchars - 1] == L'\n' &&
1808 msg[nchars - 2] == L'\r') {
1809 msg[nchars - 2] = L'\0';
1812 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1814 LocalFree(msg);
1817 if (module != NULL) {
1818 FreeLibrary(module);
1821 return retval;
1824 void qmp_guest_set_user_password(const char *username,
1825 const char *password,
1826 bool crypted,
1827 Error **errp)
1829 NET_API_STATUS nas;
1830 char *rawpasswddata = NULL;
1831 size_t rawpasswdlen;
1832 wchar_t *user = NULL, *wpass = NULL;
1833 USER_INFO_1003 pi1003 = { 0, };
1834 GError *gerr = NULL;
1836 if (crypted) {
1837 error_setg(errp, QERR_UNSUPPORTED);
1838 return;
1841 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1842 if (!rawpasswddata) {
1843 return;
1845 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1846 rawpasswddata[rawpasswdlen] = '\0';
1848 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1849 if (!user) {
1850 goto done;
1853 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1854 if (!wpass) {
1855 goto done;
1858 pi1003.usri1003_password = wpass;
1859 nas = NetUserSetInfo(NULL, user,
1860 1003, (LPBYTE)&pi1003,
1861 NULL);
1863 if (nas != NERR_Success) {
1864 gchar *msg = get_net_error_message(nas);
1865 error_setg(errp, "failed to set password: %s", msg);
1866 g_free(msg);
1869 done:
1870 if (gerr) {
1871 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1872 g_error_free(gerr);
1874 g_free(user);
1875 g_free(wpass);
1876 g_free(rawpasswddata);
1879 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1881 error_setg(errp, QERR_UNSUPPORTED);
1882 return NULL;
1885 GuestMemoryBlockResponseList *
1886 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1888 error_setg(errp, QERR_UNSUPPORTED);
1889 return NULL;
1892 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1894 error_setg(errp, QERR_UNSUPPORTED);
1895 return NULL;
1898 /* add unsupported commands to the blacklist */
1899 GList *ga_command_blacklist_init(GList *blacklist)
1901 const char *list_unsupported[] = {
1902 "guest-suspend-hybrid",
1903 "guest-set-vcpus",
1904 "guest-get-memory-blocks", "guest-set-memory-blocks",
1905 "guest-get-memory-block-size", "guest-get-memory-block-info",
1906 NULL};
1907 char **p = (char **)list_unsupported;
1909 while (*p) {
1910 blacklist = g_list_append(blacklist, g_strdup(*p++));
1913 if (!vss_init(true)) {
1914 g_debug("vss_init failed, vss commands are going to be disabled");
1915 const char *list[] = {
1916 "guest-get-fsinfo", "guest-fsfreeze-status",
1917 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1918 p = (char **)list;
1920 while (*p) {
1921 blacklist = g_list_append(blacklist, g_strdup(*p++));
1925 return blacklist;
1928 /* register init/cleanup routines for stateful command groups */
1929 void ga_command_state_init(GAState *s, GACommandState *cs)
1931 if (!vss_initialized()) {
1932 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1936 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1937 typedef struct _GA_WTSINFOA {
1938 WTS_CONNECTSTATE_CLASS State;
1939 DWORD SessionId;
1940 DWORD IncomingBytes;
1941 DWORD OutgoingBytes;
1942 DWORD IncomingFrames;
1943 DWORD OutgoingFrames;
1944 DWORD IncomingCompressedBytes;
1945 DWORD OutgoingCompressedBy;
1946 CHAR WinStationName[WINSTATIONNAME_LENGTH];
1947 CHAR Domain[DOMAIN_LENGTH];
1948 CHAR UserName[USERNAME_LENGTH + 1];
1949 LARGE_INTEGER ConnectTime;
1950 LARGE_INTEGER DisconnectTime;
1951 LARGE_INTEGER LastInputTime;
1952 LARGE_INTEGER LogonTime;
1953 LARGE_INTEGER CurrentTime;
1955 } GA_WTSINFOA;
1957 GuestUserList *qmp_guest_get_users(Error **errp)
1959 #define QGA_NANOSECONDS 10000000
1961 GHashTable *cache = NULL;
1962 GuestUserList *head = NULL, *cur_item = NULL;
1964 DWORD buffer_size = 0, count = 0, i = 0;
1965 GA_WTSINFOA *info = NULL;
1966 WTS_SESSION_INFOA *entries = NULL;
1967 GuestUserList *item = NULL;
1968 GuestUser *user = NULL;
1969 gpointer value = NULL;
1970 INT64 login = 0;
1971 double login_time = 0;
1973 cache = g_hash_table_new(g_str_hash, g_str_equal);
1975 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
1976 for (i = 0; i < count; ++i) {
1977 buffer_size = 0;
1978 info = NULL;
1979 if (WTSQuerySessionInformationA(
1980 NULL,
1981 entries[i].SessionId,
1982 WTSSessionInfo,
1983 (LPSTR *)&info,
1984 &buffer_size
1985 )) {
1987 if (strlen(info->UserName) == 0) {
1988 WTSFreeMemory(info);
1989 continue;
1992 login = info->LogonTime.QuadPart;
1993 login -= W32_FT_OFFSET;
1994 login_time = ((double)login) / QGA_NANOSECONDS;
1996 if (g_hash_table_contains(cache, info->UserName)) {
1997 value = g_hash_table_lookup(cache, info->UserName);
1998 user = (GuestUser *)value;
1999 if (user->login_time > login_time) {
2000 user->login_time = login_time;
2002 } else {
2003 item = g_new0(GuestUserList, 1);
2004 item->value = g_new0(GuestUser, 1);
2006 item->value->user = g_strdup(info->UserName);
2007 item->value->domain = g_strdup(info->Domain);
2008 item->value->has_domain = true;
2010 item->value->login_time = login_time;
2012 g_hash_table_add(cache, item->value->user);
2014 if (!cur_item) {
2015 head = cur_item = item;
2016 } else {
2017 cur_item->next = item;
2018 cur_item = item;
2022 WTSFreeMemory(info);
2024 WTSFreeMemory(entries);
2026 g_hash_table_destroy(cache);
2027 return head;
2030 typedef struct _ga_matrix_lookup_t {
2031 int major;
2032 int minor;
2033 char const *version;
2034 char const *version_id;
2035 } ga_matrix_lookup_t;
2037 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
2039 /* Desktop editions */
2040 { 5, 0, "Microsoft Windows 2000", "2000"},
2041 { 5, 1, "Microsoft Windows XP", "xp"},
2042 { 6, 0, "Microsoft Windows Vista", "vista"},
2043 { 6, 1, "Microsoft Windows 7" "7"},
2044 { 6, 2, "Microsoft Windows 8", "8"},
2045 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2046 {10, 0, "Microsoft Windows 10", "10"},
2047 { 0, 0, 0}
2049 /* Server editions */
2050 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2051 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2052 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2053 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2054 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2055 { 0, 0, 0},
2056 { 0, 0, 0},
2057 { 0, 0, 0}
2061 typedef struct _ga_win_10_0_server_t {
2062 int final_build;
2063 char const *version;
2064 char const *version_id;
2065 } ga_win_10_0_server_t;
2067 static ga_win_10_0_server_t const WIN_10_0_SERVER_VERSION_MATRIX[3] = {
2068 {14393, "Microsoft Windows Server 2016", "2016"},
2069 {17763, "Microsoft Windows Server 2019", "2019"},
2070 {0, 0}
2073 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2075 typedef NTSTATUS(WINAPI * rtl_get_version_t)(
2076 RTL_OSVERSIONINFOEXW *os_version_info_ex);
2078 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2080 HMODULE module = GetModuleHandle("ntdll");
2081 PVOID fun = GetProcAddress(module, "RtlGetVersion");
2082 if (fun == NULL) {
2083 error_setg(errp, QERR_QGA_COMMAND_FAILED,
2084 "Failed to get address of RtlGetVersion");
2085 return;
2088 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2089 rtl_get_version(info);
2090 return;
2093 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
2095 DWORD major = os_version->dwMajorVersion;
2096 DWORD minor = os_version->dwMinorVersion;
2097 DWORD build = os_version->dwBuildNumber;
2098 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2099 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
2100 ga_win_10_0_server_t const *win_10_0_table = WIN_10_0_SERVER_VERSION_MATRIX;
2101 while (table->version != NULL) {
2102 if (major == 10 && minor == 0 && tbl_idx) {
2103 while (win_10_0_table->version != NULL) {
2104 if (build <= win_10_0_table->final_build) {
2105 if (id) {
2106 return g_strdup(win_10_0_table->version_id);
2107 } else {
2108 return g_strdup(win_10_0_table->version);
2111 win_10_0_table++;
2113 } else if (major == table->major && minor == table->minor) {
2114 if (id) {
2115 return g_strdup(table->version_id);
2116 } else {
2117 return g_strdup(table->version);
2120 ++table;
2122 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2123 major, minor);
2124 return g_strdup("N/A");
2127 static char *ga_get_win_product_name(Error **errp)
2129 HKEY key = NULL;
2130 DWORD size = 128;
2131 char *result = g_malloc0(size);
2132 LONG err = ERROR_SUCCESS;
2134 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2135 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2136 &key);
2137 if (err != ERROR_SUCCESS) {
2138 error_setg_win32(errp, err, "failed to open registry key");
2139 goto fail;
2142 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2143 (LPBYTE)result, &size);
2144 if (err == ERROR_MORE_DATA) {
2145 slog("ProductName longer than expected (%lu bytes), retrying",
2146 size);
2147 g_free(result);
2148 result = NULL;
2149 if (size > 0) {
2150 result = g_malloc0(size);
2151 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2152 (LPBYTE)result, &size);
2155 if (err != ERROR_SUCCESS) {
2156 error_setg_win32(errp, err, "failed to retrive ProductName");
2157 goto fail;
2160 return result;
2162 fail:
2163 g_free(result);
2164 return NULL;
2167 static char *ga_get_current_arch(void)
2169 SYSTEM_INFO info;
2170 GetNativeSystemInfo(&info);
2171 char *result = NULL;
2172 switch (info.wProcessorArchitecture) {
2173 case PROCESSOR_ARCHITECTURE_AMD64:
2174 result = g_strdup("x86_64");
2175 break;
2176 case PROCESSOR_ARCHITECTURE_ARM:
2177 result = g_strdup("arm");
2178 break;
2179 case PROCESSOR_ARCHITECTURE_IA64:
2180 result = g_strdup("ia64");
2181 break;
2182 case PROCESSOR_ARCHITECTURE_INTEL:
2183 result = g_strdup("x86");
2184 break;
2185 case PROCESSOR_ARCHITECTURE_UNKNOWN:
2186 default:
2187 slog("unknown processor architecture 0x%0x",
2188 info.wProcessorArchitecture);
2189 result = g_strdup("unknown");
2190 break;
2192 return result;
2195 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2197 Error *local_err = NULL;
2198 OSVERSIONINFOEXW os_version = {0};
2199 bool server;
2200 char *product_name;
2201 GuestOSInfo *info;
2203 ga_get_win_version(&os_version, &local_err);
2204 if (local_err) {
2205 error_propagate(errp, local_err);
2206 return NULL;
2209 server = os_version.wProductType != VER_NT_WORKSTATION;
2210 product_name = ga_get_win_product_name(&local_err);
2211 if (product_name == NULL) {
2212 error_propagate(errp, local_err);
2213 return NULL;
2216 info = g_new0(GuestOSInfo, 1);
2218 info->has_kernel_version = true;
2219 info->kernel_version = g_strdup_printf("%lu.%lu",
2220 os_version.dwMajorVersion,
2221 os_version.dwMinorVersion);
2222 info->has_kernel_release = true;
2223 info->kernel_release = g_strdup_printf("%lu",
2224 os_version.dwBuildNumber);
2225 info->has_machine = true;
2226 info->machine = ga_get_current_arch();
2228 info->has_id = true;
2229 info->id = g_strdup("mswindows");
2230 info->has_name = true;
2231 info->name = g_strdup("Microsoft Windows");
2232 info->has_pretty_name = true;
2233 info->pretty_name = product_name;
2234 info->has_version = true;
2235 info->version = ga_get_win_name(&os_version, false);
2236 info->has_version_id = true;
2237 info->version_id = ga_get_win_name(&os_version, true);
2238 info->has_variant = true;
2239 info->variant = g_strdup(server ? "server" : "client");
2240 info->has_variant_id = true;
2241 info->variant_id = g_strdup(server ? "server" : "client");
2243 return info;