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
;
962 char vol_info
[MAX_PATH
+1];
964 uint64_t i64FreeBytesToCaller
, i64TotalBytes
, i64FreeBytes
;
965 GuestFilesystemInfo
*fs
= NULL
;
967 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
968 if (GetLastError() != ERROR_MORE_DATA
) {
969 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
973 mnt_point
= g_malloc(info_size
+ 1);
974 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
976 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
980 len
= strlen(mnt_point
);
981 mnt_point
[len
] = '\\';
982 mnt_point
[len
+1] = 0;
983 if (!GetVolumeInformation(mnt_point
, vol_info
, sizeof(vol_info
), NULL
, NULL
,
984 NULL
, (LPSTR
)&fs_name
, sizeof(fs_name
))) {
985 if (GetLastError() != ERROR_NOT_READY
) {
986 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
991 fs_name
[sizeof(fs_name
) - 1] = 0;
992 fs
= g_malloc(sizeof(*fs
));
993 fs
->name
= g_strdup(guid
);
994 fs
->has_total_bytes
= false;
995 fs
->has_used_bytes
= false;
997 fs
->mountpoint
= g_strdup("System Reserved");
999 fs
->mountpoint
= g_strndup(mnt_point
, len
);
1000 if (GetDiskFreeSpaceEx(fs
->mountpoint
,
1001 (PULARGE_INTEGER
) & i64FreeBytesToCaller
,
1002 (PULARGE_INTEGER
) & i64TotalBytes
,
1003 (PULARGE_INTEGER
) & i64FreeBytes
)) {
1004 fs
->used_bytes
= i64TotalBytes
- i64FreeBytes
;
1005 fs
->total_bytes
= i64TotalBytes
;
1006 fs
->has_total_bytes
= true;
1007 fs
->has_used_bytes
= true;
1010 fs
->type
= g_strdup(fs_name
);
1011 fs
->disk
= build_guest_disk_info(guid
, errp
);
1017 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1020 GuestFilesystemInfoList
*new, *ret
= NULL
;
1023 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
1024 if (vol_h
== INVALID_HANDLE_VALUE
) {
1025 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1030 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, errp
);
1034 new = g_malloc(sizeof(*ret
));
1038 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
1040 if (GetLastError() != ERROR_NO_MORE_FILES
) {
1041 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
1044 FindVolumeClose(vol_h
);
1049 * Return status of freeze/thaw
1051 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1053 if (!vss_initialized()) {
1054 error_setg(errp
, QERR_UNSUPPORTED
);
1058 if (ga_is_frozen(ga_state
)) {
1059 return GUEST_FSFREEZE_STATUS_FROZEN
;
1062 return GUEST_FSFREEZE_STATUS_THAWED
;
1066 * Freeze local file systems using Volume Shadow-copy Service.
1067 * The frozen state is limited for up to 10 seconds by VSS.
1069 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1071 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1074 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1075 strList
*mountpoints
,
1079 Error
*local_err
= NULL
;
1081 if (!vss_initialized()) {
1082 error_setg(errp
, QERR_UNSUPPORTED
);
1086 slog("guest-fsfreeze called");
1088 /* cannot risk guest agent blocking itself on a write in this state */
1089 ga_set_frozen(ga_state
);
1091 qga_vss_fsfreeze(&i
, true, mountpoints
, &local_err
);
1093 error_propagate(errp
, local_err
);
1101 qmp_guest_fsfreeze_thaw(&local_err
);
1103 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
1104 error_free(local_err
);
1110 * Thaw local file systems using Volume Shadow-copy Service.
1112 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1116 if (!vss_initialized()) {
1117 error_setg(errp
, QERR_UNSUPPORTED
);
1121 qga_vss_fsfreeze(&i
, false, NULL
, errp
);
1123 ga_unset_frozen(ga_state
);
1127 static void guest_fsfreeze_cleanup(void)
1131 if (!vss_initialized()) {
1135 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1136 qmp_guest_fsfreeze_thaw(&err
);
1138 slog("failed to clean up frozen filesystems: %s",
1139 error_get_pretty(err
));
1148 * Walk list of mounted file systems in the guest, and discard unused
1151 GuestFilesystemTrimResponse
*
1152 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1154 GuestFilesystemTrimResponse
*resp
;
1156 WCHAR guid
[MAX_PATH
] = L
"";
1160 ZeroMemory(&osvi
, sizeof(OSVERSIONINFO
));
1161 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1162 GetVersionEx(&osvi
);
1163 win8_or_later
= (osvi
.dwMajorVersion
> 6 ||
1164 ((osvi
.dwMajorVersion
== 6) &&
1165 (osvi
.dwMinorVersion
>= 2)));
1166 if (!win8_or_later
) {
1167 error_setg(errp
, "fstrim is only supported for Win8+");
1171 handle
= FindFirstVolumeW(guid
, ARRAYSIZE(guid
));
1172 if (handle
== INVALID_HANDLE_VALUE
) {
1173 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1177 resp
= g_new0(GuestFilesystemTrimResponse
, 1);
1180 GuestFilesystemTrimResult
*res
;
1181 GuestFilesystemTrimResultList
*list
;
1183 DWORD char_count
= 0;
1185 GError
*gerr
= NULL
;
1188 GetVolumePathNamesForVolumeNameW(guid
, NULL
, 0, &char_count
);
1190 if (GetLastError() != ERROR_MORE_DATA
) {
1193 if (GetDriveTypeW(guid
) != DRIVE_FIXED
) {
1197 uc_path
= g_malloc(sizeof(WCHAR
) * char_count
);
1198 if (!GetVolumePathNamesForVolumeNameW(guid
, uc_path
, char_count
,
1199 &char_count
) || !*uc_path
) {
1200 /* strange, but this condition could be faced even with size == 2 */
1205 res
= g_new0(GuestFilesystemTrimResult
, 1);
1207 path
= g_utf16_to_utf8(uc_path
, char_count
, NULL
, NULL
, &gerr
);
1212 res
->has_error
= true;
1213 res
->error
= g_strdup(gerr
->message
);
1220 list
= g_new0(GuestFilesystemTrimResultList
, 1);
1222 list
->next
= resp
->paths
;
1226 memset(argv
, 0, sizeof(argv
));
1227 argv
[0] = (gchar
*)"defrag.exe";
1228 argv
[1] = (gchar
*)"/L";
1231 if (!g_spawn_sync(NULL
, argv
, NULL
, G_SPAWN_SEARCH_PATH
, NULL
, NULL
,
1232 &out
/* stdout */, NULL
/* stdin */,
1234 res
->has_error
= true;
1235 res
->error
= g_strdup(gerr
->message
);
1238 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1239 Error is reported in the output with something like
1240 (x89000020) etc code in the stdout */
1243 gchar
**lines
= g_strsplit(out
, "\r\n", 0);
1246 for (i
= 0; lines
[i
] != NULL
; i
++) {
1247 if (g_strstr_len(lines
[i
], -1, "(0x") == NULL
) {
1250 res
->has_error
= true;
1251 res
->error
= g_strdup(lines
[i
]);
1256 } while (FindNextVolumeW(handle
, guid
, ARRAYSIZE(guid
)));
1258 FindVolumeClose(handle
);
1263 GUEST_SUSPEND_MODE_DISK
,
1264 GUEST_SUSPEND_MODE_RAM
1267 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
1269 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
1271 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
1272 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
1273 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1274 "failed to determine guest suspend capabilities");
1279 case GUEST_SUSPEND_MODE_DISK
:
1280 if (!sys_pwr_caps
.SystemS4
) {
1281 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1282 "suspend-to-disk not supported by OS");
1285 case GUEST_SUSPEND_MODE_RAM
:
1286 if (!sys_pwr_caps
.SystemS3
) {
1287 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1288 "suspend-to-ram not supported by OS");
1292 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "mode",
1293 "GuestSuspendMode");
1297 static DWORD WINAPI
do_suspend(LPVOID opaque
)
1299 GuestSuspendMode
*mode
= opaque
;
1302 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
1303 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
1304 slog("failed to suspend guest: %s", emsg
);
1311 void qmp_guest_suspend_disk(Error
**errp
)
1313 Error
*local_err
= NULL
;
1314 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1316 *mode
= GUEST_SUSPEND_MODE_DISK
;
1317 check_suspend_mode(*mode
, &local_err
);
1321 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1325 execute_async(do_suspend
, mode
, &local_err
);
1329 error_propagate(errp
, local_err
);
1334 void qmp_guest_suspend_ram(Error
**errp
)
1336 Error
*local_err
= NULL
;
1337 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1339 *mode
= GUEST_SUSPEND_MODE_RAM
;
1340 check_suspend_mode(*mode
, &local_err
);
1344 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1348 execute_async(do_suspend
, mode
, &local_err
);
1352 error_propagate(errp
, local_err
);
1357 void qmp_guest_suspend_hybrid(Error
**errp
)
1359 error_setg(errp
, QERR_UNSUPPORTED
);
1362 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
1364 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
1365 ULONG adptr_addrs_len
= 0;
1368 /* Call the first time to get the adptr_addrs_len. */
1369 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1370 NULL
, adptr_addrs
, &adptr_addrs_len
);
1372 adptr_addrs
= g_malloc(adptr_addrs_len
);
1373 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1374 NULL
, adptr_addrs
, &adptr_addrs_len
);
1375 if (ret
!= ERROR_SUCCESS
) {
1376 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
1377 g_free(adptr_addrs
);
1383 static char *guest_wctomb_dup(WCHAR
*wstr
)
1388 str_size
= WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, NULL
, 0, NULL
, NULL
);
1389 /* add 1 to str_size for NULL terminator */
1390 str
= g_malloc(str_size
+ 1);
1391 WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, str
, str_size
, NULL
, NULL
);
1395 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
1398 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
1402 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
1403 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1404 len
= sizeof(addr_str
);
1405 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
1406 ip_addr
->Address
.iSockaddrLength
,
1411 error_setg_win32(errp
, WSAGetLastError(),
1412 "failed address presentation form conversion");
1415 return g_strdup(addr_str
);
1420 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1422 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1423 * field to obtain the prefix.
1425 return ip_addr
->OnLinkPrefixLength
;
1428 #define INTERFACE_PATH_BUF_SZ 512
1430 static DWORD
get_interface_index(const char *guid
)
1434 wchar_t wbuf
[INTERFACE_PATH_BUF_SZ
];
1435 snwprintf(wbuf
, INTERFACE_PATH_BUF_SZ
, L
"\\device\\tcpip_%s", guid
);
1436 wbuf
[INTERFACE_PATH_BUF_SZ
- 1] = 0;
1437 status
= GetAdapterIndex (wbuf
, &index
);
1438 if (status
!= NO_ERROR
) {
1445 typedef NETIOAPI_API (WINAPI
*GetIfEntry2Func
)(PMIB_IF_ROW2 Row
);
1447 static int guest_get_network_stats(const char *name
,
1448 GuestNetworkInterfaceStat
*stats
)
1450 OSVERSIONINFO os_ver
;
1452 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1453 GetVersionEx(&os_ver
);
1454 if (os_ver
.dwMajorVersion
>= 6) {
1455 MIB_IF_ROW2 a_mid_ifrow
;
1456 GetIfEntry2Func getifentry2_ex
;
1458 HMODULE module
= GetModuleHandle("iphlpapi");
1459 PVOID func
= GetProcAddress(module
, "GetIfEntry2");
1465 getifentry2_ex
= (GetIfEntry2Func
)func
;
1466 if_index
= get_interface_index(name
);
1467 if (if_index
== (DWORD
)~0) {
1471 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1472 a_mid_ifrow
.InterfaceIndex
= if_index
;
1473 if (NO_ERROR
== getifentry2_ex(&a_mid_ifrow
)) {
1474 stats
->rx_bytes
= a_mid_ifrow
.InOctets
;
1475 stats
->rx_packets
= a_mid_ifrow
.InUcastPkts
;
1476 stats
->rx_errs
= a_mid_ifrow
.InErrors
;
1477 stats
->rx_dropped
= a_mid_ifrow
.InDiscards
;
1478 stats
->tx_bytes
= a_mid_ifrow
.OutOctets
;
1479 stats
->tx_packets
= a_mid_ifrow
.OutUcastPkts
;
1480 stats
->tx_errs
= a_mid_ifrow
.OutErrors
;
1481 stats
->tx_dropped
= a_mid_ifrow
.OutDiscards
;
1488 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1490 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1491 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1492 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1493 GuestIpAddressList
*head_addr
, *cur_addr
;
1494 GuestNetworkInterfaceList
*info
;
1495 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1496 GuestIpAddressList
*address_item
= NULL
;
1497 unsigned char *mac_addr
;
1503 adptr_addrs
= guest_get_adapters_addresses(errp
);
1504 if (adptr_addrs
== NULL
) {
1508 /* Make WSA APIs available. */
1509 wsa_version
= MAKEWORD(2, 2);
1510 ret
= WSAStartup(wsa_version
, &wsa_data
);
1512 error_setg_win32(errp
, ret
, "failed socket startup");
1516 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1517 info
= g_malloc0(sizeof(*info
));
1519 if (cur_item
== NULL
) {
1520 head
= cur_item
= info
;
1522 cur_item
->next
= info
;
1526 info
->value
= g_malloc0(sizeof(*info
->value
));
1527 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1529 if (addr
->PhysicalAddressLength
!= 0) {
1530 mac_addr
= addr
->PhysicalAddress
;
1532 info
->value
->hardware_address
=
1533 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1534 (int) mac_addr
[0], (int) mac_addr
[1],
1535 (int) mac_addr
[2], (int) mac_addr
[3],
1536 (int) mac_addr
[4], (int) mac_addr
[5]);
1538 info
->value
->has_hardware_address
= true;
1543 for (ip_addr
= addr
->FirstUnicastAddress
;
1545 ip_addr
= ip_addr
->Next
) {
1546 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1547 if (addr_str
== NULL
) {
1551 address_item
= g_malloc0(sizeof(*address_item
));
1554 head_addr
= cur_addr
= address_item
;
1556 cur_addr
->next
= address_item
;
1557 cur_addr
= address_item
;
1560 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1561 address_item
->value
->ip_address
= addr_str
;
1562 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1563 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1564 address_item
->value
->ip_address_type
=
1565 GUEST_IP_ADDRESS_TYPE_IPV4
;
1566 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1567 address_item
->value
->ip_address_type
=
1568 GUEST_IP_ADDRESS_TYPE_IPV6
;
1572 info
->value
->has_ip_addresses
= true;
1573 info
->value
->ip_addresses
= head_addr
;
1575 if (!info
->value
->has_statistics
) {
1576 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1577 if (guest_get_network_stats(addr
->AdapterName
,
1578 interface_stat
) == -1) {
1579 info
->value
->has_statistics
= false;
1580 g_free(interface_stat
);
1582 info
->value
->statistics
= interface_stat
;
1583 info
->value
->has_statistics
= true;
1589 g_free(adptr_addrs
);
1593 int64_t qmp_guest_get_time(Error
**errp
)
1595 SYSTEMTIME ts
= {0};
1599 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1600 error_setg(errp
, "Failed to get time");
1604 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1605 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1609 return ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1610 - W32_FT_OFFSET
) * 100;
1613 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1615 Error
*local_err
= NULL
;
1621 /* Unfortunately, Windows libraries don't provide an easy way to access
1624 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1626 * Instead, a workaround is to use the Windows win32tm command to
1627 * resync the time using the Windows Time service.
1632 HRESULT hr
= system("w32tm /resync /nowait");
1634 if (GetLastError() != 0) {
1635 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1636 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1637 } else if (hr
!= 0) {
1638 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1639 error_setg(errp
, "Windows Time service not running on the "
1642 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1643 FORMAT_MESSAGE_FROM_SYSTEM
|
1644 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1645 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1646 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1648 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1649 "t retrieve error message", hr
);
1651 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1652 (LPCTSTR
)msg_buffer
);
1653 LocalFree(msg_buffer
);
1656 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1657 error_setg(errp
, "No internet connection on guest, sync not "
1663 /* Validate time passed by user. */
1664 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1665 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1669 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1671 tf
.dwLowDateTime
= (DWORD
) time
;
1672 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1674 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1675 error_setg(errp
, "Failed to convert system time %d",
1676 (int)GetLastError());
1680 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1682 error_propagate(errp
, local_err
);
1686 if (!SetSystemTime(&ts
)) {
1687 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1692 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1694 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1696 GuestLogicalProcessorList
*head
, **link
;
1697 Error
*local_err
= NULL
;
1706 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1707 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1708 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1709 ptr
= pslpi
= g_malloc0(length
);
1710 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1711 error_setg(&local_err
, "Failed to get processor information: %d",
1712 (int)GetLastError());
1715 error_setg(&local_err
,
1716 "Failed to get processor information buffer length: %d",
1717 (int)GetLastError());
1720 while ((local_err
== NULL
) && (length
> 0)) {
1721 if (pslpi
->Relationship
== RelationProcessorCore
) {
1722 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1724 while (cpu_bits
> 0) {
1725 if (!!(cpu_bits
& 1)) {
1726 GuestLogicalProcessor
*vcpu
;
1727 GuestLogicalProcessorList
*entry
;
1729 vcpu
= g_malloc0(sizeof *vcpu
);
1730 vcpu
->logical_id
= current
++;
1731 vcpu
->online
= true;
1732 vcpu
->has_can_offline
= true;
1734 entry
= g_malloc0(sizeof *entry
);
1735 entry
->value
= vcpu
;
1738 link
= &entry
->next
;
1743 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1744 pslpi
++; /* next entry */
1749 if (local_err
== NULL
) {
1753 /* there's no guest with zero VCPUs */
1754 error_setg(&local_err
, "Guest reported zero VCPUs");
1757 qapi_free_GuestLogicalProcessorList(head
);
1758 error_propagate(errp
, local_err
);
1762 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1764 error_setg(errp
, QERR_UNSUPPORTED
);
1769 get_net_error_message(gint error
)
1771 HMODULE module
= NULL
;
1772 gchar
*retval
= NULL
;
1773 wchar_t *msg
= NULL
;
1777 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1778 FORMAT_MESSAGE_IGNORE_INSERTS
|
1779 FORMAT_MESSAGE_FROM_SYSTEM
;
1781 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1782 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1784 if (module
!= NULL
) {
1785 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1789 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1792 nchars
= wcslen(msg
);
1795 msg
[nchars
- 1] == L
'\n' &&
1796 msg
[nchars
- 2] == L
'\r') {
1797 msg
[nchars
- 2] = L
'\0';
1800 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1805 if (module
!= NULL
) {
1806 FreeLibrary(module
);
1812 void qmp_guest_set_user_password(const char *username
,
1813 const char *password
,
1818 char *rawpasswddata
= NULL
;
1819 size_t rawpasswdlen
;
1820 wchar_t *user
= NULL
, *wpass
= NULL
;
1821 USER_INFO_1003 pi1003
= { 0, };
1822 GError
*gerr
= NULL
;
1825 error_setg(errp
, QERR_UNSUPPORTED
);
1829 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1830 if (!rawpasswddata
) {
1833 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1834 rawpasswddata
[rawpasswdlen
] = '\0';
1836 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1841 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1846 pi1003
.usri1003_password
= wpass
;
1847 nas
= NetUserSetInfo(NULL
, user
,
1848 1003, (LPBYTE
)&pi1003
,
1851 if (nas
!= NERR_Success
) {
1852 gchar
*msg
= get_net_error_message(nas
);
1853 error_setg(errp
, "failed to set password: %s", msg
);
1859 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1864 g_free(rawpasswddata
);
1867 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1869 error_setg(errp
, QERR_UNSUPPORTED
);
1873 GuestMemoryBlockResponseList
*
1874 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1876 error_setg(errp
, QERR_UNSUPPORTED
);
1880 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1882 error_setg(errp
, QERR_UNSUPPORTED
);
1886 /* add unsupported commands to the blacklist */
1887 GList
*ga_command_blacklist_init(GList
*blacklist
)
1889 const char *list_unsupported
[] = {
1890 "guest-suspend-hybrid",
1892 "guest-get-memory-blocks", "guest-set-memory-blocks",
1893 "guest-get-memory-block-size", "guest-get-memory-block-info",
1895 char **p
= (char **)list_unsupported
;
1898 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1901 if (!vss_init(true)) {
1902 g_debug("vss_init failed, vss commands are going to be disabled");
1903 const char *list
[] = {
1904 "guest-get-fsinfo", "guest-fsfreeze-status",
1905 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1909 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1916 /* register init/cleanup routines for stateful command groups */
1917 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1919 if (!vss_initialized()) {
1920 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1924 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1925 typedef struct _GA_WTSINFOA
{
1926 WTS_CONNECTSTATE_CLASS State
;
1928 DWORD IncomingBytes
;
1929 DWORD OutgoingBytes
;
1930 DWORD IncomingFrames
;
1931 DWORD OutgoingFrames
;
1932 DWORD IncomingCompressedBytes
;
1933 DWORD OutgoingCompressedBy
;
1934 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
1935 CHAR Domain
[DOMAIN_LENGTH
];
1936 CHAR UserName
[USERNAME_LENGTH
+ 1];
1937 LARGE_INTEGER ConnectTime
;
1938 LARGE_INTEGER DisconnectTime
;
1939 LARGE_INTEGER LastInputTime
;
1940 LARGE_INTEGER LogonTime
;
1941 LARGE_INTEGER CurrentTime
;
1945 GuestUserList
*qmp_guest_get_users(Error
**errp
)
1947 #define QGA_NANOSECONDS 10000000
1949 GHashTable
*cache
= NULL
;
1950 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
1952 DWORD buffer_size
= 0, count
= 0, i
= 0;
1953 GA_WTSINFOA
*info
= NULL
;
1954 WTS_SESSION_INFOA
*entries
= NULL
;
1955 GuestUserList
*item
= NULL
;
1956 GuestUser
*user
= NULL
;
1957 gpointer value
= NULL
;
1959 double login_time
= 0;
1961 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
1963 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
1964 for (i
= 0; i
< count
; ++i
) {
1967 if (WTSQuerySessionInformationA(
1969 entries
[i
].SessionId
,
1975 if (strlen(info
->UserName
) == 0) {
1976 WTSFreeMemory(info
);
1980 login
= info
->LogonTime
.QuadPart
;
1981 login
-= W32_FT_OFFSET
;
1982 login_time
= ((double)login
) / QGA_NANOSECONDS
;
1984 if (g_hash_table_contains(cache
, info
->UserName
)) {
1985 value
= g_hash_table_lookup(cache
, info
->UserName
);
1986 user
= (GuestUser
*)value
;
1987 if (user
->login_time
> login_time
) {
1988 user
->login_time
= login_time
;
1991 item
= g_new0(GuestUserList
, 1);
1992 item
->value
= g_new0(GuestUser
, 1);
1994 item
->value
->user
= g_strdup(info
->UserName
);
1995 item
->value
->domain
= g_strdup(info
->Domain
);
1996 item
->value
->has_domain
= true;
1998 item
->value
->login_time
= login_time
;
2000 g_hash_table_add(cache
, item
->value
->user
);
2003 head
= cur_item
= item
;
2005 cur_item
->next
= item
;
2010 WTSFreeMemory(info
);
2012 WTSFreeMemory(entries
);
2014 g_hash_table_destroy(cache
);
2018 typedef struct _ga_matrix_lookup_t
{
2021 char const *version
;
2022 char const *version_id
;
2023 } ga_matrix_lookup_t
;
2025 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][8] = {
2027 /* Desktop editions */
2028 { 5, 0, "Microsoft Windows 2000", "2000"},
2029 { 5, 1, "Microsoft Windows XP", "xp"},
2030 { 6, 0, "Microsoft Windows Vista", "vista"},
2031 { 6, 1, "Microsoft Windows 7" "7"},
2032 { 6, 2, "Microsoft Windows 8", "8"},
2033 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2034 {10, 0, "Microsoft Windows 10", "10"},
2037 /* Server editions */
2038 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2039 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2040 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2041 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2042 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2049 typedef struct _ga_win_10_0_server_t
{
2051 char const *version
;
2052 char const *version_id
;
2053 } ga_win_10_0_server_t
;
2055 static ga_win_10_0_server_t
const WIN_10_0_SERVER_VERSION_MATRIX
[3] = {
2056 {14393, "Microsoft Windows Server 2016", "2016"},
2057 {17763, "Microsoft Windows Server 2019", "2019"},
2061 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
2063 typedef NTSTATUS(WINAPI
* rtl_get_version_t
)(
2064 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
2066 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
2068 HMODULE module
= GetModuleHandle("ntdll");
2069 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
2071 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
2072 "Failed to get address of RtlGetVersion");
2076 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
2077 rtl_get_version(info
);
2081 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
2083 DWORD major
= os_version
->dwMajorVersion
;
2084 DWORD minor
= os_version
->dwMinorVersion
;
2085 DWORD build
= os_version
->dwBuildNumber
;
2086 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
2087 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
2088 ga_win_10_0_server_t
const *win_10_0_table
= WIN_10_0_SERVER_VERSION_MATRIX
;
2089 while (table
->version
!= NULL
) {
2090 if (major
== 10 && minor
== 0 && tbl_idx
) {
2091 while (win_10_0_table
->version
!= NULL
) {
2092 if (build
<= win_10_0_table
->final_build
) {
2094 return g_strdup(win_10_0_table
->version_id
);
2096 return g_strdup(win_10_0_table
->version
);
2101 } else if (major
== table
->major
&& minor
== table
->minor
) {
2103 return g_strdup(table
->version_id
);
2105 return g_strdup(table
->version
);
2110 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2112 return g_strdup("N/A");
2115 static char *ga_get_win_product_name(Error
**errp
)
2119 char *result
= g_malloc0(size
);
2120 LONG err
= ERROR_SUCCESS
;
2122 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
2123 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2125 if (err
!= ERROR_SUCCESS
) {
2126 error_setg_win32(errp
, err
, "failed to open registry key");
2130 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2131 (LPBYTE
)result
, &size
);
2132 if (err
== ERROR_MORE_DATA
) {
2133 slog("ProductName longer than expected (%lu bytes), retrying",
2138 result
= g_malloc0(size
);
2139 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2140 (LPBYTE
)result
, &size
);
2143 if (err
!= ERROR_SUCCESS
) {
2144 error_setg_win32(errp
, err
, "failed to retrive ProductName");
2155 static char *ga_get_current_arch(void)
2158 GetNativeSystemInfo(&info
);
2159 char *result
= NULL
;
2160 switch (info
.wProcessorArchitecture
) {
2161 case PROCESSOR_ARCHITECTURE_AMD64
:
2162 result
= g_strdup("x86_64");
2164 case PROCESSOR_ARCHITECTURE_ARM
:
2165 result
= g_strdup("arm");
2167 case PROCESSOR_ARCHITECTURE_IA64
:
2168 result
= g_strdup("ia64");
2170 case PROCESSOR_ARCHITECTURE_INTEL
:
2171 result
= g_strdup("x86");
2173 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
2175 slog("unknown processor architecture 0x%0x",
2176 info
.wProcessorArchitecture
);
2177 result
= g_strdup("unknown");
2183 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2185 Error
*local_err
= NULL
;
2186 OSVERSIONINFOEXW os_version
= {0};
2191 ga_get_win_version(&os_version
, &local_err
);
2193 error_propagate(errp
, local_err
);
2197 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
2198 product_name
= ga_get_win_product_name(errp
);
2199 if (product_name
== NULL
) {
2203 info
= g_new0(GuestOSInfo
, 1);
2205 info
->has_kernel_version
= true;
2206 info
->kernel_version
= g_strdup_printf("%lu.%lu",
2207 os_version
.dwMajorVersion
,
2208 os_version
.dwMinorVersion
);
2209 info
->has_kernel_release
= true;
2210 info
->kernel_release
= g_strdup_printf("%lu",
2211 os_version
.dwBuildNumber
);
2212 info
->has_machine
= true;
2213 info
->machine
= ga_get_current_arch();
2215 info
->has_id
= true;
2216 info
->id
= g_strdup("mswindows");
2217 info
->has_name
= true;
2218 info
->name
= g_strdup("Microsoft Windows");
2219 info
->has_pretty_name
= true;
2220 info
->pretty_name
= product_name
;
2221 info
->has_version
= true;
2222 info
->version
= ga_get_win_name(&os_version
, false);
2223 info
->has_version_id
= true;
2224 info
->version_id
= ga_get_win_name(&os_version
, true);
2225 info
->has_variant
= true;
2226 info
->variant
= g_strdup(server
? "server" : "client");
2227 info
->has_variant_id
= true;
2228 info
->variant_id
= g_strdup(server
? "server" : "client");