hw/dma: Add SiFive platform DMA controller emulation
[qemu/ar7.git] / qga / commands-win32.c
blob15c9d7944b8e5fd7092ad5b54273dd3a9a234e8f
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"
40 #include "commands-common.h"
42 #ifndef SHTDN_REASON_FLAG_PLANNED
43 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
44 #endif
46 /* multiple of 100 nanoseconds elapsed between windows baseline
47 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
48 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
49 (365 * (1970 - 1601) + \
50 (1970 - 1601) / 4 - 3))
52 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
54 struct GuestFileHandle {
55 int64_t id;
56 HANDLE fh;
57 QTAILQ_ENTRY(GuestFileHandle) next;
60 static struct {
61 QTAILQ_HEAD(, GuestFileHandle) filehandles;
62 } guest_file_state = {
63 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
66 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
68 typedef struct OpenFlags {
69 const char *forms;
70 DWORD desired_access;
71 DWORD creation_disposition;
72 } OpenFlags;
73 static OpenFlags guest_file_open_modes[] = {
74 {"r", GENERIC_READ, OPEN_EXISTING},
75 {"rb", GENERIC_READ, OPEN_EXISTING},
76 {"w", GENERIC_WRITE, CREATE_ALWAYS},
77 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
78 {"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
79 {"r+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
80 {"rb+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
81 {"r+b", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
82 {"w+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
83 {"wb+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
84 {"w+b", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
85 {"a+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
86 {"ab+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
87 {"a+b", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS }
90 #define debug_error(msg) do { \
91 char *suffix = g_win32_error_message(GetLastError()); \
92 g_debug("%s: %s", (msg), suffix); \
93 g_free(suffix); \
94 } while (0)
96 static OpenFlags *find_open_flag(const char *mode_str)
98 int mode;
99 Error **errp = NULL;
101 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
102 OpenFlags *flags = guest_file_open_modes + mode;
104 if (strcmp(flags->forms, mode_str) == 0) {
105 return flags;
109 error_setg(errp, "invalid file open mode '%s'", mode_str);
110 return NULL;
113 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
115 GuestFileHandle *gfh;
116 int64_t handle;
118 handle = ga_get_fd_handle(ga_state, errp);
119 if (handle < 0) {
120 return -1;
122 gfh = g_new0(GuestFileHandle, 1);
123 gfh->id = handle;
124 gfh->fh = fh;
125 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
127 return handle;
130 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
132 GuestFileHandle *gfh;
133 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
134 if (gfh->id == id) {
135 return gfh;
138 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
139 return NULL;
142 static void handle_set_nonblocking(HANDLE fh)
144 DWORD file_type, pipe_state;
145 file_type = GetFileType(fh);
146 if (file_type != FILE_TYPE_PIPE) {
147 return;
149 /* If file_type == FILE_TYPE_PIPE, according to MSDN
150 * the specified file is socket or named pipe */
151 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
152 NULL, NULL, NULL, 0)) {
153 return;
155 /* The fd is named pipe fd */
156 if (pipe_state & PIPE_NOWAIT) {
157 return;
160 pipe_state |= PIPE_NOWAIT;
161 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
164 int64_t qmp_guest_file_open(const char *path, bool has_mode,
165 const char *mode, Error **errp)
167 int64_t fd = -1;
168 HANDLE fh;
169 HANDLE templ_file = NULL;
170 DWORD share_mode = FILE_SHARE_READ;
171 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
172 LPSECURITY_ATTRIBUTES sa_attr = NULL;
173 OpenFlags *guest_flags;
174 GError *gerr = NULL;
175 wchar_t *w_path = NULL;
177 if (!has_mode) {
178 mode = "r";
180 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
181 guest_flags = find_open_flag(mode);
182 if (guest_flags == NULL) {
183 error_setg(errp, "invalid file open mode");
184 goto done;
187 w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
188 if (!w_path) {
189 goto done;
192 fh = CreateFileW(w_path, guest_flags->desired_access, share_mode, sa_attr,
193 guest_flags->creation_disposition, flags_and_attr,
194 templ_file);
195 if (fh == INVALID_HANDLE_VALUE) {
196 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
197 path);
198 goto done;
201 /* set fd non-blocking to avoid common use cases (like reading from a
202 * named pipe) from hanging the agent
204 handle_set_nonblocking(fh);
206 fd = guest_file_handle_add(fh, errp);
207 if (fd < 0) {
208 CloseHandle(fh);
209 error_setg(errp, "failed to add handle to qmp handle table");
210 goto done;
213 slog("guest-file-open, handle: % " PRId64, fd);
215 done:
216 if (gerr) {
217 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
218 g_error_free(gerr);
220 g_free(w_path);
221 return fd;
224 void qmp_guest_file_close(int64_t handle, Error **errp)
226 bool ret;
227 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
228 slog("guest-file-close called, handle: %" PRId64, handle);
229 if (gfh == NULL) {
230 return;
232 ret = CloseHandle(gfh->fh);
233 if (!ret) {
234 error_setg_win32(errp, GetLastError(), "failed close handle");
235 return;
238 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
239 g_free(gfh);
242 static void acquire_privilege(const char *name, Error **errp)
244 HANDLE token = NULL;
245 TOKEN_PRIVILEGES priv;
246 Error *local_err = NULL;
248 if (OpenProcessToken(GetCurrentProcess(),
249 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
251 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
252 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
253 "no luid for requested privilege");
254 goto out;
257 priv.PrivilegeCount = 1;
258 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
260 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
261 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
262 "unable to acquire requested privilege");
263 goto out;
266 } else {
267 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
268 "failed to open privilege token");
271 out:
272 if (token) {
273 CloseHandle(token);
275 error_propagate(errp, local_err);
278 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
279 Error **errp)
281 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
282 if (!thread) {
283 error_setg(errp, QERR_QGA_COMMAND_FAILED,
284 "failed to dispatch asynchronous command");
288 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
290 Error *local_err = NULL;
291 UINT shutdown_flag = EWX_FORCE;
293 slog("guest-shutdown called, mode: %s", mode);
295 if (!has_mode || strcmp(mode, "powerdown") == 0) {
296 shutdown_flag |= EWX_POWEROFF;
297 } else if (strcmp(mode, "halt") == 0) {
298 shutdown_flag |= EWX_SHUTDOWN;
299 } else if (strcmp(mode, "reboot") == 0) {
300 shutdown_flag |= EWX_REBOOT;
301 } else {
302 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
303 "halt|powerdown|reboot");
304 return;
307 /* Request a shutdown privilege, but try to shut down the system
308 anyway. */
309 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
310 if (local_err) {
311 error_propagate(errp, local_err);
312 return;
315 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
316 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
317 slog("guest-shutdown failed: %s", emsg);
318 error_setg_win32(errp, GetLastError(), "guest-shutdown failed");
322 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
323 int64_t count, Error **errp)
325 GuestFileRead *read_data = NULL;
326 guchar *buf;
327 HANDLE fh = gfh->fh;
328 bool is_ok;
329 DWORD read_count;
331 buf = g_malloc0(count + 1);
332 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
333 if (!is_ok) {
334 error_setg_win32(errp, GetLastError(), "failed to read file");
335 } else {
336 buf[read_count] = 0;
337 read_data = g_new0(GuestFileRead, 1);
338 read_data->count = (size_t)read_count;
339 read_data->eof = read_count == 0;
341 if (read_count != 0) {
342 read_data->buf_b64 = g_base64_encode(buf, read_count);
345 g_free(buf);
347 return read_data;
350 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
351 bool has_count, int64_t count,
352 Error **errp)
354 GuestFileWrite *write_data = NULL;
355 guchar *buf;
356 gsize buf_len;
357 bool is_ok;
358 DWORD write_count;
359 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
360 HANDLE fh;
362 if (!gfh) {
363 return NULL;
365 fh = gfh->fh;
366 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
367 if (!buf) {
368 return NULL;
371 if (!has_count) {
372 count = buf_len;
373 } else if (count < 0 || count > buf_len) {
374 error_setg(errp, "value '%" PRId64
375 "' is invalid for argument count", count);
376 goto done;
379 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
380 if (!is_ok) {
381 error_setg_win32(errp, GetLastError(), "failed to write to file");
382 slog("guest-file-write-failed, handle: %" PRId64, handle);
383 } else {
384 write_data = g_new0(GuestFileWrite, 1);
385 write_data->count = (size_t) write_count;
388 done:
389 g_free(buf);
390 return write_data;
393 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
394 GuestFileWhence *whence_code,
395 Error **errp)
397 GuestFileHandle *gfh;
398 GuestFileSeek *seek_data;
399 HANDLE fh;
400 LARGE_INTEGER new_pos, off_pos;
401 off_pos.QuadPart = offset;
402 BOOL res;
403 int whence;
404 Error *err = NULL;
406 gfh = guest_file_handle_find(handle, errp);
407 if (!gfh) {
408 return NULL;
411 /* We stupidly exposed 'whence':'int' in our qapi */
412 whence = ga_parse_whence(whence_code, &err);
413 if (err) {
414 error_propagate(errp, err);
415 return NULL;
418 fh = gfh->fh;
419 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
420 if (!res) {
421 error_setg_win32(errp, GetLastError(), "failed to seek file");
422 return NULL;
424 seek_data = g_new0(GuestFileSeek, 1);
425 seek_data->position = new_pos.QuadPart;
426 return seek_data;
429 void qmp_guest_file_flush(int64_t handle, Error **errp)
431 HANDLE fh;
432 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
433 if (!gfh) {
434 return;
437 fh = gfh->fh;
438 if (!FlushFileBuffers(fh)) {
439 error_setg_win32(errp, GetLastError(), "failed to flush file");
443 #ifdef CONFIG_QGA_NTDDSCSI
445 static GuestDiskBusType win2qemu[] = {
446 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
447 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
448 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
449 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
450 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
451 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
452 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
453 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
454 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
455 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
456 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
457 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
458 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
459 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
460 #if (_WIN32_WINNT >= 0x0601)
461 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
462 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
463 #endif
466 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
468 if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
469 return GUEST_DISK_BUS_TYPE_UNKNOWN;
471 return win2qemu[(int)bus];
474 DEFINE_GUID(GUID_DEVINTERFACE_DISK,
475 0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2,
476 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
477 DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT,
478 0x2accfe60L, 0xc130, 0x11d2, 0xb0, 0x82,
479 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
481 static GuestPCIAddress *get_pci_info(int number, Error **errp)
483 HDEVINFO dev_info;
484 SP_DEVINFO_DATA dev_info_data;
485 SP_DEVICE_INTERFACE_DATA dev_iface_data;
486 HANDLE dev_file;
487 int i;
488 GuestPCIAddress *pci = NULL;
489 bool partial_pci = false;
491 pci = g_malloc0(sizeof(*pci));
492 pci->domain = -1;
493 pci->slot = -1;
494 pci->function = -1;
495 pci->bus = -1;
497 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
498 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
499 if (dev_info == INVALID_HANDLE_VALUE) {
500 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
501 goto out;
504 g_debug("enumerating devices");
505 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
506 dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
507 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
508 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
509 STORAGE_DEVICE_NUMBER sdn;
510 char *parent_dev_id = NULL;
511 HDEVINFO parent_dev_info;
512 SP_DEVINFO_DATA parent_dev_info_data;
513 DWORD j;
514 DWORD size = 0;
516 g_debug("getting device path");
517 if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
518 &GUID_DEVINTERFACE_DISK, 0,
519 &dev_iface_data)) {
520 while (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
521 pdev_iface_detail_data,
522 size, &size,
523 &dev_info_data)) {
524 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
525 pdev_iface_detail_data = g_malloc(size);
526 pdev_iface_detail_data->cbSize =
527 sizeof(*pdev_iface_detail_data);
528 } else {
529 error_setg_win32(errp, GetLastError(),
530 "failed to get device interfaces");
531 goto free_dev_info;
535 dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
536 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
537 NULL);
538 g_free(pdev_iface_detail_data);
540 if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
541 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
542 CloseHandle(dev_file);
543 error_setg_win32(errp, GetLastError(),
544 "failed to get device slot number");
545 goto free_dev_info;
548 CloseHandle(dev_file);
549 if (sdn.DeviceNumber != number) {
550 continue;
552 } else {
553 error_setg_win32(errp, GetLastError(),
554 "failed to get device interfaces");
555 goto free_dev_info;
558 g_debug("found device slot %d. Getting storage controller", number);
560 CONFIGRET cr;
561 DEVINST dev_inst, parent_dev_inst;
562 ULONG dev_id_size = 0;
564 size = 0;
565 while (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
566 parent_dev_id, size, &size)) {
567 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
568 parent_dev_id = g_malloc(size);
569 } else {
570 error_setg_win32(errp, GetLastError(),
571 "failed to get device instance ID");
572 goto out;
577 * CM API used here as opposed to
578 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
579 * which exports are only available in mingw-w64 6+
581 cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
582 if (cr != CR_SUCCESS) {
583 g_error("CM_Locate_DevInst failed with code %lx", cr);
584 error_setg_win32(errp, GetLastError(),
585 "failed to get device instance");
586 goto out;
588 cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
589 if (cr != CR_SUCCESS) {
590 g_error("CM_Get_Parent failed with code %lx", cr);
591 error_setg_win32(errp, GetLastError(),
592 "failed to get parent device instance");
593 goto out;
596 cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
597 if (cr != CR_SUCCESS) {
598 g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
599 error_setg_win32(errp, GetLastError(),
600 "failed to get parent device ID length");
601 goto out;
604 ++dev_id_size;
605 if (dev_id_size > size) {
606 g_free(parent_dev_id);
607 parent_dev_id = g_malloc(dev_id_size);
610 cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
612 if (cr != CR_SUCCESS) {
613 g_error("CM_Get_Device_ID failed with code %lx", cr);
614 error_setg_win32(errp, GetLastError(),
615 "failed to get parent device ID");
616 goto out;
620 g_debug("querying storage controller %s for PCI information",
621 parent_dev_id);
622 parent_dev_info =
623 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
624 NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
625 g_free(parent_dev_id);
627 if (parent_dev_info == INVALID_HANDLE_VALUE) {
628 error_setg_win32(errp, GetLastError(),
629 "failed to get parent device");
630 goto out;
633 parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
634 if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
635 error_setg_win32(errp, GetLastError(),
636 "failed to get parent device data");
637 goto out;
640 for (j = 0;
641 SetupDiEnumDeviceInfo(parent_dev_info, j, &parent_dev_info_data);
642 j++) {
643 DWORD addr, bus, ui_slot, type;
644 int func, slot;
647 * There is no need to allocate buffer in the next functions. The
648 * size is known and ULONG according to
649 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
651 if (!SetupDiGetDeviceRegistryProperty(
652 parent_dev_info, &parent_dev_info_data, SPDRP_BUSNUMBER,
653 &type, (PBYTE)&bus, size, NULL)) {
654 debug_error("failed to get PCI bus");
655 bus = -1;
656 partial_pci = true;
660 * The function retrieves the device's address. This value will be
661 * transformed into device function and number
663 if (!SetupDiGetDeviceRegistryProperty(
664 parent_dev_info, &parent_dev_info_data, SPDRP_ADDRESS,
665 &type, (PBYTE)&addr, size, NULL)) {
666 debug_error("failed to get PCI address");
667 addr = -1;
668 partial_pci = true;
672 * This call returns UINumber of DEVICE_CAPABILITIES structure.
673 * This number is typically a user-perceived slot number.
675 if (!SetupDiGetDeviceRegistryProperty(
676 parent_dev_info, &parent_dev_info_data, SPDRP_UI_NUMBER,
677 &type, (PBYTE)&ui_slot, size, NULL)) {
678 debug_error("failed to get PCI slot");
679 ui_slot = -1;
680 partial_pci = true;
684 * SetupApi gives us the same information as driver with
685 * IoGetDeviceProperty. According to Microsoft:
687 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
688 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
689 * SPDRP_ADDRESS is propertyAddress, so we do the same.
691 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
693 if (partial_pci) {
694 pci->domain = -1;
695 pci->slot = -1;
696 pci->function = -1;
697 pci->bus = -1;
698 continue;
699 } else {
700 func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
701 slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
702 if ((int)ui_slot != slot) {
703 g_debug("mismatch with reported slot values: %d vs %d",
704 (int)ui_slot, slot);
706 pci->domain = 0;
707 pci->slot = (int)ui_slot;
708 pci->function = func;
709 pci->bus = (int)bus;
710 break;
713 SetupDiDestroyDeviceInfoList(parent_dev_info);
714 break;
717 free_dev_info:
718 SetupDiDestroyDeviceInfoList(dev_info);
719 out:
720 return pci;
723 static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
724 Error **errp)
726 STORAGE_PROPERTY_QUERY query;
727 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
728 DWORD received;
729 ULONG size = sizeof(buf);
731 dev_desc = &buf;
732 query.PropertyId = StorageDeviceProperty;
733 query.QueryType = PropertyStandardQuery;
735 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
736 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
737 size, &received, NULL)) {
738 error_setg_win32(errp, GetLastError(), "failed to get bus type");
739 return;
741 disk->bus_type = find_bus_type(dev_desc->BusType);
742 g_debug("bus type %d", disk->bus_type);
744 /* Query once more. Now with long enough buffer. */
745 size = dev_desc->Size;
746 dev_desc = g_malloc0(size);
747 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
748 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
749 size, &received, NULL)) {
750 error_setg_win32(errp, GetLastError(), "failed to get serial number");
751 g_debug("failed to get serial number");
752 goto out_free;
754 if (dev_desc->SerialNumberOffset > 0) {
755 const char *serial;
756 size_t len;
758 if (dev_desc->SerialNumberOffset >= received) {
759 error_setg(errp, "failed to get serial number: offset outside the buffer");
760 g_debug("serial number offset outside the buffer");
761 goto out_free;
763 serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
764 len = received - dev_desc->SerialNumberOffset;
765 g_debug("serial number \"%s\"", serial);
766 if (*serial != 0) {
767 disk->serial = g_strndup(serial, len);
768 disk->has_serial = true;
771 out_free:
772 g_free(dev_desc);
774 return;
777 static void get_single_disk_info(int disk_number,
778 GuestDiskAddress *disk, Error **errp)
780 SCSI_ADDRESS addr, *scsi_ad;
781 DWORD len;
782 HANDLE disk_h;
783 Error *local_err = NULL;
785 scsi_ad = &addr;
787 g_debug("getting disk info for: %s", disk->dev);
788 disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
789 0, NULL);
790 if (disk_h == INVALID_HANDLE_VALUE) {
791 error_setg_win32(errp, GetLastError(), "failed to open disk");
792 return;
795 get_disk_properties(disk_h, disk, &local_err);
796 if (local_err) {
797 error_propagate(errp, local_err);
798 goto err_close;
801 g_debug("bus type %d", disk->bus_type);
802 /* always set pci_controller as required by schema. get_pci_info() should
803 * report -1 values for non-PCI buses rather than fail. fail the command
804 * if that doesn't hold since that suggests some other unexpected
805 * breakage
807 disk->pci_controller = get_pci_info(disk_number, &local_err);
808 if (local_err) {
809 error_propagate(errp, local_err);
810 goto err_close;
812 if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
813 || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
814 || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
815 /* This bus type is not supported before Windows Server 2003 SP1 */
816 || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
818 /* We are able to use the same ioctls for different bus types
819 * according to Microsoft docs
820 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
821 g_debug("getting SCSI info");
822 if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
823 sizeof(SCSI_ADDRESS), &len, NULL)) {
824 disk->unit = addr.Lun;
825 disk->target = addr.TargetId;
826 disk->bus = addr.PathId;
828 /* We do not set error in this case, because we still have enough
829 * information about volume. */
832 err_close:
833 CloseHandle(disk_h);
834 return;
837 /* VSS provider works with volumes, thus there is no difference if
838 * the volume consist of spanned disks. Info about the first disk in the
839 * volume is returned for the spanned disk group (LVM) */
840 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
842 Error *local_err = NULL;
843 GuestDiskAddressList *list = NULL, *cur_item = NULL;
844 GuestDiskAddress *disk = NULL;
845 int i;
846 HANDLE vol_h;
847 DWORD size;
848 PVOLUME_DISK_EXTENTS extents = NULL;
850 /* strip final backslash */
851 char *name = g_strdup(guid);
852 if (g_str_has_suffix(name, "\\")) {
853 name[strlen(name) - 1] = 0;
856 g_debug("opening %s", name);
857 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
858 0, NULL);
859 if (vol_h == INVALID_HANDLE_VALUE) {
860 error_setg_win32(errp, GetLastError(), "failed to open volume");
861 goto out;
864 /* Get list of extents */
865 g_debug("getting disk extents");
866 size = sizeof(VOLUME_DISK_EXTENTS);
867 extents = g_malloc0(size);
868 if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
869 0, extents, size, &size, NULL)) {
870 DWORD last_err = GetLastError();
871 if (last_err == ERROR_MORE_DATA) {
872 /* Try once more with big enough buffer */
873 g_free(extents);
874 extents = g_malloc0(size);
875 if (!DeviceIoControl(
876 vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
877 0, extents, size, NULL, NULL)) {
878 error_setg_win32(errp, GetLastError(),
879 "failed to get disk extents");
880 goto out;
882 } else if (last_err == ERROR_INVALID_FUNCTION) {
883 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
884 g_debug("volume not on disk");
885 disk = g_malloc0(sizeof(GuestDiskAddress));
886 disk->has_dev = true;
887 disk->dev = g_strdup(name);
888 get_single_disk_info(0xffffffff, disk, &local_err);
889 if (local_err) {
890 g_debug("failed to get disk info, ignoring error: %s",
891 error_get_pretty(local_err));
892 error_free(local_err);
893 goto out;
895 list = g_malloc0(sizeof(*list));
896 list->value = disk;
897 disk = NULL;
898 list->next = NULL;
899 goto out;
900 } else {
901 error_setg_win32(errp, GetLastError(),
902 "failed to get disk extents");
903 goto out;
906 g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
908 /* Go through each extent */
909 for (i = 0; i < extents->NumberOfDiskExtents; i++) {
910 disk = g_malloc0(sizeof(GuestDiskAddress));
912 /* Disk numbers directly correspond to numbers used in UNCs
914 * See documentation for DISK_EXTENT:
915 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
917 * See also Naming Files, Paths and Namespaces:
918 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
920 disk->has_dev = true;
921 disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
922 extents->Extents[i].DiskNumber);
924 get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
925 if (local_err) {
926 error_propagate(errp, local_err);
927 goto out;
929 cur_item = g_malloc0(sizeof(*list));
930 cur_item->value = disk;
931 disk = NULL;
932 cur_item->next = list;
933 list = cur_item;
937 out:
938 if (vol_h != INVALID_HANDLE_VALUE) {
939 CloseHandle(vol_h);
941 qapi_free_GuestDiskAddress(disk);
942 g_free(extents);
943 g_free(name);
945 return list;
948 #else
950 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
952 return NULL;
955 #endif /* CONFIG_QGA_NTDDSCSI */
957 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
959 DWORD info_size;
960 char mnt, *mnt_point;
961 wchar_t wfs_name[32];
962 char fs_name[32];
963 wchar_t vol_info[MAX_PATH + 1];
964 size_t len;
965 uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
966 GuestFilesystemInfo *fs = NULL;
967 HANDLE hLocalDiskHandle = NULL;
969 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
970 if (GetLastError() != ERROR_MORE_DATA) {
971 error_setg_win32(errp, GetLastError(), "failed to get volume name");
972 return NULL;
975 mnt_point = g_malloc(info_size + 1);
976 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
977 &info_size)) {
978 error_setg_win32(errp, GetLastError(), "failed to get volume name");
979 goto free;
982 hLocalDiskHandle = CreateFile(guid, 0 , 0, NULL, OPEN_EXISTING,
983 FILE_ATTRIBUTE_NORMAL |
984 FILE_FLAG_BACKUP_SEMANTICS, NULL);
985 if (INVALID_HANDLE_VALUE == hLocalDiskHandle) {
986 error_setg_win32(errp, GetLastError(), "failed to get handle for volume");
987 goto free;
990 len = strlen(mnt_point);
991 mnt_point[len] = '\\';
992 mnt_point[len+1] = 0;
994 if (!GetVolumeInformationByHandleW(hLocalDiskHandle, vol_info,
995 sizeof(vol_info), NULL, NULL, NULL,
996 (LPWSTR) & wfs_name, sizeof(wfs_name))) {
997 if (GetLastError() != ERROR_NOT_READY) {
998 error_setg_win32(errp, GetLastError(), "failed to get volume info");
1000 goto free;
1003 fs = g_malloc(sizeof(*fs));
1004 fs->name = g_strdup(guid);
1005 fs->has_total_bytes = false;
1006 fs->has_used_bytes = false;
1007 if (len == 0) {
1008 fs->mountpoint = g_strdup("System Reserved");
1009 } else {
1010 fs->mountpoint = g_strndup(mnt_point, len);
1011 if (GetDiskFreeSpaceEx(fs->mountpoint,
1012 (PULARGE_INTEGER) & i64FreeBytesToCaller,
1013 (PULARGE_INTEGER) & i64TotalBytes,
1014 (PULARGE_INTEGER) & i64FreeBytes)) {
1015 fs->used_bytes = i64TotalBytes - i64FreeBytes;
1016 fs->total_bytes = i64TotalBytes;
1017 fs->has_total_bytes = true;
1018 fs->has_used_bytes = true;
1021 wcstombs(fs_name, wfs_name, sizeof(wfs_name));
1022 fs->type = g_strdup(fs_name);
1023 fs->disk = build_guest_disk_info(guid, errp);
1024 free:
1025 CloseHandle(hLocalDiskHandle);
1026 g_free(mnt_point);
1027 return fs;
1030 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1032 HANDLE vol_h;
1033 GuestFilesystemInfoList *new, *ret = NULL;
1034 char guid[256];
1036 vol_h = FindFirstVolume(guid, sizeof(guid));
1037 if (vol_h == INVALID_HANDLE_VALUE) {
1038 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1039 return NULL;
1042 do {
1043 Error *local_err = NULL;
1044 GuestFilesystemInfo *info = build_guest_fsinfo(guid, &local_err);
1045 if (local_err) {
1046 g_debug("failed to get filesystem info, ignoring error: %s",
1047 error_get_pretty(local_err));
1048 error_free(local_err);
1049 continue;
1051 new = g_malloc(sizeof(*ret));
1052 new->value = info;
1053 new->next = ret;
1054 ret = new;
1055 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
1057 if (GetLastError() != ERROR_NO_MORE_FILES) {
1058 error_setg_win32(errp, GetLastError(), "failed to find next volume");
1061 FindVolumeClose(vol_h);
1062 return ret;
1066 * Return status of freeze/thaw
1068 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1070 if (!vss_initialized()) {
1071 error_setg(errp, QERR_UNSUPPORTED);
1072 return 0;
1075 if (ga_is_frozen(ga_state)) {
1076 return GUEST_FSFREEZE_STATUS_FROZEN;
1079 return GUEST_FSFREEZE_STATUS_THAWED;
1083 * Freeze local file systems using Volume Shadow-copy Service.
1084 * The frozen state is limited for up to 10 seconds by VSS.
1086 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1088 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1091 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1092 strList *mountpoints,
1093 Error **errp)
1095 int i;
1096 Error *local_err = NULL;
1098 if (!vss_initialized()) {
1099 error_setg(errp, QERR_UNSUPPORTED);
1100 return 0;
1103 slog("guest-fsfreeze called");
1105 /* cannot risk guest agent blocking itself on a write in this state */
1106 ga_set_frozen(ga_state);
1108 qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
1109 if (local_err) {
1110 error_propagate(errp, local_err);
1111 goto error;
1114 return i;
1116 error:
1117 local_err = NULL;
1118 qmp_guest_fsfreeze_thaw(&local_err);
1119 if (local_err) {
1120 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
1121 error_free(local_err);
1123 return 0;
1127 * Thaw local file systems using Volume Shadow-copy Service.
1129 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1131 int i;
1133 if (!vss_initialized()) {
1134 error_setg(errp, QERR_UNSUPPORTED);
1135 return 0;
1138 qga_vss_fsfreeze(&i, false, NULL, errp);
1140 ga_unset_frozen(ga_state);
1141 return i;
1144 static void guest_fsfreeze_cleanup(void)
1146 Error *err = NULL;
1148 if (!vss_initialized()) {
1149 return;
1152 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1153 qmp_guest_fsfreeze_thaw(&err);
1154 if (err) {
1155 slog("failed to clean up frozen filesystems: %s",
1156 error_get_pretty(err));
1157 error_free(err);
1161 vss_deinit(true);
1165 * Walk list of mounted file systems in the guest, and discard unused
1166 * areas.
1168 GuestFilesystemTrimResponse *
1169 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1171 GuestFilesystemTrimResponse *resp;
1172 HANDLE handle;
1173 WCHAR guid[MAX_PATH] = L"";
1174 OSVERSIONINFO osvi;
1175 BOOL win8_or_later;
1177 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
1178 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1179 GetVersionEx(&osvi);
1180 win8_or_later = (osvi.dwMajorVersion > 6 ||
1181 ((osvi.dwMajorVersion == 6) &&
1182 (osvi.dwMinorVersion >= 2)));
1183 if (!win8_or_later) {
1184 error_setg(errp, "fstrim is only supported for Win8+");
1185 return NULL;
1188 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
1189 if (handle == INVALID_HANDLE_VALUE) {
1190 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1191 return NULL;
1194 resp = g_new0(GuestFilesystemTrimResponse, 1);
1196 do {
1197 GuestFilesystemTrimResult *res;
1198 GuestFilesystemTrimResultList *list;
1199 PWCHAR uc_path;
1200 DWORD char_count = 0;
1201 char *path, *out;
1202 GError *gerr = NULL;
1203 gchar * argv[4];
1205 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1207 if (GetLastError() != ERROR_MORE_DATA) {
1208 continue;
1210 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1211 continue;
1214 uc_path = g_malloc(sizeof(WCHAR) * char_count);
1215 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1216 &char_count) || !*uc_path) {
1217 /* strange, but this condition could be faced even with size == 2 */
1218 g_free(uc_path);
1219 continue;
1222 res = g_new0(GuestFilesystemTrimResult, 1);
1224 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1226 g_free(uc_path);
1228 if (!path) {
1229 res->has_error = true;
1230 res->error = g_strdup(gerr->message);
1231 g_error_free(gerr);
1232 break;
1235 res->path = path;
1237 list = g_new0(GuestFilesystemTrimResultList, 1);
1238 list->value = res;
1239 list->next = resp->paths;
1241 resp->paths = list;
1243 memset(argv, 0, sizeof(argv));
1244 argv[0] = (gchar *)"defrag.exe";
1245 argv[1] = (gchar *)"/L";
1246 argv[2] = path;
1248 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1249 &out /* stdout */, NULL /* stdin */,
1250 NULL, &gerr)) {
1251 res->has_error = true;
1252 res->error = g_strdup(gerr->message);
1253 g_error_free(gerr);
1254 } else {
1255 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1256 Error is reported in the output with something like
1257 (x89000020) etc code in the stdout */
1259 int i;
1260 gchar **lines = g_strsplit(out, "\r\n", 0);
1261 g_free(out);
1263 for (i = 0; lines[i] != NULL; i++) {
1264 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1265 continue;
1267 res->has_error = true;
1268 res->error = g_strdup(lines[i]);
1269 break;
1271 g_strfreev(lines);
1273 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1275 FindVolumeClose(handle);
1276 return resp;
1279 typedef enum {
1280 GUEST_SUSPEND_MODE_DISK,
1281 GUEST_SUSPEND_MODE_RAM
1282 } GuestSuspendMode;
1284 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
1286 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1288 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1289 if (!GetPwrCapabilities(&sys_pwr_caps)) {
1290 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1291 "failed to determine guest suspend capabilities");
1292 return;
1295 switch (mode) {
1296 case GUEST_SUSPEND_MODE_DISK:
1297 if (!sys_pwr_caps.SystemS4) {
1298 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1299 "suspend-to-disk not supported by OS");
1301 break;
1302 case GUEST_SUSPEND_MODE_RAM:
1303 if (!sys_pwr_caps.SystemS3) {
1304 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1305 "suspend-to-ram not supported by OS");
1307 break;
1308 default:
1309 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
1310 "GuestSuspendMode");
1314 static DWORD WINAPI do_suspend(LPVOID opaque)
1316 GuestSuspendMode *mode = opaque;
1317 DWORD ret = 0;
1319 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1320 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
1321 slog("failed to suspend guest: %s", emsg);
1322 ret = -1;
1324 g_free(mode);
1325 return ret;
1328 void qmp_guest_suspend_disk(Error **errp)
1330 Error *local_err = NULL;
1331 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1333 *mode = GUEST_SUSPEND_MODE_DISK;
1334 check_suspend_mode(*mode, &local_err);
1335 if (local_err) {
1336 goto out;
1338 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1339 if (local_err) {
1340 goto out;
1342 execute_async(do_suspend, mode, &local_err);
1344 out:
1345 if (local_err) {
1346 error_propagate(errp, local_err);
1347 g_free(mode);
1351 void qmp_guest_suspend_ram(Error **errp)
1353 Error *local_err = NULL;
1354 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1356 *mode = GUEST_SUSPEND_MODE_RAM;
1357 check_suspend_mode(*mode, &local_err);
1358 if (local_err) {
1359 goto out;
1361 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1362 if (local_err) {
1363 goto out;
1365 execute_async(do_suspend, mode, &local_err);
1367 out:
1368 if (local_err) {
1369 error_propagate(errp, local_err);
1370 g_free(mode);
1374 void qmp_guest_suspend_hybrid(Error **errp)
1376 error_setg(errp, QERR_UNSUPPORTED);
1379 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1381 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1382 ULONG adptr_addrs_len = 0;
1383 DWORD ret;
1385 /* Call the first time to get the adptr_addrs_len. */
1386 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1387 NULL, adptr_addrs, &adptr_addrs_len);
1389 adptr_addrs = g_malloc(adptr_addrs_len);
1390 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1391 NULL, adptr_addrs, &adptr_addrs_len);
1392 if (ret != ERROR_SUCCESS) {
1393 error_setg_win32(errp, ret, "failed to get adapters addresses");
1394 g_free(adptr_addrs);
1395 adptr_addrs = NULL;
1397 return adptr_addrs;
1400 static char *guest_wctomb_dup(WCHAR *wstr)
1402 char *str;
1403 size_t str_size;
1405 str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
1406 /* add 1 to str_size for NULL terminator */
1407 str = g_malloc(str_size + 1);
1408 WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
1409 return str;
1412 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1413 Error **errp)
1415 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1416 DWORD len;
1417 int ret;
1419 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1420 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1421 len = sizeof(addr_str);
1422 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1423 ip_addr->Address.iSockaddrLength,
1424 NULL,
1425 addr_str,
1426 &len);
1427 if (ret != 0) {
1428 error_setg_win32(errp, WSAGetLastError(),
1429 "failed address presentation form conversion");
1430 return NULL;
1432 return g_strdup(addr_str);
1434 return NULL;
1437 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1439 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1440 * field to obtain the prefix.
1442 return ip_addr->OnLinkPrefixLength;
1445 #define INTERFACE_PATH_BUF_SZ 512
1447 static DWORD get_interface_index(const char *guid)
1449 ULONG index;
1450 DWORD status;
1451 wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1452 snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1453 wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1454 status = GetAdapterIndex (wbuf, &index);
1455 if (status != NO_ERROR) {
1456 return (DWORD)~0;
1457 } else {
1458 return index;
1462 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1464 static int guest_get_network_stats(const char *name,
1465 GuestNetworkInterfaceStat *stats)
1467 OSVERSIONINFO os_ver;
1469 os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1470 GetVersionEx(&os_ver);
1471 if (os_ver.dwMajorVersion >= 6) {
1472 MIB_IF_ROW2 a_mid_ifrow;
1473 GetIfEntry2Func getifentry2_ex;
1474 DWORD if_index = 0;
1475 HMODULE module = GetModuleHandle("iphlpapi");
1476 PVOID func = GetProcAddress(module, "GetIfEntry2");
1478 if (func == NULL) {
1479 return -1;
1482 getifentry2_ex = (GetIfEntry2Func)func;
1483 if_index = get_interface_index(name);
1484 if (if_index == (DWORD)~0) {
1485 return -1;
1488 memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1489 a_mid_ifrow.InterfaceIndex = if_index;
1490 if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1491 stats->rx_bytes = a_mid_ifrow.InOctets;
1492 stats->rx_packets = a_mid_ifrow.InUcastPkts;
1493 stats->rx_errs = a_mid_ifrow.InErrors;
1494 stats->rx_dropped = a_mid_ifrow.InDiscards;
1495 stats->tx_bytes = a_mid_ifrow.OutOctets;
1496 stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1497 stats->tx_errs = a_mid_ifrow.OutErrors;
1498 stats->tx_dropped = a_mid_ifrow.OutDiscards;
1499 return 0;
1502 return -1;
1505 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1507 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1508 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1509 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1510 GuestIpAddressList *head_addr, *cur_addr;
1511 GuestNetworkInterfaceList *info;
1512 GuestNetworkInterfaceStat *interface_stat = NULL;
1513 GuestIpAddressList *address_item = NULL;
1514 unsigned char *mac_addr;
1515 char *addr_str;
1516 WORD wsa_version;
1517 WSADATA wsa_data;
1518 int ret;
1520 adptr_addrs = guest_get_adapters_addresses(errp);
1521 if (adptr_addrs == NULL) {
1522 return NULL;
1525 /* Make WSA APIs available. */
1526 wsa_version = MAKEWORD(2, 2);
1527 ret = WSAStartup(wsa_version, &wsa_data);
1528 if (ret != 0) {
1529 error_setg_win32(errp, ret, "failed socket startup");
1530 goto out;
1533 for (addr = adptr_addrs; addr; addr = addr->Next) {
1534 info = g_malloc0(sizeof(*info));
1536 if (cur_item == NULL) {
1537 head = cur_item = info;
1538 } else {
1539 cur_item->next = info;
1540 cur_item = info;
1543 info->value = g_malloc0(sizeof(*info->value));
1544 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1546 if (addr->PhysicalAddressLength != 0) {
1547 mac_addr = addr->PhysicalAddress;
1549 info->value->hardware_address =
1550 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1551 (int) mac_addr[0], (int) mac_addr[1],
1552 (int) mac_addr[2], (int) mac_addr[3],
1553 (int) mac_addr[4], (int) mac_addr[5]);
1555 info->value->has_hardware_address = true;
1558 head_addr = NULL;
1559 cur_addr = NULL;
1560 for (ip_addr = addr->FirstUnicastAddress;
1561 ip_addr;
1562 ip_addr = ip_addr->Next) {
1563 addr_str = guest_addr_to_str(ip_addr, errp);
1564 if (addr_str == NULL) {
1565 continue;
1568 address_item = g_malloc0(sizeof(*address_item));
1570 if (!cur_addr) {
1571 head_addr = cur_addr = address_item;
1572 } else {
1573 cur_addr->next = address_item;
1574 cur_addr = address_item;
1577 address_item->value = g_malloc0(sizeof(*address_item->value));
1578 address_item->value->ip_address = addr_str;
1579 address_item->value->prefix = guest_ip_prefix(ip_addr);
1580 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1581 address_item->value->ip_address_type =
1582 GUEST_IP_ADDRESS_TYPE_IPV4;
1583 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1584 address_item->value->ip_address_type =
1585 GUEST_IP_ADDRESS_TYPE_IPV6;
1588 if (head_addr) {
1589 info->value->has_ip_addresses = true;
1590 info->value->ip_addresses = head_addr;
1592 if (!info->value->has_statistics) {
1593 interface_stat = g_malloc0(sizeof(*interface_stat));
1594 if (guest_get_network_stats(addr->AdapterName,
1595 interface_stat) == -1) {
1596 info->value->has_statistics = false;
1597 g_free(interface_stat);
1598 } else {
1599 info->value->statistics = interface_stat;
1600 info->value->has_statistics = true;
1604 WSACleanup();
1605 out:
1606 g_free(adptr_addrs);
1607 return head;
1610 int64_t qmp_guest_get_time(Error **errp)
1612 SYSTEMTIME ts = {0};
1613 FILETIME tf;
1615 GetSystemTime(&ts);
1616 if (ts.wYear < 1601 || ts.wYear > 30827) {
1617 error_setg(errp, "Failed to get time");
1618 return -1;
1621 if (!SystemTimeToFileTime(&ts, &tf)) {
1622 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1623 return -1;
1626 return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1627 - W32_FT_OFFSET) * 100;
1630 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1632 Error *local_err = NULL;
1633 SYSTEMTIME ts;
1634 FILETIME tf;
1635 LONGLONG time;
1637 if (!has_time) {
1638 /* Unfortunately, Windows libraries don't provide an easy way to access
1639 * RTC yet:
1641 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1643 * Instead, a workaround is to use the Windows win32tm command to
1644 * resync the time using the Windows Time service.
1646 LPVOID msg_buffer;
1647 DWORD ret_flags;
1649 HRESULT hr = system("w32tm /resync /nowait");
1651 if (GetLastError() != 0) {
1652 strerror_s((LPTSTR) & msg_buffer, 0, errno);
1653 error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1654 } else if (hr != 0) {
1655 if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1656 error_setg(errp, "Windows Time service not running on the "
1657 "guest");
1658 } else {
1659 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1660 FORMAT_MESSAGE_FROM_SYSTEM |
1661 FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1662 (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1663 SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1664 NULL)) {
1665 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1666 "t retrieve error message", hr);
1667 } else {
1668 error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1669 (LPCTSTR)msg_buffer);
1670 LocalFree(msg_buffer);
1673 } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1674 error_setg(errp, "No internet connection on guest, sync not "
1675 "accurate");
1677 return;
1680 /* Validate time passed by user. */
1681 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1682 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1683 return;
1686 time = time_ns / 100 + W32_FT_OFFSET;
1688 tf.dwLowDateTime = (DWORD) time;
1689 tf.dwHighDateTime = (DWORD) (time >> 32);
1691 if (!FileTimeToSystemTime(&tf, &ts)) {
1692 error_setg(errp, "Failed to convert system time %d",
1693 (int)GetLastError());
1694 return;
1697 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1698 if (local_err) {
1699 error_propagate(errp, local_err);
1700 return;
1703 if (!SetSystemTime(&ts)) {
1704 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1705 return;
1709 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1711 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1712 DWORD length;
1713 GuestLogicalProcessorList *head, **link;
1714 Error *local_err = NULL;
1715 int64_t current;
1717 ptr = pslpi = NULL;
1718 length = 0;
1719 current = 0;
1720 head = NULL;
1721 link = &head;
1723 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1724 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1725 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1726 ptr = pslpi = g_malloc0(length);
1727 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1728 error_setg(&local_err, "Failed to get processor information: %d",
1729 (int)GetLastError());
1731 } else {
1732 error_setg(&local_err,
1733 "Failed to get processor information buffer length: %d",
1734 (int)GetLastError());
1737 while ((local_err == NULL) && (length > 0)) {
1738 if (pslpi->Relationship == RelationProcessorCore) {
1739 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1741 while (cpu_bits > 0) {
1742 if (!!(cpu_bits & 1)) {
1743 GuestLogicalProcessor *vcpu;
1744 GuestLogicalProcessorList *entry;
1746 vcpu = g_malloc0(sizeof *vcpu);
1747 vcpu->logical_id = current++;
1748 vcpu->online = true;
1749 vcpu->has_can_offline = true;
1751 entry = g_malloc0(sizeof *entry);
1752 entry->value = vcpu;
1754 *link = entry;
1755 link = &entry->next;
1757 cpu_bits >>= 1;
1760 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1761 pslpi++; /* next entry */
1764 g_free(ptr);
1766 if (local_err == NULL) {
1767 if (head != NULL) {
1768 return head;
1770 /* there's no guest with zero VCPUs */
1771 error_setg(&local_err, "Guest reported zero VCPUs");
1774 qapi_free_GuestLogicalProcessorList(head);
1775 error_propagate(errp, local_err);
1776 return NULL;
1779 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1781 error_setg(errp, QERR_UNSUPPORTED);
1782 return -1;
1785 static gchar *
1786 get_net_error_message(gint error)
1788 HMODULE module = NULL;
1789 gchar *retval = NULL;
1790 wchar_t *msg = NULL;
1791 int flags;
1792 size_t nchars;
1794 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1795 FORMAT_MESSAGE_IGNORE_INSERTS |
1796 FORMAT_MESSAGE_FROM_SYSTEM;
1798 if (error >= NERR_BASE && error <= MAX_NERR) {
1799 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1801 if (module != NULL) {
1802 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1806 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1808 if (msg != NULL) {
1809 nchars = wcslen(msg);
1811 if (nchars >= 2 &&
1812 msg[nchars - 1] == L'\n' &&
1813 msg[nchars - 2] == L'\r') {
1814 msg[nchars - 2] = L'\0';
1817 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1819 LocalFree(msg);
1822 if (module != NULL) {
1823 FreeLibrary(module);
1826 return retval;
1829 void qmp_guest_set_user_password(const char *username,
1830 const char *password,
1831 bool crypted,
1832 Error **errp)
1834 NET_API_STATUS nas;
1835 char *rawpasswddata = NULL;
1836 size_t rawpasswdlen;
1837 wchar_t *user = NULL, *wpass = NULL;
1838 USER_INFO_1003 pi1003 = { 0, };
1839 GError *gerr = NULL;
1841 if (crypted) {
1842 error_setg(errp, QERR_UNSUPPORTED);
1843 return;
1846 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1847 if (!rawpasswddata) {
1848 return;
1850 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1851 rawpasswddata[rawpasswdlen] = '\0';
1853 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1854 if (!user) {
1855 goto done;
1858 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1859 if (!wpass) {
1860 goto done;
1863 pi1003.usri1003_password = wpass;
1864 nas = NetUserSetInfo(NULL, user,
1865 1003, (LPBYTE)&pi1003,
1866 NULL);
1868 if (nas != NERR_Success) {
1869 gchar *msg = get_net_error_message(nas);
1870 error_setg(errp, "failed to set password: %s", msg);
1871 g_free(msg);
1874 done:
1875 if (gerr) {
1876 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1877 g_error_free(gerr);
1879 g_free(user);
1880 g_free(wpass);
1881 g_free(rawpasswddata);
1884 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1886 error_setg(errp, QERR_UNSUPPORTED);
1887 return NULL;
1890 GuestMemoryBlockResponseList *
1891 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1893 error_setg(errp, QERR_UNSUPPORTED);
1894 return NULL;
1897 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1899 error_setg(errp, QERR_UNSUPPORTED);
1900 return NULL;
1903 /* add unsupported commands to the blacklist */
1904 GList *ga_command_blacklist_init(GList *blacklist)
1906 const char *list_unsupported[] = {
1907 "guest-suspend-hybrid",
1908 "guest-set-vcpus",
1909 "guest-get-memory-blocks", "guest-set-memory-blocks",
1910 "guest-get-memory-block-size", "guest-get-memory-block-info",
1911 NULL};
1912 char **p = (char **)list_unsupported;
1914 while (*p) {
1915 blacklist = g_list_append(blacklist, g_strdup(*p++));
1918 if (!vss_init(true)) {
1919 g_debug("vss_init failed, vss commands are going to be disabled");
1920 const char *list[] = {
1921 "guest-get-fsinfo", "guest-fsfreeze-status",
1922 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1923 p = (char **)list;
1925 while (*p) {
1926 blacklist = g_list_append(blacklist, g_strdup(*p++));
1930 return blacklist;
1933 /* register init/cleanup routines for stateful command groups */
1934 void ga_command_state_init(GAState *s, GACommandState *cs)
1936 if (!vss_initialized()) {
1937 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1941 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1942 typedef struct _GA_WTSINFOA {
1943 WTS_CONNECTSTATE_CLASS State;
1944 DWORD SessionId;
1945 DWORD IncomingBytes;
1946 DWORD OutgoingBytes;
1947 DWORD IncomingFrames;
1948 DWORD OutgoingFrames;
1949 DWORD IncomingCompressedBytes;
1950 DWORD OutgoingCompressedBy;
1951 CHAR WinStationName[WINSTATIONNAME_LENGTH];
1952 CHAR Domain[DOMAIN_LENGTH];
1953 CHAR UserName[USERNAME_LENGTH + 1];
1954 LARGE_INTEGER ConnectTime;
1955 LARGE_INTEGER DisconnectTime;
1956 LARGE_INTEGER LastInputTime;
1957 LARGE_INTEGER LogonTime;
1958 LARGE_INTEGER CurrentTime;
1960 } GA_WTSINFOA;
1962 GuestUserList *qmp_guest_get_users(Error **errp)
1964 #define QGA_NANOSECONDS 10000000
1966 GHashTable *cache = NULL;
1967 GuestUserList *head = NULL, *cur_item = NULL;
1969 DWORD buffer_size = 0, count = 0, i = 0;
1970 GA_WTSINFOA *info = NULL;
1971 WTS_SESSION_INFOA *entries = NULL;
1972 GuestUserList *item = NULL;
1973 GuestUser *user = NULL;
1974 gpointer value = NULL;
1975 INT64 login = 0;
1976 double login_time = 0;
1978 cache = g_hash_table_new(g_str_hash, g_str_equal);
1980 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
1981 for (i = 0; i < count; ++i) {
1982 buffer_size = 0;
1983 info = NULL;
1984 if (WTSQuerySessionInformationA(
1985 NULL,
1986 entries[i].SessionId,
1987 WTSSessionInfo,
1988 (LPSTR *)&info,
1989 &buffer_size
1990 )) {
1992 if (strlen(info->UserName) == 0) {
1993 WTSFreeMemory(info);
1994 continue;
1997 login = info->LogonTime.QuadPart;
1998 login -= W32_FT_OFFSET;
1999 login_time = ((double)login) / QGA_NANOSECONDS;
2001 if (g_hash_table_contains(cache, info->UserName)) {
2002 value = g_hash_table_lookup(cache, info->UserName);
2003 user = (GuestUser *)value;
2004 if (user->login_time > login_time) {
2005 user->login_time = login_time;
2007 } else {
2008 item = g_new0(GuestUserList, 1);
2009 item->value = g_new0(GuestUser, 1);
2011 item->value->user = g_strdup(info->UserName);
2012 item->value->domain = g_strdup(info->Domain);
2013 item->value->has_domain = true;
2015 item->value->login_time = login_time;
2017 g_hash_table_add(cache, item->value->user);
2019 if (!cur_item) {
2020 head = cur_item = item;
2021 } else {
2022 cur_item->next = item;
2023 cur_item = item;
2027 WTSFreeMemory(info);
2029 WTSFreeMemory(entries);
2031 g_hash_table_destroy(cache);
2032 return head;
2035 typedef struct _ga_matrix_lookup_t {
2036 int major;
2037 int minor;
2038 char const *version;
2039 char const *version_id;
2040 } ga_matrix_lookup_t;
2042 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
2044 /* Desktop editions */
2045 { 5, 0, "Microsoft Windows 2000", "2000"},
2046 { 5, 1, "Microsoft Windows XP", "xp"},
2047 { 6, 0, "Microsoft Windows Vista", "vista"},
2048 { 6, 1, "Microsoft Windows 7" "7"},
2049 { 6, 2, "Microsoft Windows 8", "8"},
2050 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2051 {10, 0, "Microsoft Windows 10", "10"},
2052 { 0, 0, 0}
2054 /* Server editions */
2055 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2056 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2057 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2058 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2059 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2060 { 0, 0, 0},
2061 { 0, 0, 0},
2062 { 0, 0, 0}
2066 typedef struct _ga_win_10_0_server_t {
2067 int final_build;
2068 char const *version;
2069 char const *version_id;
2070 } ga_win_10_0_server_t;
2072 static ga_win_10_0_server_t const WIN_10_0_SERVER_VERSION_MATRIX[3] = {
2073 {14393, "Microsoft Windows Server 2016", "2016"},
2074 {17763, "Microsoft Windows Server 2019", "2019"},
2075 {0, 0}
2078 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2080 typedef NTSTATUS(WINAPI * rtl_get_version_t)(
2081 RTL_OSVERSIONINFOEXW *os_version_info_ex);
2083 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2085 HMODULE module = GetModuleHandle("ntdll");
2086 PVOID fun = GetProcAddress(module, "RtlGetVersion");
2087 if (fun == NULL) {
2088 error_setg(errp, QERR_QGA_COMMAND_FAILED,
2089 "Failed to get address of RtlGetVersion");
2090 return;
2093 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2094 rtl_get_version(info);
2095 return;
2098 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
2100 DWORD major = os_version->dwMajorVersion;
2101 DWORD minor = os_version->dwMinorVersion;
2102 DWORD build = os_version->dwBuildNumber;
2103 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2104 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
2105 ga_win_10_0_server_t const *win_10_0_table = WIN_10_0_SERVER_VERSION_MATRIX;
2106 while (table->version != NULL) {
2107 if (major == 10 && minor == 0 && tbl_idx) {
2108 while (win_10_0_table->version != NULL) {
2109 if (build <= win_10_0_table->final_build) {
2110 if (id) {
2111 return g_strdup(win_10_0_table->version_id);
2112 } else {
2113 return g_strdup(win_10_0_table->version);
2116 win_10_0_table++;
2118 } else if (major == table->major && minor == table->minor) {
2119 if (id) {
2120 return g_strdup(table->version_id);
2121 } else {
2122 return g_strdup(table->version);
2125 ++table;
2127 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2128 major, minor);
2129 return g_strdup("N/A");
2132 static char *ga_get_win_product_name(Error **errp)
2134 HKEY key = NULL;
2135 DWORD size = 128;
2136 char *result = g_malloc0(size);
2137 LONG err = ERROR_SUCCESS;
2139 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2140 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2141 &key);
2142 if (err != ERROR_SUCCESS) {
2143 error_setg_win32(errp, err, "failed to open registry key");
2144 goto fail;
2147 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2148 (LPBYTE)result, &size);
2149 if (err == ERROR_MORE_DATA) {
2150 slog("ProductName longer than expected (%lu bytes), retrying",
2151 size);
2152 g_free(result);
2153 result = NULL;
2154 if (size > 0) {
2155 result = g_malloc0(size);
2156 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2157 (LPBYTE)result, &size);
2160 if (err != ERROR_SUCCESS) {
2161 error_setg_win32(errp, err, "failed to retrive ProductName");
2162 goto fail;
2165 return result;
2167 fail:
2168 g_free(result);
2169 return NULL;
2172 static char *ga_get_current_arch(void)
2174 SYSTEM_INFO info;
2175 GetNativeSystemInfo(&info);
2176 char *result = NULL;
2177 switch (info.wProcessorArchitecture) {
2178 case PROCESSOR_ARCHITECTURE_AMD64:
2179 result = g_strdup("x86_64");
2180 break;
2181 case PROCESSOR_ARCHITECTURE_ARM:
2182 result = g_strdup("arm");
2183 break;
2184 case PROCESSOR_ARCHITECTURE_IA64:
2185 result = g_strdup("ia64");
2186 break;
2187 case PROCESSOR_ARCHITECTURE_INTEL:
2188 result = g_strdup("x86");
2189 break;
2190 case PROCESSOR_ARCHITECTURE_UNKNOWN:
2191 default:
2192 slog("unknown processor architecture 0x%0x",
2193 info.wProcessorArchitecture);
2194 result = g_strdup("unknown");
2195 break;
2197 return result;
2200 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2202 Error *local_err = NULL;
2203 OSVERSIONINFOEXW os_version = {0};
2204 bool server;
2205 char *product_name;
2206 GuestOSInfo *info;
2208 ga_get_win_version(&os_version, &local_err);
2209 if (local_err) {
2210 error_propagate(errp, local_err);
2211 return NULL;
2214 server = os_version.wProductType != VER_NT_WORKSTATION;
2215 product_name = ga_get_win_product_name(errp);
2216 if (product_name == NULL) {
2217 return NULL;
2220 info = g_new0(GuestOSInfo, 1);
2222 info->has_kernel_version = true;
2223 info->kernel_version = g_strdup_printf("%lu.%lu",
2224 os_version.dwMajorVersion,
2225 os_version.dwMinorVersion);
2226 info->has_kernel_release = true;
2227 info->kernel_release = g_strdup_printf("%lu",
2228 os_version.dwBuildNumber);
2229 info->has_machine = true;
2230 info->machine = ga_get_current_arch();
2232 info->has_id = true;
2233 info->id = g_strdup("mswindows");
2234 info->has_name = true;
2235 info->name = g_strdup("Microsoft Windows");
2236 info->has_pretty_name = true;
2237 info->pretty_name = product_name;
2238 info->has_version = true;
2239 info->version = ga_get_win_name(&os_version, false);
2240 info->has_version_id = true;
2241 info->version_id = ga_get_win_name(&os_version, true);
2242 info->has_variant = true;
2243 info->variant = g_strdup(server ? "server" : "client");
2244 info->has_variant_id = true;
2245 info->variant_id = g_strdup(server ? "server" : "client");
2247 return info;