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"
26 #include <devpropdef.h>
31 #include "guest-agent-core.h"
32 #include "vss-win32.h"
33 #include "qga-qapi-commands.h"
34 #include "qapi/error.h"
35 #include "qapi/qmp/qerror.h"
36 #include "qemu/queue.h"
37 #include "qemu/host-utils.h"
38 #include "qemu/base64.h"
39 #include "commands-common.h"
42 * The following should be in devpkey.h, but it isn't. The key names were
43 * prefixed to avoid (future) name clashes. Once the definitions get into
44 * mingw the following lines can be removed.
46 DEFINE_DEVPROPKEY(qga_DEVPKEY_NAME
, 0xb725f130, 0x47ef, 0x101a, 0xa5,
47 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac, 10);
48 /* DEVPROP_TYPE_STRING */
49 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_HardwareIds
, 0xa45c254e, 0xdf1c,
50 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 3);
51 /* DEVPROP_TYPE_STRING_LIST */
52 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverDate
, 0xa8b865dd, 0x2e3d,
53 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 2);
54 /* DEVPROP_TYPE_FILETIME */
55 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverVersion
, 0xa8b865dd, 0x2e3d,
56 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 3);
57 /* DEVPROP_TYPE_STRING */
58 /* The CM_Get_DevNode_PropertyW prototype is only sometimes in cfgmgr32.h */
59 #ifndef CM_Get_DevNode_Property
60 #pragma GCC diagnostic push
61 #pragma GCC diagnostic ignored "-Wredundant-decls"
62 CMAPI CONFIGRET WINAPI
CM_Get_DevNode_PropertyW(
64 CONST DEVPROPKEY
* PropertyKey
,
65 DEVPROPTYPE
* PropertyType
,
67 PULONG PropertyBufferSize
,
70 #define CM_Get_DevNode_Property CM_Get_DevNode_PropertyW
71 #pragma GCC diagnostic pop
74 #ifndef SHTDN_REASON_FLAG_PLANNED
75 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
78 /* multiple of 100 nanoseconds elapsed between windows baseline
79 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
80 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
81 (365 * (1970 - 1601) + \
82 (1970 - 1601) / 4 - 3))
84 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
86 struct GuestFileHandle
{
89 QTAILQ_ENTRY(GuestFileHandle
) next
;
93 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
94 } guest_file_state
= {
95 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
98 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
100 typedef struct OpenFlags
{
102 DWORD desired_access
;
103 DWORD creation_disposition
;
105 static OpenFlags guest_file_open_modes
[] = {
106 {"r", GENERIC_READ
, OPEN_EXISTING
},
107 {"rb", GENERIC_READ
, OPEN_EXISTING
},
108 {"w", GENERIC_WRITE
, CREATE_ALWAYS
},
109 {"wb", GENERIC_WRITE
, CREATE_ALWAYS
},
110 {"a", FILE_GENERIC_APPEND
, OPEN_ALWAYS
},
111 {"r+", GENERIC_WRITE
| GENERIC_READ
, OPEN_EXISTING
},
112 {"rb+", GENERIC_WRITE
| GENERIC_READ
, OPEN_EXISTING
},
113 {"r+b", GENERIC_WRITE
| GENERIC_READ
, OPEN_EXISTING
},
114 {"w+", GENERIC_WRITE
| GENERIC_READ
, CREATE_ALWAYS
},
115 {"wb+", GENERIC_WRITE
| GENERIC_READ
, CREATE_ALWAYS
},
116 {"w+b", GENERIC_WRITE
| GENERIC_READ
, CREATE_ALWAYS
},
117 {"a+", FILE_GENERIC_APPEND
| GENERIC_READ
, OPEN_ALWAYS
},
118 {"ab+", FILE_GENERIC_APPEND
| GENERIC_READ
, OPEN_ALWAYS
},
119 {"a+b", FILE_GENERIC_APPEND
| GENERIC_READ
, OPEN_ALWAYS
}
122 #define debug_error(msg) do { \
123 char *suffix = g_win32_error_message(GetLastError()); \
124 g_debug("%s: %s", (msg), suffix); \
128 static OpenFlags
*find_open_flag(const char *mode_str
)
133 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
134 OpenFlags
*flags
= guest_file_open_modes
+ mode
;
136 if (strcmp(flags
->forms
, mode_str
) == 0) {
141 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
145 static int64_t guest_file_handle_add(HANDLE fh
, Error
**errp
)
147 GuestFileHandle
*gfh
;
150 handle
= ga_get_fd_handle(ga_state
, errp
);
154 gfh
= g_new0(GuestFileHandle
, 1);
157 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
162 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
164 GuestFileHandle
*gfh
;
165 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
) {
170 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
174 static void handle_set_nonblocking(HANDLE fh
)
176 DWORD file_type
, pipe_state
;
177 file_type
= GetFileType(fh
);
178 if (file_type
!= FILE_TYPE_PIPE
) {
181 /* If file_type == FILE_TYPE_PIPE, according to MSDN
182 * the specified file is socket or named pipe */
183 if (!GetNamedPipeHandleState(fh
, &pipe_state
, NULL
,
184 NULL
, NULL
, NULL
, 0)) {
187 /* The fd is named pipe fd */
188 if (pipe_state
& PIPE_NOWAIT
) {
192 pipe_state
|= PIPE_NOWAIT
;
193 SetNamedPipeHandleState(fh
, &pipe_state
, NULL
, NULL
);
196 int64_t qmp_guest_file_open(const char *path
, const char *mode
, Error
**errp
)
200 HANDLE templ_file
= NULL
;
201 DWORD share_mode
= FILE_SHARE_READ
;
202 DWORD flags_and_attr
= FILE_ATTRIBUTE_NORMAL
;
203 LPSECURITY_ATTRIBUTES sa_attr
= NULL
;
204 OpenFlags
*guest_flags
;
206 wchar_t *w_path
= NULL
;
211 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
212 guest_flags
= find_open_flag(mode
);
213 if (guest_flags
== NULL
) {
214 error_setg(errp
, "invalid file open mode");
218 w_path
= g_utf8_to_utf16(path
, -1, NULL
, NULL
, &gerr
);
223 fh
= CreateFileW(w_path
, guest_flags
->desired_access
, share_mode
, sa_attr
,
224 guest_flags
->creation_disposition
, flags_and_attr
,
226 if (fh
== INVALID_HANDLE_VALUE
) {
227 error_setg_win32(errp
, GetLastError(), "failed to open file '%s'",
232 /* set fd non-blocking to avoid common use cases (like reading from a
233 * named pipe) from hanging the agent
235 handle_set_nonblocking(fh
);
237 fd
= guest_file_handle_add(fh
, errp
);
240 error_setg(errp
, "failed to add handle to qmp handle table");
244 slog("guest-file-open, handle: % " PRId64
, fd
);
248 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
255 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
258 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
259 slog("guest-file-close called, handle: %" PRId64
, handle
);
263 ret
= CloseHandle(gfh
->fh
);
265 error_setg_win32(errp
, GetLastError(), "failed close handle");
269 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
273 static void acquire_privilege(const char *name
, Error
**errp
)
276 TOKEN_PRIVILEGES priv
;
278 if (OpenProcessToken(GetCurrentProcess(),
279 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &token
))
281 if (!LookupPrivilegeValue(NULL
, name
, &priv
.Privileges
[0].Luid
)) {
282 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
283 "no luid for requested privilege");
287 priv
.PrivilegeCount
= 1;
288 priv
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
290 if (!AdjustTokenPrivileges(token
, FALSE
, &priv
, 0, NULL
, 0)) {
291 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
292 "unable to acquire requested privilege");
297 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
298 "failed to open privilege token");
307 static void execute_async(DWORD
WINAPI (*func
)(LPVOID
), LPVOID opaque
,
310 HANDLE thread
= CreateThread(NULL
, 0, func
, opaque
, 0, NULL
);
312 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
313 "failed to dispatch asynchronous command");
317 void qmp_guest_shutdown(const char *mode
, Error
**errp
)
319 Error
*local_err
= NULL
;
320 UINT shutdown_flag
= EWX_FORCE
;
322 slog("guest-shutdown called, mode: %s", mode
);
324 if (!mode
|| strcmp(mode
, "powerdown") == 0) {
325 shutdown_flag
|= EWX_POWEROFF
;
326 } else if (strcmp(mode
, "halt") == 0) {
327 shutdown_flag
|= EWX_SHUTDOWN
;
328 } else if (strcmp(mode
, "reboot") == 0) {
329 shutdown_flag
|= EWX_REBOOT
;
331 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "mode",
332 "'halt', 'powerdown', or 'reboot'");
336 /* Request a shutdown privilege, but try to shut down the system
338 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
340 error_propagate(errp
, local_err
);
344 if (!ExitWindowsEx(shutdown_flag
, SHTDN_REASON_FLAG_PLANNED
)) {
345 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
346 slog("guest-shutdown failed: %s", emsg
);
347 error_setg_win32(errp
, GetLastError(), "guest-shutdown failed");
351 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
352 int64_t count
, Error
**errp
)
354 GuestFileRead
*read_data
= NULL
;
360 buf
= g_malloc0(count
+ 1);
361 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
363 error_setg_win32(errp
, GetLastError(), "failed to read file");
366 read_data
= g_new0(GuestFileRead
, 1);
367 read_data
->count
= (size_t)read_count
;
368 read_data
->eof
= read_count
== 0;
370 if (read_count
!= 0) {
371 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
379 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
380 bool has_count
, int64_t count
,
383 GuestFileWrite
*write_data
= NULL
;
388 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
395 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
402 } else if (count
< 0 || count
> buf_len
) {
403 error_setg(errp
, "value '%" PRId64
404 "' is invalid for argument count", count
);
408 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
410 error_setg_win32(errp
, GetLastError(), "failed to write to file");
411 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
413 write_data
= g_new0(GuestFileWrite
, 1);
414 write_data
->count
= (size_t) write_count
;
422 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
423 GuestFileWhence
*whence_code
,
426 GuestFileHandle
*gfh
;
427 GuestFileSeek
*seek_data
;
429 LARGE_INTEGER new_pos
, off_pos
;
430 off_pos
.QuadPart
= offset
;
435 gfh
= guest_file_handle_find(handle
, errp
);
440 /* We stupidly exposed 'whence':'int' in our qapi */
441 whence
= ga_parse_whence(whence_code
, &err
);
443 error_propagate(errp
, err
);
448 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
450 error_setg_win32(errp
, GetLastError(), "failed to seek file");
453 seek_data
= g_new0(GuestFileSeek
, 1);
454 seek_data
->position
= new_pos
.QuadPart
;
458 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
461 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
467 if (!FlushFileBuffers(fh
)) {
468 error_setg_win32(errp
, GetLastError(), "failed to flush file");
472 static GuestDiskBusType win2qemu
[] = {
473 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
474 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
475 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
476 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
477 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
478 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
479 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
480 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
481 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
482 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
483 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
484 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
485 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
486 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
487 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
488 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
490 * BusTypeSpaces currently is not supported
492 [BusTypeSpaces
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
493 [BusTypeNvme
] = GUEST_DISK_BUS_TYPE_NVME
,
496 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
498 if (bus
>= ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
499 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
501 return win2qemu
[(int)bus
];
504 static void get_pci_address_for_device(GuestPCIAddress
*pci
,
507 SP_DEVINFO_DATA dev_info_data
;
510 bool partial_pci
= false;
512 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
515 SetupDiEnumDeviceInfo(dev_info
, j
, &dev_info_data
);
517 DWORD addr
, bus
, ui_slot
, type
;
519 size
= sizeof(DWORD
);
522 * There is no need to allocate buffer in the next functions. The
523 * size is known and ULONG according to
524 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
526 if (!SetupDiGetDeviceRegistryProperty(
527 dev_info
, &dev_info_data
, SPDRP_BUSNUMBER
,
528 &type
, (PBYTE
)&bus
, size
, NULL
)) {
529 debug_error("failed to get PCI bus");
535 * The function retrieves the device's address. This value will be
536 * transformed into device function and number
538 if (!SetupDiGetDeviceRegistryProperty(
539 dev_info
, &dev_info_data
, SPDRP_ADDRESS
,
540 &type
, (PBYTE
)&addr
, size
, NULL
)) {
541 debug_error("failed to get PCI address");
547 * This call returns UINumber of DEVICE_CAPABILITIES structure.
548 * This number is typically a user-perceived slot number.
550 if (!SetupDiGetDeviceRegistryProperty(
551 dev_info
, &dev_info_data
, SPDRP_UI_NUMBER
,
552 &type
, (PBYTE
)&ui_slot
, size
, NULL
)) {
553 debug_error("failed to get PCI slot");
559 * SetupApi gives us the same information as driver with
560 * IoGetDeviceProperty. According to Microsoft:
562 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
563 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
564 * SPDRP_ADDRESS is propertyAddress, so we do the same.
566 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
575 func
= ((int)addr
== -1) ? -1 : addr
& 0x0000FFFF;
576 slot
= ((int)addr
== -1) ? -1 : (addr
>> 16) & 0x0000FFFF;
577 if ((int)ui_slot
!= slot
) {
578 g_debug("mismatch with reported slot values: %d vs %d",
582 pci
->slot
= (int)ui_slot
;
583 pci
->function
= func
;
590 static GuestPCIAddress
*get_empty_pci_address(void)
592 GuestPCIAddress
*pci
= NULL
;
594 pci
= g_malloc0(sizeof(*pci
));
602 static GuestPCIAddress
*get_pci_info(int number
, Error
**errp
)
604 HDEVINFO dev_info
= INVALID_HANDLE_VALUE
;
605 HDEVINFO parent_dev_info
= INVALID_HANDLE_VALUE
;
607 SP_DEVINFO_DATA dev_info_data
;
608 SP_DEVICE_INTERFACE_DATA dev_iface_data
;
611 GuestPCIAddress
*pci
= get_empty_pci_address();
613 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK
, 0, 0,
614 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
615 if (dev_info
== INVALID_HANDLE_VALUE
) {
616 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
620 g_debug("enumerating devices");
621 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
622 dev_iface_data
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
623 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
624 g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data
= NULL
;
625 STORAGE_DEVICE_NUMBER sdn
;
626 g_autofree
char *parent_dev_id
= NULL
;
627 SP_DEVINFO_DATA parent_dev_info_data
;
630 g_debug("getting device path");
631 if (SetupDiEnumDeviceInterfaces(dev_info
, &dev_info_data
,
632 &GUID_DEVINTERFACE_DISK
, 0,
634 if (!SetupDiGetDeviceInterfaceDetail(dev_info
, &dev_iface_data
,
635 pdev_iface_detail_data
,
638 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
639 pdev_iface_detail_data
= g_malloc(size
);
640 pdev_iface_detail_data
->cbSize
=
641 sizeof(*pdev_iface_detail_data
);
643 error_setg_win32(errp
, GetLastError(),
644 "failed to get device interfaces");
649 if (!SetupDiGetDeviceInterfaceDetail(dev_info
, &dev_iface_data
,
650 pdev_iface_detail_data
,
653 // pdev_iface_detail_data already is allocated
654 error_setg_win32(errp
, GetLastError(),
655 "failed to get device interfaces");
659 dev_file
= CreateFile(pdev_iface_detail_data
->DevicePath
, 0,
660 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0,
663 if (!DeviceIoControl(dev_file
, IOCTL_STORAGE_GET_DEVICE_NUMBER
,
664 NULL
, 0, &sdn
, sizeof(sdn
), &size
, NULL
)) {
665 CloseHandle(dev_file
);
666 error_setg_win32(errp
, GetLastError(),
667 "failed to get device slot number");
671 CloseHandle(dev_file
);
672 if (sdn
.DeviceNumber
!= number
) {
676 error_setg_win32(errp
, GetLastError(),
677 "failed to get device interfaces");
681 g_debug("found device slot %d. Getting storage controller", number
);
684 DEVINST dev_inst
, parent_dev_inst
;
685 ULONG dev_id_size
= 0;
688 if (!SetupDiGetDeviceInstanceId(dev_info
, &dev_info_data
,
689 parent_dev_id
, size
, &size
)) {
690 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
691 parent_dev_id
= g_malloc(size
);
693 error_setg_win32(errp
, GetLastError(),
694 "failed to get device instance ID");
699 if (!SetupDiGetDeviceInstanceId(dev_info
, &dev_info_data
,
700 parent_dev_id
, size
, &size
)) {
701 // parent_dev_id already is allocated
702 error_setg_win32(errp
, GetLastError(),
703 "failed to get device instance ID");
708 * CM API used here as opposed to
709 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
710 * which exports are only available in mingw-w64 6+
712 cr
= CM_Locate_DevInst(&dev_inst
, parent_dev_id
, 0);
713 if (cr
!= CR_SUCCESS
) {
714 g_error("CM_Locate_DevInst failed with code %lx", cr
);
715 error_setg_win32(errp
, GetLastError(),
716 "failed to get device instance");
719 cr
= CM_Get_Parent(&parent_dev_inst
, dev_inst
, 0);
720 if (cr
!= CR_SUCCESS
) {
721 g_error("CM_Get_Parent failed with code %lx", cr
);
722 error_setg_win32(errp
, GetLastError(),
723 "failed to get parent device instance");
727 cr
= CM_Get_Device_ID_Size(&dev_id_size
, parent_dev_inst
, 0);
728 if (cr
!= CR_SUCCESS
) {
729 g_error("CM_Get_Device_ID_Size failed with code %lx", cr
);
730 error_setg_win32(errp
, GetLastError(),
731 "failed to get parent device ID length");
736 if (dev_id_size
> size
) {
737 g_free(parent_dev_id
);
738 parent_dev_id
= g_malloc(dev_id_size
);
741 cr
= CM_Get_Device_ID(parent_dev_inst
, parent_dev_id
, dev_id_size
,
743 if (cr
!= CR_SUCCESS
) {
744 g_error("CM_Get_Device_ID failed with code %lx", cr
);
745 error_setg_win32(errp
, GetLastError(),
746 "failed to get parent device ID");
751 g_debug("querying storage controller %s for PCI information",
754 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT
, parent_dev_id
,
755 NULL
, DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
757 if (parent_dev_info
== INVALID_HANDLE_VALUE
) {
758 error_setg_win32(errp
, GetLastError(),
759 "failed to get parent device");
763 parent_dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
764 if (!SetupDiEnumDeviceInfo(parent_dev_info
, 0, &parent_dev_info_data
)) {
765 error_setg_win32(errp
, GetLastError(),
766 "failed to get parent device data");
770 get_pci_address_for_device(pci
, parent_dev_info
);
776 if (parent_dev_info
!= INVALID_HANDLE_VALUE
) {
777 SetupDiDestroyDeviceInfoList(parent_dev_info
);
779 if (dev_info
!= INVALID_HANDLE_VALUE
) {
780 SetupDiDestroyDeviceInfoList(dev_info
);
785 static void get_disk_properties(HANDLE vol_h
, GuestDiskAddress
*disk
,
788 STORAGE_PROPERTY_QUERY query
;
789 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
791 ULONG size
= sizeof(buf
);
794 query
.PropertyId
= StorageDeviceProperty
;
795 query
.QueryType
= PropertyStandardQuery
;
797 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
798 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
799 size
, &received
, NULL
)) {
800 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
803 disk
->bus_type
= find_bus_type(dev_desc
->BusType
);
804 g_debug("bus type %d", disk
->bus_type
);
806 /* Query once more. Now with long enough buffer. */
807 size
= dev_desc
->Size
;
808 dev_desc
= g_malloc0(size
);
809 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
810 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
811 size
, &received
, NULL
)) {
812 error_setg_win32(errp
, GetLastError(), "failed to get serial number");
813 g_debug("failed to get serial number");
816 if (dev_desc
->SerialNumberOffset
> 0) {
820 if (dev_desc
->SerialNumberOffset
>= received
) {
821 error_setg(errp
, "failed to get serial number: offset outside the buffer");
822 g_debug("serial number offset outside the buffer");
825 serial
= (char *)dev_desc
+ dev_desc
->SerialNumberOffset
;
826 len
= received
- dev_desc
->SerialNumberOffset
;
827 g_debug("serial number \"%s\"", serial
);
829 disk
->serial
= g_strndup(serial
, len
);
838 static void get_single_disk_info(int disk_number
,
839 GuestDiskAddress
*disk
, Error
**errp
)
841 SCSI_ADDRESS addr
, *scsi_ad
;
844 Error
*local_err
= NULL
;
848 g_debug("getting disk info for: %s", disk
->dev
);
849 disk_h
= CreateFile(disk
->dev
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
851 if (disk_h
== INVALID_HANDLE_VALUE
) {
852 error_setg_win32(errp
, GetLastError(), "failed to open disk");
856 get_disk_properties(disk_h
, disk
, &local_err
);
858 error_propagate(errp
, local_err
);
862 g_debug("bus type %d", disk
->bus_type
);
863 /* always set pci_controller as required by schema. get_pci_info() should
864 * report -1 values for non-PCI buses rather than fail. fail the command
865 * if that doesn't hold since that suggests some other unexpected
868 if (disk
->bus_type
== GUEST_DISK_BUS_TYPE_USB
) {
869 disk
->pci_controller
= get_empty_pci_address();
871 disk
->pci_controller
= get_pci_info(disk_number
, &local_err
);
873 error_propagate(errp
, local_err
);
877 if (disk
->bus_type
== GUEST_DISK_BUS_TYPE_SCSI
878 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_IDE
879 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_RAID
880 /* This bus type is not supported before Windows Server 2003 SP1 */
881 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_SAS
883 /* We are able to use the same ioctls for different bus types
884 * according to Microsoft docs
885 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
886 g_debug("getting SCSI info");
887 if (DeviceIoControl(disk_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
888 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
889 disk
->unit
= addr
.Lun
;
890 disk
->target
= addr
.TargetId
;
891 disk
->bus
= addr
.PathId
;
893 /* We do not set error in this case, because we still have enough
894 * information about volume. */
902 /* VSS provider works with volumes, thus there is no difference if
903 * the volume consist of spanned disks. Info about the first disk in the
904 * volume is returned for the spanned disk group (LVM) */
905 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
907 Error
*local_err
= NULL
;
908 GuestDiskAddressList
*list
= NULL
;
909 GuestDiskAddress
*disk
= NULL
;
913 PVOLUME_DISK_EXTENTS extents
= NULL
;
915 /* strip final backslash */
916 char *name
= g_strdup(guid
);
917 if (g_str_has_suffix(name
, "\\")) {
918 name
[strlen(name
) - 1] = 0;
921 g_debug("opening %s", name
);
922 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
924 if (vol_h
== INVALID_HANDLE_VALUE
) {
925 error_setg_win32(errp
, GetLastError(), "failed to open volume");
929 /* Get list of extents */
930 g_debug("getting disk extents");
931 size
= sizeof(VOLUME_DISK_EXTENTS
);
932 extents
= g_malloc0(size
);
933 if (!DeviceIoControl(vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
934 0, extents
, size
, &size
, NULL
)) {
935 DWORD last_err
= GetLastError();
936 if (last_err
== ERROR_MORE_DATA
) {
937 /* Try once more with big enough buffer */
939 extents
= g_malloc0(size
);
940 if (!DeviceIoControl(
941 vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
942 0, extents
, size
, NULL
, NULL
)) {
943 error_setg_win32(errp
, GetLastError(),
944 "failed to get disk extents");
947 } else if (last_err
== ERROR_INVALID_FUNCTION
) {
948 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
949 g_debug("volume not on disk");
950 disk
= g_new0(GuestDiskAddress
, 1);
951 disk
->dev
= g_strdup(name
);
952 get_single_disk_info(0xffffffff, disk
, &local_err
);
954 g_debug("failed to get disk info, ignoring error: %s",
955 error_get_pretty(local_err
));
956 error_free(local_err
);
959 QAPI_LIST_PREPEND(list
, disk
);
963 error_setg_win32(errp
, GetLastError(),
964 "failed to get disk extents");
968 g_debug("Number of extents: %lu", extents
->NumberOfDiskExtents
);
970 /* Go through each extent */
971 for (i
= 0; i
< extents
->NumberOfDiskExtents
; i
++) {
972 disk
= g_new0(GuestDiskAddress
, 1);
974 /* Disk numbers directly correspond to numbers used in UNCs
976 * See documentation for DISK_EXTENT:
977 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
979 * See also Naming Files, Paths and Namespaces:
980 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
982 disk
->dev
= g_strdup_printf("\\\\.\\PhysicalDrive%lu",
983 extents
->Extents
[i
].DiskNumber
);
985 get_single_disk_info(extents
->Extents
[i
].DiskNumber
, disk
, &local_err
);
987 error_propagate(errp
, local_err
);
990 QAPI_LIST_PREPEND(list
, disk
);
996 if (vol_h
!= INVALID_HANDLE_VALUE
) {
999 qapi_free_GuestDiskAddress(disk
);
1006 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1008 GuestDiskInfoList
*ret
= NULL
;
1010 SP_DEVICE_INTERFACE_DATA dev_iface_data
;
1013 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK
, 0, 0,
1014 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
1015 if (dev_info
== INVALID_HANDLE_VALUE
) {
1016 error_setg_win32(errp
, GetLastError(), "failed to get device tree");
1020 g_debug("enumerating devices");
1021 dev_iface_data
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
1023 SetupDiEnumDeviceInterfaces(dev_info
, NULL
, &GUID_DEVINTERFACE_DISK
,
1024 i
, &dev_iface_data
);
1026 GuestDiskAddress
*address
= NULL
;
1027 GuestDiskInfo
*disk
= NULL
;
1028 Error
*local_err
= NULL
;
1029 g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA
1030 pdev_iface_detail_data
= NULL
;
1031 STORAGE_DEVICE_NUMBER sdn
;
1037 g_debug(" getting device path");
1038 for (attempt
= 0, result
= FALSE
; attempt
< 2 && !result
; attempt
++) {
1039 result
= SetupDiGetDeviceInterfaceDetail(dev_info
,
1040 &dev_iface_data
, pdev_iface_detail_data
, size
, &size
, NULL
);
1044 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
1045 pdev_iface_detail_data
= g_realloc(pdev_iface_detail_data
,
1047 pdev_iface_detail_data
->cbSize
=
1048 sizeof(*pdev_iface_detail_data
);
1050 g_debug("failed to get device interface details");
1055 g_debug("skipping device");
1059 g_debug(" device: %s", pdev_iface_detail_data
->DevicePath
);
1060 dev_file
= CreateFile(pdev_iface_detail_data
->DevicePath
, 0,
1061 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, NULL
);
1062 if (!DeviceIoControl(dev_file
, IOCTL_STORAGE_GET_DEVICE_NUMBER
,
1063 NULL
, 0, &sdn
, sizeof(sdn
), &size
, NULL
)) {
1064 CloseHandle(dev_file
);
1065 debug_error("failed to get storage device number");
1068 CloseHandle(dev_file
);
1070 disk
= g_new0(GuestDiskInfo
, 1);
1071 disk
->name
= g_strdup_printf("\\\\.\\PhysicalDrive%lu",
1074 g_debug(" number: %lu", sdn
.DeviceNumber
);
1075 address
= g_new0(GuestDiskAddress
, 1);
1076 address
->dev
= g_strdup(disk
->name
);
1077 get_single_disk_info(sdn
.DeviceNumber
, address
, &local_err
);
1079 g_debug("failed to get disk info: %s",
1080 error_get_pretty(local_err
));
1081 error_free(local_err
);
1082 qapi_free_GuestDiskAddress(address
);
1085 disk
->address
= address
;
1088 QAPI_LIST_PREPEND(ret
, disk
);
1091 SetupDiDestroyDeviceInfoList(dev_info
);
1095 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
1098 char mnt
, *mnt_point
;
1099 wchar_t wfs_name
[32];
1101 wchar_t vol_info
[MAX_PATH
+ 1];
1103 uint64_t i64FreeBytesToCaller
, i64TotalBytes
, i64FreeBytes
;
1104 GuestFilesystemInfo
*fs
= NULL
;
1105 HANDLE hLocalDiskHandle
= INVALID_HANDLE_VALUE
;
1107 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
1108 if (GetLastError() != ERROR_MORE_DATA
) {
1109 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
1113 mnt_point
= g_malloc(info_size
+ 1);
1114 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
1116 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
1120 hLocalDiskHandle
= CreateFile(guid
, 0 , 0, NULL
, OPEN_EXISTING
,
1121 FILE_ATTRIBUTE_NORMAL
|
1122 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1123 if (INVALID_HANDLE_VALUE
== hLocalDiskHandle
) {
1124 error_setg_win32(errp
, GetLastError(), "failed to get handle for volume");
1128 len
= strlen(mnt_point
);
1129 mnt_point
[len
] = '\\';
1130 mnt_point
[len
+ 1] = 0;
1132 if (!GetVolumeInformationByHandleW(hLocalDiskHandle
, vol_info
,
1133 sizeof(vol_info
), NULL
, NULL
, NULL
,
1134 (LPWSTR
) & wfs_name
, sizeof(wfs_name
))) {
1135 if (GetLastError() != ERROR_NOT_READY
) {
1136 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
1141 fs
= g_malloc(sizeof(*fs
));
1142 fs
->name
= g_strdup(guid
);
1143 fs
->has_total_bytes
= false;
1144 fs
->has_used_bytes
= false;
1146 fs
->mountpoint
= g_strdup("System Reserved");
1148 fs
->mountpoint
= g_strndup(mnt_point
, len
);
1149 if (GetDiskFreeSpaceEx(fs
->mountpoint
,
1150 (PULARGE_INTEGER
) & i64FreeBytesToCaller
,
1151 (PULARGE_INTEGER
) & i64TotalBytes
,
1152 (PULARGE_INTEGER
) & i64FreeBytes
)) {
1153 fs
->used_bytes
= i64TotalBytes
- i64FreeBytes
;
1154 fs
->total_bytes
= i64TotalBytes
;
1155 fs
->has_total_bytes
= true;
1156 fs
->has_used_bytes
= true;
1159 wcstombs(fs_name
, wfs_name
, sizeof(wfs_name
));
1160 fs
->type
= g_strdup(fs_name
);
1161 fs
->disk
= build_guest_disk_info(guid
, errp
);
1163 if (hLocalDiskHandle
!= INVALID_HANDLE_VALUE
) {
1164 CloseHandle(hLocalDiskHandle
);
1170 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1173 GuestFilesystemInfoList
*ret
= NULL
;
1176 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
1177 if (vol_h
== INVALID_HANDLE_VALUE
) {
1178 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1183 Error
*local_err
= NULL
;
1184 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, &local_err
);
1186 g_debug("failed to get filesystem info, ignoring error: %s",
1187 error_get_pretty(local_err
));
1188 error_free(local_err
);
1191 QAPI_LIST_PREPEND(ret
, info
);
1192 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
1194 if (GetLastError() != ERROR_NO_MORE_FILES
) {
1195 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
1198 FindVolumeClose(vol_h
);
1203 * Return status of freeze/thaw
1205 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1207 if (!vss_initialized()) {
1208 error_setg(errp
, QERR_UNSUPPORTED
);
1212 if (ga_is_frozen(ga_state
)) {
1213 return GUEST_FSFREEZE_STATUS_FROZEN
;
1216 return GUEST_FSFREEZE_STATUS_THAWED
;
1220 * Freeze local file systems using Volume Shadow-copy Service.
1221 * The frozen state is limited for up to 10 seconds by VSS.
1223 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1225 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1228 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1229 strList
*mountpoints
,
1233 Error
*local_err
= NULL
;
1235 if (!vss_initialized()) {
1236 error_setg(errp
, QERR_UNSUPPORTED
);
1240 slog("guest-fsfreeze called");
1242 /* cannot risk guest agent blocking itself on a write in this state */
1243 ga_set_frozen(ga_state
);
1245 qga_vss_fsfreeze(&i
, true, mountpoints
, &local_err
);
1247 error_propagate(errp
, local_err
);
1255 qmp_guest_fsfreeze_thaw(&local_err
);
1257 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
1258 error_free(local_err
);
1264 * Thaw local file systems using Volume Shadow-copy Service.
1266 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1270 if (!vss_initialized()) {
1271 error_setg(errp
, QERR_UNSUPPORTED
);
1275 qga_vss_fsfreeze(&i
, false, NULL
, errp
);
1277 ga_unset_frozen(ga_state
);
1281 static void guest_fsfreeze_cleanup(void)
1285 if (!vss_initialized()) {
1289 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1290 qmp_guest_fsfreeze_thaw(&err
);
1292 slog("failed to clean up frozen filesystems: %s",
1293 error_get_pretty(err
));
1302 * Walk list of mounted file systems in the guest, and discard unused
1305 GuestFilesystemTrimResponse
*
1306 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1308 GuestFilesystemTrimResponse
*resp
;
1310 WCHAR guid
[MAX_PATH
] = L
"";
1314 ZeroMemory(&osvi
, sizeof(OSVERSIONINFO
));
1315 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1316 GetVersionEx(&osvi
);
1317 win8_or_later
= (osvi
.dwMajorVersion
> 6 ||
1318 ((osvi
.dwMajorVersion
== 6) &&
1319 (osvi
.dwMinorVersion
>= 2)));
1320 if (!win8_or_later
) {
1321 error_setg(errp
, "fstrim is only supported for Win8+");
1325 handle
= FindFirstVolumeW(guid
, ARRAYSIZE(guid
));
1326 if (handle
== INVALID_HANDLE_VALUE
) {
1327 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1331 resp
= g_new0(GuestFilesystemTrimResponse
, 1);
1334 GuestFilesystemTrimResult
*res
;
1336 DWORD char_count
= 0;
1338 GError
*gerr
= NULL
;
1341 GetVolumePathNamesForVolumeNameW(guid
, NULL
, 0, &char_count
);
1343 if (GetLastError() != ERROR_MORE_DATA
) {
1346 if (GetDriveTypeW(guid
) != DRIVE_FIXED
) {
1350 uc_path
= g_new(WCHAR
, char_count
);
1351 if (!GetVolumePathNamesForVolumeNameW(guid
, uc_path
, char_count
,
1352 &char_count
) || !*uc_path
) {
1353 /* strange, but this condition could be faced even with size == 2 */
1358 res
= g_new0(GuestFilesystemTrimResult
, 1);
1360 path
= g_utf16_to_utf8(uc_path
, char_count
, NULL
, NULL
, &gerr
);
1365 res
->error
= g_strdup(gerr
->message
);
1372 QAPI_LIST_PREPEND(resp
->paths
, res
);
1374 memset(argv
, 0, sizeof(argv
));
1375 argv
[0] = (gchar
*)"defrag.exe";
1376 argv
[1] = (gchar
*)"/L";
1379 if (!g_spawn_sync(NULL
, argv
, NULL
, G_SPAWN_SEARCH_PATH
, NULL
, NULL
,
1380 &out
/* stdout */, NULL
/* stdin */,
1382 res
->error
= g_strdup(gerr
->message
);
1385 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1386 Error is reported in the output with something like
1387 (x89000020) etc code in the stdout */
1390 gchar
**lines
= g_strsplit(out
, "\r\n", 0);
1393 for (i
= 0; lines
[i
] != NULL
; i
++) {
1394 if (g_strstr_len(lines
[i
], -1, "(0x") == NULL
) {
1397 res
->error
= g_strdup(lines
[i
]);
1402 } while (FindNextVolumeW(handle
, guid
, ARRAYSIZE(guid
)));
1404 FindVolumeClose(handle
);
1409 GUEST_SUSPEND_MODE_DISK
,
1410 GUEST_SUSPEND_MODE_RAM
1413 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
1415 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
1417 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
1418 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
1419 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1420 "failed to determine guest suspend capabilities");
1425 case GUEST_SUSPEND_MODE_DISK
:
1426 if (!sys_pwr_caps
.SystemS4
) {
1427 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1428 "suspend-to-disk not supported by OS");
1431 case GUEST_SUSPEND_MODE_RAM
:
1432 if (!sys_pwr_caps
.SystemS3
) {
1433 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1434 "suspend-to-ram not supported by OS");
1442 static DWORD WINAPI
do_suspend(LPVOID opaque
)
1444 GuestSuspendMode
*mode
= opaque
;
1447 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
1448 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
1449 slog("failed to suspend guest: %s", emsg
);
1456 void qmp_guest_suspend_disk(Error
**errp
)
1458 Error
*local_err
= NULL
;
1459 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1461 *mode
= GUEST_SUSPEND_MODE_DISK
;
1462 check_suspend_mode(*mode
, &local_err
);
1466 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1470 execute_async(do_suspend
, mode
, &local_err
);
1474 error_propagate(errp
, local_err
);
1479 void qmp_guest_suspend_ram(Error
**errp
)
1481 Error
*local_err
= NULL
;
1482 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1484 *mode
= GUEST_SUSPEND_MODE_RAM
;
1485 check_suspend_mode(*mode
, &local_err
);
1489 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1493 execute_async(do_suspend
, mode
, &local_err
);
1497 error_propagate(errp
, local_err
);
1502 void qmp_guest_suspend_hybrid(Error
**errp
)
1504 error_setg(errp
, QERR_UNSUPPORTED
);
1507 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
1509 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
1510 ULONG adptr_addrs_len
= 0;
1513 /* Call the first time to get the adptr_addrs_len. */
1514 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1515 NULL
, adptr_addrs
, &adptr_addrs_len
);
1517 adptr_addrs
= g_malloc(adptr_addrs_len
);
1518 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1519 NULL
, adptr_addrs
, &adptr_addrs_len
);
1520 if (ret
!= ERROR_SUCCESS
) {
1521 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
1522 g_free(adptr_addrs
);
1528 static char *guest_wctomb_dup(WCHAR
*wstr
)
1533 str_size
= WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, NULL
, 0, NULL
, NULL
);
1534 /* add 1 to str_size for NULL terminator */
1535 str
= g_malloc(str_size
+ 1);
1536 WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, str
, str_size
, NULL
, NULL
);
1540 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
1543 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
1547 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
1548 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1549 len
= sizeof(addr_str
);
1550 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
1551 ip_addr
->Address
.iSockaddrLength
,
1556 error_setg_win32(errp
, WSAGetLastError(),
1557 "failed address presentation form conversion");
1560 return g_strdup(addr_str
);
1565 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1567 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1568 * field to obtain the prefix.
1570 return ip_addr
->OnLinkPrefixLength
;
1573 #define INTERFACE_PATH_BUF_SZ 512
1575 static DWORD
get_interface_index(const char *guid
)
1579 wchar_t wbuf
[INTERFACE_PATH_BUF_SZ
];
1580 snwprintf(wbuf
, INTERFACE_PATH_BUF_SZ
, L
"\\device\\tcpip_%s", guid
);
1581 wbuf
[INTERFACE_PATH_BUF_SZ
- 1] = 0;
1582 status
= GetAdapterIndex (wbuf
, &index
);
1583 if (status
!= NO_ERROR
) {
1590 typedef NETIOAPI_API (WINAPI
*GetIfEntry2Func
)(PMIB_IF_ROW2 Row
);
1592 static int guest_get_network_stats(const char *name
,
1593 GuestNetworkInterfaceStat
*stats
)
1595 OSVERSIONINFO os_ver
;
1597 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1598 GetVersionEx(&os_ver
);
1599 if (os_ver
.dwMajorVersion
>= 6) {
1600 MIB_IF_ROW2 a_mid_ifrow
;
1601 GetIfEntry2Func getifentry2_ex
;
1603 HMODULE module
= GetModuleHandle("iphlpapi");
1604 PVOID func
= GetProcAddress(module
, "GetIfEntry2");
1610 getifentry2_ex
= (GetIfEntry2Func
)func
;
1611 if_index
= get_interface_index(name
);
1612 if (if_index
== (DWORD
)~0) {
1616 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1617 a_mid_ifrow
.InterfaceIndex
= if_index
;
1618 if (NO_ERROR
== getifentry2_ex(&a_mid_ifrow
)) {
1619 stats
->rx_bytes
= a_mid_ifrow
.InOctets
;
1620 stats
->rx_packets
= a_mid_ifrow
.InUcastPkts
;
1621 stats
->rx_errs
= a_mid_ifrow
.InErrors
;
1622 stats
->rx_dropped
= a_mid_ifrow
.InDiscards
;
1623 stats
->tx_bytes
= a_mid_ifrow
.OutOctets
;
1624 stats
->tx_packets
= a_mid_ifrow
.OutUcastPkts
;
1625 stats
->tx_errs
= a_mid_ifrow
.OutErrors
;
1626 stats
->tx_dropped
= a_mid_ifrow
.OutDiscards
;
1633 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1635 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1636 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1637 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
1638 GuestIpAddressList
*head_addr
, **tail_addr
;
1639 GuestNetworkInterface
*info
;
1640 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1641 GuestIpAddress
*address_item
= NULL
;
1642 unsigned char *mac_addr
;
1648 adptr_addrs
= guest_get_adapters_addresses(errp
);
1649 if (adptr_addrs
== NULL
) {
1653 /* Make WSA APIs available. */
1654 wsa_version
= MAKEWORD(2, 2);
1655 ret
= WSAStartup(wsa_version
, &wsa_data
);
1657 error_setg_win32(errp
, ret
, "failed socket startup");
1661 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1662 info
= g_malloc0(sizeof(*info
));
1664 QAPI_LIST_APPEND(tail
, info
);
1666 info
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1668 if (addr
->PhysicalAddressLength
!= 0) {
1669 mac_addr
= addr
->PhysicalAddress
;
1671 info
->hardware_address
=
1672 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1673 (int) mac_addr
[0], (int) mac_addr
[1],
1674 (int) mac_addr
[2], (int) mac_addr
[3],
1675 (int) mac_addr
[4], (int) mac_addr
[5]);
1679 tail_addr
= &head_addr
;
1680 for (ip_addr
= addr
->FirstUnicastAddress
;
1682 ip_addr
= ip_addr
->Next
) {
1683 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1684 if (addr_str
== NULL
) {
1688 address_item
= g_malloc0(sizeof(*address_item
));
1690 QAPI_LIST_APPEND(tail_addr
, address_item
);
1692 address_item
->ip_address
= addr_str
;
1693 address_item
->prefix
= guest_ip_prefix(ip_addr
);
1694 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1695 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1696 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1697 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1701 info
->has_ip_addresses
= true;
1702 info
->ip_addresses
= head_addr
;
1704 if (!info
->statistics
) {
1705 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1706 if (guest_get_network_stats(addr
->AdapterName
, interface_stat
)
1708 g_free(interface_stat
);
1710 info
->statistics
= interface_stat
;
1716 g_free(adptr_addrs
);
1720 static int64_t filetime_to_ns(const FILETIME
*tf
)
1722 return ((((int64_t)tf
->dwHighDateTime
<< 32) | tf
->dwLowDateTime
)
1723 - W32_FT_OFFSET
) * 100;
1726 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1728 Error
*local_err
= NULL
;
1734 /* Unfortunately, Windows libraries don't provide an easy way to access
1737 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1739 * Instead, a workaround is to use the Windows win32tm command to
1740 * resync the time using the Windows Time service.
1745 HRESULT hr
= system("w32tm /resync /nowait");
1747 if (GetLastError() != 0) {
1748 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1749 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1750 } else if (hr
!= 0) {
1751 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1752 error_setg(errp
, "Windows Time service not running on the "
1755 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1756 FORMAT_MESSAGE_FROM_SYSTEM
|
1757 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1758 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1759 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1761 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1762 "t retrieve error message", hr
);
1764 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1765 (LPCTSTR
)msg_buffer
);
1766 LocalFree(msg_buffer
);
1769 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1770 error_setg(errp
, "No internet connection on guest, sync not "
1776 /* Validate time passed by user. */
1777 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1778 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1782 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1784 tf
.dwLowDateTime
= (DWORD
) time
;
1785 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1787 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1788 error_setg(errp
, "Failed to convert system time %d",
1789 (int)GetLastError());
1793 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1795 error_propagate(errp
, local_err
);
1799 if (!SetSystemTime(&ts
)) {
1800 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1805 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1807 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1809 GuestLogicalProcessorList
*head
, **tail
;
1810 Error
*local_err
= NULL
;
1819 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1820 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1821 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1822 ptr
= pslpi
= g_malloc0(length
);
1823 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1824 error_setg(&local_err
, "Failed to get processor information: %d",
1825 (int)GetLastError());
1828 error_setg(&local_err
,
1829 "Failed to get processor information buffer length: %d",
1830 (int)GetLastError());
1833 while ((local_err
== NULL
) && (length
> 0)) {
1834 if (pslpi
->Relationship
== RelationProcessorCore
) {
1835 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1837 while (cpu_bits
> 0) {
1838 if (!!(cpu_bits
& 1)) {
1839 GuestLogicalProcessor
*vcpu
;
1841 vcpu
= g_malloc0(sizeof *vcpu
);
1842 vcpu
->logical_id
= current
++;
1843 vcpu
->online
= true;
1844 vcpu
->has_can_offline
= true;
1846 QAPI_LIST_APPEND(tail
, vcpu
);
1851 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1852 pslpi
++; /* next entry */
1857 if (local_err
== NULL
) {
1861 /* there's no guest with zero VCPUs */
1862 error_setg(&local_err
, "Guest reported zero VCPUs");
1865 qapi_free_GuestLogicalProcessorList(head
);
1866 error_propagate(errp
, local_err
);
1870 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1872 error_setg(errp
, QERR_UNSUPPORTED
);
1877 get_net_error_message(gint error
)
1879 HMODULE module
= NULL
;
1880 gchar
*retval
= NULL
;
1881 wchar_t *msg
= NULL
;
1885 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1886 FORMAT_MESSAGE_IGNORE_INSERTS
|
1887 FORMAT_MESSAGE_FROM_SYSTEM
;
1889 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1890 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1892 if (module
!= NULL
) {
1893 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1897 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1900 nchars
= wcslen(msg
);
1903 msg
[nchars
- 1] == L
'\n' &&
1904 msg
[nchars
- 2] == L
'\r') {
1905 msg
[nchars
- 2] = L
'\0';
1908 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1913 if (module
!= NULL
) {
1914 FreeLibrary(module
);
1920 void qmp_guest_set_user_password(const char *username
,
1921 const char *password
,
1926 char *rawpasswddata
= NULL
;
1927 size_t rawpasswdlen
;
1928 wchar_t *user
= NULL
, *wpass
= NULL
;
1929 USER_INFO_1003 pi1003
= { 0, };
1930 GError
*gerr
= NULL
;
1933 error_setg(errp
, QERR_UNSUPPORTED
);
1937 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1938 if (!rawpasswddata
) {
1941 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1942 rawpasswddata
[rawpasswdlen
] = '\0';
1944 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1949 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1954 pi1003
.usri1003_password
= wpass
;
1955 nas
= NetUserSetInfo(NULL
, user
,
1956 1003, (LPBYTE
)&pi1003
,
1959 if (nas
!= NERR_Success
) {
1960 gchar
*msg
= get_net_error_message(nas
);
1961 error_setg(errp
, "failed to set password: %s", msg
);
1967 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1972 g_free(rawpasswddata
);
1975 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1977 error_setg(errp
, QERR_UNSUPPORTED
);
1981 GuestMemoryBlockResponseList
*
1982 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1984 error_setg(errp
, QERR_UNSUPPORTED
);
1988 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1990 error_setg(errp
, QERR_UNSUPPORTED
);
1994 /* add unsupported commands to the list of blocked RPCs */
1995 GList
*ga_command_init_blockedrpcs(GList
*blockedrpcs
)
1997 const char *list_unsupported
[] = {
1998 "guest-suspend-hybrid",
2000 "guest-get-memory-blocks", "guest-set-memory-blocks",
2001 "guest-get-memory-block-size", "guest-get-memory-block-info",
2003 char **p
= (char **)list_unsupported
;
2006 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
2009 if (!vss_init(true)) {
2010 g_debug("vss_init failed, vss commands are going to be disabled");
2011 const char *list
[] = {
2012 "guest-get-fsinfo", "guest-fsfreeze-status",
2013 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
2017 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
2024 /* register init/cleanup routines for stateful command groups */
2025 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2027 if (!vss_initialized()) {
2028 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
2032 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
2033 typedef struct _GA_WTSINFOA
{
2034 WTS_CONNECTSTATE_CLASS State
;
2036 DWORD IncomingBytes
;
2037 DWORD OutgoingBytes
;
2038 DWORD IncomingFrames
;
2039 DWORD OutgoingFrames
;
2040 DWORD IncomingCompressedBytes
;
2041 DWORD OutgoingCompressedBy
;
2042 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
2043 CHAR Domain
[DOMAIN_LENGTH
];
2044 CHAR UserName
[USERNAME_LENGTH
+ 1];
2045 LARGE_INTEGER ConnectTime
;
2046 LARGE_INTEGER DisconnectTime
;
2047 LARGE_INTEGER LastInputTime
;
2048 LARGE_INTEGER LogonTime
;
2049 LARGE_INTEGER CurrentTime
;
2053 GuestUserList
*qmp_guest_get_users(Error
**errp
)
2055 #define QGA_NANOSECONDS 10000000
2057 GHashTable
*cache
= NULL
;
2058 GuestUserList
*head
= NULL
, **tail
= &head
;
2060 DWORD buffer_size
= 0, count
= 0, i
= 0;
2061 GA_WTSINFOA
*info
= NULL
;
2062 WTS_SESSION_INFOA
*entries
= NULL
;
2063 GuestUser
*user
= NULL
;
2064 gpointer value
= NULL
;
2066 double login_time
= 0;
2068 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
2070 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
2071 for (i
= 0; i
< count
; ++i
) {
2074 if (WTSQuerySessionInformationA(
2076 entries
[i
].SessionId
,
2082 if (strlen(info
->UserName
) == 0) {
2083 WTSFreeMemory(info
);
2087 login
= info
->LogonTime
.QuadPart
;
2088 login
-= W32_FT_OFFSET
;
2089 login_time
= ((double)login
) / QGA_NANOSECONDS
;
2091 if (g_hash_table_contains(cache
, info
->UserName
)) {
2092 value
= g_hash_table_lookup(cache
, info
->UserName
);
2093 user
= (GuestUser
*)value
;
2094 if (user
->login_time
> login_time
) {
2095 user
->login_time
= login_time
;
2098 user
= g_new0(GuestUser
, 1);
2100 user
->user
= g_strdup(info
->UserName
);
2101 user
->domain
= g_strdup(info
->Domain
);
2103 user
->login_time
= login_time
;
2105 g_hash_table_add(cache
, user
->user
);
2107 QAPI_LIST_APPEND(tail
, user
);
2110 WTSFreeMemory(info
);
2112 WTSFreeMemory(entries
);
2114 g_hash_table_destroy(cache
);
2118 typedef struct _ga_matrix_lookup_t
{
2121 char const *version
;
2122 char const *version_id
;
2123 } ga_matrix_lookup_t
;
2125 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][7] = {
2127 /* Desktop editions */
2128 { 5, 0, "Microsoft Windows 2000", "2000"},
2129 { 5, 1, "Microsoft Windows XP", "xp"},
2130 { 6, 0, "Microsoft Windows Vista", "vista"},
2131 { 6, 1, "Microsoft Windows 7" "7"},
2132 { 6, 2, "Microsoft Windows 8", "8"},
2133 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2136 /* Server editions */
2137 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2138 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2139 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2140 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2141 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2147 typedef struct _ga_win_10_0_t
{
2149 char const *version
;
2150 char const *version_id
;
2153 static ga_win_10_0_t
const WIN_10_0_SERVER_VERSION_MATRIX
[4] = {
2154 {14393, "Microsoft Windows Server 2016", "2016"},
2155 {17763, "Microsoft Windows Server 2019", "2019"},
2156 {20344, "Microsoft Windows Server 2022", "2022"},
2160 static ga_win_10_0_t
const WIN_10_0_CLIENT_VERSION_MATRIX
[3] = {
2161 {10240, "Microsoft Windows 10", "10"},
2162 {22000, "Microsoft Windows 11", "11"},
2166 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
2168 typedef NTSTATUS(WINAPI
*rtl_get_version_t
)(
2169 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
2171 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
2173 HMODULE module
= GetModuleHandle("ntdll");
2174 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
2176 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
2177 "Failed to get address of RtlGetVersion");
2181 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
2182 rtl_get_version(info
);
2186 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
2188 DWORD major
= os_version
->dwMajorVersion
;
2189 DWORD minor
= os_version
->dwMinorVersion
;
2190 DWORD build
= os_version
->dwBuildNumber
;
2191 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
2192 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
2193 ga_win_10_0_t
const *win_10_0_table
= tbl_idx
?
2194 WIN_10_0_SERVER_VERSION_MATRIX
: WIN_10_0_CLIENT_VERSION_MATRIX
;
2195 ga_win_10_0_t
const *win_10_0_version
= NULL
;
2196 while (table
->version
!= NULL
) {
2197 if (major
== 10 && minor
== 0) {
2198 while (win_10_0_table
->version
!= NULL
) {
2199 if (build
>= win_10_0_table
->first_build
) {
2200 win_10_0_version
= win_10_0_table
;
2204 if (win_10_0_table
) {
2206 return g_strdup(win_10_0_version
->version_id
);
2208 return g_strdup(win_10_0_version
->version
);
2211 } else if (major
== table
->major
&& minor
== table
->minor
) {
2213 return g_strdup(table
->version_id
);
2215 return g_strdup(table
->version
);
2220 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2222 return g_strdup("N/A");
2225 static char *ga_get_win_product_name(Error
**errp
)
2227 HKEY key
= INVALID_HANDLE_VALUE
;
2229 char *result
= g_malloc0(size
);
2230 LONG err
= ERROR_SUCCESS
;
2232 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
2233 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2235 if (err
!= ERROR_SUCCESS
) {
2236 error_setg_win32(errp
, err
, "failed to open registry key");
2241 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2242 (LPBYTE
)result
, &size
);
2243 if (err
== ERROR_MORE_DATA
) {
2244 slog("ProductName longer than expected (%lu bytes), retrying",
2249 result
= g_malloc0(size
);
2250 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2251 (LPBYTE
)result
, &size
);
2254 if (err
!= ERROR_SUCCESS
) {
2255 error_setg_win32(errp
, err
, "failed to retrieve ProductName");
2263 if (key
!= INVALID_HANDLE_VALUE
) {
2270 static char *ga_get_current_arch(void)
2273 GetNativeSystemInfo(&info
);
2274 char *result
= NULL
;
2275 switch (info
.wProcessorArchitecture
) {
2276 case PROCESSOR_ARCHITECTURE_AMD64
:
2277 result
= g_strdup("x86_64");
2279 case PROCESSOR_ARCHITECTURE_ARM
:
2280 result
= g_strdup("arm");
2282 case PROCESSOR_ARCHITECTURE_IA64
:
2283 result
= g_strdup("ia64");
2285 case PROCESSOR_ARCHITECTURE_INTEL
:
2286 result
= g_strdup("x86");
2288 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
2290 slog("unknown processor architecture 0x%0x",
2291 info
.wProcessorArchitecture
);
2292 result
= g_strdup("unknown");
2298 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2300 Error
*local_err
= NULL
;
2301 OSVERSIONINFOEXW os_version
= {0};
2306 ga_get_win_version(&os_version
, &local_err
);
2308 error_propagate(errp
, local_err
);
2312 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
2313 product_name
= ga_get_win_product_name(errp
);
2314 if (product_name
== NULL
) {
2318 info
= g_new0(GuestOSInfo
, 1);
2320 info
->kernel_version
= g_strdup_printf("%lu.%lu",
2321 os_version
.dwMajorVersion
,
2322 os_version
.dwMinorVersion
);
2323 info
->kernel_release
= g_strdup_printf("%lu",
2324 os_version
.dwBuildNumber
);
2325 info
->machine
= ga_get_current_arch();
2327 info
->id
= g_strdup("mswindows");
2328 info
->name
= g_strdup("Microsoft Windows");
2329 info
->pretty_name
= product_name
;
2330 info
->version
= ga_get_win_name(&os_version
, false);
2331 info
->version_id
= ga_get_win_name(&os_version
, true);
2332 info
->variant
= g_strdup(server
? "server" : "client");
2333 info
->variant_id
= g_strdup(server
? "server" : "client");
2339 * Safely get device property. Returned strings are using wide characters.
2340 * Caller is responsible for freeing the buffer.
2342 static LPBYTE
cm_get_property(DEVINST devInst
, const DEVPROPKEY
*propName
,
2343 PDEVPROPTYPE propType
)
2346 g_autofree LPBYTE buffer
= NULL
;
2347 ULONG buffer_len
= 0;
2349 /* First query for needed space */
2350 cr
= CM_Get_DevNode_PropertyW(devInst
, propName
, propType
,
2351 buffer
, &buffer_len
, 0);
2352 if (cr
!= CR_SUCCESS
&& cr
!= CR_BUFFER_SMALL
) {
2354 slog("failed to get property size, error=0x%lx", cr
);
2357 buffer
= g_new0(BYTE
, buffer_len
+ 1);
2358 cr
= CM_Get_DevNode_PropertyW(devInst
, propName
, propType
,
2359 buffer
, &buffer_len
, 0);
2360 if (cr
!= CR_SUCCESS
) {
2361 slog("failed to get device property, error=0x%lx", cr
);
2364 return g_steal_pointer(&buffer
);
2367 static GStrv
ga_get_hardware_ids(DEVINST devInstance
)
2369 GArray
*values
= NULL
;
2370 DEVPROPTYPE cm_type
;
2372 g_autofree LPWSTR property
= (LPWSTR
)cm_get_property(devInstance
,
2373 &qga_DEVPKEY_Device_HardwareIds
, &cm_type
);
2374 if (property
== NULL
) {
2375 slog("failed to get hardware IDs");
2378 if (*property
== '\0') {
2382 values
= g_array_new(TRUE
, TRUE
, sizeof(gchar
*));
2383 for (id
= property
; '\0' != *id
; id
+= lstrlenW(id
) + 1) {
2384 gchar
*id8
= g_utf16_to_utf8(id
, -1, NULL
, NULL
, NULL
);
2385 g_array_append_val(values
, id8
);
2387 return (GStrv
)g_array_free(values
, FALSE
);
2391 * https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
2393 #define DEVICE_PCI_RE "PCI\\\\VEN_(1AF4|1B36)&DEV_([0-9A-B]{4})(&|$)"
2395 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
2397 GuestDeviceInfoList
*head
= NULL
, **tail
= &head
;
2398 HDEVINFO dev_info
= INVALID_HANDLE_VALUE
;
2399 SP_DEVINFO_DATA dev_info_data
;
2401 GError
*gerr
= NULL
;
2402 g_autoptr(GRegex
) device_pci_re
= NULL
;
2403 DEVPROPTYPE cm_type
;
2405 device_pci_re
= g_regex_new(DEVICE_PCI_RE
,
2406 G_REGEX_ANCHORED
| G_REGEX_OPTIMIZE
, 0,
2408 g_assert(device_pci_re
!= NULL
);
2410 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
2411 dev_info
= SetupDiGetClassDevs(0, 0, 0, DIGCF_PRESENT
| DIGCF_ALLCLASSES
);
2412 if (dev_info
== INVALID_HANDLE_VALUE
) {
2413 error_setg(errp
, "failed to get device tree");
2417 slog("enumerating devices");
2418 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
2420 g_autofree LPWSTR name
= NULL
;
2421 g_autofree LPFILETIME date
= NULL
;
2422 g_autofree LPWSTR version
= NULL
;
2423 g_auto(GStrv
) hw_ids
= NULL
;
2424 g_autoptr(GuestDeviceInfo
) device
= g_new0(GuestDeviceInfo
, 1);
2425 g_autofree
char *vendor_id
= NULL
;
2426 g_autofree
char *device_id
= NULL
;
2428 name
= (LPWSTR
)cm_get_property(dev_info_data
.DevInst
,
2429 &qga_DEVPKEY_NAME
, &cm_type
);
2431 slog("failed to get device description");
2434 device
->driver_name
= g_utf16_to_utf8(name
, -1, NULL
, NULL
, NULL
);
2435 if (device
->driver_name
== NULL
) {
2436 error_setg(errp
, "conversion to utf8 failed (driver name)");
2439 slog("querying device: %s", device
->driver_name
);
2440 hw_ids
= ga_get_hardware_ids(dev_info_data
.DevInst
);
2441 if (hw_ids
== NULL
) {
2444 for (j
= 0; hw_ids
[j
] != NULL
; j
++) {
2445 g_autoptr(GMatchInfo
) match_info
;
2446 GuestDeviceIdPCI
*id
;
2447 if (!g_regex_match(device_pci_re
, hw_ids
[j
], 0, &match_info
)) {
2452 vendor_id
= g_match_info_fetch(match_info
, 1);
2453 device_id
= g_match_info_fetch(match_info
, 2);
2455 device
->id
= g_new0(GuestDeviceId
, 1);
2456 device
->id
->type
= GUEST_DEVICE_TYPE_PCI
;
2457 id
= &device
->id
->u
.pci
;
2458 id
->vendor_id
= g_ascii_strtoull(vendor_id
, NULL
, 16);
2459 id
->device_id
= g_ascii_strtoull(device_id
, NULL
, 16);
2467 version
= (LPWSTR
)cm_get_property(dev_info_data
.DevInst
,
2468 &qga_DEVPKEY_Device_DriverVersion
, &cm_type
);
2469 if (version
== NULL
) {
2470 slog("failed to get driver version");
2473 device
->driver_version
= g_utf16_to_utf8(version
, -1, NULL
,
2475 if (device
->driver_version
== NULL
) {
2476 error_setg(errp
, "conversion to utf8 failed (driver version)");
2480 date
= (LPFILETIME
)cm_get_property(dev_info_data
.DevInst
,
2481 &qga_DEVPKEY_Device_DriverDate
, &cm_type
);
2483 slog("failed to get driver date");
2486 device
->driver_date
= filetime_to_ns(date
);
2487 device
->has_driver_date
= true;
2489 slog("driver: %s\ndriver version: %" PRId64
",%s\n",
2490 device
->driver_name
, device
->driver_date
,
2491 device
->driver_version
);
2492 QAPI_LIST_APPEND(tail
, g_steal_pointer(&device
));
2495 if (dev_info
!= INVALID_HANDLE_VALUE
) {
2496 SetupDiDestroyDeviceInfoList(dev_info
);
2501 char *qga_get_host_name(Error
**errp
)
2503 wchar_t tmp
[MAX_COMPUTERNAME_LENGTH
+ 1];
2504 DWORD size
= G_N_ELEMENTS(tmp
);
2506 if (GetComputerNameW(tmp
, &size
) == 0) {
2507 error_setg_win32(errp
, GetLastError(), "failed close handle");
2511 return g_utf16_to_utf8(tmp
, size
, NULL
, NULL
, NULL
);
2514 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
2516 error_setg(errp
, QERR_UNSUPPORTED
);
2520 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
2522 error_setg(errp
, QERR_UNSUPPORTED
);