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_try_malloc0(count
+ 1);
349 "failed to allocate sufficient memory "
350 "to complete the requested service");
353 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
355 error_setg_win32(errp
, GetLastError(), "failed to read file");
356 slog("guest-file-read failed, handle %" PRId64
, handle
);
359 read_data
= g_new0(GuestFileRead
, 1);
360 read_data
->count
= (size_t)read_count
;
361 read_data
->eof
= read_count
== 0;
363 if (read_count
!= 0) {
364 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
372 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
373 bool has_count
, int64_t count
,
376 GuestFileWrite
*write_data
= NULL
;
381 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
388 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
395 } else if (count
< 0 || count
> buf_len
) {
396 error_setg(errp
, "value '%" PRId64
397 "' is invalid for argument count", count
);
401 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
403 error_setg_win32(errp
, GetLastError(), "failed to write to file");
404 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
406 write_data
= g_new0(GuestFileWrite
, 1);
407 write_data
->count
= (size_t) write_count
;
415 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
416 GuestFileWhence
*whence_code
,
419 GuestFileHandle
*gfh
;
420 GuestFileSeek
*seek_data
;
422 LARGE_INTEGER new_pos
, off_pos
;
423 off_pos
.QuadPart
= offset
;
428 gfh
= guest_file_handle_find(handle
, errp
);
433 /* We stupidly exposed 'whence':'int' in our qapi */
434 whence
= ga_parse_whence(whence_code
, &err
);
436 error_propagate(errp
, err
);
441 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
443 error_setg_win32(errp
, GetLastError(), "failed to seek file");
446 seek_data
= g_new0(GuestFileSeek
, 1);
447 seek_data
->position
= new_pos
.QuadPart
;
451 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
454 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
460 if (!FlushFileBuffers(fh
)) {
461 error_setg_win32(errp
, GetLastError(), "failed to flush file");
465 #ifdef CONFIG_QGA_NTDDSCSI
467 static GuestDiskBusType win2qemu
[] = {
468 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
469 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
470 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
471 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
472 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
473 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
474 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
475 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
476 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
477 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
478 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
479 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
480 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
481 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
482 #if (_WIN32_WINNT >= 0x0601)
483 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
484 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
488 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
490 if (bus
>= ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
491 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
493 return win2qemu
[(int)bus
];
496 DEFINE_GUID(GUID_DEVINTERFACE_DISK
,
497 0x53f56307L
, 0xb6bf, 0x11d0, 0x94, 0xf2,
498 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
499 DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT
,
500 0x2accfe60L
, 0xc130, 0x11d2, 0xb0, 0x82,
501 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
503 static GuestPCIAddress
*get_pci_info(int number
, Error
**errp
)
506 SP_DEVINFO_DATA dev_info_data
;
507 SP_DEVICE_INTERFACE_DATA dev_iface_data
;
510 GuestPCIAddress
*pci
= NULL
;
511 bool partial_pci
= false;
513 pci
= g_malloc0(sizeof(*pci
));
519 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK
, 0, 0,
520 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
521 if (dev_info
== INVALID_HANDLE_VALUE
) {
522 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
526 g_debug("enumerating devices");
527 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
528 dev_iface_data
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
529 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
530 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data
= NULL
;
531 STORAGE_DEVICE_NUMBER sdn
;
532 char *parent_dev_id
= NULL
;
533 HDEVINFO parent_dev_info
;
534 SP_DEVINFO_DATA parent_dev_info_data
;
538 g_debug("getting device path");
539 if (SetupDiEnumDeviceInterfaces(dev_info
, &dev_info_data
,
540 &GUID_DEVINTERFACE_DISK
, 0,
542 while (!SetupDiGetDeviceInterfaceDetail(dev_info
, &dev_iface_data
,
543 pdev_iface_detail_data
,
546 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
547 pdev_iface_detail_data
= g_malloc(size
);
548 pdev_iface_detail_data
->cbSize
=
549 sizeof(*pdev_iface_detail_data
);
551 error_setg_win32(errp
, GetLastError(),
552 "failed to get device interfaces");
557 dev_file
= CreateFile(pdev_iface_detail_data
->DevicePath
, 0,
558 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0,
560 g_free(pdev_iface_detail_data
);
562 if (!DeviceIoControl(dev_file
, IOCTL_STORAGE_GET_DEVICE_NUMBER
,
563 NULL
, 0, &sdn
, sizeof(sdn
), &size
, NULL
)) {
564 CloseHandle(dev_file
);
565 error_setg_win32(errp
, GetLastError(),
566 "failed to get device slot number");
570 CloseHandle(dev_file
);
571 if (sdn
.DeviceNumber
!= number
) {
575 error_setg_win32(errp
, GetLastError(),
576 "failed to get device interfaces");
580 g_debug("found device slot %d. Getting storage controller", number
);
583 DEVINST dev_inst
, parent_dev_inst
;
584 ULONG dev_id_size
= 0;
587 while (!SetupDiGetDeviceInstanceId(dev_info
, &dev_info_data
,
588 parent_dev_id
, size
, &size
)) {
589 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
590 parent_dev_id
= g_malloc(size
);
592 error_setg_win32(errp
, GetLastError(),
593 "failed to get device instance ID");
599 * CM API used here as opposed to
600 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
601 * which exports are only available in mingw-w64 6+
603 cr
= CM_Locate_DevInst(&dev_inst
, parent_dev_id
, 0);
604 if (cr
!= CR_SUCCESS
) {
605 g_error("CM_Locate_DevInst failed with code %lx", cr
);
606 error_setg_win32(errp
, GetLastError(),
607 "failed to get device instance");
610 cr
= CM_Get_Parent(&parent_dev_inst
, dev_inst
, 0);
611 if (cr
!= CR_SUCCESS
) {
612 g_error("CM_Get_Parent failed with code %lx", cr
);
613 error_setg_win32(errp
, GetLastError(),
614 "failed to get parent device instance");
618 cr
= CM_Get_Device_ID_Size(&dev_id_size
, parent_dev_inst
, 0);
619 if (cr
!= CR_SUCCESS
) {
620 g_error("CM_Get_Device_ID_Size failed with code %lx", cr
);
621 error_setg_win32(errp
, GetLastError(),
622 "failed to get parent device ID length");
627 if (dev_id_size
> size
) {
628 g_free(parent_dev_id
);
629 parent_dev_id
= g_malloc(dev_id_size
);
632 cr
= CM_Get_Device_ID(parent_dev_inst
, parent_dev_id
, dev_id_size
,
634 if (cr
!= CR_SUCCESS
) {
635 g_error("CM_Get_Device_ID failed with code %lx", cr
);
636 error_setg_win32(errp
, GetLastError(),
637 "failed to get parent device ID");
642 g_debug("querying storage controller %s for PCI information",
645 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT
, parent_dev_id
,
646 NULL
, DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
647 g_free(parent_dev_id
);
649 if (parent_dev_info
== INVALID_HANDLE_VALUE
) {
650 error_setg_win32(errp
, GetLastError(),
651 "failed to get parent device");
655 parent_dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
656 if (!SetupDiEnumDeviceInfo(parent_dev_info
, 0, &parent_dev_info_data
)) {
657 error_setg_win32(errp
, GetLastError(),
658 "failed to get parent device data");
663 SetupDiEnumDeviceInfo(parent_dev_info
, j
, &parent_dev_info_data
);
665 DWORD addr
, bus
, ui_slot
, type
;
669 * There is no need to allocate buffer in the next functions. The
670 * size is known and ULONG according to
671 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
673 if (!SetupDiGetDeviceRegistryProperty(
674 parent_dev_info
, &parent_dev_info_data
, SPDRP_BUSNUMBER
,
675 &type
, (PBYTE
)&bus
, size
, NULL
)) {
676 debug_error("failed to get PCI bus");
682 * The function retrieves the device's address. This value will be
683 * transformed into device function and number
685 if (!SetupDiGetDeviceRegistryProperty(
686 parent_dev_info
, &parent_dev_info_data
, SPDRP_ADDRESS
,
687 &type
, (PBYTE
)&addr
, size
, NULL
)) {
688 debug_error("failed to get PCI address");
694 * This call returns UINumber of DEVICE_CAPABILITIES structure.
695 * This number is typically a user-perceived slot number.
697 if (!SetupDiGetDeviceRegistryProperty(
698 parent_dev_info
, &parent_dev_info_data
, SPDRP_UI_NUMBER
,
699 &type
, (PBYTE
)&ui_slot
, size
, NULL
)) {
700 debug_error("failed to get PCI slot");
706 * SetupApi gives us the same information as driver with
707 * IoGetDeviceProperty. According to Microsoft:
709 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
710 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
711 * SPDRP_ADDRESS is propertyAddress, so we do the same.
713 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
722 func
= ((int)addr
== -1) ? -1 : addr
& 0x0000FFFF;
723 slot
= ((int)addr
== -1) ? -1 : (addr
>> 16) & 0x0000FFFF;
724 if ((int)ui_slot
!= slot
) {
725 g_debug("mismatch with reported slot values: %d vs %d",
729 pci
->slot
= (int)ui_slot
;
730 pci
->function
= func
;
735 SetupDiDestroyDeviceInfoList(parent_dev_info
);
740 SetupDiDestroyDeviceInfoList(dev_info
);
745 static void get_disk_properties(HANDLE vol_h
, GuestDiskAddress
*disk
,
748 STORAGE_PROPERTY_QUERY query
;
749 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
751 ULONG size
= sizeof(buf
);
754 query
.PropertyId
= StorageDeviceProperty
;
755 query
.QueryType
= PropertyStandardQuery
;
757 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
758 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
759 size
, &received
, NULL
)) {
760 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
763 disk
->bus_type
= find_bus_type(dev_desc
->BusType
);
764 g_debug("bus type %d", disk
->bus_type
);
766 /* Query once more. Now with long enough buffer. */
767 size
= dev_desc
->Size
;
768 dev_desc
= g_malloc0(size
);
769 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
770 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
771 size
, &received
, NULL
)) {
772 error_setg_win32(errp
, GetLastError(), "failed to get serial number");
773 g_debug("failed to get serial number");
776 if (dev_desc
->SerialNumberOffset
> 0) {
780 if (dev_desc
->SerialNumberOffset
>= received
) {
781 error_setg(errp
, "failed to get serial number: offset outside the buffer");
782 g_debug("serial number offset outside the buffer");
785 serial
= (char *)dev_desc
+ dev_desc
->SerialNumberOffset
;
786 len
= received
- dev_desc
->SerialNumberOffset
;
787 g_debug("serial number \"%s\"", serial
);
789 disk
->serial
= g_strndup(serial
, len
);
790 disk
->has_serial
= true;
799 static void get_single_disk_info(int disk_number
,
800 GuestDiskAddress
*disk
, Error
**errp
)
802 SCSI_ADDRESS addr
, *scsi_ad
;
805 Error
*local_err
= NULL
;
809 g_debug("getting disk info for: %s", disk
->dev
);
810 disk_h
= CreateFile(disk
->dev
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
812 if (disk_h
== INVALID_HANDLE_VALUE
) {
813 error_setg_win32(errp
, GetLastError(), "failed to open disk");
817 get_disk_properties(disk_h
, disk
, &local_err
);
819 error_propagate(errp
, local_err
);
823 g_debug("bus type %d", disk
->bus_type
);
824 /* always set pci_controller as required by schema. get_pci_info() should
825 * report -1 values for non-PCI buses rather than fail. fail the command
826 * if that doesn't hold since that suggests some other unexpected
829 disk
->pci_controller
= get_pci_info(disk_number
, &local_err
);
831 error_propagate(errp
, local_err
);
834 if (disk
->bus_type
== GUEST_DISK_BUS_TYPE_SCSI
835 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_IDE
836 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_RAID
837 /* This bus type is not supported before Windows Server 2003 SP1 */
838 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_SAS
840 /* We are able to use the same ioctls for different bus types
841 * according to Microsoft docs
842 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
843 g_debug("getting SCSI info");
844 if (DeviceIoControl(disk_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
845 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
846 disk
->unit
= addr
.Lun
;
847 disk
->target
= addr
.TargetId
;
848 disk
->bus
= addr
.PathId
;
850 /* We do not set error in this case, because we still have enough
851 * information about volume. */
859 /* VSS provider works with volumes, thus there is no difference if
860 * the volume consist of spanned disks. Info about the first disk in the
861 * volume is returned for the spanned disk group (LVM) */
862 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
864 Error
*local_err
= NULL
;
865 GuestDiskAddressList
*list
= NULL
, *cur_item
= NULL
;
866 GuestDiskAddress
*disk
= NULL
;
870 PVOLUME_DISK_EXTENTS extents
= NULL
;
872 /* strip final backslash */
873 char *name
= g_strdup(guid
);
874 if (g_str_has_suffix(name
, "\\")) {
875 name
[strlen(name
) - 1] = 0;
878 g_debug("opening %s", name
);
879 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
881 if (vol_h
== INVALID_HANDLE_VALUE
) {
882 error_setg_win32(errp
, GetLastError(), "failed to open volume");
886 /* Get list of extents */
887 g_debug("getting disk extents");
888 size
= sizeof(VOLUME_DISK_EXTENTS
);
889 extents
= g_malloc0(size
);
890 if (!DeviceIoControl(vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
891 0, extents
, size
, &size
, NULL
)) {
892 DWORD last_err
= GetLastError();
893 if (last_err
== ERROR_MORE_DATA
) {
894 /* Try once more with big enough buffer */
896 extents
= g_malloc0(size
);
897 if (!DeviceIoControl(
898 vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
899 0, extents
, size
, NULL
, NULL
)) {
900 error_setg_win32(errp
, GetLastError(),
901 "failed to get disk extents");
904 } else if (last_err
== ERROR_INVALID_FUNCTION
) {
905 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
906 g_debug("volume not on disk");
907 disk
= g_malloc0(sizeof(GuestDiskAddress
));
908 disk
->has_dev
= true;
909 disk
->dev
= g_strdup(name
);
910 get_single_disk_info(0xffffffff, disk
, &local_err
);
912 g_debug("failed to get disk info, ignoring error: %s",
913 error_get_pretty(local_err
));
914 error_free(local_err
);
917 list
= g_malloc0(sizeof(*list
));
923 error_setg_win32(errp
, GetLastError(),
924 "failed to get disk extents");
928 g_debug("Number of extents: %lu", extents
->NumberOfDiskExtents
);
930 /* Go through each extent */
931 for (i
= 0; i
< extents
->NumberOfDiskExtents
; i
++) {
932 disk
= g_malloc0(sizeof(GuestDiskAddress
));
934 /* Disk numbers directly correspond to numbers used in UNCs
936 * See documentation for DISK_EXTENT:
937 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
939 * See also Naming Files, Paths and Namespaces:
940 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
942 disk
->has_dev
= true;
943 disk
->dev
= g_strdup_printf("\\\\.\\PhysicalDrive%lu",
944 extents
->Extents
[i
].DiskNumber
);
946 get_single_disk_info(extents
->Extents
[i
].DiskNumber
, disk
, &local_err
);
948 error_propagate(errp
, local_err
);
951 cur_item
= g_malloc0(sizeof(*list
));
952 cur_item
->value
= disk
;
954 cur_item
->next
= list
;
960 if (vol_h
!= INVALID_HANDLE_VALUE
) {
963 qapi_free_GuestDiskAddress(disk
);
972 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
977 #endif /* CONFIG_QGA_NTDDSCSI */
979 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
982 char mnt
, *mnt_point
;
984 char vol_info
[MAX_PATH
+1];
986 uint64_t i64FreeBytesToCaller
, i64TotalBytes
, i64FreeBytes
;
987 GuestFilesystemInfo
*fs
= NULL
;
989 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
990 if (GetLastError() != ERROR_MORE_DATA
) {
991 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
995 mnt_point
= g_malloc(info_size
+ 1);
996 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
998 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
1002 len
= strlen(mnt_point
);
1003 mnt_point
[len
] = '\\';
1004 mnt_point
[len
+1] = 0;
1005 if (!GetVolumeInformation(mnt_point
, vol_info
, sizeof(vol_info
), NULL
, NULL
,
1006 NULL
, (LPSTR
)&fs_name
, sizeof(fs_name
))) {
1007 if (GetLastError() != ERROR_NOT_READY
) {
1008 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
1013 fs_name
[sizeof(fs_name
) - 1] = 0;
1014 fs
= g_malloc(sizeof(*fs
));
1015 fs
->name
= g_strdup(guid
);
1016 fs
->has_total_bytes
= false;
1017 fs
->has_used_bytes
= false;
1019 fs
->mountpoint
= g_strdup("System Reserved");
1021 fs
->mountpoint
= g_strndup(mnt_point
, len
);
1022 if (GetDiskFreeSpaceEx(fs
->mountpoint
,
1023 (PULARGE_INTEGER
) & i64FreeBytesToCaller
,
1024 (PULARGE_INTEGER
) & i64TotalBytes
,
1025 (PULARGE_INTEGER
) & i64FreeBytes
)) {
1026 fs
->used_bytes
= i64TotalBytes
- i64FreeBytes
;
1027 fs
->total_bytes
= i64TotalBytes
;
1028 fs
->has_total_bytes
= true;
1029 fs
->has_used_bytes
= true;
1032 fs
->type
= g_strdup(fs_name
);
1033 fs
->disk
= build_guest_disk_info(guid
, errp
);
1039 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1042 GuestFilesystemInfoList
*new, *ret
= NULL
;
1045 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
1046 if (vol_h
== INVALID_HANDLE_VALUE
) {
1047 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1052 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, errp
);
1056 new = g_malloc(sizeof(*ret
));
1060 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
1062 if (GetLastError() != ERROR_NO_MORE_FILES
) {
1063 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
1066 FindVolumeClose(vol_h
);
1071 * Return status of freeze/thaw
1073 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1075 if (!vss_initialized()) {
1076 error_setg(errp
, QERR_UNSUPPORTED
);
1080 if (ga_is_frozen(ga_state
)) {
1081 return GUEST_FSFREEZE_STATUS_FROZEN
;
1084 return GUEST_FSFREEZE_STATUS_THAWED
;
1088 * Freeze local file systems using Volume Shadow-copy Service.
1089 * The frozen state is limited for up to 10 seconds by VSS.
1091 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1093 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1096 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1097 strList
*mountpoints
,
1101 Error
*local_err
= NULL
;
1103 if (!vss_initialized()) {
1104 error_setg(errp
, QERR_UNSUPPORTED
);
1108 slog("guest-fsfreeze called");
1110 /* cannot risk guest agent blocking itself on a write in this state */
1111 ga_set_frozen(ga_state
);
1113 qga_vss_fsfreeze(&i
, true, mountpoints
, &local_err
);
1115 error_propagate(errp
, local_err
);
1123 qmp_guest_fsfreeze_thaw(&local_err
);
1125 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
1126 error_free(local_err
);
1132 * Thaw local file systems using Volume Shadow-copy Service.
1134 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1138 if (!vss_initialized()) {
1139 error_setg(errp
, QERR_UNSUPPORTED
);
1143 qga_vss_fsfreeze(&i
, false, NULL
, errp
);
1145 ga_unset_frozen(ga_state
);
1149 static void guest_fsfreeze_cleanup(void)
1153 if (!vss_initialized()) {
1157 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1158 qmp_guest_fsfreeze_thaw(&err
);
1160 slog("failed to clean up frozen filesystems: %s",
1161 error_get_pretty(err
));
1170 * Walk list of mounted file systems in the guest, and discard unused
1173 GuestFilesystemTrimResponse
*
1174 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1176 GuestFilesystemTrimResponse
*resp
;
1178 WCHAR guid
[MAX_PATH
] = L
"";
1182 ZeroMemory(&osvi
, sizeof(OSVERSIONINFO
));
1183 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1184 GetVersionEx(&osvi
);
1185 win8_or_later
= (osvi
.dwMajorVersion
> 6 ||
1186 ((osvi
.dwMajorVersion
== 6) &&
1187 (osvi
.dwMinorVersion
>= 2)));
1188 if (!win8_or_later
) {
1189 error_setg(errp
, "fstrim is only supported for Win8+");
1193 handle
= FindFirstVolumeW(guid
, ARRAYSIZE(guid
));
1194 if (handle
== INVALID_HANDLE_VALUE
) {
1195 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1199 resp
= g_new0(GuestFilesystemTrimResponse
, 1);
1202 GuestFilesystemTrimResult
*res
;
1203 GuestFilesystemTrimResultList
*list
;
1205 DWORD char_count
= 0;
1207 GError
*gerr
= NULL
;
1210 GetVolumePathNamesForVolumeNameW(guid
, NULL
, 0, &char_count
);
1212 if (GetLastError() != ERROR_MORE_DATA
) {
1215 if (GetDriveTypeW(guid
) != DRIVE_FIXED
) {
1219 uc_path
= g_malloc(sizeof(WCHAR
) * char_count
);
1220 if (!GetVolumePathNamesForVolumeNameW(guid
, uc_path
, char_count
,
1221 &char_count
) || !*uc_path
) {
1222 /* strange, but this condition could be faced even with size == 2 */
1227 res
= g_new0(GuestFilesystemTrimResult
, 1);
1229 path
= g_utf16_to_utf8(uc_path
, char_count
, NULL
, NULL
, &gerr
);
1234 res
->has_error
= true;
1235 res
->error
= g_strdup(gerr
->message
);
1242 list
= g_new0(GuestFilesystemTrimResultList
, 1);
1244 list
->next
= resp
->paths
;
1248 memset(argv
, 0, sizeof(argv
));
1249 argv
[0] = (gchar
*)"defrag.exe";
1250 argv
[1] = (gchar
*)"/L";
1253 if (!g_spawn_sync(NULL
, argv
, NULL
, G_SPAWN_SEARCH_PATH
, NULL
, NULL
,
1254 &out
/* stdout */, NULL
/* stdin */,
1256 res
->has_error
= true;
1257 res
->error
= g_strdup(gerr
->message
);
1260 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1261 Error is reported in the output with something like
1262 (x89000020) etc code in the stdout */
1265 gchar
**lines
= g_strsplit(out
, "\r\n", 0);
1268 for (i
= 0; lines
[i
] != NULL
; i
++) {
1269 if (g_strstr_len(lines
[i
], -1, "(0x") == NULL
) {
1272 res
->has_error
= true;
1273 res
->error
= g_strdup(lines
[i
]);
1278 } while (FindNextVolumeW(handle
, guid
, ARRAYSIZE(guid
)));
1280 FindVolumeClose(handle
);
1285 GUEST_SUSPEND_MODE_DISK
,
1286 GUEST_SUSPEND_MODE_RAM
1289 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
1291 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
1292 Error
*local_err
= NULL
;
1294 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
1295 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
1296 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1297 "failed to determine guest suspend capabilities");
1302 case GUEST_SUSPEND_MODE_DISK
:
1303 if (!sys_pwr_caps
.SystemS4
) {
1304 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1305 "suspend-to-disk not supported by OS");
1308 case GUEST_SUSPEND_MODE_RAM
:
1309 if (!sys_pwr_caps
.SystemS3
) {
1310 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1311 "suspend-to-ram not supported by OS");
1315 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "mode",
1316 "GuestSuspendMode");
1320 error_propagate(errp
, local_err
);
1323 static DWORD WINAPI
do_suspend(LPVOID opaque
)
1325 GuestSuspendMode
*mode
= opaque
;
1328 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
1329 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
1330 slog("failed to suspend guest: %s", emsg
);
1337 void qmp_guest_suspend_disk(Error
**errp
)
1339 Error
*local_err
= NULL
;
1340 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1342 *mode
= GUEST_SUSPEND_MODE_DISK
;
1343 check_suspend_mode(*mode
, &local_err
);
1344 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1345 execute_async(do_suspend
, mode
, &local_err
);
1348 error_propagate(errp
, local_err
);
1353 void qmp_guest_suspend_ram(Error
**errp
)
1355 Error
*local_err
= NULL
;
1356 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1358 *mode
= GUEST_SUSPEND_MODE_RAM
;
1359 check_suspend_mode(*mode
, &local_err
);
1360 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1361 execute_async(do_suspend
, mode
, &local_err
);
1364 error_propagate(errp
, local_err
);
1369 void qmp_guest_suspend_hybrid(Error
**errp
)
1371 error_setg(errp
, QERR_UNSUPPORTED
);
1374 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
1376 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
1377 ULONG adptr_addrs_len
= 0;
1380 /* Call the first time to get the adptr_addrs_len. */
1381 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1382 NULL
, adptr_addrs
, &adptr_addrs_len
);
1384 adptr_addrs
= g_malloc(adptr_addrs_len
);
1385 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1386 NULL
, adptr_addrs
, &adptr_addrs_len
);
1387 if (ret
!= ERROR_SUCCESS
) {
1388 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
1389 g_free(adptr_addrs
);
1395 static char *guest_wctomb_dup(WCHAR
*wstr
)
1400 str_size
= WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, NULL
, 0, NULL
, NULL
);
1401 /* add 1 to str_size for NULL terminator */
1402 str
= g_malloc(str_size
+ 1);
1403 WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, str
, str_size
, NULL
, NULL
);
1407 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
1410 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
1414 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
1415 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1416 len
= sizeof(addr_str
);
1417 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
1418 ip_addr
->Address
.iSockaddrLength
,
1423 error_setg_win32(errp
, WSAGetLastError(),
1424 "failed address presentation form conversion");
1427 return g_strdup(addr_str
);
1432 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1434 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1435 * field to obtain the prefix.
1437 return ip_addr
->OnLinkPrefixLength
;
1440 #define INTERFACE_PATH_BUF_SZ 512
1442 static DWORD
get_interface_index(const char *guid
)
1446 wchar_t wbuf
[INTERFACE_PATH_BUF_SZ
];
1447 snwprintf(wbuf
, INTERFACE_PATH_BUF_SZ
, L
"\\device\\tcpip_%s", guid
);
1448 wbuf
[INTERFACE_PATH_BUF_SZ
- 1] = 0;
1449 status
= GetAdapterIndex (wbuf
, &index
);
1450 if (status
!= NO_ERROR
) {
1457 typedef NETIOAPI_API (WINAPI
*GetIfEntry2Func
)(PMIB_IF_ROW2 Row
);
1459 static int guest_get_network_stats(const char *name
,
1460 GuestNetworkInterfaceStat
*stats
)
1462 OSVERSIONINFO os_ver
;
1464 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1465 GetVersionEx(&os_ver
);
1466 if (os_ver
.dwMajorVersion
>= 6) {
1467 MIB_IF_ROW2 a_mid_ifrow
;
1468 GetIfEntry2Func getifentry2_ex
;
1470 HMODULE module
= GetModuleHandle("iphlpapi");
1471 PVOID func
= GetProcAddress(module
, "GetIfEntry2");
1477 getifentry2_ex
= (GetIfEntry2Func
)func
;
1478 if_index
= get_interface_index(name
);
1479 if (if_index
== (DWORD
)~0) {
1483 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1484 a_mid_ifrow
.InterfaceIndex
= if_index
;
1485 if (NO_ERROR
== getifentry2_ex(&a_mid_ifrow
)) {
1486 stats
->rx_bytes
= a_mid_ifrow
.InOctets
;
1487 stats
->rx_packets
= a_mid_ifrow
.InUcastPkts
;
1488 stats
->rx_errs
= a_mid_ifrow
.InErrors
;
1489 stats
->rx_dropped
= a_mid_ifrow
.InDiscards
;
1490 stats
->tx_bytes
= a_mid_ifrow
.OutOctets
;
1491 stats
->tx_packets
= a_mid_ifrow
.OutUcastPkts
;
1492 stats
->tx_errs
= a_mid_ifrow
.OutErrors
;
1493 stats
->tx_dropped
= a_mid_ifrow
.OutDiscards
;
1500 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1502 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1503 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1504 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1505 GuestIpAddressList
*head_addr
, *cur_addr
;
1506 GuestNetworkInterfaceList
*info
;
1507 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1508 GuestIpAddressList
*address_item
= NULL
;
1509 unsigned char *mac_addr
;
1515 adptr_addrs
= guest_get_adapters_addresses(errp
);
1516 if (adptr_addrs
== NULL
) {
1520 /* Make WSA APIs available. */
1521 wsa_version
= MAKEWORD(2, 2);
1522 ret
= WSAStartup(wsa_version
, &wsa_data
);
1524 error_setg_win32(errp
, ret
, "failed socket startup");
1528 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1529 info
= g_malloc0(sizeof(*info
));
1531 if (cur_item
== NULL
) {
1532 head
= cur_item
= info
;
1534 cur_item
->next
= info
;
1538 info
->value
= g_malloc0(sizeof(*info
->value
));
1539 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1541 if (addr
->PhysicalAddressLength
!= 0) {
1542 mac_addr
= addr
->PhysicalAddress
;
1544 info
->value
->hardware_address
=
1545 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1546 (int) mac_addr
[0], (int) mac_addr
[1],
1547 (int) mac_addr
[2], (int) mac_addr
[3],
1548 (int) mac_addr
[4], (int) mac_addr
[5]);
1550 info
->value
->has_hardware_address
= true;
1555 for (ip_addr
= addr
->FirstUnicastAddress
;
1557 ip_addr
= ip_addr
->Next
) {
1558 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1559 if (addr_str
== NULL
) {
1563 address_item
= g_malloc0(sizeof(*address_item
));
1566 head_addr
= cur_addr
= address_item
;
1568 cur_addr
->next
= address_item
;
1569 cur_addr
= address_item
;
1572 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1573 address_item
->value
->ip_address
= addr_str
;
1574 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1575 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1576 address_item
->value
->ip_address_type
=
1577 GUEST_IP_ADDRESS_TYPE_IPV4
;
1578 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1579 address_item
->value
->ip_address_type
=
1580 GUEST_IP_ADDRESS_TYPE_IPV6
;
1584 info
->value
->has_ip_addresses
= true;
1585 info
->value
->ip_addresses
= head_addr
;
1587 if (!info
->value
->has_statistics
) {
1588 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1589 if (guest_get_network_stats(addr
->AdapterName
,
1590 interface_stat
) == -1) {
1591 info
->value
->has_statistics
= false;
1592 g_free(interface_stat
);
1594 info
->value
->statistics
= interface_stat
;
1595 info
->value
->has_statistics
= true;
1601 g_free(adptr_addrs
);
1605 int64_t qmp_guest_get_time(Error
**errp
)
1607 SYSTEMTIME ts
= {0};
1611 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1612 error_setg(errp
, "Failed to get time");
1616 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1617 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1621 return ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1622 - W32_FT_OFFSET
) * 100;
1625 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1627 Error
*local_err
= NULL
;
1633 /* Unfortunately, Windows libraries don't provide an easy way to access
1636 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1638 * Instead, a workaround is to use the Windows win32tm command to
1639 * resync the time using the Windows Time service.
1644 HRESULT hr
= system("w32tm /resync /nowait");
1646 if (GetLastError() != 0) {
1647 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1648 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1649 } else if (hr
!= 0) {
1650 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1651 error_setg(errp
, "Windows Time service not running on the "
1654 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1655 FORMAT_MESSAGE_FROM_SYSTEM
|
1656 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1657 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1658 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1660 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1661 "t retrieve error message", hr
);
1663 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1664 (LPCTSTR
)msg_buffer
);
1665 LocalFree(msg_buffer
);
1668 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1669 error_setg(errp
, "No internet connection on guest, sync not "
1675 /* Validate time passed by user. */
1676 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1677 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1681 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1683 tf
.dwLowDateTime
= (DWORD
) time
;
1684 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1686 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1687 error_setg(errp
, "Failed to convert system time %d",
1688 (int)GetLastError());
1692 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1694 error_propagate(errp
, local_err
);
1698 if (!SetSystemTime(&ts
)) {
1699 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1704 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1706 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1708 GuestLogicalProcessorList
*head
, **link
;
1709 Error
*local_err
= NULL
;
1718 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1719 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1720 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1721 ptr
= pslpi
= g_malloc0(length
);
1722 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1723 error_setg(&local_err
, "Failed to get processor information: %d",
1724 (int)GetLastError());
1727 error_setg(&local_err
,
1728 "Failed to get processor information buffer length: %d",
1729 (int)GetLastError());
1732 while ((local_err
== NULL
) && (length
> 0)) {
1733 if (pslpi
->Relationship
== RelationProcessorCore
) {
1734 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1736 while (cpu_bits
> 0) {
1737 if (!!(cpu_bits
& 1)) {
1738 GuestLogicalProcessor
*vcpu
;
1739 GuestLogicalProcessorList
*entry
;
1741 vcpu
= g_malloc0(sizeof *vcpu
);
1742 vcpu
->logical_id
= current
++;
1743 vcpu
->online
= true;
1744 vcpu
->has_can_offline
= true;
1746 entry
= g_malloc0(sizeof *entry
);
1747 entry
->value
= vcpu
;
1750 link
= &entry
->next
;
1755 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1756 pslpi
++; /* next entry */
1761 if (local_err
== NULL
) {
1765 /* there's no guest with zero VCPUs */
1766 error_setg(&local_err
, "Guest reported zero VCPUs");
1769 qapi_free_GuestLogicalProcessorList(head
);
1770 error_propagate(errp
, local_err
);
1774 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1776 error_setg(errp
, QERR_UNSUPPORTED
);
1781 get_net_error_message(gint error
)
1783 HMODULE module
= NULL
;
1784 gchar
*retval
= NULL
;
1785 wchar_t *msg
= NULL
;
1789 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1790 FORMAT_MESSAGE_IGNORE_INSERTS
|
1791 FORMAT_MESSAGE_FROM_SYSTEM
;
1793 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1794 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1796 if (module
!= NULL
) {
1797 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1801 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1804 nchars
= wcslen(msg
);
1807 msg
[nchars
- 1] == L
'\n' &&
1808 msg
[nchars
- 2] == L
'\r') {
1809 msg
[nchars
- 2] = L
'\0';
1812 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1817 if (module
!= NULL
) {
1818 FreeLibrary(module
);
1824 void qmp_guest_set_user_password(const char *username
,
1825 const char *password
,
1830 char *rawpasswddata
= NULL
;
1831 size_t rawpasswdlen
;
1832 wchar_t *user
= NULL
, *wpass
= NULL
;
1833 USER_INFO_1003 pi1003
= { 0, };
1834 GError
*gerr
= NULL
;
1837 error_setg(errp
, QERR_UNSUPPORTED
);
1841 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1842 if (!rawpasswddata
) {
1845 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1846 rawpasswddata
[rawpasswdlen
] = '\0';
1848 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1853 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1858 pi1003
.usri1003_password
= wpass
;
1859 nas
= NetUserSetInfo(NULL
, user
,
1860 1003, (LPBYTE
)&pi1003
,
1863 if (nas
!= NERR_Success
) {
1864 gchar
*msg
= get_net_error_message(nas
);
1865 error_setg(errp
, "failed to set password: %s", msg
);
1871 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1876 g_free(rawpasswddata
);
1879 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1881 error_setg(errp
, QERR_UNSUPPORTED
);
1885 GuestMemoryBlockResponseList
*
1886 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1888 error_setg(errp
, QERR_UNSUPPORTED
);
1892 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1894 error_setg(errp
, QERR_UNSUPPORTED
);
1898 /* add unsupported commands to the blacklist */
1899 GList
*ga_command_blacklist_init(GList
*blacklist
)
1901 const char *list_unsupported
[] = {
1902 "guest-suspend-hybrid",
1904 "guest-get-memory-blocks", "guest-set-memory-blocks",
1905 "guest-get-memory-block-size", "guest-get-memory-block-info",
1907 char **p
= (char **)list_unsupported
;
1910 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1913 if (!vss_init(true)) {
1914 g_debug("vss_init failed, vss commands are going to be disabled");
1915 const char *list
[] = {
1916 "guest-get-fsinfo", "guest-fsfreeze-status",
1917 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1921 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1928 /* register init/cleanup routines for stateful command groups */
1929 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1931 if (!vss_initialized()) {
1932 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1936 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1937 typedef struct _GA_WTSINFOA
{
1938 WTS_CONNECTSTATE_CLASS State
;
1940 DWORD IncomingBytes
;
1941 DWORD OutgoingBytes
;
1942 DWORD IncomingFrames
;
1943 DWORD OutgoingFrames
;
1944 DWORD IncomingCompressedBytes
;
1945 DWORD OutgoingCompressedBy
;
1946 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
1947 CHAR Domain
[DOMAIN_LENGTH
];
1948 CHAR UserName
[USERNAME_LENGTH
+ 1];
1949 LARGE_INTEGER ConnectTime
;
1950 LARGE_INTEGER DisconnectTime
;
1951 LARGE_INTEGER LastInputTime
;
1952 LARGE_INTEGER LogonTime
;
1953 LARGE_INTEGER CurrentTime
;
1957 GuestUserList
*qmp_guest_get_users(Error
**errp
)
1959 #define QGA_NANOSECONDS 10000000
1961 GHashTable
*cache
= NULL
;
1962 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
1964 DWORD buffer_size
= 0, count
= 0, i
= 0;
1965 GA_WTSINFOA
*info
= NULL
;
1966 WTS_SESSION_INFOA
*entries
= NULL
;
1967 GuestUserList
*item
= NULL
;
1968 GuestUser
*user
= NULL
;
1969 gpointer value
= NULL
;
1971 double login_time
= 0;
1973 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
1975 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
1976 for (i
= 0; i
< count
; ++i
) {
1979 if (WTSQuerySessionInformationA(
1981 entries
[i
].SessionId
,
1987 if (strlen(info
->UserName
) == 0) {
1988 WTSFreeMemory(info
);
1992 login
= info
->LogonTime
.QuadPart
;
1993 login
-= W32_FT_OFFSET
;
1994 login_time
= ((double)login
) / QGA_NANOSECONDS
;
1996 if (g_hash_table_contains(cache
, info
->UserName
)) {
1997 value
= g_hash_table_lookup(cache
, info
->UserName
);
1998 user
= (GuestUser
*)value
;
1999 if (user
->login_time
> login_time
) {
2000 user
->login_time
= login_time
;
2003 item
= g_new0(GuestUserList
, 1);
2004 item
->value
= g_new0(GuestUser
, 1);
2006 item
->value
->user
= g_strdup(info
->UserName
);
2007 item
->value
->domain
= g_strdup(info
->Domain
);
2008 item
->value
->has_domain
= true;
2010 item
->value
->login_time
= login_time
;
2012 g_hash_table_add(cache
, item
->value
->user
);
2015 head
= cur_item
= item
;
2017 cur_item
->next
= item
;
2022 WTSFreeMemory(info
);
2024 WTSFreeMemory(entries
);
2026 g_hash_table_destroy(cache
);
2030 typedef struct _ga_matrix_lookup_t
{
2033 char const *version
;
2034 char const *version_id
;
2035 } ga_matrix_lookup_t
;
2037 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][8] = {
2039 /* Desktop editions */
2040 { 5, 0, "Microsoft Windows 2000", "2000"},
2041 { 5, 1, "Microsoft Windows XP", "xp"},
2042 { 6, 0, "Microsoft Windows Vista", "vista"},
2043 { 6, 1, "Microsoft Windows 7" "7"},
2044 { 6, 2, "Microsoft Windows 8", "8"},
2045 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2046 {10, 0, "Microsoft Windows 10", "10"},
2049 /* Server editions */
2050 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2051 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2052 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2053 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2054 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2061 typedef struct _ga_win_10_0_server_t
{
2063 char const *version
;
2064 char const *version_id
;
2065 } ga_win_10_0_server_t
;
2067 static ga_win_10_0_server_t
const WIN_10_0_SERVER_VERSION_MATRIX
[3] = {
2068 {14393, "Microsoft Windows Server 2016", "2016"},
2069 {17763, "Microsoft Windows Server 2019", "2019"},
2073 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
2075 typedef NTSTATUS(WINAPI
* rtl_get_version_t
)(
2076 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
2078 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
2080 HMODULE module
= GetModuleHandle("ntdll");
2081 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
2083 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
2084 "Failed to get address of RtlGetVersion");
2088 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
2089 rtl_get_version(info
);
2093 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
2095 DWORD major
= os_version
->dwMajorVersion
;
2096 DWORD minor
= os_version
->dwMinorVersion
;
2097 DWORD build
= os_version
->dwBuildNumber
;
2098 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
2099 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
2100 ga_win_10_0_server_t
const *win_10_0_table
= WIN_10_0_SERVER_VERSION_MATRIX
;
2101 while (table
->version
!= NULL
) {
2102 if (major
== 10 && minor
== 0 && tbl_idx
) {
2103 while (win_10_0_table
->version
!= NULL
) {
2104 if (build
<= win_10_0_table
->final_build
) {
2106 return g_strdup(win_10_0_table
->version_id
);
2108 return g_strdup(win_10_0_table
->version
);
2113 } else if (major
== table
->major
&& minor
== table
->minor
) {
2115 return g_strdup(table
->version_id
);
2117 return g_strdup(table
->version
);
2122 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2124 return g_strdup("N/A");
2127 static char *ga_get_win_product_name(Error
**errp
)
2131 char *result
= g_malloc0(size
);
2132 LONG err
= ERROR_SUCCESS
;
2134 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
2135 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2137 if (err
!= ERROR_SUCCESS
) {
2138 error_setg_win32(errp
, err
, "failed to open registry key");
2142 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2143 (LPBYTE
)result
, &size
);
2144 if (err
== ERROR_MORE_DATA
) {
2145 slog("ProductName longer than expected (%lu bytes), retrying",
2150 result
= g_malloc0(size
);
2151 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2152 (LPBYTE
)result
, &size
);
2155 if (err
!= ERROR_SUCCESS
) {
2156 error_setg_win32(errp
, err
, "failed to retrive ProductName");
2167 static char *ga_get_current_arch(void)
2170 GetNativeSystemInfo(&info
);
2171 char *result
= NULL
;
2172 switch (info
.wProcessorArchitecture
) {
2173 case PROCESSOR_ARCHITECTURE_AMD64
:
2174 result
= g_strdup("x86_64");
2176 case PROCESSOR_ARCHITECTURE_ARM
:
2177 result
= g_strdup("arm");
2179 case PROCESSOR_ARCHITECTURE_IA64
:
2180 result
= g_strdup("ia64");
2182 case PROCESSOR_ARCHITECTURE_INTEL
:
2183 result
= g_strdup("x86");
2185 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
2187 slog("unknown processor architecture 0x%0x",
2188 info
.wProcessorArchitecture
);
2189 result
= g_strdup("unknown");
2195 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2197 Error
*local_err
= NULL
;
2198 OSVERSIONINFOEXW os_version
= {0};
2203 ga_get_win_version(&os_version
, &local_err
);
2205 error_propagate(errp
, local_err
);
2209 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
2210 product_name
= ga_get_win_product_name(&local_err
);
2211 if (product_name
== NULL
) {
2212 error_propagate(errp
, local_err
);
2216 info
= g_new0(GuestOSInfo
, 1);
2218 info
->has_kernel_version
= true;
2219 info
->kernel_version
= g_strdup_printf("%lu.%lu",
2220 os_version
.dwMajorVersion
,
2221 os_version
.dwMinorVersion
);
2222 info
->has_kernel_release
= true;
2223 info
->kernel_release
= g_strdup_printf("%lu",
2224 os_version
.dwBuildNumber
);
2225 info
->has_machine
= true;
2226 info
->machine
= ga_get_current_arch();
2228 info
->has_id
= true;
2229 info
->id
= g_strdup("mswindows");
2230 info
->has_name
= true;
2231 info
->name
= g_strdup("Microsoft Windows");
2232 info
->has_pretty_name
= true;
2233 info
->pretty_name
= product_name
;
2234 info
->has_version
= true;
2235 info
->version
= ga_get_win_name(&os_version
, false);
2236 info
->has_version_id
= true;
2237 info
->version_id
= ga_get_win_name(&os_version
, true);
2238 info
->has_variant
= true;
2239 info
->variant
= g_strdup(server
? "server" : "client");
2240 info
->has_variant_id
= true;
2241 info
->variant_id
= g_strdup(server
? "server" : "client");