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