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 slog("guest-shutdown failed: %lu", GetLastError());
319 error_setg(errp
, QERR_UNDEFINED_ERROR
);
323 GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
324 int64_t count
, Error
**errp
)
326 GuestFileRead
*read_data
= NULL
;
331 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
337 count
= QGA_READ_COUNT_DEFAULT
;
338 } else if (count
< 0 || count
>= UINT32_MAX
) {
339 error_setg(errp
, "value '%" PRId64
340 "' is invalid for argument count", count
);
345 buf
= g_malloc0(count
+1);
346 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
348 error_setg_win32(errp
, GetLastError(), "failed to read file");
349 slog("guest-file-read failed, handle %" PRId64
, handle
);
352 read_data
= g_new0(GuestFileRead
, 1);
353 read_data
->count
= (size_t)read_count
;
354 read_data
->eof
= read_count
== 0;
356 if (read_count
!= 0) {
357 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
365 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
366 bool has_count
, int64_t count
,
369 GuestFileWrite
*write_data
= NULL
;
374 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
381 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
388 } else if (count
< 0 || count
> buf_len
) {
389 error_setg(errp
, "value '%" PRId64
390 "' is invalid for argument count", count
);
394 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
396 error_setg_win32(errp
, GetLastError(), "failed to write to file");
397 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
399 write_data
= g_new0(GuestFileWrite
, 1);
400 write_data
->count
= (size_t) write_count
;
408 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
409 GuestFileWhence
*whence_code
,
412 GuestFileHandle
*gfh
;
413 GuestFileSeek
*seek_data
;
415 LARGE_INTEGER new_pos
, off_pos
;
416 off_pos
.QuadPart
= offset
;
421 gfh
= guest_file_handle_find(handle
, errp
);
426 /* We stupidly exposed 'whence':'int' in our qapi */
427 whence
= ga_parse_whence(whence_code
, &err
);
429 error_propagate(errp
, err
);
434 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
436 error_setg_win32(errp
, GetLastError(), "failed to seek file");
439 seek_data
= g_new0(GuestFileSeek
, 1);
440 seek_data
->position
= new_pos
.QuadPart
;
444 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
447 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
453 if (!FlushFileBuffers(fh
)) {
454 error_setg_win32(errp
, GetLastError(), "failed to flush file");
458 #ifdef CONFIG_QGA_NTDDSCSI
460 static GuestDiskBusType win2qemu
[] = {
461 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
462 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
463 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
464 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
465 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
466 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
467 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
468 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
469 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
470 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
471 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
472 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
473 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
474 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
475 #if (_WIN32_WINNT >= 0x0601)
476 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
477 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
481 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
483 if (bus
>= ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
484 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
486 return win2qemu
[(int)bus
];
489 DEFINE_GUID(GUID_DEVINTERFACE_DISK
,
490 0x53f56307L
, 0xb6bf, 0x11d0, 0x94, 0xf2,
491 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
492 DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT
,
493 0x2accfe60L
, 0xc130, 0x11d2, 0xb0, 0x82,
494 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
496 static GuestPCIAddress
*get_pci_info(int number
, Error
**errp
)
499 SP_DEVINFO_DATA dev_info_data
;
500 SP_DEVICE_INTERFACE_DATA dev_iface_data
;
503 GuestPCIAddress
*pci
= NULL
;
504 bool partial_pci
= false;
506 pci
= g_malloc0(sizeof(*pci
));
512 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK
, 0, 0,
513 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
514 if (dev_info
== INVALID_HANDLE_VALUE
) {
515 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
519 g_debug("enumerating devices");
520 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
521 dev_iface_data
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
522 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
523 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data
= NULL
;
524 STORAGE_DEVICE_NUMBER sdn
;
525 char *parent_dev_id
= NULL
;
526 HDEVINFO parent_dev_info
;
527 SP_DEVINFO_DATA parent_dev_info_data
;
531 g_debug("getting device path");
532 if (SetupDiEnumDeviceInterfaces(dev_info
, &dev_info_data
,
533 &GUID_DEVINTERFACE_DISK
, 0,
535 while (!SetupDiGetDeviceInterfaceDetail(dev_info
, &dev_iface_data
,
536 pdev_iface_detail_data
,
539 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
540 pdev_iface_detail_data
= g_malloc(size
);
541 pdev_iface_detail_data
->cbSize
=
542 sizeof(*pdev_iface_detail_data
);
544 error_setg_win32(errp
, GetLastError(),
545 "failed to get device interfaces");
550 dev_file
= CreateFile(pdev_iface_detail_data
->DevicePath
, 0,
551 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0,
553 g_free(pdev_iface_detail_data
);
555 if (!DeviceIoControl(dev_file
, IOCTL_STORAGE_GET_DEVICE_NUMBER
,
556 NULL
, 0, &sdn
, sizeof(sdn
), &size
, NULL
)) {
557 CloseHandle(dev_file
);
558 error_setg_win32(errp
, GetLastError(),
559 "failed to get device slot number");
563 CloseHandle(dev_file
);
564 if (sdn
.DeviceNumber
!= number
) {
568 error_setg_win32(errp
, GetLastError(),
569 "failed to get device interfaces");
573 g_debug("found device slot %d. Getting storage controller", number
);
576 DEVINST dev_inst
, parent_dev_inst
;
577 ULONG dev_id_size
= 0;
580 while (!SetupDiGetDeviceInstanceId(dev_info
, &dev_info_data
,
581 parent_dev_id
, size
, &size
)) {
582 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
583 parent_dev_id
= g_malloc(size
);
585 error_setg_win32(errp
, GetLastError(),
586 "failed to get device instance ID");
592 * CM API used here as opposed to
593 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
594 * which exports are only available in mingw-w64 6+
596 cr
= CM_Locate_DevInst(&dev_inst
, parent_dev_id
, 0);
597 if (cr
!= CR_SUCCESS
) {
598 g_error("CM_Locate_DevInst failed with code %lx", cr
);
599 error_setg_win32(errp
, GetLastError(),
600 "failed to get device instance");
603 cr
= CM_Get_Parent(&parent_dev_inst
, dev_inst
, 0);
604 if (cr
!= CR_SUCCESS
) {
605 g_error("CM_Get_Parent failed with code %lx", cr
);
606 error_setg_win32(errp
, GetLastError(),
607 "failed to get parent device instance");
611 cr
= CM_Get_Device_ID_Size(&dev_id_size
, parent_dev_inst
, 0);
612 if (cr
!= CR_SUCCESS
) {
613 g_error("CM_Get_Device_ID_Size failed with code %lx", cr
);
614 error_setg_win32(errp
, GetLastError(),
615 "failed to get parent device ID length");
620 if (dev_id_size
> size
) {
621 g_free(parent_dev_id
);
622 parent_dev_id
= g_malloc(dev_id_size
);
625 cr
= CM_Get_Device_ID(parent_dev_inst
, parent_dev_id
, dev_id_size
,
627 if (cr
!= CR_SUCCESS
) {
628 g_error("CM_Get_Device_ID failed with code %lx", cr
);
629 error_setg_win32(errp
, GetLastError(),
630 "failed to get parent device ID");
635 g_debug("querying storage controller %s for PCI information",
638 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT
, parent_dev_id
,
639 NULL
, DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
640 g_free(parent_dev_id
);
642 if (parent_dev_info
== INVALID_HANDLE_VALUE
) {
643 error_setg_win32(errp
, GetLastError(),
644 "failed to get parent device");
648 parent_dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
649 if (!SetupDiEnumDeviceInfo(parent_dev_info
, 0, &parent_dev_info_data
)) {
650 error_setg_win32(errp
, GetLastError(),
651 "failed to get parent device data");
656 SetupDiEnumDeviceInfo(parent_dev_info
, j
, &parent_dev_info_data
);
658 DWORD addr
, bus
, ui_slot
, type
;
662 * There is no need to allocate buffer in the next functions. The
663 * size is known and ULONG according to
664 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
666 if (!SetupDiGetDeviceRegistryProperty(
667 parent_dev_info
, &parent_dev_info_data
, SPDRP_BUSNUMBER
,
668 &type
, (PBYTE
)&bus
, size
, NULL
)) {
669 debug_error("failed to get PCI bus");
675 * The function retrieves the device's address. This value will be
676 * transformed into device function and number
678 if (!SetupDiGetDeviceRegistryProperty(
679 parent_dev_info
, &parent_dev_info_data
, SPDRP_ADDRESS
,
680 &type
, (PBYTE
)&addr
, size
, NULL
)) {
681 debug_error("failed to get PCI address");
687 * This call returns UINumber of DEVICE_CAPABILITIES structure.
688 * This number is typically a user-perceived slot number.
690 if (!SetupDiGetDeviceRegistryProperty(
691 parent_dev_info
, &parent_dev_info_data
, SPDRP_UI_NUMBER
,
692 &type
, (PBYTE
)&ui_slot
, size
, NULL
)) {
693 debug_error("failed to get PCI slot");
699 * SetupApi gives us the same information as driver with
700 * IoGetDeviceProperty. According to Microsoft:
702 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
703 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
704 * SPDRP_ADDRESS is propertyAddress, so we do the same.
706 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
715 func
= ((int)addr
== -1) ? -1 : addr
& 0x0000FFFF;
716 slot
= ((int)addr
== -1) ? -1 : (addr
>> 16) & 0x0000FFFF;
717 if ((int)ui_slot
!= slot
) {
718 g_debug("mismatch with reported slot values: %d vs %d",
722 pci
->slot
= (int)ui_slot
;
723 pci
->function
= func
;
728 SetupDiDestroyDeviceInfoList(parent_dev_info
);
733 SetupDiDestroyDeviceInfoList(dev_info
);
738 static void get_disk_properties(HANDLE vol_h
, GuestDiskAddress
*disk
,
741 STORAGE_PROPERTY_QUERY query
;
742 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
744 ULONG size
= sizeof(buf
);
747 query
.PropertyId
= StorageDeviceProperty
;
748 query
.QueryType
= PropertyStandardQuery
;
750 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
751 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
752 size
, &received
, NULL
)) {
753 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
756 disk
->bus_type
= find_bus_type(dev_desc
->BusType
);
757 g_debug("bus type %d", disk
->bus_type
);
759 /* Query once more. Now with long enough buffer. */
760 size
= dev_desc
->Size
;
761 dev_desc
= g_malloc0(size
);
762 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
763 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
764 size
, &received
, NULL
)) {
765 error_setg_win32(errp
, GetLastError(), "failed to get serial number");
766 g_debug("failed to get serial number");
769 if (dev_desc
->SerialNumberOffset
> 0) {
773 if (dev_desc
->SerialNumberOffset
>= received
) {
774 error_setg(errp
, "failed to get serial number: offset outside the buffer");
775 g_debug("serial number offset outside the buffer");
778 serial
= (char *)dev_desc
+ dev_desc
->SerialNumberOffset
;
779 len
= received
- dev_desc
->SerialNumberOffset
;
780 g_debug("serial number \"%s\"", serial
);
782 disk
->serial
= g_strndup(serial
, len
);
783 disk
->has_serial
= true;
792 static void get_single_disk_info(int disk_number
,
793 GuestDiskAddress
*disk
, Error
**errp
)
795 SCSI_ADDRESS addr
, *scsi_ad
;
798 Error
*local_err
= NULL
;
802 g_debug("getting disk info for: %s", disk
->dev
);
803 disk_h
= CreateFile(disk
->dev
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
805 if (disk_h
== INVALID_HANDLE_VALUE
) {
806 error_setg_win32(errp
, GetLastError(), "failed to open disk");
810 get_disk_properties(disk_h
, disk
, &local_err
);
812 error_propagate(errp
, local_err
);
816 g_debug("bus type %d", disk
->bus_type
);
817 /* always set pci_controller as required by schema. get_pci_info() should
818 * report -1 values for non-PCI buses rather than fail. fail the command
819 * if that doesn't hold since that suggests some other unexpected
822 disk
->pci_controller
= get_pci_info(disk_number
, &local_err
);
824 error_propagate(errp
, local_err
);
827 if (disk
->bus_type
== GUEST_DISK_BUS_TYPE_SCSI
828 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_IDE
829 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_RAID
830 /* This bus type is not supported before Windows Server 2003 SP1 */
831 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_SAS
833 /* We are able to use the same ioctls for different bus types
834 * according to Microsoft docs
835 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
836 g_debug("getting SCSI info");
837 if (DeviceIoControl(disk_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
838 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
839 disk
->unit
= addr
.Lun
;
840 disk
->target
= addr
.TargetId
;
841 disk
->bus
= addr
.PathId
;
843 /* We do not set error in this case, because we still have enough
844 * information about volume. */
852 /* VSS provider works with volumes, thus there is no difference if
853 * the volume consist of spanned disks. Info about the first disk in the
854 * volume is returned for the spanned disk group (LVM) */
855 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
857 Error
*local_err
= NULL
;
858 GuestDiskAddressList
*list
= NULL
, *cur_item
= NULL
;
859 GuestDiskAddress
*disk
= NULL
;
863 PVOLUME_DISK_EXTENTS extents
= NULL
;
865 /* strip final backslash */
866 char *name
= g_strdup(guid
);
867 if (g_str_has_suffix(name
, "\\")) {
868 name
[strlen(name
) - 1] = 0;
871 g_debug("opening %s", name
);
872 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
874 if (vol_h
== INVALID_HANDLE_VALUE
) {
875 error_setg_win32(errp
, GetLastError(), "failed to open volume");
879 /* Get list of extents */
880 g_debug("getting disk extents");
881 size
= sizeof(VOLUME_DISK_EXTENTS
);
882 extents
= g_malloc0(size
);
883 if (!DeviceIoControl(vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
884 0, extents
, size
, &size
, NULL
)) {
885 DWORD last_err
= GetLastError();
886 if (last_err
== ERROR_MORE_DATA
) {
887 /* Try once more with big enough buffer */
889 extents
= g_malloc0(size
);
890 if (!DeviceIoControl(
891 vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
892 0, extents
, size
, NULL
, NULL
)) {
893 error_setg_win32(errp
, GetLastError(),
894 "failed to get disk extents");
897 } else if (last_err
== ERROR_INVALID_FUNCTION
) {
898 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
899 g_debug("volume not on disk");
900 disk
= g_malloc0(sizeof(GuestDiskAddress
));
901 disk
->has_dev
= true;
902 disk
->dev
= g_strdup(name
);
903 get_single_disk_info(0xffffffff, disk
, &local_err
);
905 g_debug("failed to get disk info, ignoring error: %s",
906 error_get_pretty(local_err
));
907 error_free(local_err
);
910 list
= g_malloc0(sizeof(*list
));
916 error_setg_win32(errp
, GetLastError(),
917 "failed to get disk extents");
921 g_debug("Number of extents: %lu", extents
->NumberOfDiskExtents
);
923 /* Go through each extent */
924 for (i
= 0; i
< extents
->NumberOfDiskExtents
; i
++) {
925 disk
= g_malloc0(sizeof(GuestDiskAddress
));
927 /* Disk numbers directly correspond to numbers used in UNCs
929 * See documentation for DISK_EXTENT:
930 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
932 * See also Naming Files, Paths and Namespaces:
933 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
935 disk
->has_dev
= true;
936 disk
->dev
= g_strdup_printf("\\\\.\\PhysicalDrive%lu",
937 extents
->Extents
[i
].DiskNumber
);
939 get_single_disk_info(extents
->Extents
[i
].DiskNumber
, disk
, &local_err
);
941 error_propagate(errp
, local_err
);
944 cur_item
= g_malloc0(sizeof(*list
));
945 cur_item
->value
= disk
;
947 cur_item
->next
= list
;
953 if (vol_h
!= INVALID_HANDLE_VALUE
) {
956 qapi_free_GuestDiskAddress(disk
);
965 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
970 #endif /* CONFIG_QGA_NTDDSCSI */
972 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
975 char mnt
, *mnt_point
;
977 char vol_info
[MAX_PATH
+1];
979 uint64_t i64FreeBytesToCaller
, i64TotalBytes
, i64FreeBytes
;
980 GuestFilesystemInfo
*fs
= NULL
;
982 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
983 if (GetLastError() != ERROR_MORE_DATA
) {
984 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
988 mnt_point
= g_malloc(info_size
+ 1);
989 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
991 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
995 len
= strlen(mnt_point
);
996 mnt_point
[len
] = '\\';
997 mnt_point
[len
+1] = 0;
998 if (!GetVolumeInformation(mnt_point
, vol_info
, sizeof(vol_info
), NULL
, NULL
,
999 NULL
, (LPSTR
)&fs_name
, sizeof(fs_name
))) {
1000 if (GetLastError() != ERROR_NOT_READY
) {
1001 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
1006 fs_name
[sizeof(fs_name
) - 1] = 0;
1007 fs
= g_malloc(sizeof(*fs
));
1008 fs
->name
= g_strdup(guid
);
1009 fs
->has_total_bytes
= false;
1010 fs
->has_used_bytes
= false;
1012 fs
->mountpoint
= g_strdup("System Reserved");
1014 fs
->mountpoint
= g_strndup(mnt_point
, len
);
1015 if (GetDiskFreeSpaceEx(fs
->mountpoint
,
1016 (PULARGE_INTEGER
) & i64FreeBytesToCaller
,
1017 (PULARGE_INTEGER
) & i64TotalBytes
,
1018 (PULARGE_INTEGER
) & i64FreeBytes
)) {
1019 fs
->used_bytes
= i64TotalBytes
- i64FreeBytes
;
1020 fs
->total_bytes
= i64TotalBytes
;
1021 fs
->has_total_bytes
= true;
1022 fs
->has_used_bytes
= true;
1025 fs
->type
= g_strdup(fs_name
);
1026 fs
->disk
= build_guest_disk_info(guid
, errp
);
1032 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1035 GuestFilesystemInfoList
*new, *ret
= NULL
;
1038 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
1039 if (vol_h
== INVALID_HANDLE_VALUE
) {
1040 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1045 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, errp
);
1049 new = g_malloc(sizeof(*ret
));
1053 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
1055 if (GetLastError() != ERROR_NO_MORE_FILES
) {
1056 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
1059 FindVolumeClose(vol_h
);
1064 * Return status of freeze/thaw
1066 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1068 if (!vss_initialized()) {
1069 error_setg(errp
, QERR_UNSUPPORTED
);
1073 if (ga_is_frozen(ga_state
)) {
1074 return GUEST_FSFREEZE_STATUS_FROZEN
;
1077 return GUEST_FSFREEZE_STATUS_THAWED
;
1081 * Freeze local file systems using Volume Shadow-copy Service.
1082 * The frozen state is limited for up to 10 seconds by VSS.
1084 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1086 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1089 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1090 strList
*mountpoints
,
1094 Error
*local_err
= NULL
;
1096 if (!vss_initialized()) {
1097 error_setg(errp
, QERR_UNSUPPORTED
);
1101 slog("guest-fsfreeze called");
1103 /* cannot risk guest agent blocking itself on a write in this state */
1104 ga_set_frozen(ga_state
);
1106 qga_vss_fsfreeze(&i
, true, mountpoints
, &local_err
);
1108 error_propagate(errp
, local_err
);
1116 qmp_guest_fsfreeze_thaw(&local_err
);
1118 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
1119 error_free(local_err
);
1125 * Thaw local file systems using Volume Shadow-copy Service.
1127 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1131 if (!vss_initialized()) {
1132 error_setg(errp
, QERR_UNSUPPORTED
);
1136 qga_vss_fsfreeze(&i
, false, NULL
, errp
);
1138 ga_unset_frozen(ga_state
);
1142 static void guest_fsfreeze_cleanup(void)
1146 if (!vss_initialized()) {
1150 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1151 qmp_guest_fsfreeze_thaw(&err
);
1153 slog("failed to clean up frozen filesystems: %s",
1154 error_get_pretty(err
));
1163 * Walk list of mounted file systems in the guest, and discard unused
1166 GuestFilesystemTrimResponse
*
1167 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1169 GuestFilesystemTrimResponse
*resp
;
1171 WCHAR guid
[MAX_PATH
] = L
"";
1175 ZeroMemory(&osvi
, sizeof(OSVERSIONINFO
));
1176 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1177 GetVersionEx(&osvi
);
1178 win8_or_later
= (osvi
.dwMajorVersion
> 6 ||
1179 ((osvi
.dwMajorVersion
== 6) &&
1180 (osvi
.dwMinorVersion
>= 2)));
1181 if (!win8_or_later
) {
1182 error_setg(errp
, "fstrim is only supported for Win8+");
1186 handle
= FindFirstVolumeW(guid
, ARRAYSIZE(guid
));
1187 if (handle
== INVALID_HANDLE_VALUE
) {
1188 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1192 resp
= g_new0(GuestFilesystemTrimResponse
, 1);
1195 GuestFilesystemTrimResult
*res
;
1196 GuestFilesystemTrimResultList
*list
;
1198 DWORD char_count
= 0;
1200 GError
*gerr
= NULL
;
1203 GetVolumePathNamesForVolumeNameW(guid
, NULL
, 0, &char_count
);
1205 if (GetLastError() != ERROR_MORE_DATA
) {
1208 if (GetDriveTypeW(guid
) != DRIVE_FIXED
) {
1212 uc_path
= g_malloc(sizeof(WCHAR
) * char_count
);
1213 if (!GetVolumePathNamesForVolumeNameW(guid
, uc_path
, char_count
,
1214 &char_count
) || !*uc_path
) {
1215 /* strange, but this condition could be faced even with size == 2 */
1220 res
= g_new0(GuestFilesystemTrimResult
, 1);
1222 path
= g_utf16_to_utf8(uc_path
, char_count
, NULL
, NULL
, &gerr
);
1227 res
->has_error
= true;
1228 res
->error
= g_strdup(gerr
->message
);
1235 list
= g_new0(GuestFilesystemTrimResultList
, 1);
1237 list
->next
= resp
->paths
;
1241 memset(argv
, 0, sizeof(argv
));
1242 argv
[0] = (gchar
*)"defrag.exe";
1243 argv
[1] = (gchar
*)"/L";
1246 if (!g_spawn_sync(NULL
, argv
, NULL
, G_SPAWN_SEARCH_PATH
, NULL
, NULL
,
1247 &out
/* stdout */, NULL
/* stdin */,
1249 res
->has_error
= true;
1250 res
->error
= g_strdup(gerr
->message
);
1253 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1254 Error is reported in the output with something like
1255 (x89000020) etc code in the stdout */
1258 gchar
**lines
= g_strsplit(out
, "\r\n", 0);
1261 for (i
= 0; lines
[i
] != NULL
; i
++) {
1262 if (g_strstr_len(lines
[i
], -1, "(0x") == NULL
) {
1265 res
->has_error
= true;
1266 res
->error
= g_strdup(lines
[i
]);
1271 } while (FindNextVolumeW(handle
, guid
, ARRAYSIZE(guid
)));
1273 FindVolumeClose(handle
);
1278 GUEST_SUSPEND_MODE_DISK
,
1279 GUEST_SUSPEND_MODE_RAM
1282 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
1284 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
1285 Error
*local_err
= NULL
;
1287 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
1288 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
1289 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1290 "failed to determine guest suspend capabilities");
1295 case GUEST_SUSPEND_MODE_DISK
:
1296 if (!sys_pwr_caps
.SystemS4
) {
1297 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1298 "suspend-to-disk not supported by OS");
1301 case GUEST_SUSPEND_MODE_RAM
:
1302 if (!sys_pwr_caps
.SystemS3
) {
1303 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1304 "suspend-to-ram not supported by OS");
1308 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "mode",
1309 "GuestSuspendMode");
1313 error_propagate(errp
, local_err
);
1316 static DWORD WINAPI
do_suspend(LPVOID opaque
)
1318 GuestSuspendMode
*mode
= opaque
;
1321 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
1322 slog("failed to suspend guest, %lu", GetLastError());
1329 void qmp_guest_suspend_disk(Error
**errp
)
1331 Error
*local_err
= NULL
;
1332 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1334 *mode
= GUEST_SUSPEND_MODE_DISK
;
1335 check_suspend_mode(*mode
, &local_err
);
1336 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1337 execute_async(do_suspend
, mode
, &local_err
);
1340 error_propagate(errp
, local_err
);
1345 void qmp_guest_suspend_ram(Error
**errp
)
1347 Error
*local_err
= NULL
;
1348 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1350 *mode
= GUEST_SUSPEND_MODE_RAM
;
1351 check_suspend_mode(*mode
, &local_err
);
1352 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1353 execute_async(do_suspend
, mode
, &local_err
);
1356 error_propagate(errp
, local_err
);
1361 void qmp_guest_suspend_hybrid(Error
**errp
)
1363 error_setg(errp
, QERR_UNSUPPORTED
);
1366 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
1368 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
1369 ULONG adptr_addrs_len
= 0;
1372 /* Call the first time to get the adptr_addrs_len. */
1373 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1374 NULL
, adptr_addrs
, &adptr_addrs_len
);
1376 adptr_addrs
= g_malloc(adptr_addrs_len
);
1377 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1378 NULL
, adptr_addrs
, &adptr_addrs_len
);
1379 if (ret
!= ERROR_SUCCESS
) {
1380 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
1381 g_free(adptr_addrs
);
1387 static char *guest_wctomb_dup(WCHAR
*wstr
)
1392 i
= wcslen(wstr
) + 1;
1394 WideCharToMultiByte(CP_ACP
, WC_COMPOSITECHECK
,
1395 wstr
, -1, str
, i
, NULL
, NULL
);
1399 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
1402 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
1406 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
1407 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1408 len
= sizeof(addr_str
);
1409 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
1410 ip_addr
->Address
.iSockaddrLength
,
1415 error_setg_win32(errp
, WSAGetLastError(),
1416 "failed address presentation form conversion");
1419 return g_strdup(addr_str
);
1424 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1426 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1427 * field to obtain the prefix.
1429 return ip_addr
->OnLinkPrefixLength
;
1432 #define INTERFACE_PATH_BUF_SZ 512
1434 static DWORD
get_interface_index(const char *guid
)
1438 wchar_t wbuf
[INTERFACE_PATH_BUF_SZ
];
1439 snwprintf(wbuf
, INTERFACE_PATH_BUF_SZ
, L
"\\device\\tcpip_%s", guid
);
1440 wbuf
[INTERFACE_PATH_BUF_SZ
- 1] = 0;
1441 status
= GetAdapterIndex (wbuf
, &index
);
1442 if (status
!= NO_ERROR
) {
1449 typedef NETIOAPI_API (WINAPI
*GetIfEntry2Func
)(PMIB_IF_ROW2 Row
);
1451 static int guest_get_network_stats(const char *name
,
1452 GuestNetworkInterfaceStat
*stats
)
1454 OSVERSIONINFO os_ver
;
1456 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1457 GetVersionEx(&os_ver
);
1458 if (os_ver
.dwMajorVersion
>= 6) {
1459 MIB_IF_ROW2 a_mid_ifrow
;
1460 GetIfEntry2Func getifentry2_ex
;
1462 HMODULE module
= GetModuleHandle("iphlpapi");
1463 PVOID func
= GetProcAddress(module
, "GetIfEntry2");
1469 getifentry2_ex
= (GetIfEntry2Func
)func
;
1470 if_index
= get_interface_index(name
);
1471 if (if_index
== (DWORD
)~0) {
1475 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1476 a_mid_ifrow
.InterfaceIndex
= if_index
;
1477 if (NO_ERROR
== getifentry2_ex(&a_mid_ifrow
)) {
1478 stats
->rx_bytes
= a_mid_ifrow
.InOctets
;
1479 stats
->rx_packets
= a_mid_ifrow
.InUcastPkts
;
1480 stats
->rx_errs
= a_mid_ifrow
.InErrors
;
1481 stats
->rx_dropped
= a_mid_ifrow
.InDiscards
;
1482 stats
->tx_bytes
= a_mid_ifrow
.OutOctets
;
1483 stats
->tx_packets
= a_mid_ifrow
.OutUcastPkts
;
1484 stats
->tx_errs
= a_mid_ifrow
.OutErrors
;
1485 stats
->tx_dropped
= a_mid_ifrow
.OutDiscards
;
1492 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1494 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1495 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1496 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1497 GuestIpAddressList
*head_addr
, *cur_addr
;
1498 GuestNetworkInterfaceList
*info
;
1499 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1500 GuestIpAddressList
*address_item
= NULL
;
1501 unsigned char *mac_addr
;
1507 adptr_addrs
= guest_get_adapters_addresses(errp
);
1508 if (adptr_addrs
== NULL
) {
1512 /* Make WSA APIs available. */
1513 wsa_version
= MAKEWORD(2, 2);
1514 ret
= WSAStartup(wsa_version
, &wsa_data
);
1516 error_setg_win32(errp
, ret
, "failed socket startup");
1520 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1521 info
= g_malloc0(sizeof(*info
));
1523 if (cur_item
== NULL
) {
1524 head
= cur_item
= info
;
1526 cur_item
->next
= info
;
1530 info
->value
= g_malloc0(sizeof(*info
->value
));
1531 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1533 if (addr
->PhysicalAddressLength
!= 0) {
1534 mac_addr
= addr
->PhysicalAddress
;
1536 info
->value
->hardware_address
=
1537 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1538 (int) mac_addr
[0], (int) mac_addr
[1],
1539 (int) mac_addr
[2], (int) mac_addr
[3],
1540 (int) mac_addr
[4], (int) mac_addr
[5]);
1542 info
->value
->has_hardware_address
= true;
1547 for (ip_addr
= addr
->FirstUnicastAddress
;
1549 ip_addr
= ip_addr
->Next
) {
1550 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1551 if (addr_str
== NULL
) {
1555 address_item
= g_malloc0(sizeof(*address_item
));
1558 head_addr
= cur_addr
= address_item
;
1560 cur_addr
->next
= address_item
;
1561 cur_addr
= address_item
;
1564 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1565 address_item
->value
->ip_address
= addr_str
;
1566 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1567 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1568 address_item
->value
->ip_address_type
=
1569 GUEST_IP_ADDRESS_TYPE_IPV4
;
1570 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1571 address_item
->value
->ip_address_type
=
1572 GUEST_IP_ADDRESS_TYPE_IPV6
;
1576 info
->value
->has_ip_addresses
= true;
1577 info
->value
->ip_addresses
= head_addr
;
1579 if (!info
->value
->has_statistics
) {
1580 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1581 if (guest_get_network_stats(addr
->AdapterName
,
1582 interface_stat
) == -1) {
1583 info
->value
->has_statistics
= false;
1584 g_free(interface_stat
);
1586 info
->value
->statistics
= interface_stat
;
1587 info
->value
->has_statistics
= true;
1593 g_free(adptr_addrs
);
1597 int64_t qmp_guest_get_time(Error
**errp
)
1599 SYSTEMTIME ts
= {0};
1603 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1604 error_setg(errp
, "Failed to get time");
1608 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1609 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1613 return ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1614 - W32_FT_OFFSET
) * 100;
1617 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1619 Error
*local_err
= NULL
;
1625 /* Unfortunately, Windows libraries don't provide an easy way to access
1628 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1630 * Instead, a workaround is to use the Windows win32tm command to
1631 * resync the time using the Windows Time service.
1636 HRESULT hr
= system("w32tm /resync /nowait");
1638 if (GetLastError() != 0) {
1639 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1640 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1641 } else if (hr
!= 0) {
1642 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1643 error_setg(errp
, "Windows Time service not running on the "
1646 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1647 FORMAT_MESSAGE_FROM_SYSTEM
|
1648 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1649 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1650 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1652 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1653 "t retrieve error message", hr
);
1655 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1656 (LPCTSTR
)msg_buffer
);
1657 LocalFree(msg_buffer
);
1660 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1661 error_setg(errp
, "No internet connection on guest, sync not "
1667 /* Validate time passed by user. */
1668 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1669 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1673 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1675 tf
.dwLowDateTime
= (DWORD
) time
;
1676 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1678 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1679 error_setg(errp
, "Failed to convert system time %d",
1680 (int)GetLastError());
1684 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1686 error_propagate(errp
, local_err
);
1690 if (!SetSystemTime(&ts
)) {
1691 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1696 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1698 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1700 GuestLogicalProcessorList
*head
, **link
;
1701 Error
*local_err
= NULL
;
1710 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1711 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1712 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1713 ptr
= pslpi
= g_malloc0(length
);
1714 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1715 error_setg(&local_err
, "Failed to get processor information: %d",
1716 (int)GetLastError());
1719 error_setg(&local_err
,
1720 "Failed to get processor information buffer length: %d",
1721 (int)GetLastError());
1724 while ((local_err
== NULL
) && (length
> 0)) {
1725 if (pslpi
->Relationship
== RelationProcessorCore
) {
1726 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1728 while (cpu_bits
> 0) {
1729 if (!!(cpu_bits
& 1)) {
1730 GuestLogicalProcessor
*vcpu
;
1731 GuestLogicalProcessorList
*entry
;
1733 vcpu
= g_malloc0(sizeof *vcpu
);
1734 vcpu
->logical_id
= current
++;
1735 vcpu
->online
= true;
1736 vcpu
->has_can_offline
= true;
1738 entry
= g_malloc0(sizeof *entry
);
1739 entry
->value
= vcpu
;
1742 link
= &entry
->next
;
1747 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1748 pslpi
++; /* next entry */
1753 if (local_err
== NULL
) {
1757 /* there's no guest with zero VCPUs */
1758 error_setg(&local_err
, "Guest reported zero VCPUs");
1761 qapi_free_GuestLogicalProcessorList(head
);
1762 error_propagate(errp
, local_err
);
1766 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1768 error_setg(errp
, QERR_UNSUPPORTED
);
1773 get_net_error_message(gint error
)
1775 HMODULE module
= NULL
;
1776 gchar
*retval
= NULL
;
1777 wchar_t *msg
= NULL
;
1781 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1782 FORMAT_MESSAGE_IGNORE_INSERTS
|
1783 FORMAT_MESSAGE_FROM_SYSTEM
;
1785 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1786 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1788 if (module
!= NULL
) {
1789 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1793 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1796 nchars
= wcslen(msg
);
1799 msg
[nchars
- 1] == L
'\n' &&
1800 msg
[nchars
- 2] == L
'\r') {
1801 msg
[nchars
- 2] = L
'\0';
1804 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1809 if (module
!= NULL
) {
1810 FreeLibrary(module
);
1816 void qmp_guest_set_user_password(const char *username
,
1817 const char *password
,
1822 char *rawpasswddata
= NULL
;
1823 size_t rawpasswdlen
;
1824 wchar_t *user
= NULL
, *wpass
= NULL
;
1825 USER_INFO_1003 pi1003
= { 0, };
1826 GError
*gerr
= NULL
;
1829 error_setg(errp
, QERR_UNSUPPORTED
);
1833 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1834 if (!rawpasswddata
) {
1837 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1838 rawpasswddata
[rawpasswdlen
] = '\0';
1840 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1845 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1850 pi1003
.usri1003_password
= wpass
;
1851 nas
= NetUserSetInfo(NULL
, user
,
1852 1003, (LPBYTE
)&pi1003
,
1855 if (nas
!= NERR_Success
) {
1856 gchar
*msg
= get_net_error_message(nas
);
1857 error_setg(errp
, "failed to set password: %s", msg
);
1863 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1868 g_free(rawpasswddata
);
1871 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1873 error_setg(errp
, QERR_UNSUPPORTED
);
1877 GuestMemoryBlockResponseList
*
1878 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1880 error_setg(errp
, QERR_UNSUPPORTED
);
1884 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1886 error_setg(errp
, QERR_UNSUPPORTED
);
1890 /* add unsupported commands to the blacklist */
1891 GList
*ga_command_blacklist_init(GList
*blacklist
)
1893 const char *list_unsupported
[] = {
1894 "guest-suspend-hybrid",
1896 "guest-get-memory-blocks", "guest-set-memory-blocks",
1897 "guest-get-memory-block-size",
1899 char **p
= (char **)list_unsupported
;
1902 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1905 if (!vss_init(true)) {
1906 g_debug("vss_init failed, vss commands are going to be disabled");
1907 const char *list
[] = {
1908 "guest-get-fsinfo", "guest-fsfreeze-status",
1909 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1913 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1920 /* register init/cleanup routines for stateful command groups */
1921 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1923 if (!vss_initialized()) {
1924 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1928 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1929 typedef struct _GA_WTSINFOA
{
1930 WTS_CONNECTSTATE_CLASS State
;
1932 DWORD IncomingBytes
;
1933 DWORD OutgoingBytes
;
1934 DWORD IncomingFrames
;
1935 DWORD OutgoingFrames
;
1936 DWORD IncomingCompressedBytes
;
1937 DWORD OutgoingCompressedBy
;
1938 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
1939 CHAR Domain
[DOMAIN_LENGTH
];
1940 CHAR UserName
[USERNAME_LENGTH
+ 1];
1941 LARGE_INTEGER ConnectTime
;
1942 LARGE_INTEGER DisconnectTime
;
1943 LARGE_INTEGER LastInputTime
;
1944 LARGE_INTEGER LogonTime
;
1945 LARGE_INTEGER CurrentTime
;
1949 GuestUserList
*qmp_guest_get_users(Error
**err
)
1951 #define QGA_NANOSECONDS 10000000
1953 GHashTable
*cache
= NULL
;
1954 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
1956 DWORD buffer_size
= 0, count
= 0, i
= 0;
1957 GA_WTSINFOA
*info
= NULL
;
1958 WTS_SESSION_INFOA
*entries
= NULL
;
1959 GuestUserList
*item
= NULL
;
1960 GuestUser
*user
= NULL
;
1961 gpointer value
= NULL
;
1963 double login_time
= 0;
1965 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
1967 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
1968 for (i
= 0; i
< count
; ++i
) {
1971 if (WTSQuerySessionInformationA(
1973 entries
[i
].SessionId
,
1979 if (strlen(info
->UserName
) == 0) {
1980 WTSFreeMemory(info
);
1984 login
= info
->LogonTime
.QuadPart
;
1985 login
-= W32_FT_OFFSET
;
1986 login_time
= ((double)login
) / QGA_NANOSECONDS
;
1988 if (g_hash_table_contains(cache
, info
->UserName
)) {
1989 value
= g_hash_table_lookup(cache
, info
->UserName
);
1990 user
= (GuestUser
*)value
;
1991 if (user
->login_time
> login_time
) {
1992 user
->login_time
= login_time
;
1995 item
= g_new0(GuestUserList
, 1);
1996 item
->value
= g_new0(GuestUser
, 1);
1998 item
->value
->user
= g_strdup(info
->UserName
);
1999 item
->value
->domain
= g_strdup(info
->Domain
);
2000 item
->value
->has_domain
= true;
2002 item
->value
->login_time
= login_time
;
2004 g_hash_table_add(cache
, item
->value
->user
);
2007 head
= cur_item
= item
;
2009 cur_item
->next
= item
;
2014 WTSFreeMemory(info
);
2016 WTSFreeMemory(entries
);
2018 g_hash_table_destroy(cache
);
2022 typedef struct _ga_matrix_lookup_t
{
2025 char const *version
;
2026 char const *version_id
;
2027 } ga_matrix_lookup_t
;
2029 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][8] = {
2031 /* Desktop editions */
2032 { 5, 0, "Microsoft Windows 2000", "2000"},
2033 { 5, 1, "Microsoft Windows XP", "xp"},
2034 { 6, 0, "Microsoft Windows Vista", "vista"},
2035 { 6, 1, "Microsoft Windows 7" "7"},
2036 { 6, 2, "Microsoft Windows 8", "8"},
2037 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2038 {10, 0, "Microsoft Windows 10", "10"},
2041 /* Server editions */
2042 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2043 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2044 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2045 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2046 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2053 typedef struct _ga_win_10_0_server_t
{
2055 char const *version
;
2056 char const *version_id
;
2057 } ga_win_10_0_server_t
;
2059 static ga_win_10_0_server_t
const WIN_10_0_SERVER_VERSION_MATRIX
[3] = {
2060 {14393, "Microsoft Windows Server 2016", "2016"},
2061 {17763, "Microsoft Windows Server 2019", "2019"},
2065 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
2067 typedef NTSTATUS(WINAPI
* rtl_get_version_t
)(
2068 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
2070 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
2072 HMODULE module
= GetModuleHandle("ntdll");
2073 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
2075 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
2076 "Failed to get address of RtlGetVersion");
2080 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
2081 rtl_get_version(info
);
2085 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
2087 DWORD major
= os_version
->dwMajorVersion
;
2088 DWORD minor
= os_version
->dwMinorVersion
;
2089 DWORD build
= os_version
->dwBuildNumber
;
2090 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
2091 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
2092 ga_win_10_0_server_t
const *win_10_0_table
= WIN_10_0_SERVER_VERSION_MATRIX
;
2093 while (table
->version
!= NULL
) {
2094 if (major
== 10 && minor
== 0 && tbl_idx
) {
2095 while (win_10_0_table
->version
!= NULL
) {
2096 if (build
<= win_10_0_table
->final_build
) {
2098 return g_strdup(win_10_0_table
->version_id
);
2100 return g_strdup(win_10_0_table
->version
);
2105 } else if (major
== table
->major
&& minor
== table
->minor
) {
2107 return g_strdup(table
->version_id
);
2109 return g_strdup(table
->version
);
2114 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2116 return g_strdup("N/A");
2119 static char *ga_get_win_product_name(Error
**errp
)
2123 char *result
= g_malloc0(size
);
2124 LONG err
= ERROR_SUCCESS
;
2126 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
2127 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2129 if (err
!= ERROR_SUCCESS
) {
2130 error_setg_win32(errp
, err
, "failed to open registry key");
2134 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2135 (LPBYTE
)result
, &size
);
2136 if (err
== ERROR_MORE_DATA
) {
2137 slog("ProductName longer than expected (%lu bytes), retrying",
2142 result
= g_malloc0(size
);
2143 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2144 (LPBYTE
)result
, &size
);
2147 if (err
!= ERROR_SUCCESS
) {
2148 error_setg_win32(errp
, err
, "failed to retrive ProductName");
2159 static char *ga_get_current_arch(void)
2162 GetNativeSystemInfo(&info
);
2163 char *result
= NULL
;
2164 switch (info
.wProcessorArchitecture
) {
2165 case PROCESSOR_ARCHITECTURE_AMD64
:
2166 result
= g_strdup("x86_64");
2168 case PROCESSOR_ARCHITECTURE_ARM
:
2169 result
= g_strdup("arm");
2171 case PROCESSOR_ARCHITECTURE_IA64
:
2172 result
= g_strdup("ia64");
2174 case PROCESSOR_ARCHITECTURE_INTEL
:
2175 result
= g_strdup("x86");
2177 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
2179 slog("unknown processor architecture 0x%0x",
2180 info
.wProcessorArchitecture
);
2181 result
= g_strdup("unknown");
2187 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2189 Error
*local_err
= NULL
;
2190 OSVERSIONINFOEXW os_version
= {0};
2195 ga_get_win_version(&os_version
, &local_err
);
2197 error_propagate(errp
, local_err
);
2201 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
2202 product_name
= ga_get_win_product_name(&local_err
);
2203 if (product_name
== NULL
) {
2204 error_propagate(errp
, local_err
);
2208 info
= g_new0(GuestOSInfo
, 1);
2210 info
->has_kernel_version
= true;
2211 info
->kernel_version
= g_strdup_printf("%lu.%lu",
2212 os_version
.dwMajorVersion
,
2213 os_version
.dwMinorVersion
);
2214 info
->has_kernel_release
= true;
2215 info
->kernel_release
= g_strdup_printf("%lu",
2216 os_version
.dwBuildNumber
);
2217 info
->has_machine
= true;
2218 info
->machine
= ga_get_current_arch();
2220 info
->has_id
= true;
2221 info
->id
= g_strdup("mswindows");
2222 info
->has_name
= true;
2223 info
->name
= g_strdup("Microsoft Windows");
2224 info
->has_pretty_name
= true;
2225 info
->pretty_name
= product_name
;
2226 info
->has_version
= true;
2227 info
->version
= ga_get_win_name(&os_version
, false);
2228 info
->has_version_id
= true;
2229 info
->version_id
= ga_get_win_name(&os_version
, true);
2230 info
->has_variant
= true;
2231 info
->variant
= g_strdup(server
? "server" : "client");
2232 info
->has_variant_id
= true;
2233 info
->variant_id
= g_strdup(server
? "server" : "client");