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"
41 #ifndef SHTDN_REASON_FLAG_PLANNED
42 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
45 /* multiple of 100 nanoseconds elapsed between windows baseline
46 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
47 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
48 (365 * (1970 - 1601) + \
49 (1970 - 1601) / 4 - 3))
51 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
53 typedef struct GuestFileHandle
{
56 QTAILQ_ENTRY(GuestFileHandle
) next
;
60 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
61 } guest_file_state
= {
62 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
65 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
67 typedef struct OpenFlags
{
70 DWORD creation_disposition
;
72 static OpenFlags guest_file_open_modes
[] = {
73 {"r", GENERIC_READ
, OPEN_EXISTING
},
74 {"rb", GENERIC_READ
, OPEN_EXISTING
},
75 {"w", GENERIC_WRITE
, CREATE_ALWAYS
},
76 {"wb", GENERIC_WRITE
, CREATE_ALWAYS
},
77 {"a", FILE_GENERIC_APPEND
, OPEN_ALWAYS
},
78 {"r+", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
79 {"rb+", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
80 {"r+b", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
81 {"w+", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
82 {"wb+", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
83 {"w+b", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
84 {"a+", FILE_GENERIC_APPEND
|GENERIC_READ
, OPEN_ALWAYS
},
85 {"ab+", FILE_GENERIC_APPEND
|GENERIC_READ
, OPEN_ALWAYS
},
86 {"a+b", FILE_GENERIC_APPEND
|GENERIC_READ
, OPEN_ALWAYS
}
89 #define debug_error(msg) do { \
90 char *suffix = g_win32_error_message(GetLastError()); \
91 g_debug("%s: %s", (msg), suffix); \
95 static OpenFlags
*find_open_flag(const char *mode_str
)
100 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
101 OpenFlags
*flags
= guest_file_open_modes
+ mode
;
103 if (strcmp(flags
->forms
, mode_str
) == 0) {
108 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
112 static int64_t guest_file_handle_add(HANDLE fh
, Error
**errp
)
114 GuestFileHandle
*gfh
;
117 handle
= ga_get_fd_handle(ga_state
, errp
);
121 gfh
= g_new0(GuestFileHandle
, 1);
124 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
129 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
131 GuestFileHandle
*gfh
;
132 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
) {
137 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
141 static void handle_set_nonblocking(HANDLE fh
)
143 DWORD file_type
, pipe_state
;
144 file_type
= GetFileType(fh
);
145 if (file_type
!= FILE_TYPE_PIPE
) {
148 /* If file_type == FILE_TYPE_PIPE, according to MSDN
149 * the specified file is socket or named pipe */
150 if (!GetNamedPipeHandleState(fh
, &pipe_state
, NULL
,
151 NULL
, NULL
, NULL
, 0)) {
154 /* The fd is named pipe fd */
155 if (pipe_state
& PIPE_NOWAIT
) {
159 pipe_state
|= PIPE_NOWAIT
;
160 SetNamedPipeHandleState(fh
, &pipe_state
, NULL
, NULL
);
163 int64_t qmp_guest_file_open(const char *path
, bool has_mode
,
164 const char *mode
, Error
**errp
)
168 HANDLE templ_file
= NULL
;
169 DWORD share_mode
= FILE_SHARE_READ
;
170 DWORD flags_and_attr
= FILE_ATTRIBUTE_NORMAL
;
171 LPSECURITY_ATTRIBUTES sa_attr
= NULL
;
172 OpenFlags
*guest_flags
;
174 wchar_t *w_path
= NULL
;
179 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
180 guest_flags
= find_open_flag(mode
);
181 if (guest_flags
== NULL
) {
182 error_setg(errp
, "invalid file open mode");
186 w_path
= g_utf8_to_utf16(path
, -1, NULL
, NULL
, &gerr
);
191 fh
= CreateFileW(w_path
, guest_flags
->desired_access
, share_mode
, sa_attr
,
192 guest_flags
->creation_disposition
, flags_and_attr
,
194 if (fh
== INVALID_HANDLE_VALUE
) {
195 error_setg_win32(errp
, GetLastError(), "failed to open file '%s'",
200 /* set fd non-blocking to avoid common use cases (like reading from a
201 * named pipe) from hanging the agent
203 handle_set_nonblocking(fh
);
205 fd
= guest_file_handle_add(fh
, errp
);
208 error_setg(errp
, "failed to add handle to qmp handle table");
212 slog("guest-file-open, handle: % " PRId64
, fd
);
216 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
223 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
226 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
227 slog("guest-file-close called, handle: %" PRId64
, handle
);
231 ret
= CloseHandle(gfh
->fh
);
233 error_setg_win32(errp
, GetLastError(), "failed close handle");
237 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
241 static void acquire_privilege(const char *name
, Error
**errp
)
244 TOKEN_PRIVILEGES priv
;
245 Error
*local_err
= NULL
;
247 if (OpenProcessToken(GetCurrentProcess(),
248 TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY
, &token
))
250 if (!LookupPrivilegeValue(NULL
, name
, &priv
.Privileges
[0].Luid
)) {
251 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
252 "no luid for requested privilege");
256 priv
.PrivilegeCount
= 1;
257 priv
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
259 if (!AdjustTokenPrivileges(token
, FALSE
, &priv
, 0, NULL
, 0)) {
260 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
261 "unable to acquire requested privilege");
266 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
267 "failed to open privilege token");
274 error_propagate(errp
, local_err
);
277 static void execute_async(DWORD
WINAPI (*func
)(LPVOID
), LPVOID opaque
,
280 Error
*local_err
= NULL
;
282 HANDLE thread
= CreateThread(NULL
, 0, func
, opaque
, 0, NULL
);
284 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
285 "failed to dispatch asynchronous command");
286 error_propagate(errp
, local_err
);
290 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
292 Error
*local_err
= NULL
;
293 UINT shutdown_flag
= EWX_FORCE
;
295 slog("guest-shutdown called, mode: %s", mode
);
297 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
298 shutdown_flag
|= EWX_POWEROFF
;
299 } else if (strcmp(mode
, "halt") == 0) {
300 shutdown_flag
|= EWX_SHUTDOWN
;
301 } else if (strcmp(mode
, "reboot") == 0) {
302 shutdown_flag
|= EWX_REBOOT
;
304 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "mode",
305 "halt|powerdown|reboot");
309 /* Request a shutdown privilege, but try to shut down the system
311 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
313 error_propagate(errp
, local_err
);
317 if (!ExitWindowsEx(shutdown_flag
, SHTDN_REASON_FLAG_PLANNED
)) {
318 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
319 slog("guest-shutdown failed: %s", emsg
);
320 error_setg_win32(errp
, GetLastError(), "guest-shutdown failed");
324 GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
325 int64_t count
, Error
**errp
)
327 GuestFileRead
*read_data
= NULL
;
332 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
338 count
= QGA_READ_COUNT_DEFAULT
;
339 } else if (count
< 0 || count
>= UINT32_MAX
) {
340 error_setg(errp
, "value '%" PRId64
341 "' is invalid for argument count", count
);
346 buf
= g_malloc0(count
+1);
347 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
349 error_setg_win32(errp
, GetLastError(), "failed to read file");
350 slog("guest-file-read failed, handle %" PRId64
, handle
);
353 read_data
= g_new0(GuestFileRead
, 1);
354 read_data
->count
= (size_t)read_count
;
355 read_data
->eof
= read_count
== 0;
357 if (read_count
!= 0) {
358 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
366 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
367 bool has_count
, int64_t count
,
370 GuestFileWrite
*write_data
= NULL
;
375 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
382 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
389 } else if (count
< 0 || count
> buf_len
) {
390 error_setg(errp
, "value '%" PRId64
391 "' is invalid for argument count", count
);
395 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
397 error_setg_win32(errp
, GetLastError(), "failed to write to file");
398 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
400 write_data
= g_new0(GuestFileWrite
, 1);
401 write_data
->count
= (size_t) write_count
;
409 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
410 GuestFileWhence
*whence_code
,
413 GuestFileHandle
*gfh
;
414 GuestFileSeek
*seek_data
;
416 LARGE_INTEGER new_pos
, off_pos
;
417 off_pos
.QuadPart
= offset
;
422 gfh
= guest_file_handle_find(handle
, errp
);
427 /* We stupidly exposed 'whence':'int' in our qapi */
428 whence
= ga_parse_whence(whence_code
, &err
);
430 error_propagate(errp
, err
);
435 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
437 error_setg_win32(errp
, GetLastError(), "failed to seek file");
440 seek_data
= g_new0(GuestFileSeek
, 1);
441 seek_data
->position
= new_pos
.QuadPart
;
445 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
448 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
454 if (!FlushFileBuffers(fh
)) {
455 error_setg_win32(errp
, GetLastError(), "failed to flush file");
459 #ifdef CONFIG_QGA_NTDDSCSI
461 static GuestDiskBusType win2qemu
[] = {
462 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
463 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
464 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
465 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
466 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
467 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
468 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
469 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
470 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
471 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
472 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
473 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
474 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
475 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
476 #if (_WIN32_WINNT >= 0x0601)
477 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
478 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
482 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
484 if (bus
>= ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
485 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
487 return win2qemu
[(int)bus
];
490 DEFINE_GUID(GUID_DEVINTERFACE_DISK
,
491 0x53f56307L
, 0xb6bf, 0x11d0, 0x94, 0xf2,
492 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
493 DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT
,
494 0x2accfe60L
, 0xc130, 0x11d2, 0xb0, 0x82,
495 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
497 static GuestPCIAddress
*get_pci_info(int number
, Error
**errp
)
500 SP_DEVINFO_DATA dev_info_data
;
501 SP_DEVICE_INTERFACE_DATA dev_iface_data
;
504 GuestPCIAddress
*pci
= NULL
;
505 bool partial_pci
= false;
507 pci
= g_malloc0(sizeof(*pci
));
513 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK
, 0, 0,
514 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
515 if (dev_info
== INVALID_HANDLE_VALUE
) {
516 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
520 g_debug("enumerating devices");
521 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
522 dev_iface_data
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
523 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
524 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data
= NULL
;
525 STORAGE_DEVICE_NUMBER sdn
;
526 char *parent_dev_id
= NULL
;
527 HDEVINFO parent_dev_info
;
528 SP_DEVINFO_DATA parent_dev_info_data
;
532 g_debug("getting device path");
533 if (SetupDiEnumDeviceInterfaces(dev_info
, &dev_info_data
,
534 &GUID_DEVINTERFACE_DISK
, 0,
536 while (!SetupDiGetDeviceInterfaceDetail(dev_info
, &dev_iface_data
,
537 pdev_iface_detail_data
,
540 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
541 pdev_iface_detail_data
= g_malloc(size
);
542 pdev_iface_detail_data
->cbSize
=
543 sizeof(*pdev_iface_detail_data
);
545 error_setg_win32(errp
, GetLastError(),
546 "failed to get device interfaces");
551 dev_file
= CreateFile(pdev_iface_detail_data
->DevicePath
, 0,
552 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0,
554 g_free(pdev_iface_detail_data
);
556 if (!DeviceIoControl(dev_file
, IOCTL_STORAGE_GET_DEVICE_NUMBER
,
557 NULL
, 0, &sdn
, sizeof(sdn
), &size
, NULL
)) {
558 CloseHandle(dev_file
);
559 error_setg_win32(errp
, GetLastError(),
560 "failed to get device slot number");
564 CloseHandle(dev_file
);
565 if (sdn
.DeviceNumber
!= number
) {
569 error_setg_win32(errp
, GetLastError(),
570 "failed to get device interfaces");
574 g_debug("found device slot %d. Getting storage controller", number
);
577 DEVINST dev_inst
, parent_dev_inst
;
578 ULONG dev_id_size
= 0;
581 while (!SetupDiGetDeviceInstanceId(dev_info
, &dev_info_data
,
582 parent_dev_id
, size
, &size
)) {
583 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
584 parent_dev_id
= g_malloc(size
);
586 error_setg_win32(errp
, GetLastError(),
587 "failed to get device instance ID");
593 * CM API used here as opposed to
594 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
595 * which exports are only available in mingw-w64 6+
597 cr
= CM_Locate_DevInst(&dev_inst
, parent_dev_id
, 0);
598 if (cr
!= CR_SUCCESS
) {
599 g_error("CM_Locate_DevInst failed with code %lx", cr
);
600 error_setg_win32(errp
, GetLastError(),
601 "failed to get device instance");
604 cr
= CM_Get_Parent(&parent_dev_inst
, dev_inst
, 0);
605 if (cr
!= CR_SUCCESS
) {
606 g_error("CM_Get_Parent failed with code %lx", cr
);
607 error_setg_win32(errp
, GetLastError(),
608 "failed to get parent device instance");
612 cr
= CM_Get_Device_ID_Size(&dev_id_size
, parent_dev_inst
, 0);
613 if (cr
!= CR_SUCCESS
) {
614 g_error("CM_Get_Device_ID_Size failed with code %lx", cr
);
615 error_setg_win32(errp
, GetLastError(),
616 "failed to get parent device ID length");
621 if (dev_id_size
> size
) {
622 g_free(parent_dev_id
);
623 parent_dev_id
= g_malloc(dev_id_size
);
626 cr
= CM_Get_Device_ID(parent_dev_inst
, parent_dev_id
, dev_id_size
,
628 if (cr
!= CR_SUCCESS
) {
629 g_error("CM_Get_Device_ID failed with code %lx", cr
);
630 error_setg_win32(errp
, GetLastError(),
631 "failed to get parent device ID");
636 g_debug("querying storage controller %s for PCI information",
639 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT
, parent_dev_id
,
640 NULL
, DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
641 g_free(parent_dev_id
);
643 if (parent_dev_info
== INVALID_HANDLE_VALUE
) {
644 error_setg_win32(errp
, GetLastError(),
645 "failed to get parent device");
649 parent_dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
650 if (!SetupDiEnumDeviceInfo(parent_dev_info
, 0, &parent_dev_info_data
)) {
651 error_setg_win32(errp
, GetLastError(),
652 "failed to get parent device data");
657 SetupDiEnumDeviceInfo(parent_dev_info
, j
, &parent_dev_info_data
);
659 DWORD addr
, bus
, ui_slot
, type
;
663 * There is no need to allocate buffer in the next functions. The
664 * size is known and ULONG according to
665 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
667 if (!SetupDiGetDeviceRegistryProperty(
668 parent_dev_info
, &parent_dev_info_data
, SPDRP_BUSNUMBER
,
669 &type
, (PBYTE
)&bus
, size
, NULL
)) {
670 debug_error("failed to get PCI bus");
676 * The function retrieves the device's address. This value will be
677 * transformed into device function and number
679 if (!SetupDiGetDeviceRegistryProperty(
680 parent_dev_info
, &parent_dev_info_data
, SPDRP_ADDRESS
,
681 &type
, (PBYTE
)&addr
, size
, NULL
)) {
682 debug_error("failed to get PCI address");
688 * This call returns UINumber of DEVICE_CAPABILITIES structure.
689 * This number is typically a user-perceived slot number.
691 if (!SetupDiGetDeviceRegistryProperty(
692 parent_dev_info
, &parent_dev_info_data
, SPDRP_UI_NUMBER
,
693 &type
, (PBYTE
)&ui_slot
, size
, NULL
)) {
694 debug_error("failed to get PCI slot");
700 * SetupApi gives us the same information as driver with
701 * IoGetDeviceProperty. According to Microsoft:
703 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
704 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
705 * SPDRP_ADDRESS is propertyAddress, so we do the same.
707 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
716 func
= ((int)addr
== -1) ? -1 : addr
& 0x0000FFFF;
717 slot
= ((int)addr
== -1) ? -1 : (addr
>> 16) & 0x0000FFFF;
718 if ((int)ui_slot
!= slot
) {
719 g_debug("mismatch with reported slot values: %d vs %d",
723 pci
->slot
= (int)ui_slot
;
724 pci
->function
= func
;
729 SetupDiDestroyDeviceInfoList(parent_dev_info
);
734 SetupDiDestroyDeviceInfoList(dev_info
);
739 static void get_disk_properties(HANDLE vol_h
, GuestDiskAddress
*disk
,
742 STORAGE_PROPERTY_QUERY query
;
743 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
745 ULONG size
= sizeof(buf
);
748 query
.PropertyId
= StorageDeviceProperty
;
749 query
.QueryType
= PropertyStandardQuery
;
751 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
752 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
753 size
, &received
, NULL
)) {
754 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
757 disk
->bus_type
= find_bus_type(dev_desc
->BusType
);
758 g_debug("bus type %d", disk
->bus_type
);
760 /* Query once more. Now with long enough buffer. */
761 size
= dev_desc
->Size
;
762 dev_desc
= g_malloc0(size
);
763 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
764 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
765 size
, &received
, NULL
)) {
766 error_setg_win32(errp
, GetLastError(), "failed to get serial number");
767 g_debug("failed to get serial number");
770 if (dev_desc
->SerialNumberOffset
> 0) {
774 if (dev_desc
->SerialNumberOffset
>= received
) {
775 error_setg(errp
, "failed to get serial number: offset outside the buffer");
776 g_debug("serial number offset outside the buffer");
779 serial
= (char *)dev_desc
+ dev_desc
->SerialNumberOffset
;
780 len
= received
- dev_desc
->SerialNumberOffset
;
781 g_debug("serial number \"%s\"", serial
);
783 disk
->serial
= g_strndup(serial
, len
);
784 disk
->has_serial
= true;
793 static void get_single_disk_info(int disk_number
,
794 GuestDiskAddress
*disk
, Error
**errp
)
796 SCSI_ADDRESS addr
, *scsi_ad
;
799 Error
*local_err
= NULL
;
803 g_debug("getting disk info for: %s", disk
->dev
);
804 disk_h
= CreateFile(disk
->dev
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
806 if (disk_h
== INVALID_HANDLE_VALUE
) {
807 error_setg_win32(errp
, GetLastError(), "failed to open disk");
811 get_disk_properties(disk_h
, disk
, &local_err
);
813 error_propagate(errp
, local_err
);
817 g_debug("bus type %d", disk
->bus_type
);
818 /* always set pci_controller as required by schema. get_pci_info() should
819 * report -1 values for non-PCI buses rather than fail. fail the command
820 * if that doesn't hold since that suggests some other unexpected
823 disk
->pci_controller
= get_pci_info(disk_number
, &local_err
);
825 error_propagate(errp
, local_err
);
828 if (disk
->bus_type
== GUEST_DISK_BUS_TYPE_SCSI
829 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_IDE
830 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_RAID
831 /* This bus type is not supported before Windows Server 2003 SP1 */
832 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_SAS
834 /* We are able to use the same ioctls for different bus types
835 * according to Microsoft docs
836 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
837 g_debug("getting SCSI info");
838 if (DeviceIoControl(disk_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
839 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
840 disk
->unit
= addr
.Lun
;
841 disk
->target
= addr
.TargetId
;
842 disk
->bus
= addr
.PathId
;
844 /* We do not set error in this case, because we still have enough
845 * information about volume. */
853 /* VSS provider works with volumes, thus there is no difference if
854 * the volume consist of spanned disks. Info about the first disk in the
855 * volume is returned for the spanned disk group (LVM) */
856 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
858 Error
*local_err
= NULL
;
859 GuestDiskAddressList
*list
= NULL
, *cur_item
= NULL
;
860 GuestDiskAddress
*disk
= NULL
;
864 PVOLUME_DISK_EXTENTS extents
= NULL
;
866 /* strip final backslash */
867 char *name
= g_strdup(guid
);
868 if (g_str_has_suffix(name
, "\\")) {
869 name
[strlen(name
) - 1] = 0;
872 g_debug("opening %s", name
);
873 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
875 if (vol_h
== INVALID_HANDLE_VALUE
) {
876 error_setg_win32(errp
, GetLastError(), "failed to open volume");
880 /* Get list of extents */
881 g_debug("getting disk extents");
882 size
= sizeof(VOLUME_DISK_EXTENTS
);
883 extents
= g_malloc0(size
);
884 if (!DeviceIoControl(vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
885 0, extents
, size
, &size
, NULL
)) {
886 DWORD last_err
= GetLastError();
887 if (last_err
== ERROR_MORE_DATA
) {
888 /* Try once more with big enough buffer */
890 extents
= g_malloc0(size
);
891 if (!DeviceIoControl(
892 vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
893 0, extents
, size
, NULL
, NULL
)) {
894 error_setg_win32(errp
, GetLastError(),
895 "failed to get disk extents");
898 } else if (last_err
== ERROR_INVALID_FUNCTION
) {
899 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
900 g_debug("volume not on disk");
901 disk
= g_malloc0(sizeof(GuestDiskAddress
));
902 disk
->has_dev
= true;
903 disk
->dev
= g_strdup(name
);
904 get_single_disk_info(0xffffffff, disk
, &local_err
);
906 g_debug("failed to get disk info, ignoring error: %s",
907 error_get_pretty(local_err
));
908 error_free(local_err
);
911 list
= g_malloc0(sizeof(*list
));
917 error_setg_win32(errp
, GetLastError(),
918 "failed to get disk extents");
922 g_debug("Number of extents: %lu", extents
->NumberOfDiskExtents
);
924 /* Go through each extent */
925 for (i
= 0; i
< extents
->NumberOfDiskExtents
; i
++) {
926 disk
= g_malloc0(sizeof(GuestDiskAddress
));
928 /* Disk numbers directly correspond to numbers used in UNCs
930 * See documentation for DISK_EXTENT:
931 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
933 * See also Naming Files, Paths and Namespaces:
934 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
936 disk
->has_dev
= true;
937 disk
->dev
= g_strdup_printf("\\\\.\\PhysicalDrive%lu",
938 extents
->Extents
[i
].DiskNumber
);
940 get_single_disk_info(extents
->Extents
[i
].DiskNumber
, disk
, &local_err
);
942 error_propagate(errp
, local_err
);
945 cur_item
= g_malloc0(sizeof(*list
));
946 cur_item
->value
= disk
;
948 cur_item
->next
= list
;
954 if (vol_h
!= INVALID_HANDLE_VALUE
) {
957 qapi_free_GuestDiskAddress(disk
);
966 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
971 #endif /* CONFIG_QGA_NTDDSCSI */
973 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
976 char mnt
, *mnt_point
;
978 char vol_info
[MAX_PATH
+1];
980 uint64_t i64FreeBytesToCaller
, i64TotalBytes
, i64FreeBytes
;
981 GuestFilesystemInfo
*fs
= NULL
;
983 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
984 if (GetLastError() != ERROR_MORE_DATA
) {
985 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
989 mnt_point
= g_malloc(info_size
+ 1);
990 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
992 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
996 len
= strlen(mnt_point
);
997 mnt_point
[len
] = '\\';
998 mnt_point
[len
+1] = 0;
999 if (!GetVolumeInformation(mnt_point
, vol_info
, sizeof(vol_info
), NULL
, NULL
,
1000 NULL
, (LPSTR
)&fs_name
, sizeof(fs_name
))) {
1001 if (GetLastError() != ERROR_NOT_READY
) {
1002 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
1007 fs_name
[sizeof(fs_name
) - 1] = 0;
1008 fs
= g_malloc(sizeof(*fs
));
1009 fs
->name
= g_strdup(guid
);
1010 fs
->has_total_bytes
= false;
1011 fs
->has_used_bytes
= false;
1013 fs
->mountpoint
= g_strdup("System Reserved");
1015 fs
->mountpoint
= g_strndup(mnt_point
, len
);
1016 if (GetDiskFreeSpaceEx(fs
->mountpoint
,
1017 (PULARGE_INTEGER
) & i64FreeBytesToCaller
,
1018 (PULARGE_INTEGER
) & i64TotalBytes
,
1019 (PULARGE_INTEGER
) & i64FreeBytes
)) {
1020 fs
->used_bytes
= i64TotalBytes
- i64FreeBytes
;
1021 fs
->total_bytes
= i64TotalBytes
;
1022 fs
->has_total_bytes
= true;
1023 fs
->has_used_bytes
= true;
1026 fs
->type
= g_strdup(fs_name
);
1027 fs
->disk
= build_guest_disk_info(guid
, errp
);
1033 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1036 GuestFilesystemInfoList
*new, *ret
= NULL
;
1039 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
1040 if (vol_h
== INVALID_HANDLE_VALUE
) {
1041 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1046 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, errp
);
1050 new = g_malloc(sizeof(*ret
));
1054 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
1056 if (GetLastError() != ERROR_NO_MORE_FILES
) {
1057 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
1060 FindVolumeClose(vol_h
);
1065 * Return status of freeze/thaw
1067 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1069 if (!vss_initialized()) {
1070 error_setg(errp
, QERR_UNSUPPORTED
);
1074 if (ga_is_frozen(ga_state
)) {
1075 return GUEST_FSFREEZE_STATUS_FROZEN
;
1078 return GUEST_FSFREEZE_STATUS_THAWED
;
1082 * Freeze local file systems using Volume Shadow-copy Service.
1083 * The frozen state is limited for up to 10 seconds by VSS.
1085 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1087 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1090 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1091 strList
*mountpoints
,
1095 Error
*local_err
= NULL
;
1097 if (!vss_initialized()) {
1098 error_setg(errp
, QERR_UNSUPPORTED
);
1102 slog("guest-fsfreeze called");
1104 /* cannot risk guest agent blocking itself on a write in this state */
1105 ga_set_frozen(ga_state
);
1107 qga_vss_fsfreeze(&i
, true, mountpoints
, &local_err
);
1109 error_propagate(errp
, local_err
);
1117 qmp_guest_fsfreeze_thaw(&local_err
);
1119 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
1120 error_free(local_err
);
1126 * Thaw local file systems using Volume Shadow-copy Service.
1128 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1132 if (!vss_initialized()) {
1133 error_setg(errp
, QERR_UNSUPPORTED
);
1137 qga_vss_fsfreeze(&i
, false, NULL
, errp
);
1139 ga_unset_frozen(ga_state
);
1143 static void guest_fsfreeze_cleanup(void)
1147 if (!vss_initialized()) {
1151 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1152 qmp_guest_fsfreeze_thaw(&err
);
1154 slog("failed to clean up frozen filesystems: %s",
1155 error_get_pretty(err
));
1164 * Walk list of mounted file systems in the guest, and discard unused
1167 GuestFilesystemTrimResponse
*
1168 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1170 GuestFilesystemTrimResponse
*resp
;
1172 WCHAR guid
[MAX_PATH
] = L
"";
1176 ZeroMemory(&osvi
, sizeof(OSVERSIONINFO
));
1177 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1178 GetVersionEx(&osvi
);
1179 win8_or_later
= (osvi
.dwMajorVersion
> 6 ||
1180 ((osvi
.dwMajorVersion
== 6) &&
1181 (osvi
.dwMinorVersion
>= 2)));
1182 if (!win8_or_later
) {
1183 error_setg(errp
, "fstrim is only supported for Win8+");
1187 handle
= FindFirstVolumeW(guid
, ARRAYSIZE(guid
));
1188 if (handle
== INVALID_HANDLE_VALUE
) {
1189 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1193 resp
= g_new0(GuestFilesystemTrimResponse
, 1);
1196 GuestFilesystemTrimResult
*res
;
1197 GuestFilesystemTrimResultList
*list
;
1199 DWORD char_count
= 0;
1201 GError
*gerr
= NULL
;
1204 GetVolumePathNamesForVolumeNameW(guid
, NULL
, 0, &char_count
);
1206 if (GetLastError() != ERROR_MORE_DATA
) {
1209 if (GetDriveTypeW(guid
) != DRIVE_FIXED
) {
1213 uc_path
= g_malloc(sizeof(WCHAR
) * char_count
);
1214 if (!GetVolumePathNamesForVolumeNameW(guid
, uc_path
, char_count
,
1215 &char_count
) || !*uc_path
) {
1216 /* strange, but this condition could be faced even with size == 2 */
1221 res
= g_new0(GuestFilesystemTrimResult
, 1);
1223 path
= g_utf16_to_utf8(uc_path
, char_count
, NULL
, NULL
, &gerr
);
1228 res
->has_error
= true;
1229 res
->error
= g_strdup(gerr
->message
);
1236 list
= g_new0(GuestFilesystemTrimResultList
, 1);
1238 list
->next
= resp
->paths
;
1242 memset(argv
, 0, sizeof(argv
));
1243 argv
[0] = (gchar
*)"defrag.exe";
1244 argv
[1] = (gchar
*)"/L";
1247 if (!g_spawn_sync(NULL
, argv
, NULL
, G_SPAWN_SEARCH_PATH
, NULL
, NULL
,
1248 &out
/* stdout */, NULL
/* stdin */,
1250 res
->has_error
= true;
1251 res
->error
= g_strdup(gerr
->message
);
1254 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1255 Error is reported in the output with something like
1256 (x89000020) etc code in the stdout */
1259 gchar
**lines
= g_strsplit(out
, "\r\n", 0);
1262 for (i
= 0; lines
[i
] != NULL
; i
++) {
1263 if (g_strstr_len(lines
[i
], -1, "(0x") == NULL
) {
1266 res
->has_error
= true;
1267 res
->error
= g_strdup(lines
[i
]);
1272 } while (FindNextVolumeW(handle
, guid
, ARRAYSIZE(guid
)));
1274 FindVolumeClose(handle
);
1279 GUEST_SUSPEND_MODE_DISK
,
1280 GUEST_SUSPEND_MODE_RAM
1283 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
1285 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
1286 Error
*local_err
= NULL
;
1288 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
1289 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
1290 error_setg(&local_err
, 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(&local_err
, 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(&local_err
, QERR_QGA_COMMAND_FAILED
,
1305 "suspend-to-ram not supported by OS");
1309 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "mode",
1310 "GuestSuspendMode");
1314 error_propagate(errp
, local_err
);
1317 static DWORD WINAPI
do_suspend(LPVOID opaque
)
1319 GuestSuspendMode
*mode
= opaque
;
1322 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
1323 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
1324 slog("failed to suspend guest: %s", emsg
);
1331 void qmp_guest_suspend_disk(Error
**errp
)
1333 Error
*local_err
= NULL
;
1334 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1336 *mode
= GUEST_SUSPEND_MODE_DISK
;
1337 check_suspend_mode(*mode
, &local_err
);
1338 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1339 execute_async(do_suspend
, mode
, &local_err
);
1342 error_propagate(errp
, local_err
);
1347 void qmp_guest_suspend_ram(Error
**errp
)
1349 Error
*local_err
= NULL
;
1350 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1352 *mode
= GUEST_SUSPEND_MODE_RAM
;
1353 check_suspend_mode(*mode
, &local_err
);
1354 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1355 execute_async(do_suspend
, mode
, &local_err
);
1358 error_propagate(errp
, local_err
);
1363 void qmp_guest_suspend_hybrid(Error
**errp
)
1365 error_setg(errp
, QERR_UNSUPPORTED
);
1368 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
1370 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
1371 ULONG adptr_addrs_len
= 0;
1374 /* Call the first time to get the adptr_addrs_len. */
1375 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1376 NULL
, adptr_addrs
, &adptr_addrs_len
);
1378 adptr_addrs
= g_malloc(adptr_addrs_len
);
1379 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1380 NULL
, adptr_addrs
, &adptr_addrs_len
);
1381 if (ret
!= ERROR_SUCCESS
) {
1382 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
1383 g_free(adptr_addrs
);
1389 static char *guest_wctomb_dup(WCHAR
*wstr
)
1394 str_size
= WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, NULL
, 0, NULL
, NULL
);
1395 /* add 1 to str_size for NULL terminator */
1396 str
= g_malloc(str_size
+ 1);
1397 WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, str
, str_size
, NULL
, NULL
);
1401 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
1404 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
1408 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
1409 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1410 len
= sizeof(addr_str
);
1411 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
1412 ip_addr
->Address
.iSockaddrLength
,
1417 error_setg_win32(errp
, WSAGetLastError(),
1418 "failed address presentation form conversion");
1421 return g_strdup(addr_str
);
1426 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1428 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1429 * field to obtain the prefix.
1431 return ip_addr
->OnLinkPrefixLength
;
1434 #define INTERFACE_PATH_BUF_SZ 512
1436 static DWORD
get_interface_index(const char *guid
)
1440 wchar_t wbuf
[INTERFACE_PATH_BUF_SZ
];
1441 snwprintf(wbuf
, INTERFACE_PATH_BUF_SZ
, L
"\\device\\tcpip_%s", guid
);
1442 wbuf
[INTERFACE_PATH_BUF_SZ
- 1] = 0;
1443 status
= GetAdapterIndex (wbuf
, &index
);
1444 if (status
!= NO_ERROR
) {
1451 typedef NETIOAPI_API (WINAPI
*GetIfEntry2Func
)(PMIB_IF_ROW2 Row
);
1453 static int guest_get_network_stats(const char *name
,
1454 GuestNetworkInterfaceStat
*stats
)
1456 OSVERSIONINFO os_ver
;
1458 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1459 GetVersionEx(&os_ver
);
1460 if (os_ver
.dwMajorVersion
>= 6) {
1461 MIB_IF_ROW2 a_mid_ifrow
;
1462 GetIfEntry2Func getifentry2_ex
;
1464 HMODULE module
= GetModuleHandle("iphlpapi");
1465 PVOID func
= GetProcAddress(module
, "GetIfEntry2");
1471 getifentry2_ex
= (GetIfEntry2Func
)func
;
1472 if_index
= get_interface_index(name
);
1473 if (if_index
== (DWORD
)~0) {
1477 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1478 a_mid_ifrow
.InterfaceIndex
= if_index
;
1479 if (NO_ERROR
== getifentry2_ex(&a_mid_ifrow
)) {
1480 stats
->rx_bytes
= a_mid_ifrow
.InOctets
;
1481 stats
->rx_packets
= a_mid_ifrow
.InUcastPkts
;
1482 stats
->rx_errs
= a_mid_ifrow
.InErrors
;
1483 stats
->rx_dropped
= a_mid_ifrow
.InDiscards
;
1484 stats
->tx_bytes
= a_mid_ifrow
.OutOctets
;
1485 stats
->tx_packets
= a_mid_ifrow
.OutUcastPkts
;
1486 stats
->tx_errs
= a_mid_ifrow
.OutErrors
;
1487 stats
->tx_dropped
= a_mid_ifrow
.OutDiscards
;
1494 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1496 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1497 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1498 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1499 GuestIpAddressList
*head_addr
, *cur_addr
;
1500 GuestNetworkInterfaceList
*info
;
1501 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1502 GuestIpAddressList
*address_item
= NULL
;
1503 unsigned char *mac_addr
;
1509 adptr_addrs
= guest_get_adapters_addresses(errp
);
1510 if (adptr_addrs
== NULL
) {
1514 /* Make WSA APIs available. */
1515 wsa_version
= MAKEWORD(2, 2);
1516 ret
= WSAStartup(wsa_version
, &wsa_data
);
1518 error_setg_win32(errp
, ret
, "failed socket startup");
1522 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1523 info
= g_malloc0(sizeof(*info
));
1525 if (cur_item
== NULL
) {
1526 head
= cur_item
= info
;
1528 cur_item
->next
= info
;
1532 info
->value
= g_malloc0(sizeof(*info
->value
));
1533 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1535 if (addr
->PhysicalAddressLength
!= 0) {
1536 mac_addr
= addr
->PhysicalAddress
;
1538 info
->value
->hardware_address
=
1539 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1540 (int) mac_addr
[0], (int) mac_addr
[1],
1541 (int) mac_addr
[2], (int) mac_addr
[3],
1542 (int) mac_addr
[4], (int) mac_addr
[5]);
1544 info
->value
->has_hardware_address
= true;
1549 for (ip_addr
= addr
->FirstUnicastAddress
;
1551 ip_addr
= ip_addr
->Next
) {
1552 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1553 if (addr_str
== NULL
) {
1557 address_item
= g_malloc0(sizeof(*address_item
));
1560 head_addr
= cur_addr
= address_item
;
1562 cur_addr
->next
= address_item
;
1563 cur_addr
= address_item
;
1566 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1567 address_item
->value
->ip_address
= addr_str
;
1568 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1569 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1570 address_item
->value
->ip_address_type
=
1571 GUEST_IP_ADDRESS_TYPE_IPV4
;
1572 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1573 address_item
->value
->ip_address_type
=
1574 GUEST_IP_ADDRESS_TYPE_IPV6
;
1578 info
->value
->has_ip_addresses
= true;
1579 info
->value
->ip_addresses
= head_addr
;
1581 if (!info
->value
->has_statistics
) {
1582 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1583 if (guest_get_network_stats(addr
->AdapterName
,
1584 interface_stat
) == -1) {
1585 info
->value
->has_statistics
= false;
1586 g_free(interface_stat
);
1588 info
->value
->statistics
= interface_stat
;
1589 info
->value
->has_statistics
= true;
1595 g_free(adptr_addrs
);
1599 int64_t qmp_guest_get_time(Error
**errp
)
1601 SYSTEMTIME ts
= {0};
1605 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1606 error_setg(errp
, "Failed to get time");
1610 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1611 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1615 return ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1616 - W32_FT_OFFSET
) * 100;
1619 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1621 Error
*local_err
= NULL
;
1627 /* Unfortunately, Windows libraries don't provide an easy way to access
1630 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1632 * Instead, a workaround is to use the Windows win32tm command to
1633 * resync the time using the Windows Time service.
1638 HRESULT hr
= system("w32tm /resync /nowait");
1640 if (GetLastError() != 0) {
1641 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1642 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1643 } else if (hr
!= 0) {
1644 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1645 error_setg(errp
, "Windows Time service not running on the "
1648 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1649 FORMAT_MESSAGE_FROM_SYSTEM
|
1650 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1651 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1652 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1654 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1655 "t retrieve error message", hr
);
1657 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1658 (LPCTSTR
)msg_buffer
);
1659 LocalFree(msg_buffer
);
1662 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1663 error_setg(errp
, "No internet connection on guest, sync not "
1669 /* Validate time passed by user. */
1670 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1671 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1675 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1677 tf
.dwLowDateTime
= (DWORD
) time
;
1678 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1680 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1681 error_setg(errp
, "Failed to convert system time %d",
1682 (int)GetLastError());
1686 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1688 error_propagate(errp
, local_err
);
1692 if (!SetSystemTime(&ts
)) {
1693 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1698 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1700 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1702 GuestLogicalProcessorList
*head
, **link
;
1703 Error
*local_err
= NULL
;
1712 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1713 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1714 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1715 ptr
= pslpi
= g_malloc0(length
);
1716 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1717 error_setg(&local_err
, "Failed to get processor information: %d",
1718 (int)GetLastError());
1721 error_setg(&local_err
,
1722 "Failed to get processor information buffer length: %d",
1723 (int)GetLastError());
1726 while ((local_err
== NULL
) && (length
> 0)) {
1727 if (pslpi
->Relationship
== RelationProcessorCore
) {
1728 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1730 while (cpu_bits
> 0) {
1731 if (!!(cpu_bits
& 1)) {
1732 GuestLogicalProcessor
*vcpu
;
1733 GuestLogicalProcessorList
*entry
;
1735 vcpu
= g_malloc0(sizeof *vcpu
);
1736 vcpu
->logical_id
= current
++;
1737 vcpu
->online
= true;
1738 vcpu
->has_can_offline
= true;
1740 entry
= g_malloc0(sizeof *entry
);
1741 entry
->value
= vcpu
;
1744 link
= &entry
->next
;
1749 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1750 pslpi
++; /* next entry */
1755 if (local_err
== NULL
) {
1759 /* there's no guest with zero VCPUs */
1760 error_setg(&local_err
, "Guest reported zero VCPUs");
1763 qapi_free_GuestLogicalProcessorList(head
);
1764 error_propagate(errp
, local_err
);
1768 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1770 error_setg(errp
, QERR_UNSUPPORTED
);
1775 get_net_error_message(gint error
)
1777 HMODULE module
= NULL
;
1778 gchar
*retval
= NULL
;
1779 wchar_t *msg
= NULL
;
1783 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1784 FORMAT_MESSAGE_IGNORE_INSERTS
|
1785 FORMAT_MESSAGE_FROM_SYSTEM
;
1787 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1788 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1790 if (module
!= NULL
) {
1791 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1795 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1798 nchars
= wcslen(msg
);
1801 msg
[nchars
- 1] == L
'\n' &&
1802 msg
[nchars
- 2] == L
'\r') {
1803 msg
[nchars
- 2] = L
'\0';
1806 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1811 if (module
!= NULL
) {
1812 FreeLibrary(module
);
1818 void qmp_guest_set_user_password(const char *username
,
1819 const char *password
,
1824 char *rawpasswddata
= NULL
;
1825 size_t rawpasswdlen
;
1826 wchar_t *user
= NULL
, *wpass
= NULL
;
1827 USER_INFO_1003 pi1003
= { 0, };
1828 GError
*gerr
= NULL
;
1831 error_setg(errp
, QERR_UNSUPPORTED
);
1835 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1836 if (!rawpasswddata
) {
1839 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1840 rawpasswddata
[rawpasswdlen
] = '\0';
1842 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1847 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1852 pi1003
.usri1003_password
= wpass
;
1853 nas
= NetUserSetInfo(NULL
, user
,
1854 1003, (LPBYTE
)&pi1003
,
1857 if (nas
!= NERR_Success
) {
1858 gchar
*msg
= get_net_error_message(nas
);
1859 error_setg(errp
, "failed to set password: %s", msg
);
1865 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1870 g_free(rawpasswddata
);
1873 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1875 error_setg(errp
, QERR_UNSUPPORTED
);
1879 GuestMemoryBlockResponseList
*
1880 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1882 error_setg(errp
, QERR_UNSUPPORTED
);
1886 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1888 error_setg(errp
, QERR_UNSUPPORTED
);
1892 /* add unsupported commands to the blacklist */
1893 GList
*ga_command_blacklist_init(GList
*blacklist
)
1895 const char *list_unsupported
[] = {
1896 "guest-suspend-hybrid",
1898 "guest-get-memory-blocks", "guest-set-memory-blocks",
1899 "guest-get-memory-block-size", "guest-get-memory-block-info",
1901 char **p
= (char **)list_unsupported
;
1904 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1907 if (!vss_init(true)) {
1908 g_debug("vss_init failed, vss commands are going to be disabled");
1909 const char *list
[] = {
1910 "guest-get-fsinfo", "guest-fsfreeze-status",
1911 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1915 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1922 /* register init/cleanup routines for stateful command groups */
1923 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1925 if (!vss_initialized()) {
1926 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1930 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1931 typedef struct _GA_WTSINFOA
{
1932 WTS_CONNECTSTATE_CLASS State
;
1934 DWORD IncomingBytes
;
1935 DWORD OutgoingBytes
;
1936 DWORD IncomingFrames
;
1937 DWORD OutgoingFrames
;
1938 DWORD IncomingCompressedBytes
;
1939 DWORD OutgoingCompressedBy
;
1940 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
1941 CHAR Domain
[DOMAIN_LENGTH
];
1942 CHAR UserName
[USERNAME_LENGTH
+ 1];
1943 LARGE_INTEGER ConnectTime
;
1944 LARGE_INTEGER DisconnectTime
;
1945 LARGE_INTEGER LastInputTime
;
1946 LARGE_INTEGER LogonTime
;
1947 LARGE_INTEGER CurrentTime
;
1951 GuestUserList
*qmp_guest_get_users(Error
**errp
)
1953 #define QGA_NANOSECONDS 10000000
1955 GHashTable
*cache
= NULL
;
1956 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
1958 DWORD buffer_size
= 0, count
= 0, i
= 0;
1959 GA_WTSINFOA
*info
= NULL
;
1960 WTS_SESSION_INFOA
*entries
= NULL
;
1961 GuestUserList
*item
= NULL
;
1962 GuestUser
*user
= NULL
;
1963 gpointer value
= NULL
;
1965 double login_time
= 0;
1967 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
1969 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
1970 for (i
= 0; i
< count
; ++i
) {
1973 if (WTSQuerySessionInformationA(
1975 entries
[i
].SessionId
,
1981 if (strlen(info
->UserName
) == 0) {
1982 WTSFreeMemory(info
);
1986 login
= info
->LogonTime
.QuadPart
;
1987 login
-= W32_FT_OFFSET
;
1988 login_time
= ((double)login
) / QGA_NANOSECONDS
;
1990 if (g_hash_table_contains(cache
, info
->UserName
)) {
1991 value
= g_hash_table_lookup(cache
, info
->UserName
);
1992 user
= (GuestUser
*)value
;
1993 if (user
->login_time
> login_time
) {
1994 user
->login_time
= login_time
;
1997 item
= g_new0(GuestUserList
, 1);
1998 item
->value
= g_new0(GuestUser
, 1);
2000 item
->value
->user
= g_strdup(info
->UserName
);
2001 item
->value
->domain
= g_strdup(info
->Domain
);
2002 item
->value
->has_domain
= true;
2004 item
->value
->login_time
= login_time
;
2006 g_hash_table_add(cache
, item
->value
->user
);
2009 head
= cur_item
= item
;
2011 cur_item
->next
= item
;
2016 WTSFreeMemory(info
);
2018 WTSFreeMemory(entries
);
2020 g_hash_table_destroy(cache
);
2024 typedef struct _ga_matrix_lookup_t
{
2027 char const *version
;
2028 char const *version_id
;
2029 } ga_matrix_lookup_t
;
2031 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][8] = {
2033 /* Desktop editions */
2034 { 5, 0, "Microsoft Windows 2000", "2000"},
2035 { 5, 1, "Microsoft Windows XP", "xp"},
2036 { 6, 0, "Microsoft Windows Vista", "vista"},
2037 { 6, 1, "Microsoft Windows 7" "7"},
2038 { 6, 2, "Microsoft Windows 8", "8"},
2039 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2040 {10, 0, "Microsoft Windows 10", "10"},
2043 /* Server editions */
2044 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2045 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2046 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2047 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2048 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2055 typedef struct _ga_win_10_0_server_t
{
2057 char const *version
;
2058 char const *version_id
;
2059 } ga_win_10_0_server_t
;
2061 static ga_win_10_0_server_t
const WIN_10_0_SERVER_VERSION_MATRIX
[3] = {
2062 {14393, "Microsoft Windows Server 2016", "2016"},
2063 {17763, "Microsoft Windows Server 2019", "2019"},
2067 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
2069 typedef NTSTATUS(WINAPI
* rtl_get_version_t
)(
2070 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
2072 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
2074 HMODULE module
= GetModuleHandle("ntdll");
2075 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
2077 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
2078 "Failed to get address of RtlGetVersion");
2082 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
2083 rtl_get_version(info
);
2087 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
2089 DWORD major
= os_version
->dwMajorVersion
;
2090 DWORD minor
= os_version
->dwMinorVersion
;
2091 DWORD build
= os_version
->dwBuildNumber
;
2092 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
2093 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
2094 ga_win_10_0_server_t
const *win_10_0_table
= WIN_10_0_SERVER_VERSION_MATRIX
;
2095 while (table
->version
!= NULL
) {
2096 if (major
== 10 && minor
== 0 && tbl_idx
) {
2097 while (win_10_0_table
->version
!= NULL
) {
2098 if (build
<= win_10_0_table
->final_build
) {
2100 return g_strdup(win_10_0_table
->version_id
);
2102 return g_strdup(win_10_0_table
->version
);
2107 } else if (major
== table
->major
&& minor
== table
->minor
) {
2109 return g_strdup(table
->version_id
);
2111 return g_strdup(table
->version
);
2116 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2118 return g_strdup("N/A");
2121 static char *ga_get_win_product_name(Error
**errp
)
2125 char *result
= g_malloc0(size
);
2126 LONG err
= ERROR_SUCCESS
;
2128 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
2129 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2131 if (err
!= ERROR_SUCCESS
) {
2132 error_setg_win32(errp
, err
, "failed to open registry key");
2136 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2137 (LPBYTE
)result
, &size
);
2138 if (err
== ERROR_MORE_DATA
) {
2139 slog("ProductName longer than expected (%lu bytes), retrying",
2144 result
= g_malloc0(size
);
2145 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2146 (LPBYTE
)result
, &size
);
2149 if (err
!= ERROR_SUCCESS
) {
2150 error_setg_win32(errp
, err
, "failed to retrive ProductName");
2161 static char *ga_get_current_arch(void)
2164 GetNativeSystemInfo(&info
);
2165 char *result
= NULL
;
2166 switch (info
.wProcessorArchitecture
) {
2167 case PROCESSOR_ARCHITECTURE_AMD64
:
2168 result
= g_strdup("x86_64");
2170 case PROCESSOR_ARCHITECTURE_ARM
:
2171 result
= g_strdup("arm");
2173 case PROCESSOR_ARCHITECTURE_IA64
:
2174 result
= g_strdup("ia64");
2176 case PROCESSOR_ARCHITECTURE_INTEL
:
2177 result
= g_strdup("x86");
2179 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
2181 slog("unknown processor architecture 0x%0x",
2182 info
.wProcessorArchitecture
);
2183 result
= g_strdup("unknown");
2189 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2191 Error
*local_err
= NULL
;
2192 OSVERSIONINFOEXW os_version
= {0};
2197 ga_get_win_version(&os_version
, &local_err
);
2199 error_propagate(errp
, local_err
);
2203 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
2204 product_name
= ga_get_win_product_name(&local_err
);
2205 if (product_name
== NULL
) {
2206 error_propagate(errp
, local_err
);
2210 info
= g_new0(GuestOSInfo
, 1);
2212 info
->has_kernel_version
= true;
2213 info
->kernel_version
= g_strdup_printf("%lu.%lu",
2214 os_version
.dwMajorVersion
,
2215 os_version
.dwMinorVersion
);
2216 info
->has_kernel_release
= true;
2217 info
->kernel_release
= g_strdup_printf("%lu",
2218 os_version
.dwBuildNumber
);
2219 info
->has_machine
= true;
2220 info
->machine
= ga_get_current_arch();
2222 info
->has_id
= true;
2223 info
->id
= g_strdup("mswindows");
2224 info
->has_name
= true;
2225 info
->name
= g_strdup("Microsoft Windows");
2226 info
->has_pretty_name
= true;
2227 info
->pretty_name
= product_name
;
2228 info
->has_version
= true;
2229 info
->version
= ga_get_win_name(&os_version
, false);
2230 info
->has_version_id
= true;
2231 info
->version_id
= ga_get_win_name(&os_version
, true);
2232 info
->has_variant
= true;
2233 info
->variant
= g_strdup(server
? "server" : "client");
2234 info
->has_variant_id
= true;
2235 info
->variant_id
= g_strdup(server
? "server" : "client");