2 * QEMU Guest Agent win32-specific command implementations
4 * Copyright IBM Corp. 2012
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"
21 #ifdef CONFIG_QGA_NTDDSCSI
28 #include <devpropdef.h>
33 #include "guest-agent-core.h"
34 #include "vss-win32.h"
35 #include "qga-qapi-commands.h"
36 #include "qapi/error.h"
37 #include "qapi/qmp/qerror.h"
38 #include "qemu/queue.h"
39 #include "qemu/host-utils.h"
40 #include "qemu/base64.h"
41 #include "commands-common.h"
44 * The following should be in devpkey.h, but it isn't. The key names were
45 * prefixed to avoid (future) name clashes. Once the definitions get into
46 * mingw the following lines can be removed.
48 DEFINE_DEVPROPKEY(qga_DEVPKEY_NAME
, 0xb725f130, 0x47ef, 0x101a, 0xa5,
49 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac, 10);
50 /* DEVPROP_TYPE_STRING */
51 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_HardwareIds
, 0xa45c254e, 0xdf1c,
52 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 3);
53 /* DEVPROP_TYPE_STRING_LIST */
54 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverDate
, 0xa8b865dd, 0x2e3d,
55 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 2);
56 /* DEVPROP_TYPE_FILETIME */
57 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverVersion
, 0xa8b865dd, 0x2e3d,
58 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 3);
59 /* DEVPROP_TYPE_STRING */
60 /* The CM_Get_DevNode_PropertyW prototype is only sometimes in cfgmgr32.h */
61 #ifndef CM_Get_DevNode_Property
62 #pragma GCC diagnostic push
63 #pragma GCC diagnostic ignored "-Wredundant-decls"
64 CMAPI CONFIGRET WINAPI
CM_Get_DevNode_PropertyW(
66 CONST DEVPROPKEY
* PropertyKey
,
67 DEVPROPTYPE
* PropertyType
,
69 PULONG PropertyBufferSize
,
72 #define CM_Get_DevNode_Property CM_Get_DevNode_PropertyW
73 #pragma GCC diagnostic pop
76 #ifndef SHTDN_REASON_FLAG_PLANNED
77 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
80 /* multiple of 100 nanoseconds elapsed between windows baseline
81 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
82 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
83 (365 * (1970 - 1601) + \
84 (1970 - 1601) / 4 - 3))
86 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
88 struct GuestFileHandle
{
91 QTAILQ_ENTRY(GuestFileHandle
) next
;
95 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
96 } guest_file_state
= {
97 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
100 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
102 typedef struct OpenFlags
{
104 DWORD desired_access
;
105 DWORD creation_disposition
;
107 static OpenFlags guest_file_open_modes
[] = {
108 {"r", GENERIC_READ
, OPEN_EXISTING
},
109 {"rb", GENERIC_READ
, OPEN_EXISTING
},
110 {"w", GENERIC_WRITE
, CREATE_ALWAYS
},
111 {"wb", GENERIC_WRITE
, CREATE_ALWAYS
},
112 {"a", FILE_GENERIC_APPEND
, OPEN_ALWAYS
},
113 {"r+", GENERIC_WRITE
| GENERIC_READ
, OPEN_EXISTING
},
114 {"rb+", GENERIC_WRITE
| GENERIC_READ
, OPEN_EXISTING
},
115 {"r+b", GENERIC_WRITE
| GENERIC_READ
, OPEN_EXISTING
},
116 {"w+", GENERIC_WRITE
| GENERIC_READ
, CREATE_ALWAYS
},
117 {"wb+", GENERIC_WRITE
| GENERIC_READ
, CREATE_ALWAYS
},
118 {"w+b", GENERIC_WRITE
| GENERIC_READ
, CREATE_ALWAYS
},
119 {"a+", FILE_GENERIC_APPEND
| GENERIC_READ
, OPEN_ALWAYS
},
120 {"ab+", FILE_GENERIC_APPEND
| GENERIC_READ
, OPEN_ALWAYS
},
121 {"a+b", FILE_GENERIC_APPEND
| GENERIC_READ
, OPEN_ALWAYS
}
124 #define debug_error(msg) do { \
125 char *suffix = g_win32_error_message(GetLastError()); \
126 g_debug("%s: %s", (msg), suffix); \
130 static OpenFlags
*find_open_flag(const char *mode_str
)
135 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
136 OpenFlags
*flags
= guest_file_open_modes
+ mode
;
138 if (strcmp(flags
->forms
, mode_str
) == 0) {
143 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
147 static int64_t guest_file_handle_add(HANDLE fh
, Error
**errp
)
149 GuestFileHandle
*gfh
;
152 handle
= ga_get_fd_handle(ga_state
, errp
);
156 gfh
= g_new0(GuestFileHandle
, 1);
159 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
164 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
166 GuestFileHandle
*gfh
;
167 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
) {
172 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
176 static void handle_set_nonblocking(HANDLE fh
)
178 DWORD file_type
, pipe_state
;
179 file_type
= GetFileType(fh
);
180 if (file_type
!= FILE_TYPE_PIPE
) {
183 /* If file_type == FILE_TYPE_PIPE, according to MSDN
184 * the specified file is socket or named pipe */
185 if (!GetNamedPipeHandleState(fh
, &pipe_state
, NULL
,
186 NULL
, NULL
, NULL
, 0)) {
189 /* The fd is named pipe fd */
190 if (pipe_state
& PIPE_NOWAIT
) {
194 pipe_state
|= PIPE_NOWAIT
;
195 SetNamedPipeHandleState(fh
, &pipe_state
, NULL
, NULL
);
198 int64_t qmp_guest_file_open(const char *path
, bool has_mode
,
199 const char *mode
, Error
**errp
)
203 HANDLE templ_file
= NULL
;
204 DWORD share_mode
= FILE_SHARE_READ
;
205 DWORD flags_and_attr
= FILE_ATTRIBUTE_NORMAL
;
206 LPSECURITY_ATTRIBUTES sa_attr
= NULL
;
207 OpenFlags
*guest_flags
;
209 wchar_t *w_path
= NULL
;
214 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
215 guest_flags
= find_open_flag(mode
);
216 if (guest_flags
== NULL
) {
217 error_setg(errp
, "invalid file open mode");
221 w_path
= g_utf8_to_utf16(path
, -1, NULL
, NULL
, &gerr
);
226 fh
= CreateFileW(w_path
, guest_flags
->desired_access
, share_mode
, sa_attr
,
227 guest_flags
->creation_disposition
, flags_and_attr
,
229 if (fh
== INVALID_HANDLE_VALUE
) {
230 error_setg_win32(errp
, GetLastError(), "failed to open file '%s'",
235 /* set fd non-blocking to avoid common use cases (like reading from a
236 * named pipe) from hanging the agent
238 handle_set_nonblocking(fh
);
240 fd
= guest_file_handle_add(fh
, errp
);
243 error_setg(errp
, "failed to add handle to qmp handle table");
247 slog("guest-file-open, handle: % " PRId64
, fd
);
251 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
258 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
261 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
262 slog("guest-file-close called, handle: %" PRId64
, handle
);
266 ret
= CloseHandle(gfh
->fh
);
268 error_setg_win32(errp
, GetLastError(), "failed close handle");
272 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
276 static void acquire_privilege(const char *name
, Error
**errp
)
279 TOKEN_PRIVILEGES priv
;
280 Error
*local_err
= NULL
;
282 if (OpenProcessToken(GetCurrentProcess(),
283 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &token
))
285 if (!LookupPrivilegeValue(NULL
, name
, &priv
.Privileges
[0].Luid
)) {
286 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
287 "no luid for requested privilege");
291 priv
.PrivilegeCount
= 1;
292 priv
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
294 if (!AdjustTokenPrivileges(token
, FALSE
, &priv
, 0, NULL
, 0)) {
295 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
296 "unable to acquire requested privilege");
301 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
302 "failed to open privilege token");
309 error_propagate(errp
, local_err
);
312 static void execute_async(DWORD
WINAPI (*func
)(LPVOID
), LPVOID opaque
,
315 HANDLE thread
= CreateThread(NULL
, 0, func
, opaque
, 0, NULL
);
317 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
318 "failed to dispatch asynchronous command");
322 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
324 Error
*local_err
= NULL
;
325 UINT shutdown_flag
= EWX_FORCE
;
327 slog("guest-shutdown called, mode: %s", mode
);
329 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
330 shutdown_flag
|= EWX_POWEROFF
;
331 } else if (strcmp(mode
, "halt") == 0) {
332 shutdown_flag
|= EWX_SHUTDOWN
;
333 } else if (strcmp(mode
, "reboot") == 0) {
334 shutdown_flag
|= EWX_REBOOT
;
336 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "mode",
337 "'halt', 'powerdown', or 'reboot'");
341 /* Request a shutdown privilege, but try to shut down the system
343 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
345 error_propagate(errp
, local_err
);
349 if (!ExitWindowsEx(shutdown_flag
, SHTDN_REASON_FLAG_PLANNED
)) {
350 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
351 slog("guest-shutdown failed: %s", emsg
);
352 error_setg_win32(errp
, GetLastError(), "guest-shutdown failed");
356 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
357 int64_t count
, Error
**errp
)
359 GuestFileRead
*read_data
= NULL
;
365 buf
= g_malloc0(count
+ 1);
366 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
368 error_setg_win32(errp
, GetLastError(), "failed to read file");
371 read_data
= g_new0(GuestFileRead
, 1);
372 read_data
->count
= (size_t)read_count
;
373 read_data
->eof
= read_count
== 0;
375 if (read_count
!= 0) {
376 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
384 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
385 bool has_count
, int64_t count
,
388 GuestFileWrite
*write_data
= NULL
;
393 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
400 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
407 } else if (count
< 0 || count
> buf_len
) {
408 error_setg(errp
, "value '%" PRId64
409 "' is invalid for argument count", count
);
413 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
415 error_setg_win32(errp
, GetLastError(), "failed to write to file");
416 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
418 write_data
= g_new0(GuestFileWrite
, 1);
419 write_data
->count
= (size_t) write_count
;
427 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
428 GuestFileWhence
*whence_code
,
431 GuestFileHandle
*gfh
;
432 GuestFileSeek
*seek_data
;
434 LARGE_INTEGER new_pos
, off_pos
;
435 off_pos
.QuadPart
= offset
;
440 gfh
= guest_file_handle_find(handle
, errp
);
445 /* We stupidly exposed 'whence':'int' in our qapi */
446 whence
= ga_parse_whence(whence_code
, &err
);
448 error_propagate(errp
, err
);
453 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
455 error_setg_win32(errp
, GetLastError(), "failed to seek file");
458 seek_data
= g_new0(GuestFileSeek
, 1);
459 seek_data
->position
= new_pos
.QuadPart
;
463 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
466 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
472 if (!FlushFileBuffers(fh
)) {
473 error_setg_win32(errp
, GetLastError(), "failed to flush file");
477 #ifdef CONFIG_QGA_NTDDSCSI
479 static GuestDiskBusType win2qemu
[] = {
480 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
481 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
482 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
483 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
484 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
485 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
486 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
487 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
488 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
489 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
490 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
491 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
492 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
493 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
494 #if (_WIN32_WINNT >= 0x0601)
495 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
496 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
500 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
502 if (bus
>= ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
503 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
505 return win2qemu
[(int)bus
];
508 DEFINE_GUID(GUID_DEVINTERFACE_DISK
,
509 0x53f56307L
, 0xb6bf, 0x11d0, 0x94, 0xf2,
510 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
511 DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT
,
512 0x2accfe60L
, 0xc130, 0x11d2, 0xb0, 0x82,
513 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
515 static GuestPCIAddress
*get_pci_info(int number
, Error
**errp
)
517 HDEVINFO dev_info
= INVALID_HANDLE_VALUE
;
518 SP_DEVINFO_DATA dev_info_data
;
519 SP_DEVICE_INTERFACE_DATA dev_iface_data
;
522 GuestPCIAddress
*pci
= NULL
;
523 bool partial_pci
= false;
525 pci
= g_malloc0(sizeof(*pci
));
531 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK
, 0, 0,
532 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
533 if (dev_info
== INVALID_HANDLE_VALUE
) {
534 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
538 g_debug("enumerating devices");
539 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
540 dev_iface_data
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
541 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
542 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data
= NULL
;
543 STORAGE_DEVICE_NUMBER sdn
;
544 char *parent_dev_id
= NULL
;
545 HDEVINFO parent_dev_info
;
546 SP_DEVINFO_DATA parent_dev_info_data
;
550 g_debug("getting device path");
551 if (SetupDiEnumDeviceInterfaces(dev_info
, &dev_info_data
,
552 &GUID_DEVINTERFACE_DISK
, 0,
554 while (!SetupDiGetDeviceInterfaceDetail(dev_info
, &dev_iface_data
,
555 pdev_iface_detail_data
,
558 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
559 pdev_iface_detail_data
= g_malloc(size
);
560 pdev_iface_detail_data
->cbSize
=
561 sizeof(*pdev_iface_detail_data
);
563 error_setg_win32(errp
, GetLastError(),
564 "failed to get device interfaces");
569 dev_file
= CreateFile(pdev_iface_detail_data
->DevicePath
, 0,
570 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0,
572 g_free(pdev_iface_detail_data
);
574 if (!DeviceIoControl(dev_file
, IOCTL_STORAGE_GET_DEVICE_NUMBER
,
575 NULL
, 0, &sdn
, sizeof(sdn
), &size
, NULL
)) {
576 CloseHandle(dev_file
);
577 error_setg_win32(errp
, GetLastError(),
578 "failed to get device slot number");
582 CloseHandle(dev_file
);
583 if (sdn
.DeviceNumber
!= number
) {
587 error_setg_win32(errp
, GetLastError(),
588 "failed to get device interfaces");
592 g_debug("found device slot %d. Getting storage controller", number
);
595 DEVINST dev_inst
, parent_dev_inst
;
596 ULONG dev_id_size
= 0;
599 while (!SetupDiGetDeviceInstanceId(dev_info
, &dev_info_data
,
600 parent_dev_id
, size
, &size
)) {
601 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
602 parent_dev_id
= g_malloc(size
);
604 error_setg_win32(errp
, GetLastError(),
605 "failed to get device instance ID");
611 * CM API used here as opposed to
612 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
613 * which exports are only available in mingw-w64 6+
615 cr
= CM_Locate_DevInst(&dev_inst
, parent_dev_id
, 0);
616 if (cr
!= CR_SUCCESS
) {
617 g_error("CM_Locate_DevInst failed with code %lx", cr
);
618 error_setg_win32(errp
, GetLastError(),
619 "failed to get device instance");
622 cr
= CM_Get_Parent(&parent_dev_inst
, dev_inst
, 0);
623 if (cr
!= CR_SUCCESS
) {
624 g_error("CM_Get_Parent failed with code %lx", cr
);
625 error_setg_win32(errp
, GetLastError(),
626 "failed to get parent device instance");
630 cr
= CM_Get_Device_ID_Size(&dev_id_size
, parent_dev_inst
, 0);
631 if (cr
!= CR_SUCCESS
) {
632 g_error("CM_Get_Device_ID_Size failed with code %lx", cr
);
633 error_setg_win32(errp
, GetLastError(),
634 "failed to get parent device ID length");
639 if (dev_id_size
> size
) {
640 g_free(parent_dev_id
);
641 parent_dev_id
= g_malloc(dev_id_size
);
644 cr
= CM_Get_Device_ID(parent_dev_inst
, parent_dev_id
, dev_id_size
,
646 if (cr
!= CR_SUCCESS
) {
647 g_error("CM_Get_Device_ID failed with code %lx", cr
);
648 error_setg_win32(errp
, GetLastError(),
649 "failed to get parent device ID");
654 g_debug("querying storage controller %s for PCI information",
657 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT
, parent_dev_id
,
658 NULL
, DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
659 g_free(parent_dev_id
);
661 if (parent_dev_info
== INVALID_HANDLE_VALUE
) {
662 error_setg_win32(errp
, GetLastError(),
663 "failed to get parent device");
667 parent_dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
668 if (!SetupDiEnumDeviceInfo(parent_dev_info
, 0, &parent_dev_info_data
)) {
669 error_setg_win32(errp
, GetLastError(),
670 "failed to get parent device data");
675 SetupDiEnumDeviceInfo(parent_dev_info
, j
, &parent_dev_info_data
);
677 DWORD addr
, bus
, ui_slot
, type
;
681 * There is no need to allocate buffer in the next functions. The
682 * size is known and ULONG according to
683 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
685 if (!SetupDiGetDeviceRegistryProperty(
686 parent_dev_info
, &parent_dev_info_data
, SPDRP_BUSNUMBER
,
687 &type
, (PBYTE
)&bus
, size
, NULL
)) {
688 debug_error("failed to get PCI bus");
694 * The function retrieves the device's address. This value will be
695 * transformed into device function and number
697 if (!SetupDiGetDeviceRegistryProperty(
698 parent_dev_info
, &parent_dev_info_data
, SPDRP_ADDRESS
,
699 &type
, (PBYTE
)&addr
, size
, NULL
)) {
700 debug_error("failed to get PCI address");
706 * This call returns UINumber of DEVICE_CAPABILITIES structure.
707 * This number is typically a user-perceived slot number.
709 if (!SetupDiGetDeviceRegistryProperty(
710 parent_dev_info
, &parent_dev_info_data
, SPDRP_UI_NUMBER
,
711 &type
, (PBYTE
)&ui_slot
, size
, NULL
)) {
712 debug_error("failed to get PCI slot");
718 * SetupApi gives us the same information as driver with
719 * IoGetDeviceProperty. According to Microsoft:
721 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
722 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
723 * SPDRP_ADDRESS is propertyAddress, so we do the same.
725 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
734 func
= ((int)addr
== -1) ? -1 : addr
& 0x0000FFFF;
735 slot
= ((int)addr
== -1) ? -1 : (addr
>> 16) & 0x0000FFFF;
736 if ((int)ui_slot
!= slot
) {
737 g_debug("mismatch with reported slot values: %d vs %d",
741 pci
->slot
= (int)ui_slot
;
742 pci
->function
= func
;
747 SetupDiDestroyDeviceInfoList(parent_dev_info
);
752 if (dev_info
!= INVALID_HANDLE_VALUE
) {
753 SetupDiDestroyDeviceInfoList(dev_info
);
759 static void get_disk_properties(HANDLE vol_h
, GuestDiskAddress
*disk
,
762 STORAGE_PROPERTY_QUERY query
;
763 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
765 ULONG size
= sizeof(buf
);
768 query
.PropertyId
= StorageDeviceProperty
;
769 query
.QueryType
= PropertyStandardQuery
;
771 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
772 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
773 size
, &received
, NULL
)) {
774 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
777 disk
->bus_type
= find_bus_type(dev_desc
->BusType
);
778 g_debug("bus type %d", disk
->bus_type
);
780 /* Query once more. Now with long enough buffer. */
781 size
= dev_desc
->Size
;
782 dev_desc
= g_malloc0(size
);
783 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
784 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
785 size
, &received
, NULL
)) {
786 error_setg_win32(errp
, GetLastError(), "failed to get serial number");
787 g_debug("failed to get serial number");
790 if (dev_desc
->SerialNumberOffset
> 0) {
794 if (dev_desc
->SerialNumberOffset
>= received
) {
795 error_setg(errp
, "failed to get serial number: offset outside the buffer");
796 g_debug("serial number offset outside the buffer");
799 serial
= (char *)dev_desc
+ dev_desc
->SerialNumberOffset
;
800 len
= received
- dev_desc
->SerialNumberOffset
;
801 g_debug("serial number \"%s\"", serial
);
803 disk
->serial
= g_strndup(serial
, len
);
804 disk
->has_serial
= true;
813 static void get_single_disk_info(int disk_number
,
814 GuestDiskAddress
*disk
, Error
**errp
)
816 SCSI_ADDRESS addr
, *scsi_ad
;
819 Error
*local_err
= NULL
;
823 g_debug("getting disk info for: %s", disk
->dev
);
824 disk_h
= CreateFile(disk
->dev
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
826 if (disk_h
== INVALID_HANDLE_VALUE
) {
827 error_setg_win32(errp
, GetLastError(), "failed to open disk");
831 get_disk_properties(disk_h
, disk
, &local_err
);
833 error_propagate(errp
, local_err
);
837 g_debug("bus type %d", disk
->bus_type
);
838 /* always set pci_controller as required by schema. get_pci_info() should
839 * report -1 values for non-PCI buses rather than fail. fail the command
840 * if that doesn't hold since that suggests some other unexpected
843 disk
->pci_controller
= get_pci_info(disk_number
, &local_err
);
845 error_propagate(errp
, local_err
);
848 if (disk
->bus_type
== GUEST_DISK_BUS_TYPE_SCSI
849 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_IDE
850 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_RAID
851 /* This bus type is not supported before Windows Server 2003 SP1 */
852 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_SAS
854 /* We are able to use the same ioctls for different bus types
855 * according to Microsoft docs
856 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
857 g_debug("getting SCSI info");
858 if (DeviceIoControl(disk_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
859 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
860 disk
->unit
= addr
.Lun
;
861 disk
->target
= addr
.TargetId
;
862 disk
->bus
= addr
.PathId
;
864 /* We do not set error in this case, because we still have enough
865 * information about volume. */
873 /* VSS provider works with volumes, thus there is no difference if
874 * the volume consist of spanned disks. Info about the first disk in the
875 * volume is returned for the spanned disk group (LVM) */
876 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
878 Error
*local_err
= NULL
;
879 GuestDiskAddressList
*list
= NULL
;
880 GuestDiskAddress
*disk
= NULL
;
884 PVOLUME_DISK_EXTENTS extents
= NULL
;
886 /* strip final backslash */
887 char *name
= g_strdup(guid
);
888 if (g_str_has_suffix(name
, "\\")) {
889 name
[strlen(name
) - 1] = 0;
892 g_debug("opening %s", name
);
893 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
895 if (vol_h
== INVALID_HANDLE_VALUE
) {
896 error_setg_win32(errp
, GetLastError(), "failed to open volume");
900 /* Get list of extents */
901 g_debug("getting disk extents");
902 size
= sizeof(VOLUME_DISK_EXTENTS
);
903 extents
= g_malloc0(size
);
904 if (!DeviceIoControl(vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
905 0, extents
, size
, &size
, NULL
)) {
906 DWORD last_err
= GetLastError();
907 if (last_err
== ERROR_MORE_DATA
) {
908 /* Try once more with big enough buffer */
910 extents
= g_malloc0(size
);
911 if (!DeviceIoControl(
912 vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
913 0, extents
, size
, NULL
, NULL
)) {
914 error_setg_win32(errp
, GetLastError(),
915 "failed to get disk extents");
918 } else if (last_err
== ERROR_INVALID_FUNCTION
) {
919 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
920 g_debug("volume not on disk");
921 disk
= g_malloc0(sizeof(GuestDiskAddress
));
922 disk
->has_dev
= true;
923 disk
->dev
= g_strdup(name
);
924 get_single_disk_info(0xffffffff, disk
, &local_err
);
926 g_debug("failed to get disk info, ignoring error: %s",
927 error_get_pretty(local_err
));
928 error_free(local_err
);
931 QAPI_LIST_PREPEND(list
, disk
);
935 error_setg_win32(errp
, GetLastError(),
936 "failed to get disk extents");
940 g_debug("Number of extents: %lu", extents
->NumberOfDiskExtents
);
942 /* Go through each extent */
943 for (i
= 0; i
< extents
->NumberOfDiskExtents
; i
++) {
944 disk
= g_malloc0(sizeof(GuestDiskAddress
));
946 /* Disk numbers directly correspond to numbers used in UNCs
948 * See documentation for DISK_EXTENT:
949 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
951 * See also Naming Files, Paths and Namespaces:
952 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
954 disk
->has_dev
= true;
955 disk
->dev
= g_strdup_printf("\\\\.\\PhysicalDrive%lu",
956 extents
->Extents
[i
].DiskNumber
);
958 get_single_disk_info(extents
->Extents
[i
].DiskNumber
, disk
, &local_err
);
960 error_propagate(errp
, local_err
);
963 QAPI_LIST_PREPEND(list
, disk
);
969 if (vol_h
!= INVALID_HANDLE_VALUE
) {
972 qapi_free_GuestDiskAddress(disk
);
979 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
981 GuestDiskInfoList
*ret
= NULL
;
983 SP_DEVICE_INTERFACE_DATA dev_iface_data
;
986 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK
, 0, 0,
987 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
988 if (dev_info
== INVALID_HANDLE_VALUE
) {
989 error_setg_win32(errp
, GetLastError(), "failed to get device tree");
993 g_debug("enumerating devices");
994 dev_iface_data
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
996 SetupDiEnumDeviceInterfaces(dev_info
, NULL
, &GUID_DEVINTERFACE_DISK
,
999 GuestDiskAddress
*address
= NULL
;
1000 GuestDiskInfo
*disk
= NULL
;
1001 Error
*local_err
= NULL
;
1002 g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA
1003 pdev_iface_detail_data
= NULL
;
1004 STORAGE_DEVICE_NUMBER sdn
;
1010 g_debug(" getting device path");
1011 for (attempt
= 0, result
= FALSE
; attempt
< 2 && !result
; attempt
++) {
1012 result
= SetupDiGetDeviceInterfaceDetail(dev_info
,
1013 &dev_iface_data
, pdev_iface_detail_data
, size
, &size
, NULL
);
1017 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
1018 pdev_iface_detail_data
= g_realloc(pdev_iface_detail_data
,
1020 pdev_iface_detail_data
->cbSize
=
1021 sizeof(*pdev_iface_detail_data
);
1023 g_debug("failed to get device interface details");
1028 g_debug("skipping device");
1032 g_debug(" device: %s", pdev_iface_detail_data
->DevicePath
);
1033 dev_file
= CreateFile(pdev_iface_detail_data
->DevicePath
, 0,
1034 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, NULL
);
1035 if (!DeviceIoControl(dev_file
, IOCTL_STORAGE_GET_DEVICE_NUMBER
,
1036 NULL
, 0, &sdn
, sizeof(sdn
), &size
, NULL
)) {
1037 CloseHandle(dev_file
);
1038 debug_error("failed to get storage device number");
1041 CloseHandle(dev_file
);
1043 disk
= g_new0(GuestDiskInfo
, 1);
1044 disk
->name
= g_strdup_printf("\\\\.\\PhysicalDrive%lu",
1047 g_debug(" number: %lu", sdn
.DeviceNumber
);
1048 address
= g_malloc0(sizeof(GuestDiskAddress
));
1049 address
->has_dev
= true;
1050 address
->dev
= g_strdup(disk
->name
);
1051 get_single_disk_info(sdn
.DeviceNumber
, address
, &local_err
);
1053 g_debug("failed to get disk info: %s",
1054 error_get_pretty(local_err
));
1055 error_free(local_err
);
1056 qapi_free_GuestDiskAddress(address
);
1059 disk
->address
= address
;
1060 disk
->has_address
= true;
1063 QAPI_LIST_PREPEND(ret
, disk
);
1066 SetupDiDestroyDeviceInfoList(dev_info
);
1072 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
1077 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1079 error_setg(errp
, QERR_UNSUPPORTED
);
1083 #endif /* CONFIG_QGA_NTDDSCSI */
1085 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
1088 char mnt
, *mnt_point
;
1089 wchar_t wfs_name
[32];
1091 wchar_t vol_info
[MAX_PATH
+ 1];
1093 uint64_t i64FreeBytesToCaller
, i64TotalBytes
, i64FreeBytes
;
1094 GuestFilesystemInfo
*fs
= NULL
;
1095 HANDLE hLocalDiskHandle
= INVALID_HANDLE_VALUE
;
1097 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
1098 if (GetLastError() != ERROR_MORE_DATA
) {
1099 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
1103 mnt_point
= g_malloc(info_size
+ 1);
1104 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
1106 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
1110 hLocalDiskHandle
= CreateFile(guid
, 0 , 0, NULL
, OPEN_EXISTING
,
1111 FILE_ATTRIBUTE_NORMAL
|
1112 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1113 if (INVALID_HANDLE_VALUE
== hLocalDiskHandle
) {
1114 error_setg_win32(errp
, GetLastError(), "failed to get handle for volume");
1118 len
= strlen(mnt_point
);
1119 mnt_point
[len
] = '\\';
1120 mnt_point
[len
+ 1] = 0;
1122 if (!GetVolumeInformationByHandleW(hLocalDiskHandle
, vol_info
,
1123 sizeof(vol_info
), NULL
, NULL
, NULL
,
1124 (LPWSTR
) & wfs_name
, sizeof(wfs_name
))) {
1125 if (GetLastError() != ERROR_NOT_READY
) {
1126 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
1131 fs
= g_malloc(sizeof(*fs
));
1132 fs
->name
= g_strdup(guid
);
1133 fs
->has_total_bytes
= false;
1134 fs
->has_used_bytes
= false;
1136 fs
->mountpoint
= g_strdup("System Reserved");
1138 fs
->mountpoint
= g_strndup(mnt_point
, len
);
1139 if (GetDiskFreeSpaceEx(fs
->mountpoint
,
1140 (PULARGE_INTEGER
) & i64FreeBytesToCaller
,
1141 (PULARGE_INTEGER
) & i64TotalBytes
,
1142 (PULARGE_INTEGER
) & i64FreeBytes
)) {
1143 fs
->used_bytes
= i64TotalBytes
- i64FreeBytes
;
1144 fs
->total_bytes
= i64TotalBytes
;
1145 fs
->has_total_bytes
= true;
1146 fs
->has_used_bytes
= true;
1149 wcstombs(fs_name
, wfs_name
, sizeof(wfs_name
));
1150 fs
->type
= g_strdup(fs_name
);
1151 fs
->disk
= build_guest_disk_info(guid
, errp
);
1153 if (hLocalDiskHandle
!= INVALID_HANDLE_VALUE
) {
1154 CloseHandle(hLocalDiskHandle
);
1160 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1163 GuestFilesystemInfoList
*ret
= NULL
;
1166 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
1167 if (vol_h
== INVALID_HANDLE_VALUE
) {
1168 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1173 Error
*local_err
= NULL
;
1174 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, &local_err
);
1176 g_debug("failed to get filesystem info, ignoring error: %s",
1177 error_get_pretty(local_err
));
1178 error_free(local_err
);
1181 QAPI_LIST_PREPEND(ret
, info
);
1182 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
1184 if (GetLastError() != ERROR_NO_MORE_FILES
) {
1185 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
1188 FindVolumeClose(vol_h
);
1193 * Return status of freeze/thaw
1195 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1197 if (!vss_initialized()) {
1198 error_setg(errp
, QERR_UNSUPPORTED
);
1202 if (ga_is_frozen(ga_state
)) {
1203 return GUEST_FSFREEZE_STATUS_FROZEN
;
1206 return GUEST_FSFREEZE_STATUS_THAWED
;
1210 * Freeze local file systems using Volume Shadow-copy Service.
1211 * The frozen state is limited for up to 10 seconds by VSS.
1213 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1215 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1218 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1219 strList
*mountpoints
,
1223 Error
*local_err
= NULL
;
1225 if (!vss_initialized()) {
1226 error_setg(errp
, QERR_UNSUPPORTED
);
1230 slog("guest-fsfreeze called");
1232 /* cannot risk guest agent blocking itself on a write in this state */
1233 ga_set_frozen(ga_state
);
1235 qga_vss_fsfreeze(&i
, true, mountpoints
, &local_err
);
1237 error_propagate(errp
, local_err
);
1245 qmp_guest_fsfreeze_thaw(&local_err
);
1247 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
1248 error_free(local_err
);
1254 * Thaw local file systems using Volume Shadow-copy Service.
1256 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1260 if (!vss_initialized()) {
1261 error_setg(errp
, QERR_UNSUPPORTED
);
1265 qga_vss_fsfreeze(&i
, false, NULL
, errp
);
1267 ga_unset_frozen(ga_state
);
1271 static void guest_fsfreeze_cleanup(void)
1275 if (!vss_initialized()) {
1279 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1280 qmp_guest_fsfreeze_thaw(&err
);
1282 slog("failed to clean up frozen filesystems: %s",
1283 error_get_pretty(err
));
1292 * Walk list of mounted file systems in the guest, and discard unused
1295 GuestFilesystemTrimResponse
*
1296 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1298 GuestFilesystemTrimResponse
*resp
;
1300 WCHAR guid
[MAX_PATH
] = L
"";
1304 ZeroMemory(&osvi
, sizeof(OSVERSIONINFO
));
1305 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1306 GetVersionEx(&osvi
);
1307 win8_or_later
= (osvi
.dwMajorVersion
> 6 ||
1308 ((osvi
.dwMajorVersion
== 6) &&
1309 (osvi
.dwMinorVersion
>= 2)));
1310 if (!win8_or_later
) {
1311 error_setg(errp
, "fstrim is only supported for Win8+");
1315 handle
= FindFirstVolumeW(guid
, ARRAYSIZE(guid
));
1316 if (handle
== INVALID_HANDLE_VALUE
) {
1317 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1321 resp
= g_new0(GuestFilesystemTrimResponse
, 1);
1324 GuestFilesystemTrimResult
*res
;
1326 DWORD char_count
= 0;
1328 GError
*gerr
= NULL
;
1331 GetVolumePathNamesForVolumeNameW(guid
, NULL
, 0, &char_count
);
1333 if (GetLastError() != ERROR_MORE_DATA
) {
1336 if (GetDriveTypeW(guid
) != DRIVE_FIXED
) {
1340 uc_path
= g_malloc(sizeof(WCHAR
) * char_count
);
1341 if (!GetVolumePathNamesForVolumeNameW(guid
, uc_path
, char_count
,
1342 &char_count
) || !*uc_path
) {
1343 /* strange, but this condition could be faced even with size == 2 */
1348 res
= g_new0(GuestFilesystemTrimResult
, 1);
1350 path
= g_utf16_to_utf8(uc_path
, char_count
, NULL
, NULL
, &gerr
);
1355 res
->has_error
= true;
1356 res
->error
= g_strdup(gerr
->message
);
1363 QAPI_LIST_PREPEND(resp
->paths
, res
);
1365 memset(argv
, 0, sizeof(argv
));
1366 argv
[0] = (gchar
*)"defrag.exe";
1367 argv
[1] = (gchar
*)"/L";
1370 if (!g_spawn_sync(NULL
, argv
, NULL
, G_SPAWN_SEARCH_PATH
, NULL
, NULL
,
1371 &out
/* stdout */, NULL
/* stdin */,
1373 res
->has_error
= true;
1374 res
->error
= g_strdup(gerr
->message
);
1377 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1378 Error is reported in the output with something like
1379 (x89000020) etc code in the stdout */
1382 gchar
**lines
= g_strsplit(out
, "\r\n", 0);
1385 for (i
= 0; lines
[i
] != NULL
; i
++) {
1386 if (g_strstr_len(lines
[i
], -1, "(0x") == NULL
) {
1389 res
->has_error
= true;
1390 res
->error
= g_strdup(lines
[i
]);
1395 } while (FindNextVolumeW(handle
, guid
, ARRAYSIZE(guid
)));
1397 FindVolumeClose(handle
);
1402 GUEST_SUSPEND_MODE_DISK
,
1403 GUEST_SUSPEND_MODE_RAM
1406 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
1408 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
1410 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
1411 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
1412 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1413 "failed to determine guest suspend capabilities");
1418 case GUEST_SUSPEND_MODE_DISK
:
1419 if (!sys_pwr_caps
.SystemS4
) {
1420 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1421 "suspend-to-disk not supported by OS");
1424 case GUEST_SUSPEND_MODE_RAM
:
1425 if (!sys_pwr_caps
.SystemS3
) {
1426 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1427 "suspend-to-ram not supported by OS");
1435 static DWORD WINAPI
do_suspend(LPVOID opaque
)
1437 GuestSuspendMode
*mode
= opaque
;
1440 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
1441 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
1442 slog("failed to suspend guest: %s", emsg
);
1449 void qmp_guest_suspend_disk(Error
**errp
)
1451 Error
*local_err
= NULL
;
1452 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1454 *mode
= GUEST_SUSPEND_MODE_DISK
;
1455 check_suspend_mode(*mode
, &local_err
);
1459 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1463 execute_async(do_suspend
, mode
, &local_err
);
1467 error_propagate(errp
, local_err
);
1472 void qmp_guest_suspend_ram(Error
**errp
)
1474 Error
*local_err
= NULL
;
1475 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1477 *mode
= GUEST_SUSPEND_MODE_RAM
;
1478 check_suspend_mode(*mode
, &local_err
);
1482 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1486 execute_async(do_suspend
, mode
, &local_err
);
1490 error_propagate(errp
, local_err
);
1495 void qmp_guest_suspend_hybrid(Error
**errp
)
1497 error_setg(errp
, QERR_UNSUPPORTED
);
1500 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
1502 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
1503 ULONG adptr_addrs_len
= 0;
1506 /* Call the first time to get the adptr_addrs_len. */
1507 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1508 NULL
, adptr_addrs
, &adptr_addrs_len
);
1510 adptr_addrs
= g_malloc(adptr_addrs_len
);
1511 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1512 NULL
, adptr_addrs
, &adptr_addrs_len
);
1513 if (ret
!= ERROR_SUCCESS
) {
1514 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
1515 g_free(adptr_addrs
);
1521 static char *guest_wctomb_dup(WCHAR
*wstr
)
1526 str_size
= WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, NULL
, 0, NULL
, NULL
);
1527 /* add 1 to str_size for NULL terminator */
1528 str
= g_malloc(str_size
+ 1);
1529 WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, str
, str_size
, NULL
, NULL
);
1533 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
1536 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
1540 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
1541 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1542 len
= sizeof(addr_str
);
1543 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
1544 ip_addr
->Address
.iSockaddrLength
,
1549 error_setg_win32(errp
, WSAGetLastError(),
1550 "failed address presentation form conversion");
1553 return g_strdup(addr_str
);
1558 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1560 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1561 * field to obtain the prefix.
1563 return ip_addr
->OnLinkPrefixLength
;
1566 #define INTERFACE_PATH_BUF_SZ 512
1568 static DWORD
get_interface_index(const char *guid
)
1572 wchar_t wbuf
[INTERFACE_PATH_BUF_SZ
];
1573 snwprintf(wbuf
, INTERFACE_PATH_BUF_SZ
, L
"\\device\\tcpip_%s", guid
);
1574 wbuf
[INTERFACE_PATH_BUF_SZ
- 1] = 0;
1575 status
= GetAdapterIndex (wbuf
, &index
);
1576 if (status
!= NO_ERROR
) {
1583 typedef NETIOAPI_API (WINAPI
*GetIfEntry2Func
)(PMIB_IF_ROW2 Row
);
1585 static int guest_get_network_stats(const char *name
,
1586 GuestNetworkInterfaceStat
*stats
)
1588 OSVERSIONINFO os_ver
;
1590 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1591 GetVersionEx(&os_ver
);
1592 if (os_ver
.dwMajorVersion
>= 6) {
1593 MIB_IF_ROW2 a_mid_ifrow
;
1594 GetIfEntry2Func getifentry2_ex
;
1596 HMODULE module
= GetModuleHandle("iphlpapi");
1597 PVOID func
= GetProcAddress(module
, "GetIfEntry2");
1603 getifentry2_ex
= (GetIfEntry2Func
)func
;
1604 if_index
= get_interface_index(name
);
1605 if (if_index
== (DWORD
)~0) {
1609 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1610 a_mid_ifrow
.InterfaceIndex
= if_index
;
1611 if (NO_ERROR
== getifentry2_ex(&a_mid_ifrow
)) {
1612 stats
->rx_bytes
= a_mid_ifrow
.InOctets
;
1613 stats
->rx_packets
= a_mid_ifrow
.InUcastPkts
;
1614 stats
->rx_errs
= a_mid_ifrow
.InErrors
;
1615 stats
->rx_dropped
= a_mid_ifrow
.InDiscards
;
1616 stats
->tx_bytes
= a_mid_ifrow
.OutOctets
;
1617 stats
->tx_packets
= a_mid_ifrow
.OutUcastPkts
;
1618 stats
->tx_errs
= a_mid_ifrow
.OutErrors
;
1619 stats
->tx_dropped
= a_mid_ifrow
.OutDiscards
;
1626 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1628 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1629 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1630 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
1631 GuestIpAddressList
*head_addr
, **tail_addr
;
1632 GuestNetworkInterface
*info
;
1633 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1634 GuestIpAddress
*address_item
= NULL
;
1635 unsigned char *mac_addr
;
1641 adptr_addrs
= guest_get_adapters_addresses(errp
);
1642 if (adptr_addrs
== NULL
) {
1646 /* Make WSA APIs available. */
1647 wsa_version
= MAKEWORD(2, 2);
1648 ret
= WSAStartup(wsa_version
, &wsa_data
);
1650 error_setg_win32(errp
, ret
, "failed socket startup");
1654 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1655 info
= g_malloc0(sizeof(*info
));
1657 QAPI_LIST_APPEND(tail
, info
);
1659 info
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1661 if (addr
->PhysicalAddressLength
!= 0) {
1662 mac_addr
= addr
->PhysicalAddress
;
1664 info
->hardware_address
=
1665 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1666 (int) mac_addr
[0], (int) mac_addr
[1],
1667 (int) mac_addr
[2], (int) mac_addr
[3],
1668 (int) mac_addr
[4], (int) mac_addr
[5]);
1670 info
->has_hardware_address
= true;
1674 tail_addr
= &head_addr
;
1675 for (ip_addr
= addr
->FirstUnicastAddress
;
1677 ip_addr
= ip_addr
->Next
) {
1678 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1679 if (addr_str
== NULL
) {
1683 address_item
= g_malloc0(sizeof(*address_item
));
1685 QAPI_LIST_APPEND(tail_addr
, address_item
);
1687 address_item
->ip_address
= addr_str
;
1688 address_item
->prefix
= guest_ip_prefix(ip_addr
);
1689 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1690 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1691 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1692 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1696 info
->has_ip_addresses
= true;
1697 info
->ip_addresses
= head_addr
;
1699 if (!info
->has_statistics
) {
1700 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1701 if (guest_get_network_stats(addr
->AdapterName
,
1702 interface_stat
) == -1) {
1703 info
->has_statistics
= false;
1704 g_free(interface_stat
);
1706 info
->statistics
= interface_stat
;
1707 info
->has_statistics
= true;
1713 g_free(adptr_addrs
);
1717 static int64_t filetime_to_ns(const FILETIME
*tf
)
1719 return ((((int64_t)tf
->dwHighDateTime
<< 32) | tf
->dwLowDateTime
)
1720 - W32_FT_OFFSET
) * 100;
1723 int64_t qmp_guest_get_time(Error
**errp
)
1725 SYSTEMTIME ts
= {0};
1729 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1730 error_setg(errp
, "Failed to get time");
1734 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1735 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1739 return filetime_to_ns(&tf
);
1742 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1744 Error
*local_err
= NULL
;
1750 /* Unfortunately, Windows libraries don't provide an easy way to access
1753 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1755 * Instead, a workaround is to use the Windows win32tm command to
1756 * resync the time using the Windows Time service.
1761 HRESULT hr
= system("w32tm /resync /nowait");
1763 if (GetLastError() != 0) {
1764 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1765 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1766 } else if (hr
!= 0) {
1767 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1768 error_setg(errp
, "Windows Time service not running on the "
1771 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1772 FORMAT_MESSAGE_FROM_SYSTEM
|
1773 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1774 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1775 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1777 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1778 "t retrieve error message", hr
);
1780 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1781 (LPCTSTR
)msg_buffer
);
1782 LocalFree(msg_buffer
);
1785 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1786 error_setg(errp
, "No internet connection on guest, sync not "
1792 /* Validate time passed by user. */
1793 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1794 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1798 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1800 tf
.dwLowDateTime
= (DWORD
) time
;
1801 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1803 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1804 error_setg(errp
, "Failed to convert system time %d",
1805 (int)GetLastError());
1809 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1811 error_propagate(errp
, local_err
);
1815 if (!SetSystemTime(&ts
)) {
1816 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1821 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1823 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1825 GuestLogicalProcessorList
*head
, **tail
;
1826 Error
*local_err
= NULL
;
1835 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1836 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1837 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1838 ptr
= pslpi
= g_malloc0(length
);
1839 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1840 error_setg(&local_err
, "Failed to get processor information: %d",
1841 (int)GetLastError());
1844 error_setg(&local_err
,
1845 "Failed to get processor information buffer length: %d",
1846 (int)GetLastError());
1849 while ((local_err
== NULL
) && (length
> 0)) {
1850 if (pslpi
->Relationship
== RelationProcessorCore
) {
1851 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1853 while (cpu_bits
> 0) {
1854 if (!!(cpu_bits
& 1)) {
1855 GuestLogicalProcessor
*vcpu
;
1857 vcpu
= g_malloc0(sizeof *vcpu
);
1858 vcpu
->logical_id
= current
++;
1859 vcpu
->online
= true;
1860 vcpu
->has_can_offline
= true;
1862 QAPI_LIST_APPEND(tail
, vcpu
);
1867 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1868 pslpi
++; /* next entry */
1873 if (local_err
== NULL
) {
1877 /* there's no guest with zero VCPUs */
1878 error_setg(&local_err
, "Guest reported zero VCPUs");
1881 qapi_free_GuestLogicalProcessorList(head
);
1882 error_propagate(errp
, local_err
);
1886 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1888 error_setg(errp
, QERR_UNSUPPORTED
);
1893 get_net_error_message(gint error
)
1895 HMODULE module
= NULL
;
1896 gchar
*retval
= NULL
;
1897 wchar_t *msg
= NULL
;
1901 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1902 FORMAT_MESSAGE_IGNORE_INSERTS
|
1903 FORMAT_MESSAGE_FROM_SYSTEM
;
1905 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1906 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1908 if (module
!= NULL
) {
1909 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1913 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1916 nchars
= wcslen(msg
);
1919 msg
[nchars
- 1] == L
'\n' &&
1920 msg
[nchars
- 2] == L
'\r') {
1921 msg
[nchars
- 2] = L
'\0';
1924 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1929 if (module
!= NULL
) {
1930 FreeLibrary(module
);
1936 void qmp_guest_set_user_password(const char *username
,
1937 const char *password
,
1942 char *rawpasswddata
= NULL
;
1943 size_t rawpasswdlen
;
1944 wchar_t *user
= NULL
, *wpass
= NULL
;
1945 USER_INFO_1003 pi1003
= { 0, };
1946 GError
*gerr
= NULL
;
1949 error_setg(errp
, QERR_UNSUPPORTED
);
1953 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1954 if (!rawpasswddata
) {
1957 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1958 rawpasswddata
[rawpasswdlen
] = '\0';
1960 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1965 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1970 pi1003
.usri1003_password
= wpass
;
1971 nas
= NetUserSetInfo(NULL
, user
,
1972 1003, (LPBYTE
)&pi1003
,
1975 if (nas
!= NERR_Success
) {
1976 gchar
*msg
= get_net_error_message(nas
);
1977 error_setg(errp
, "failed to set password: %s", msg
);
1983 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1988 g_free(rawpasswddata
);
1991 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1993 error_setg(errp
, QERR_UNSUPPORTED
);
1997 GuestMemoryBlockResponseList
*
1998 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2000 error_setg(errp
, QERR_UNSUPPORTED
);
2004 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2006 error_setg(errp
, QERR_UNSUPPORTED
);
2010 /* add unsupported commands to the blacklist */
2011 GList
*ga_command_blacklist_init(GList
*blacklist
)
2013 const char *list_unsupported
[] = {
2014 "guest-suspend-hybrid",
2016 "guest-get-memory-blocks", "guest-set-memory-blocks",
2017 "guest-get-memory-block-size", "guest-get-memory-block-info",
2019 char **p
= (char **)list_unsupported
;
2022 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2025 if (!vss_init(true)) {
2026 g_debug("vss_init failed, vss commands are going to be disabled");
2027 const char *list
[] = {
2028 "guest-get-fsinfo", "guest-fsfreeze-status",
2029 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
2033 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2040 /* register init/cleanup routines for stateful command groups */
2041 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2043 if (!vss_initialized()) {
2044 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
2048 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
2049 typedef struct _GA_WTSINFOA
{
2050 WTS_CONNECTSTATE_CLASS State
;
2052 DWORD IncomingBytes
;
2053 DWORD OutgoingBytes
;
2054 DWORD IncomingFrames
;
2055 DWORD OutgoingFrames
;
2056 DWORD IncomingCompressedBytes
;
2057 DWORD OutgoingCompressedBy
;
2058 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
2059 CHAR Domain
[DOMAIN_LENGTH
];
2060 CHAR UserName
[USERNAME_LENGTH
+ 1];
2061 LARGE_INTEGER ConnectTime
;
2062 LARGE_INTEGER DisconnectTime
;
2063 LARGE_INTEGER LastInputTime
;
2064 LARGE_INTEGER LogonTime
;
2065 LARGE_INTEGER CurrentTime
;
2069 GuestUserList
*qmp_guest_get_users(Error
**errp
)
2071 #define QGA_NANOSECONDS 10000000
2073 GHashTable
*cache
= NULL
;
2074 GuestUserList
*head
= NULL
, **tail
= &head
;
2076 DWORD buffer_size
= 0, count
= 0, i
= 0;
2077 GA_WTSINFOA
*info
= NULL
;
2078 WTS_SESSION_INFOA
*entries
= NULL
;
2079 GuestUser
*user
= NULL
;
2080 gpointer value
= NULL
;
2082 double login_time
= 0;
2084 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
2086 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
2087 for (i
= 0; i
< count
; ++i
) {
2090 if (WTSQuerySessionInformationA(
2092 entries
[i
].SessionId
,
2098 if (strlen(info
->UserName
) == 0) {
2099 WTSFreeMemory(info
);
2103 login
= info
->LogonTime
.QuadPart
;
2104 login
-= W32_FT_OFFSET
;
2105 login_time
= ((double)login
) / QGA_NANOSECONDS
;
2107 if (g_hash_table_contains(cache
, info
->UserName
)) {
2108 value
= g_hash_table_lookup(cache
, info
->UserName
);
2109 user
= (GuestUser
*)value
;
2110 if (user
->login_time
> login_time
) {
2111 user
->login_time
= login_time
;
2114 user
= g_new0(GuestUser
, 1);
2116 user
->user
= g_strdup(info
->UserName
);
2117 user
->domain
= g_strdup(info
->Domain
);
2118 user
->has_domain
= true;
2120 user
->login_time
= login_time
;
2122 g_hash_table_add(cache
, user
->user
);
2124 QAPI_LIST_APPEND(tail
, user
);
2127 WTSFreeMemory(info
);
2129 WTSFreeMemory(entries
);
2131 g_hash_table_destroy(cache
);
2135 typedef struct _ga_matrix_lookup_t
{
2138 char const *version
;
2139 char const *version_id
;
2140 } ga_matrix_lookup_t
;
2142 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][8] = {
2144 /* Desktop editions */
2145 { 5, 0, "Microsoft Windows 2000", "2000"},
2146 { 5, 1, "Microsoft Windows XP", "xp"},
2147 { 6, 0, "Microsoft Windows Vista", "vista"},
2148 { 6, 1, "Microsoft Windows 7" "7"},
2149 { 6, 2, "Microsoft Windows 8", "8"},
2150 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2151 {10, 0, "Microsoft Windows 10", "10"},
2154 /* Server editions */
2155 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2156 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2157 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2158 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2159 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2166 typedef struct _ga_win_10_0_server_t
{
2168 char const *version
;
2169 char const *version_id
;
2170 } ga_win_10_0_server_t
;
2172 static ga_win_10_0_server_t
const WIN_10_0_SERVER_VERSION_MATRIX
[4] = {
2173 {14393, "Microsoft Windows Server 2016", "2016"},
2174 {17763, "Microsoft Windows Server 2019", "2019"},
2175 {20344, "Microsoft Windows Server 2022", "2022"},
2179 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
2181 typedef NTSTATUS(WINAPI
*rtl_get_version_t
)(
2182 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
2184 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
2186 HMODULE module
= GetModuleHandle("ntdll");
2187 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
2189 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
2190 "Failed to get address of RtlGetVersion");
2194 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
2195 rtl_get_version(info
);
2199 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
2201 DWORD major
= os_version
->dwMajorVersion
;
2202 DWORD minor
= os_version
->dwMinorVersion
;
2203 DWORD build
= os_version
->dwBuildNumber
;
2204 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
2205 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
2206 ga_win_10_0_server_t
const *win_10_0_table
= WIN_10_0_SERVER_VERSION_MATRIX
;
2207 while (table
->version
!= NULL
) {
2208 if (major
== 10 && minor
== 0 && tbl_idx
) {
2209 while (win_10_0_table
->version
!= NULL
) {
2210 if (build
<= win_10_0_table
->final_build
) {
2212 return g_strdup(win_10_0_table
->version_id
);
2214 return g_strdup(win_10_0_table
->version
);
2219 } else if (major
== table
->major
&& minor
== table
->minor
) {
2221 return g_strdup(table
->version_id
);
2223 return g_strdup(table
->version
);
2228 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2230 return g_strdup("N/A");
2233 static char *ga_get_win_product_name(Error
**errp
)
2235 HKEY key
= INVALID_HANDLE_VALUE
;
2237 char *result
= g_malloc0(size
);
2238 LONG err
= ERROR_SUCCESS
;
2240 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
2241 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2243 if (err
!= ERROR_SUCCESS
) {
2244 error_setg_win32(errp
, err
, "failed to open registry key");
2249 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2250 (LPBYTE
)result
, &size
);
2251 if (err
== ERROR_MORE_DATA
) {
2252 slog("ProductName longer than expected (%lu bytes), retrying",
2257 result
= g_malloc0(size
);
2258 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2259 (LPBYTE
)result
, &size
);
2262 if (err
!= ERROR_SUCCESS
) {
2263 error_setg_win32(errp
, err
, "failed to retrive ProductName");
2271 if (key
!= INVALID_HANDLE_VALUE
) {
2278 static char *ga_get_current_arch(void)
2281 GetNativeSystemInfo(&info
);
2282 char *result
= NULL
;
2283 switch (info
.wProcessorArchitecture
) {
2284 case PROCESSOR_ARCHITECTURE_AMD64
:
2285 result
= g_strdup("x86_64");
2287 case PROCESSOR_ARCHITECTURE_ARM
:
2288 result
= g_strdup("arm");
2290 case PROCESSOR_ARCHITECTURE_IA64
:
2291 result
= g_strdup("ia64");
2293 case PROCESSOR_ARCHITECTURE_INTEL
:
2294 result
= g_strdup("x86");
2296 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
2298 slog("unknown processor architecture 0x%0x",
2299 info
.wProcessorArchitecture
);
2300 result
= g_strdup("unknown");
2306 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2308 Error
*local_err
= NULL
;
2309 OSVERSIONINFOEXW os_version
= {0};
2314 ga_get_win_version(&os_version
, &local_err
);
2316 error_propagate(errp
, local_err
);
2320 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
2321 product_name
= ga_get_win_product_name(errp
);
2322 if (product_name
== NULL
) {
2326 info
= g_new0(GuestOSInfo
, 1);
2328 info
->has_kernel_version
= true;
2329 info
->kernel_version
= g_strdup_printf("%lu.%lu",
2330 os_version
.dwMajorVersion
,
2331 os_version
.dwMinorVersion
);
2332 info
->has_kernel_release
= true;
2333 info
->kernel_release
= g_strdup_printf("%lu",
2334 os_version
.dwBuildNumber
);
2335 info
->has_machine
= true;
2336 info
->machine
= ga_get_current_arch();
2338 info
->has_id
= true;
2339 info
->id
= g_strdup("mswindows");
2340 info
->has_name
= true;
2341 info
->name
= g_strdup("Microsoft Windows");
2342 info
->has_pretty_name
= true;
2343 info
->pretty_name
= product_name
;
2344 info
->has_version
= true;
2345 info
->version
= ga_get_win_name(&os_version
, false);
2346 info
->has_version_id
= true;
2347 info
->version_id
= ga_get_win_name(&os_version
, true);
2348 info
->has_variant
= true;
2349 info
->variant
= g_strdup(server
? "server" : "client");
2350 info
->has_variant_id
= true;
2351 info
->variant_id
= g_strdup(server
? "server" : "client");
2357 * Safely get device property. Returned strings are using wide characters.
2358 * Caller is responsible for freeing the buffer.
2360 static LPBYTE
cm_get_property(DEVINST devInst
, const DEVPROPKEY
*propName
,
2361 PDEVPROPTYPE propType
)
2364 g_autofree LPBYTE buffer
= NULL
;
2365 ULONG buffer_len
= 0;
2367 /* First query for needed space */
2368 cr
= CM_Get_DevNode_PropertyW(devInst
, propName
, propType
,
2369 buffer
, &buffer_len
, 0);
2370 if (cr
!= CR_SUCCESS
&& cr
!= CR_BUFFER_SMALL
) {
2372 slog("failed to get property size, error=0x%lx", cr
);
2375 buffer
= g_new0(BYTE
, buffer_len
+ 1);
2376 cr
= CM_Get_DevNode_PropertyW(devInst
, propName
, propType
,
2377 buffer
, &buffer_len
, 0);
2378 if (cr
!= CR_SUCCESS
) {
2379 slog("failed to get device property, error=0x%lx", cr
);
2382 return g_steal_pointer(&buffer
);
2385 static GStrv
ga_get_hardware_ids(DEVINST devInstance
)
2387 GArray
*values
= NULL
;
2388 DEVPROPTYPE cm_type
;
2390 g_autofree LPWSTR property
= (LPWSTR
)cm_get_property(devInstance
,
2391 &qga_DEVPKEY_Device_HardwareIds
, &cm_type
);
2392 if (property
== NULL
) {
2393 slog("failed to get hardware IDs");
2396 if (*property
== '\0') {
2400 values
= g_array_new(TRUE
, TRUE
, sizeof(gchar
*));
2401 for (id
= property
; '\0' != *id
; id
+= lstrlenW(id
) + 1) {
2402 gchar
*id8
= g_utf16_to_utf8(id
, -1, NULL
, NULL
, NULL
);
2403 g_array_append_val(values
, id8
);
2405 return (GStrv
)g_array_free(values
, FALSE
);
2409 * https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
2411 #define DEVICE_PCI_RE "PCI\\\\VEN_(1AF4|1B36)&DEV_([0-9A-B]{4})(&|$)"
2413 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
2415 GuestDeviceInfoList
*head
= NULL
, **tail
= &head
;
2416 HDEVINFO dev_info
= INVALID_HANDLE_VALUE
;
2417 SP_DEVINFO_DATA dev_info_data
;
2419 GError
*gerr
= NULL
;
2420 g_autoptr(GRegex
) device_pci_re
= NULL
;
2421 DEVPROPTYPE cm_type
;
2423 device_pci_re
= g_regex_new(DEVICE_PCI_RE
,
2424 G_REGEX_ANCHORED
| G_REGEX_OPTIMIZE
, 0,
2426 g_assert(device_pci_re
!= NULL
);
2428 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
2429 dev_info
= SetupDiGetClassDevs(0, 0, 0, DIGCF_PRESENT
| DIGCF_ALLCLASSES
);
2430 if (dev_info
== INVALID_HANDLE_VALUE
) {
2431 error_setg(errp
, "failed to get device tree");
2435 slog("enumerating devices");
2436 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
2438 g_autofree LPWSTR name
= NULL
;
2439 g_autofree LPFILETIME date
= NULL
;
2440 g_autofree LPWSTR version
= NULL
;
2441 g_auto(GStrv
) hw_ids
= NULL
;
2442 g_autoptr(GuestDeviceInfo
) device
= g_new0(GuestDeviceInfo
, 1);
2443 g_autofree
char *vendor_id
= NULL
;
2444 g_autofree
char *device_id
= NULL
;
2446 name
= (LPWSTR
)cm_get_property(dev_info_data
.DevInst
,
2447 &qga_DEVPKEY_NAME
, &cm_type
);
2449 slog("failed to get device description");
2452 device
->driver_name
= g_utf16_to_utf8(name
, -1, NULL
, NULL
, NULL
);
2453 if (device
->driver_name
== NULL
) {
2454 error_setg(errp
, "conversion to utf8 failed (driver name)");
2457 slog("querying device: %s", device
->driver_name
);
2458 hw_ids
= ga_get_hardware_ids(dev_info_data
.DevInst
);
2459 if (hw_ids
== NULL
) {
2462 for (j
= 0; hw_ids
[j
] != NULL
; j
++) {
2463 g_autoptr(GMatchInfo
) match_info
;
2464 GuestDeviceIdPCI
*id
;
2465 if (!g_regex_match(device_pci_re
, hw_ids
[j
], 0, &match_info
)) {
2470 vendor_id
= g_match_info_fetch(match_info
, 1);
2471 device_id
= g_match_info_fetch(match_info
, 2);
2473 device
->id
= g_new0(GuestDeviceId
, 1);
2474 device
->has_id
= true;
2475 device
->id
->type
= GUEST_DEVICE_TYPE_PCI
;
2476 id
= &device
->id
->u
.pci
;
2477 id
->vendor_id
= g_ascii_strtoull(vendor_id
, NULL
, 16);
2478 id
->device_id
= g_ascii_strtoull(device_id
, NULL
, 16);
2486 version
= (LPWSTR
)cm_get_property(dev_info_data
.DevInst
,
2487 &qga_DEVPKEY_Device_DriverVersion
, &cm_type
);
2488 if (version
== NULL
) {
2489 slog("failed to get driver version");
2492 device
->driver_version
= g_utf16_to_utf8(version
, -1, NULL
,
2494 if (device
->driver_version
== NULL
) {
2495 error_setg(errp
, "conversion to utf8 failed (driver version)");
2498 device
->has_driver_version
= true;
2500 date
= (LPFILETIME
)cm_get_property(dev_info_data
.DevInst
,
2501 &qga_DEVPKEY_Device_DriverDate
, &cm_type
);
2503 slog("failed to get driver date");
2506 device
->driver_date
= filetime_to_ns(date
);
2507 device
->has_driver_date
= true;
2509 slog("driver: %s\ndriver version: %" PRId64
",%s\n",
2510 device
->driver_name
, device
->driver_date
,
2511 device
->driver_version
);
2512 QAPI_LIST_APPEND(tail
, g_steal_pointer(&device
));
2515 if (dev_info
!= INVALID_HANDLE_VALUE
) {
2516 SetupDiDestroyDeviceInfoList(dev_info
);