2 * QEMU Guest Agent win32-specific command implementations
4 * Copyright IBM Corp. 2012
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Gal Hammer <ghammer@redhat.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
13 #include "qemu/osdep.h"
21 #ifdef CONFIG_QGA_NTDDSCSI
32 #include "guest-agent-core.h"
33 #include "vss-win32.h"
34 #include "qga-qapi-commands.h"
35 #include "qapi/error.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qemu/queue.h"
38 #include "qemu/host-utils.h"
39 #include "qemu/base64.h"
40 #include "commands-common.h"
42 #ifndef SHTDN_REASON_FLAG_PLANNED
43 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
46 /* multiple of 100 nanoseconds elapsed between windows baseline
47 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
48 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
49 (365 * (1970 - 1601) + \
50 (1970 - 1601) / 4 - 3))
52 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
54 struct GuestFileHandle
{
57 QTAILQ_ENTRY(GuestFileHandle
) next
;
61 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
62 } guest_file_state
= {
63 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
66 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
68 typedef struct OpenFlags
{
71 DWORD creation_disposition
;
73 static OpenFlags guest_file_open_modes
[] = {
74 {"r", GENERIC_READ
, OPEN_EXISTING
},
75 {"rb", GENERIC_READ
, OPEN_EXISTING
},
76 {"w", GENERIC_WRITE
, CREATE_ALWAYS
},
77 {"wb", GENERIC_WRITE
, CREATE_ALWAYS
},
78 {"a", FILE_GENERIC_APPEND
, OPEN_ALWAYS
},
79 {"r+", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
80 {"rb+", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
81 {"r+b", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
82 {"w+", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
83 {"wb+", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
84 {"w+b", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
85 {"a+", FILE_GENERIC_APPEND
|GENERIC_READ
, OPEN_ALWAYS
},
86 {"ab+", FILE_GENERIC_APPEND
|GENERIC_READ
, OPEN_ALWAYS
},
87 {"a+b", FILE_GENERIC_APPEND
|GENERIC_READ
, OPEN_ALWAYS
}
90 #define debug_error(msg) do { \
91 char *suffix = g_win32_error_message(GetLastError()); \
92 g_debug("%s: %s", (msg), suffix); \
96 static OpenFlags
*find_open_flag(const char *mode_str
)
101 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
102 OpenFlags
*flags
= guest_file_open_modes
+ mode
;
104 if (strcmp(flags
->forms
, mode_str
) == 0) {
109 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
113 static int64_t guest_file_handle_add(HANDLE fh
, Error
**errp
)
115 GuestFileHandle
*gfh
;
118 handle
= ga_get_fd_handle(ga_state
, errp
);
122 gfh
= g_new0(GuestFileHandle
, 1);
125 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
130 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
132 GuestFileHandle
*gfh
;
133 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
) {
138 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
142 static void handle_set_nonblocking(HANDLE fh
)
144 DWORD file_type
, pipe_state
;
145 file_type
= GetFileType(fh
);
146 if (file_type
!= FILE_TYPE_PIPE
) {
149 /* If file_type == FILE_TYPE_PIPE, according to MSDN
150 * the specified file is socket or named pipe */
151 if (!GetNamedPipeHandleState(fh
, &pipe_state
, NULL
,
152 NULL
, NULL
, NULL
, 0)) {
155 /* The fd is named pipe fd */
156 if (pipe_state
& PIPE_NOWAIT
) {
160 pipe_state
|= PIPE_NOWAIT
;
161 SetNamedPipeHandleState(fh
, &pipe_state
, NULL
, NULL
);
164 int64_t qmp_guest_file_open(const char *path
, bool has_mode
,
165 const char *mode
, Error
**errp
)
169 HANDLE templ_file
= NULL
;
170 DWORD share_mode
= FILE_SHARE_READ
;
171 DWORD flags_and_attr
= FILE_ATTRIBUTE_NORMAL
;
172 LPSECURITY_ATTRIBUTES sa_attr
= NULL
;
173 OpenFlags
*guest_flags
;
175 wchar_t *w_path
= NULL
;
180 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
181 guest_flags
= find_open_flag(mode
);
182 if (guest_flags
== NULL
) {
183 error_setg(errp
, "invalid file open mode");
187 w_path
= g_utf8_to_utf16(path
, -1, NULL
, NULL
, &gerr
);
192 fh
= CreateFileW(w_path
, guest_flags
->desired_access
, share_mode
, sa_attr
,
193 guest_flags
->creation_disposition
, flags_and_attr
,
195 if (fh
== INVALID_HANDLE_VALUE
) {
196 error_setg_win32(errp
, GetLastError(), "failed to open file '%s'",
201 /* set fd non-blocking to avoid common use cases (like reading from a
202 * named pipe) from hanging the agent
204 handle_set_nonblocking(fh
);
206 fd
= guest_file_handle_add(fh
, errp
);
209 error_setg(errp
, "failed to add handle to qmp handle table");
213 slog("guest-file-open, handle: % " PRId64
, fd
);
217 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
224 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
227 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
228 slog("guest-file-close called, handle: %" PRId64
, handle
);
232 ret
= CloseHandle(gfh
->fh
);
234 error_setg_win32(errp
, GetLastError(), "failed close handle");
238 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
242 static void acquire_privilege(const char *name
, Error
**errp
)
245 TOKEN_PRIVILEGES priv
;
246 Error
*local_err
= NULL
;
248 if (OpenProcessToken(GetCurrentProcess(),
249 TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY
, &token
))
251 if (!LookupPrivilegeValue(NULL
, name
, &priv
.Privileges
[0].Luid
)) {
252 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
253 "no luid for requested privilege");
257 priv
.PrivilegeCount
= 1;
258 priv
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
260 if (!AdjustTokenPrivileges(token
, FALSE
, &priv
, 0, NULL
, 0)) {
261 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
262 "unable to acquire requested privilege");
267 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
268 "failed to open privilege token");
275 error_propagate(errp
, local_err
);
278 static void execute_async(DWORD
WINAPI (*func
)(LPVOID
), LPVOID opaque
,
281 Error
*local_err
= NULL
;
283 HANDLE thread
= CreateThread(NULL
, 0, func
, opaque
, 0, NULL
);
285 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
286 "failed to dispatch asynchronous command");
287 error_propagate(errp
, local_err
);
291 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
293 Error
*local_err
= NULL
;
294 UINT shutdown_flag
= EWX_FORCE
;
296 slog("guest-shutdown called, mode: %s", mode
);
298 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
299 shutdown_flag
|= EWX_POWEROFF
;
300 } else if (strcmp(mode
, "halt") == 0) {
301 shutdown_flag
|= EWX_SHUTDOWN
;
302 } else if (strcmp(mode
, "reboot") == 0) {
303 shutdown_flag
|= EWX_REBOOT
;
305 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "mode",
306 "halt|powerdown|reboot");
310 /* Request a shutdown privilege, but try to shut down the system
312 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
314 error_propagate(errp
, local_err
);
318 if (!ExitWindowsEx(shutdown_flag
, SHTDN_REASON_FLAG_PLANNED
)) {
319 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
320 slog("guest-shutdown failed: %s", emsg
);
321 error_setg_win32(errp
, GetLastError(), "guest-shutdown failed");
325 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
326 int64_t count
, Error
**errp
)
328 GuestFileRead
*read_data
= NULL
;
334 buf
= g_malloc0(count
+ 1);
335 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
337 error_setg_win32(errp
, GetLastError(), "failed to read file");
340 read_data
= g_new0(GuestFileRead
, 1);
341 read_data
->count
= (size_t)read_count
;
342 read_data
->eof
= read_count
== 0;
344 if (read_count
!= 0) {
345 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
353 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
354 bool has_count
, int64_t count
,
357 GuestFileWrite
*write_data
= NULL
;
362 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
369 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
376 } else if (count
< 0 || count
> buf_len
) {
377 error_setg(errp
, "value '%" PRId64
378 "' is invalid for argument count", count
);
382 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
384 error_setg_win32(errp
, GetLastError(), "failed to write to file");
385 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
387 write_data
= g_new0(GuestFileWrite
, 1);
388 write_data
->count
= (size_t) write_count
;
396 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
397 GuestFileWhence
*whence_code
,
400 GuestFileHandle
*gfh
;
401 GuestFileSeek
*seek_data
;
403 LARGE_INTEGER new_pos
, off_pos
;
404 off_pos
.QuadPart
= offset
;
409 gfh
= guest_file_handle_find(handle
, errp
);
414 /* We stupidly exposed 'whence':'int' in our qapi */
415 whence
= ga_parse_whence(whence_code
, &err
);
417 error_propagate(errp
, err
);
422 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
424 error_setg_win32(errp
, GetLastError(), "failed to seek file");
427 seek_data
= g_new0(GuestFileSeek
, 1);
428 seek_data
->position
= new_pos
.QuadPart
;
432 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
435 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
441 if (!FlushFileBuffers(fh
)) {
442 error_setg_win32(errp
, GetLastError(), "failed to flush file");
446 #ifdef CONFIG_QGA_NTDDSCSI
448 static GuestDiskBusType win2qemu
[] = {
449 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
450 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
451 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
452 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
453 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
454 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
455 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
456 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
457 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
458 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
459 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
460 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
461 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
462 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
463 #if (_WIN32_WINNT >= 0x0601)
464 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
465 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
469 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
471 if (bus
>= ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
472 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
474 return win2qemu
[(int)bus
];
477 DEFINE_GUID(GUID_DEVINTERFACE_DISK
,
478 0x53f56307L
, 0xb6bf, 0x11d0, 0x94, 0xf2,
479 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
480 DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT
,
481 0x2accfe60L
, 0xc130, 0x11d2, 0xb0, 0x82,
482 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
484 static GuestPCIAddress
*get_pci_info(int number
, Error
**errp
)
487 SP_DEVINFO_DATA dev_info_data
;
488 SP_DEVICE_INTERFACE_DATA dev_iface_data
;
491 GuestPCIAddress
*pci
= NULL
;
492 bool partial_pci
= false;
494 pci
= g_malloc0(sizeof(*pci
));
500 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK
, 0, 0,
501 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
502 if (dev_info
== INVALID_HANDLE_VALUE
) {
503 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
507 g_debug("enumerating devices");
508 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
509 dev_iface_data
.cbSize
= sizeof(SP_DEVICE_INTERFACE_DATA
);
510 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
511 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data
= NULL
;
512 STORAGE_DEVICE_NUMBER sdn
;
513 char *parent_dev_id
= NULL
;
514 HDEVINFO parent_dev_info
;
515 SP_DEVINFO_DATA parent_dev_info_data
;
519 g_debug("getting device path");
520 if (SetupDiEnumDeviceInterfaces(dev_info
, &dev_info_data
,
521 &GUID_DEVINTERFACE_DISK
, 0,
523 while (!SetupDiGetDeviceInterfaceDetail(dev_info
, &dev_iface_data
,
524 pdev_iface_detail_data
,
527 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
528 pdev_iface_detail_data
= g_malloc(size
);
529 pdev_iface_detail_data
->cbSize
=
530 sizeof(*pdev_iface_detail_data
);
532 error_setg_win32(errp
, GetLastError(),
533 "failed to get device interfaces");
538 dev_file
= CreateFile(pdev_iface_detail_data
->DevicePath
, 0,
539 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0,
541 g_free(pdev_iface_detail_data
);
543 if (!DeviceIoControl(dev_file
, IOCTL_STORAGE_GET_DEVICE_NUMBER
,
544 NULL
, 0, &sdn
, sizeof(sdn
), &size
, NULL
)) {
545 CloseHandle(dev_file
);
546 error_setg_win32(errp
, GetLastError(),
547 "failed to get device slot number");
551 CloseHandle(dev_file
);
552 if (sdn
.DeviceNumber
!= number
) {
556 error_setg_win32(errp
, GetLastError(),
557 "failed to get device interfaces");
561 g_debug("found device slot %d. Getting storage controller", number
);
564 DEVINST dev_inst
, parent_dev_inst
;
565 ULONG dev_id_size
= 0;
568 while (!SetupDiGetDeviceInstanceId(dev_info
, &dev_info_data
,
569 parent_dev_id
, size
, &size
)) {
570 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
571 parent_dev_id
= g_malloc(size
);
573 error_setg_win32(errp
, GetLastError(),
574 "failed to get device instance ID");
580 * CM API used here as opposed to
581 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
582 * which exports are only available in mingw-w64 6+
584 cr
= CM_Locate_DevInst(&dev_inst
, parent_dev_id
, 0);
585 if (cr
!= CR_SUCCESS
) {
586 g_error("CM_Locate_DevInst failed with code %lx", cr
);
587 error_setg_win32(errp
, GetLastError(),
588 "failed to get device instance");
591 cr
= CM_Get_Parent(&parent_dev_inst
, dev_inst
, 0);
592 if (cr
!= CR_SUCCESS
) {
593 g_error("CM_Get_Parent failed with code %lx", cr
);
594 error_setg_win32(errp
, GetLastError(),
595 "failed to get parent device instance");
599 cr
= CM_Get_Device_ID_Size(&dev_id_size
, parent_dev_inst
, 0);
600 if (cr
!= CR_SUCCESS
) {
601 g_error("CM_Get_Device_ID_Size failed with code %lx", cr
);
602 error_setg_win32(errp
, GetLastError(),
603 "failed to get parent device ID length");
608 if (dev_id_size
> size
) {
609 g_free(parent_dev_id
);
610 parent_dev_id
= g_malloc(dev_id_size
);
613 cr
= CM_Get_Device_ID(parent_dev_inst
, parent_dev_id
, dev_id_size
,
615 if (cr
!= CR_SUCCESS
) {
616 g_error("CM_Get_Device_ID failed with code %lx", cr
);
617 error_setg_win32(errp
, GetLastError(),
618 "failed to get parent device ID");
623 g_debug("querying storage controller %s for PCI information",
626 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT
, parent_dev_id
,
627 NULL
, DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
628 g_free(parent_dev_id
);
630 if (parent_dev_info
== INVALID_HANDLE_VALUE
) {
631 error_setg_win32(errp
, GetLastError(),
632 "failed to get parent device");
636 parent_dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
637 if (!SetupDiEnumDeviceInfo(parent_dev_info
, 0, &parent_dev_info_data
)) {
638 error_setg_win32(errp
, GetLastError(),
639 "failed to get parent device data");
644 SetupDiEnumDeviceInfo(parent_dev_info
, j
, &parent_dev_info_data
);
646 DWORD addr
, bus
, ui_slot
, type
;
650 * There is no need to allocate buffer in the next functions. The
651 * size is known and ULONG according to
652 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
654 if (!SetupDiGetDeviceRegistryProperty(
655 parent_dev_info
, &parent_dev_info_data
, SPDRP_BUSNUMBER
,
656 &type
, (PBYTE
)&bus
, size
, NULL
)) {
657 debug_error("failed to get PCI bus");
663 * The function retrieves the device's address. This value will be
664 * transformed into device function and number
666 if (!SetupDiGetDeviceRegistryProperty(
667 parent_dev_info
, &parent_dev_info_data
, SPDRP_ADDRESS
,
668 &type
, (PBYTE
)&addr
, size
, NULL
)) {
669 debug_error("failed to get PCI address");
675 * This call returns UINumber of DEVICE_CAPABILITIES structure.
676 * This number is typically a user-perceived slot number.
678 if (!SetupDiGetDeviceRegistryProperty(
679 parent_dev_info
, &parent_dev_info_data
, SPDRP_UI_NUMBER
,
680 &type
, (PBYTE
)&ui_slot
, size
, NULL
)) {
681 debug_error("failed to get PCI slot");
687 * SetupApi gives us the same information as driver with
688 * IoGetDeviceProperty. According to Microsoft:
690 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
691 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
692 * SPDRP_ADDRESS is propertyAddress, so we do the same.
694 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
703 func
= ((int)addr
== -1) ? -1 : addr
& 0x0000FFFF;
704 slot
= ((int)addr
== -1) ? -1 : (addr
>> 16) & 0x0000FFFF;
705 if ((int)ui_slot
!= slot
) {
706 g_debug("mismatch with reported slot values: %d vs %d",
710 pci
->slot
= (int)ui_slot
;
711 pci
->function
= func
;
716 SetupDiDestroyDeviceInfoList(parent_dev_info
);
721 SetupDiDestroyDeviceInfoList(dev_info
);
726 static void get_disk_properties(HANDLE vol_h
, GuestDiskAddress
*disk
,
729 STORAGE_PROPERTY_QUERY query
;
730 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
732 ULONG size
= sizeof(buf
);
735 query
.PropertyId
= StorageDeviceProperty
;
736 query
.QueryType
= PropertyStandardQuery
;
738 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
739 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
740 size
, &received
, NULL
)) {
741 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
744 disk
->bus_type
= find_bus_type(dev_desc
->BusType
);
745 g_debug("bus type %d", disk
->bus_type
);
747 /* Query once more. Now with long enough buffer. */
748 size
= dev_desc
->Size
;
749 dev_desc
= g_malloc0(size
);
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 serial number");
754 g_debug("failed to get serial number");
757 if (dev_desc
->SerialNumberOffset
> 0) {
761 if (dev_desc
->SerialNumberOffset
>= received
) {
762 error_setg(errp
, "failed to get serial number: offset outside the buffer");
763 g_debug("serial number offset outside the buffer");
766 serial
= (char *)dev_desc
+ dev_desc
->SerialNumberOffset
;
767 len
= received
- dev_desc
->SerialNumberOffset
;
768 g_debug("serial number \"%s\"", serial
);
770 disk
->serial
= g_strndup(serial
, len
);
771 disk
->has_serial
= true;
780 static void get_single_disk_info(int disk_number
,
781 GuestDiskAddress
*disk
, Error
**errp
)
783 SCSI_ADDRESS addr
, *scsi_ad
;
786 Error
*local_err
= NULL
;
790 g_debug("getting disk info for: %s", disk
->dev
);
791 disk_h
= CreateFile(disk
->dev
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
793 if (disk_h
== INVALID_HANDLE_VALUE
) {
794 error_setg_win32(errp
, GetLastError(), "failed to open disk");
798 get_disk_properties(disk_h
, disk
, &local_err
);
800 error_propagate(errp
, local_err
);
804 g_debug("bus type %d", disk
->bus_type
);
805 /* always set pci_controller as required by schema. get_pci_info() should
806 * report -1 values for non-PCI buses rather than fail. fail the command
807 * if that doesn't hold since that suggests some other unexpected
810 disk
->pci_controller
= get_pci_info(disk_number
, &local_err
);
812 error_propagate(errp
, local_err
);
815 if (disk
->bus_type
== GUEST_DISK_BUS_TYPE_SCSI
816 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_IDE
817 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_RAID
818 /* This bus type is not supported before Windows Server 2003 SP1 */
819 || disk
->bus_type
== GUEST_DISK_BUS_TYPE_SAS
821 /* We are able to use the same ioctls for different bus types
822 * according to Microsoft docs
823 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
824 g_debug("getting SCSI info");
825 if (DeviceIoControl(disk_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
826 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
827 disk
->unit
= addr
.Lun
;
828 disk
->target
= addr
.TargetId
;
829 disk
->bus
= addr
.PathId
;
831 /* We do not set error in this case, because we still have enough
832 * information about volume. */
840 /* VSS provider works with volumes, thus there is no difference if
841 * the volume consist of spanned disks. Info about the first disk in the
842 * volume is returned for the spanned disk group (LVM) */
843 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
845 Error
*local_err
= NULL
;
846 GuestDiskAddressList
*list
= NULL
, *cur_item
= NULL
;
847 GuestDiskAddress
*disk
= NULL
;
851 PVOLUME_DISK_EXTENTS extents
= NULL
;
853 /* strip final backslash */
854 char *name
= g_strdup(guid
);
855 if (g_str_has_suffix(name
, "\\")) {
856 name
[strlen(name
) - 1] = 0;
859 g_debug("opening %s", name
);
860 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
862 if (vol_h
== INVALID_HANDLE_VALUE
) {
863 error_setg_win32(errp
, GetLastError(), "failed to open volume");
867 /* Get list of extents */
868 g_debug("getting disk extents");
869 size
= sizeof(VOLUME_DISK_EXTENTS
);
870 extents
= g_malloc0(size
);
871 if (!DeviceIoControl(vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
872 0, extents
, size
, &size
, NULL
)) {
873 DWORD last_err
= GetLastError();
874 if (last_err
== ERROR_MORE_DATA
) {
875 /* Try once more with big enough buffer */
877 extents
= g_malloc0(size
);
878 if (!DeviceIoControl(
879 vol_h
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
,
880 0, extents
, size
, NULL
, NULL
)) {
881 error_setg_win32(errp
, GetLastError(),
882 "failed to get disk extents");
885 } else if (last_err
== ERROR_INVALID_FUNCTION
) {
886 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
887 g_debug("volume not on disk");
888 disk
= g_malloc0(sizeof(GuestDiskAddress
));
889 disk
->has_dev
= true;
890 disk
->dev
= g_strdup(name
);
891 get_single_disk_info(0xffffffff, disk
, &local_err
);
893 g_debug("failed to get disk info, ignoring error: %s",
894 error_get_pretty(local_err
));
895 error_free(local_err
);
898 list
= g_malloc0(sizeof(*list
));
904 error_setg_win32(errp
, GetLastError(),
905 "failed to get disk extents");
909 g_debug("Number of extents: %lu", extents
->NumberOfDiskExtents
);
911 /* Go through each extent */
912 for (i
= 0; i
< extents
->NumberOfDiskExtents
; i
++) {
913 disk
= g_malloc0(sizeof(GuestDiskAddress
));
915 /* Disk numbers directly correspond to numbers used in UNCs
917 * See documentation for DISK_EXTENT:
918 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
920 * See also Naming Files, Paths and Namespaces:
921 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
923 disk
->has_dev
= true;
924 disk
->dev
= g_strdup_printf("\\\\.\\PhysicalDrive%lu",
925 extents
->Extents
[i
].DiskNumber
);
927 get_single_disk_info(extents
->Extents
[i
].DiskNumber
, disk
, &local_err
);
929 error_propagate(errp
, local_err
);
932 cur_item
= g_malloc0(sizeof(*list
));
933 cur_item
->value
= disk
;
935 cur_item
->next
= list
;
941 if (vol_h
!= INVALID_HANDLE_VALUE
) {
944 qapi_free_GuestDiskAddress(disk
);
953 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
958 #endif /* CONFIG_QGA_NTDDSCSI */
960 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
963 char mnt
, *mnt_point
;
965 char vol_info
[MAX_PATH
+1];
967 uint64_t i64FreeBytesToCaller
, i64TotalBytes
, i64FreeBytes
;
968 GuestFilesystemInfo
*fs
= NULL
;
970 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
971 if (GetLastError() != ERROR_MORE_DATA
) {
972 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
976 mnt_point
= g_malloc(info_size
+ 1);
977 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
979 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
983 len
= strlen(mnt_point
);
984 mnt_point
[len
] = '\\';
985 mnt_point
[len
+1] = 0;
986 if (!GetVolumeInformation(mnt_point
, vol_info
, sizeof(vol_info
), NULL
, NULL
,
987 NULL
, (LPSTR
)&fs_name
, sizeof(fs_name
))) {
988 if (GetLastError() != ERROR_NOT_READY
) {
989 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
994 fs_name
[sizeof(fs_name
) - 1] = 0;
995 fs
= g_malloc(sizeof(*fs
));
996 fs
->name
= g_strdup(guid
);
997 fs
->has_total_bytes
= false;
998 fs
->has_used_bytes
= false;
1000 fs
->mountpoint
= g_strdup("System Reserved");
1002 fs
->mountpoint
= g_strndup(mnt_point
, len
);
1003 if (GetDiskFreeSpaceEx(fs
->mountpoint
,
1004 (PULARGE_INTEGER
) & i64FreeBytesToCaller
,
1005 (PULARGE_INTEGER
) & i64TotalBytes
,
1006 (PULARGE_INTEGER
) & i64FreeBytes
)) {
1007 fs
->used_bytes
= i64TotalBytes
- i64FreeBytes
;
1008 fs
->total_bytes
= i64TotalBytes
;
1009 fs
->has_total_bytes
= true;
1010 fs
->has_used_bytes
= true;
1013 fs
->type
= g_strdup(fs_name
);
1014 fs
->disk
= build_guest_disk_info(guid
, errp
);
1020 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1023 GuestFilesystemInfoList
*new, *ret
= NULL
;
1026 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
1027 if (vol_h
== INVALID_HANDLE_VALUE
) {
1028 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1033 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, errp
);
1037 new = g_malloc(sizeof(*ret
));
1041 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
1043 if (GetLastError() != ERROR_NO_MORE_FILES
) {
1044 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
1047 FindVolumeClose(vol_h
);
1052 * Return status of freeze/thaw
1054 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1056 if (!vss_initialized()) {
1057 error_setg(errp
, QERR_UNSUPPORTED
);
1061 if (ga_is_frozen(ga_state
)) {
1062 return GUEST_FSFREEZE_STATUS_FROZEN
;
1065 return GUEST_FSFREEZE_STATUS_THAWED
;
1069 * Freeze local file systems using Volume Shadow-copy Service.
1070 * The frozen state is limited for up to 10 seconds by VSS.
1072 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1074 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1077 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1078 strList
*mountpoints
,
1082 Error
*local_err
= NULL
;
1084 if (!vss_initialized()) {
1085 error_setg(errp
, QERR_UNSUPPORTED
);
1089 slog("guest-fsfreeze called");
1091 /* cannot risk guest agent blocking itself on a write in this state */
1092 ga_set_frozen(ga_state
);
1094 qga_vss_fsfreeze(&i
, true, mountpoints
, &local_err
);
1096 error_propagate(errp
, local_err
);
1104 qmp_guest_fsfreeze_thaw(&local_err
);
1106 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
1107 error_free(local_err
);
1113 * Thaw local file systems using Volume Shadow-copy Service.
1115 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1119 if (!vss_initialized()) {
1120 error_setg(errp
, QERR_UNSUPPORTED
);
1124 qga_vss_fsfreeze(&i
, false, NULL
, errp
);
1126 ga_unset_frozen(ga_state
);
1130 static void guest_fsfreeze_cleanup(void)
1134 if (!vss_initialized()) {
1138 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1139 qmp_guest_fsfreeze_thaw(&err
);
1141 slog("failed to clean up frozen filesystems: %s",
1142 error_get_pretty(err
));
1151 * Walk list of mounted file systems in the guest, and discard unused
1154 GuestFilesystemTrimResponse
*
1155 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1157 GuestFilesystemTrimResponse
*resp
;
1159 WCHAR guid
[MAX_PATH
] = L
"";
1163 ZeroMemory(&osvi
, sizeof(OSVERSIONINFO
));
1164 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1165 GetVersionEx(&osvi
);
1166 win8_or_later
= (osvi
.dwMajorVersion
> 6 ||
1167 ((osvi
.dwMajorVersion
== 6) &&
1168 (osvi
.dwMinorVersion
>= 2)));
1169 if (!win8_or_later
) {
1170 error_setg(errp
, "fstrim is only supported for Win8+");
1174 handle
= FindFirstVolumeW(guid
, ARRAYSIZE(guid
));
1175 if (handle
== INVALID_HANDLE_VALUE
) {
1176 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
1180 resp
= g_new0(GuestFilesystemTrimResponse
, 1);
1183 GuestFilesystemTrimResult
*res
;
1184 GuestFilesystemTrimResultList
*list
;
1186 DWORD char_count
= 0;
1188 GError
*gerr
= NULL
;
1191 GetVolumePathNamesForVolumeNameW(guid
, NULL
, 0, &char_count
);
1193 if (GetLastError() != ERROR_MORE_DATA
) {
1196 if (GetDriveTypeW(guid
) != DRIVE_FIXED
) {
1200 uc_path
= g_malloc(sizeof(WCHAR
) * char_count
);
1201 if (!GetVolumePathNamesForVolumeNameW(guid
, uc_path
, char_count
,
1202 &char_count
) || !*uc_path
) {
1203 /* strange, but this condition could be faced even with size == 2 */
1208 res
= g_new0(GuestFilesystemTrimResult
, 1);
1210 path
= g_utf16_to_utf8(uc_path
, char_count
, NULL
, NULL
, &gerr
);
1215 res
->has_error
= true;
1216 res
->error
= g_strdup(gerr
->message
);
1223 list
= g_new0(GuestFilesystemTrimResultList
, 1);
1225 list
->next
= resp
->paths
;
1229 memset(argv
, 0, sizeof(argv
));
1230 argv
[0] = (gchar
*)"defrag.exe";
1231 argv
[1] = (gchar
*)"/L";
1234 if (!g_spawn_sync(NULL
, argv
, NULL
, G_SPAWN_SEARCH_PATH
, NULL
, NULL
,
1235 &out
/* stdout */, NULL
/* stdin */,
1237 res
->has_error
= true;
1238 res
->error
= g_strdup(gerr
->message
);
1241 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1242 Error is reported in the output with something like
1243 (x89000020) etc code in the stdout */
1246 gchar
**lines
= g_strsplit(out
, "\r\n", 0);
1249 for (i
= 0; lines
[i
] != NULL
; i
++) {
1250 if (g_strstr_len(lines
[i
], -1, "(0x") == NULL
) {
1253 res
->has_error
= true;
1254 res
->error
= g_strdup(lines
[i
]);
1259 } while (FindNextVolumeW(handle
, guid
, ARRAYSIZE(guid
)));
1261 FindVolumeClose(handle
);
1266 GUEST_SUSPEND_MODE_DISK
,
1267 GUEST_SUSPEND_MODE_RAM
1270 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
1272 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
1273 Error
*local_err
= NULL
;
1275 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
1276 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
1277 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1278 "failed to determine guest suspend capabilities");
1283 case GUEST_SUSPEND_MODE_DISK
:
1284 if (!sys_pwr_caps
.SystemS4
) {
1285 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1286 "suspend-to-disk not supported by OS");
1289 case GUEST_SUSPEND_MODE_RAM
:
1290 if (!sys_pwr_caps
.SystemS3
) {
1291 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
1292 "suspend-to-ram not supported by OS");
1296 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "mode",
1297 "GuestSuspendMode");
1301 error_propagate(errp
, local_err
);
1304 static DWORD WINAPI
do_suspend(LPVOID opaque
)
1306 GuestSuspendMode
*mode
= opaque
;
1309 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
1310 g_autofree gchar
*emsg
= g_win32_error_message(GetLastError());
1311 slog("failed to suspend guest: %s", emsg
);
1318 void qmp_guest_suspend_disk(Error
**errp
)
1320 Error
*local_err
= NULL
;
1321 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1323 *mode
= GUEST_SUSPEND_MODE_DISK
;
1324 check_suspend_mode(*mode
, &local_err
);
1328 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1332 execute_async(do_suspend
, mode
, &local_err
);
1336 error_propagate(errp
, local_err
);
1341 void qmp_guest_suspend_ram(Error
**errp
)
1343 Error
*local_err
= NULL
;
1344 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1346 *mode
= GUEST_SUSPEND_MODE_RAM
;
1347 check_suspend_mode(*mode
, &local_err
);
1351 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1355 execute_async(do_suspend
, mode
, &local_err
);
1359 error_propagate(errp
, local_err
);
1364 void qmp_guest_suspend_hybrid(Error
**errp
)
1366 error_setg(errp
, QERR_UNSUPPORTED
);
1369 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
1371 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
1372 ULONG adptr_addrs_len
= 0;
1375 /* Call the first time to get the adptr_addrs_len. */
1376 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1377 NULL
, adptr_addrs
, &adptr_addrs_len
);
1379 adptr_addrs
= g_malloc(adptr_addrs_len
);
1380 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1381 NULL
, adptr_addrs
, &adptr_addrs_len
);
1382 if (ret
!= ERROR_SUCCESS
) {
1383 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
1384 g_free(adptr_addrs
);
1390 static char *guest_wctomb_dup(WCHAR
*wstr
)
1395 str_size
= WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, NULL
, 0, NULL
, NULL
);
1396 /* add 1 to str_size for NULL terminator */
1397 str
= g_malloc(str_size
+ 1);
1398 WideCharToMultiByte(CP_UTF8
, 0, wstr
, -1, str
, str_size
, NULL
, NULL
);
1402 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
1405 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
1409 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
1410 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1411 len
= sizeof(addr_str
);
1412 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
1413 ip_addr
->Address
.iSockaddrLength
,
1418 error_setg_win32(errp
, WSAGetLastError(),
1419 "failed address presentation form conversion");
1422 return g_strdup(addr_str
);
1427 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1429 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1430 * field to obtain the prefix.
1432 return ip_addr
->OnLinkPrefixLength
;
1435 #define INTERFACE_PATH_BUF_SZ 512
1437 static DWORD
get_interface_index(const char *guid
)
1441 wchar_t wbuf
[INTERFACE_PATH_BUF_SZ
];
1442 snwprintf(wbuf
, INTERFACE_PATH_BUF_SZ
, L
"\\device\\tcpip_%s", guid
);
1443 wbuf
[INTERFACE_PATH_BUF_SZ
- 1] = 0;
1444 status
= GetAdapterIndex (wbuf
, &index
);
1445 if (status
!= NO_ERROR
) {
1452 typedef NETIOAPI_API (WINAPI
*GetIfEntry2Func
)(PMIB_IF_ROW2 Row
);
1454 static int guest_get_network_stats(const char *name
,
1455 GuestNetworkInterfaceStat
*stats
)
1457 OSVERSIONINFO os_ver
;
1459 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1460 GetVersionEx(&os_ver
);
1461 if (os_ver
.dwMajorVersion
>= 6) {
1462 MIB_IF_ROW2 a_mid_ifrow
;
1463 GetIfEntry2Func getifentry2_ex
;
1465 HMODULE module
= GetModuleHandle("iphlpapi");
1466 PVOID func
= GetProcAddress(module
, "GetIfEntry2");
1472 getifentry2_ex
= (GetIfEntry2Func
)func
;
1473 if_index
= get_interface_index(name
);
1474 if (if_index
== (DWORD
)~0) {
1478 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1479 a_mid_ifrow
.InterfaceIndex
= if_index
;
1480 if (NO_ERROR
== getifentry2_ex(&a_mid_ifrow
)) {
1481 stats
->rx_bytes
= a_mid_ifrow
.InOctets
;
1482 stats
->rx_packets
= a_mid_ifrow
.InUcastPkts
;
1483 stats
->rx_errs
= a_mid_ifrow
.InErrors
;
1484 stats
->rx_dropped
= a_mid_ifrow
.InDiscards
;
1485 stats
->tx_bytes
= a_mid_ifrow
.OutOctets
;
1486 stats
->tx_packets
= a_mid_ifrow
.OutUcastPkts
;
1487 stats
->tx_errs
= a_mid_ifrow
.OutErrors
;
1488 stats
->tx_dropped
= a_mid_ifrow
.OutDiscards
;
1495 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1497 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1498 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1499 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1500 GuestIpAddressList
*head_addr
, *cur_addr
;
1501 GuestNetworkInterfaceList
*info
;
1502 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1503 GuestIpAddressList
*address_item
= NULL
;
1504 unsigned char *mac_addr
;
1510 adptr_addrs
= guest_get_adapters_addresses(errp
);
1511 if (adptr_addrs
== NULL
) {
1515 /* Make WSA APIs available. */
1516 wsa_version
= MAKEWORD(2, 2);
1517 ret
= WSAStartup(wsa_version
, &wsa_data
);
1519 error_setg_win32(errp
, ret
, "failed socket startup");
1523 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1524 info
= g_malloc0(sizeof(*info
));
1526 if (cur_item
== NULL
) {
1527 head
= cur_item
= info
;
1529 cur_item
->next
= info
;
1533 info
->value
= g_malloc0(sizeof(*info
->value
));
1534 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1536 if (addr
->PhysicalAddressLength
!= 0) {
1537 mac_addr
= addr
->PhysicalAddress
;
1539 info
->value
->hardware_address
=
1540 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1541 (int) mac_addr
[0], (int) mac_addr
[1],
1542 (int) mac_addr
[2], (int) mac_addr
[3],
1543 (int) mac_addr
[4], (int) mac_addr
[5]);
1545 info
->value
->has_hardware_address
= true;
1550 for (ip_addr
= addr
->FirstUnicastAddress
;
1552 ip_addr
= ip_addr
->Next
) {
1553 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1554 if (addr_str
== NULL
) {
1558 address_item
= g_malloc0(sizeof(*address_item
));
1561 head_addr
= cur_addr
= address_item
;
1563 cur_addr
->next
= address_item
;
1564 cur_addr
= address_item
;
1567 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1568 address_item
->value
->ip_address
= addr_str
;
1569 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1570 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1571 address_item
->value
->ip_address_type
=
1572 GUEST_IP_ADDRESS_TYPE_IPV4
;
1573 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1574 address_item
->value
->ip_address_type
=
1575 GUEST_IP_ADDRESS_TYPE_IPV6
;
1579 info
->value
->has_ip_addresses
= true;
1580 info
->value
->ip_addresses
= head_addr
;
1582 if (!info
->value
->has_statistics
) {
1583 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1584 if (guest_get_network_stats(addr
->AdapterName
,
1585 interface_stat
) == -1) {
1586 info
->value
->has_statistics
= false;
1587 g_free(interface_stat
);
1589 info
->value
->statistics
= interface_stat
;
1590 info
->value
->has_statistics
= true;
1596 g_free(adptr_addrs
);
1600 int64_t qmp_guest_get_time(Error
**errp
)
1602 SYSTEMTIME ts
= {0};
1606 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1607 error_setg(errp
, "Failed to get time");
1611 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1612 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1616 return ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1617 - W32_FT_OFFSET
) * 100;
1620 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1622 Error
*local_err
= NULL
;
1628 /* Unfortunately, Windows libraries don't provide an easy way to access
1631 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1633 * Instead, a workaround is to use the Windows win32tm command to
1634 * resync the time using the Windows Time service.
1639 HRESULT hr
= system("w32tm /resync /nowait");
1641 if (GetLastError() != 0) {
1642 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1643 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1644 } else if (hr
!= 0) {
1645 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1646 error_setg(errp
, "Windows Time service not running on the "
1649 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1650 FORMAT_MESSAGE_FROM_SYSTEM
|
1651 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1652 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1653 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1655 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1656 "t retrieve error message", hr
);
1658 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1659 (LPCTSTR
)msg_buffer
);
1660 LocalFree(msg_buffer
);
1663 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1664 error_setg(errp
, "No internet connection on guest, sync not "
1670 /* Validate time passed by user. */
1671 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1672 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1676 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1678 tf
.dwLowDateTime
= (DWORD
) time
;
1679 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1681 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1682 error_setg(errp
, "Failed to convert system time %d",
1683 (int)GetLastError());
1687 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1689 error_propagate(errp
, local_err
);
1693 if (!SetSystemTime(&ts
)) {
1694 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1699 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1701 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1703 GuestLogicalProcessorList
*head
, **link
;
1704 Error
*local_err
= NULL
;
1713 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1714 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1715 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1716 ptr
= pslpi
= g_malloc0(length
);
1717 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1718 error_setg(&local_err
, "Failed to get processor information: %d",
1719 (int)GetLastError());
1722 error_setg(&local_err
,
1723 "Failed to get processor information buffer length: %d",
1724 (int)GetLastError());
1727 while ((local_err
== NULL
) && (length
> 0)) {
1728 if (pslpi
->Relationship
== RelationProcessorCore
) {
1729 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1731 while (cpu_bits
> 0) {
1732 if (!!(cpu_bits
& 1)) {
1733 GuestLogicalProcessor
*vcpu
;
1734 GuestLogicalProcessorList
*entry
;
1736 vcpu
= g_malloc0(sizeof *vcpu
);
1737 vcpu
->logical_id
= current
++;
1738 vcpu
->online
= true;
1739 vcpu
->has_can_offline
= true;
1741 entry
= g_malloc0(sizeof *entry
);
1742 entry
->value
= vcpu
;
1745 link
= &entry
->next
;
1750 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1751 pslpi
++; /* next entry */
1756 if (local_err
== NULL
) {
1760 /* there's no guest with zero VCPUs */
1761 error_setg(&local_err
, "Guest reported zero VCPUs");
1764 qapi_free_GuestLogicalProcessorList(head
);
1765 error_propagate(errp
, local_err
);
1769 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1771 error_setg(errp
, QERR_UNSUPPORTED
);
1776 get_net_error_message(gint error
)
1778 HMODULE module
= NULL
;
1779 gchar
*retval
= NULL
;
1780 wchar_t *msg
= NULL
;
1784 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1785 FORMAT_MESSAGE_IGNORE_INSERTS
|
1786 FORMAT_MESSAGE_FROM_SYSTEM
;
1788 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1789 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1791 if (module
!= NULL
) {
1792 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1796 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1799 nchars
= wcslen(msg
);
1802 msg
[nchars
- 1] == L
'\n' &&
1803 msg
[nchars
- 2] == L
'\r') {
1804 msg
[nchars
- 2] = L
'\0';
1807 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1812 if (module
!= NULL
) {
1813 FreeLibrary(module
);
1819 void qmp_guest_set_user_password(const char *username
,
1820 const char *password
,
1825 char *rawpasswddata
= NULL
;
1826 size_t rawpasswdlen
;
1827 wchar_t *user
= NULL
, *wpass
= NULL
;
1828 USER_INFO_1003 pi1003
= { 0, };
1829 GError
*gerr
= NULL
;
1832 error_setg(errp
, QERR_UNSUPPORTED
);
1836 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1837 if (!rawpasswddata
) {
1840 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1841 rawpasswddata
[rawpasswdlen
] = '\0';
1843 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1848 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1853 pi1003
.usri1003_password
= wpass
;
1854 nas
= NetUserSetInfo(NULL
, user
,
1855 1003, (LPBYTE
)&pi1003
,
1858 if (nas
!= NERR_Success
) {
1859 gchar
*msg
= get_net_error_message(nas
);
1860 error_setg(errp
, "failed to set password: %s", msg
);
1866 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1871 g_free(rawpasswddata
);
1874 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1876 error_setg(errp
, QERR_UNSUPPORTED
);
1880 GuestMemoryBlockResponseList
*
1881 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1883 error_setg(errp
, QERR_UNSUPPORTED
);
1887 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1889 error_setg(errp
, QERR_UNSUPPORTED
);
1893 /* add unsupported commands to the blacklist */
1894 GList
*ga_command_blacklist_init(GList
*blacklist
)
1896 const char *list_unsupported
[] = {
1897 "guest-suspend-hybrid",
1899 "guest-get-memory-blocks", "guest-set-memory-blocks",
1900 "guest-get-memory-block-size", "guest-get-memory-block-info",
1902 char **p
= (char **)list_unsupported
;
1905 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1908 if (!vss_init(true)) {
1909 g_debug("vss_init failed, vss commands are going to be disabled");
1910 const char *list
[] = {
1911 "guest-get-fsinfo", "guest-fsfreeze-status",
1912 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1916 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1923 /* register init/cleanup routines for stateful command groups */
1924 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1926 if (!vss_initialized()) {
1927 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1931 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1932 typedef struct _GA_WTSINFOA
{
1933 WTS_CONNECTSTATE_CLASS State
;
1935 DWORD IncomingBytes
;
1936 DWORD OutgoingBytes
;
1937 DWORD IncomingFrames
;
1938 DWORD OutgoingFrames
;
1939 DWORD IncomingCompressedBytes
;
1940 DWORD OutgoingCompressedBy
;
1941 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
1942 CHAR Domain
[DOMAIN_LENGTH
];
1943 CHAR UserName
[USERNAME_LENGTH
+ 1];
1944 LARGE_INTEGER ConnectTime
;
1945 LARGE_INTEGER DisconnectTime
;
1946 LARGE_INTEGER LastInputTime
;
1947 LARGE_INTEGER LogonTime
;
1948 LARGE_INTEGER CurrentTime
;
1952 GuestUserList
*qmp_guest_get_users(Error
**errp
)
1954 #define QGA_NANOSECONDS 10000000
1956 GHashTable
*cache
= NULL
;
1957 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
1959 DWORD buffer_size
= 0, count
= 0, i
= 0;
1960 GA_WTSINFOA
*info
= NULL
;
1961 WTS_SESSION_INFOA
*entries
= NULL
;
1962 GuestUserList
*item
= NULL
;
1963 GuestUser
*user
= NULL
;
1964 gpointer value
= NULL
;
1966 double login_time
= 0;
1968 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
1970 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
1971 for (i
= 0; i
< count
; ++i
) {
1974 if (WTSQuerySessionInformationA(
1976 entries
[i
].SessionId
,
1982 if (strlen(info
->UserName
) == 0) {
1983 WTSFreeMemory(info
);
1987 login
= info
->LogonTime
.QuadPart
;
1988 login
-= W32_FT_OFFSET
;
1989 login_time
= ((double)login
) / QGA_NANOSECONDS
;
1991 if (g_hash_table_contains(cache
, info
->UserName
)) {
1992 value
= g_hash_table_lookup(cache
, info
->UserName
);
1993 user
= (GuestUser
*)value
;
1994 if (user
->login_time
> login_time
) {
1995 user
->login_time
= login_time
;
1998 item
= g_new0(GuestUserList
, 1);
1999 item
->value
= g_new0(GuestUser
, 1);
2001 item
->value
->user
= g_strdup(info
->UserName
);
2002 item
->value
->domain
= g_strdup(info
->Domain
);
2003 item
->value
->has_domain
= true;
2005 item
->value
->login_time
= login_time
;
2007 g_hash_table_add(cache
, item
->value
->user
);
2010 head
= cur_item
= item
;
2012 cur_item
->next
= item
;
2017 WTSFreeMemory(info
);
2019 WTSFreeMemory(entries
);
2021 g_hash_table_destroy(cache
);
2025 typedef struct _ga_matrix_lookup_t
{
2028 char const *version
;
2029 char const *version_id
;
2030 } ga_matrix_lookup_t
;
2032 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][8] = {
2034 /* Desktop editions */
2035 { 5, 0, "Microsoft Windows 2000", "2000"},
2036 { 5, 1, "Microsoft Windows XP", "xp"},
2037 { 6, 0, "Microsoft Windows Vista", "vista"},
2038 { 6, 1, "Microsoft Windows 7" "7"},
2039 { 6, 2, "Microsoft Windows 8", "8"},
2040 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2041 {10, 0, "Microsoft Windows 10", "10"},
2044 /* Server editions */
2045 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2046 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2047 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2048 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2049 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2056 typedef struct _ga_win_10_0_server_t
{
2058 char const *version
;
2059 char const *version_id
;
2060 } ga_win_10_0_server_t
;
2062 static ga_win_10_0_server_t
const WIN_10_0_SERVER_VERSION_MATRIX
[3] = {
2063 {14393, "Microsoft Windows Server 2016", "2016"},
2064 {17763, "Microsoft Windows Server 2019", "2019"},
2068 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
2070 typedef NTSTATUS(WINAPI
* rtl_get_version_t
)(
2071 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
2073 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
2075 HMODULE module
= GetModuleHandle("ntdll");
2076 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
2078 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
2079 "Failed to get address of RtlGetVersion");
2083 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
2084 rtl_get_version(info
);
2088 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
2090 DWORD major
= os_version
->dwMajorVersion
;
2091 DWORD minor
= os_version
->dwMinorVersion
;
2092 DWORD build
= os_version
->dwBuildNumber
;
2093 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
2094 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
2095 ga_win_10_0_server_t
const *win_10_0_table
= WIN_10_0_SERVER_VERSION_MATRIX
;
2096 while (table
->version
!= NULL
) {
2097 if (major
== 10 && minor
== 0 && tbl_idx
) {
2098 while (win_10_0_table
->version
!= NULL
) {
2099 if (build
<= win_10_0_table
->final_build
) {
2101 return g_strdup(win_10_0_table
->version_id
);
2103 return g_strdup(win_10_0_table
->version
);
2108 } else if (major
== table
->major
&& minor
== table
->minor
) {
2110 return g_strdup(table
->version_id
);
2112 return g_strdup(table
->version
);
2117 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2119 return g_strdup("N/A");
2122 static char *ga_get_win_product_name(Error
**errp
)
2126 char *result
= g_malloc0(size
);
2127 LONG err
= ERROR_SUCCESS
;
2129 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
2130 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2132 if (err
!= ERROR_SUCCESS
) {
2133 error_setg_win32(errp
, err
, "failed to open registry key");
2137 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2138 (LPBYTE
)result
, &size
);
2139 if (err
== ERROR_MORE_DATA
) {
2140 slog("ProductName longer than expected (%lu bytes), retrying",
2145 result
= g_malloc0(size
);
2146 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
2147 (LPBYTE
)result
, &size
);
2150 if (err
!= ERROR_SUCCESS
) {
2151 error_setg_win32(errp
, err
, "failed to retrive ProductName");
2162 static char *ga_get_current_arch(void)
2165 GetNativeSystemInfo(&info
);
2166 char *result
= NULL
;
2167 switch (info
.wProcessorArchitecture
) {
2168 case PROCESSOR_ARCHITECTURE_AMD64
:
2169 result
= g_strdup("x86_64");
2171 case PROCESSOR_ARCHITECTURE_ARM
:
2172 result
= g_strdup("arm");
2174 case PROCESSOR_ARCHITECTURE_IA64
:
2175 result
= g_strdup("ia64");
2177 case PROCESSOR_ARCHITECTURE_INTEL
:
2178 result
= g_strdup("x86");
2180 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
2182 slog("unknown processor architecture 0x%0x",
2183 info
.wProcessorArchitecture
);
2184 result
= g_strdup("unknown");
2190 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2192 Error
*local_err
= NULL
;
2193 OSVERSIONINFOEXW os_version
= {0};
2198 ga_get_win_version(&os_version
, &local_err
);
2200 error_propagate(errp
, local_err
);
2204 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
2205 product_name
= ga_get_win_product_name(&local_err
);
2206 if (product_name
== NULL
) {
2207 error_propagate(errp
, local_err
);
2211 info
= g_new0(GuestOSInfo
, 1);
2213 info
->has_kernel_version
= true;
2214 info
->kernel_version
= g_strdup_printf("%lu.%lu",
2215 os_version
.dwMajorVersion
,
2216 os_version
.dwMinorVersion
);
2217 info
->has_kernel_release
= true;
2218 info
->kernel_release
= g_strdup_printf("%lu",
2219 os_version
.dwBuildNumber
);
2220 info
->has_machine
= true;
2221 info
->machine
= ga_get_current_arch();
2223 info
->has_id
= true;
2224 info
->id
= g_strdup("mswindows");
2225 info
->has_name
= true;
2226 info
->name
= g_strdup("Microsoft Windows");
2227 info
->has_pretty_name
= true;
2228 info
->pretty_name
= product_name
;
2229 info
->has_version
= true;
2230 info
->version
= ga_get_win_name(&os_version
, false);
2231 info
->has_version_id
= true;
2232 info
->version_id
= ga_get_win_name(&os_version
, true);
2233 info
->has_variant
= true;
2234 info
->variant
= g_strdup(server
? "server" : "client");
2235 info
->has_variant_id
= true;
2236 info
->variant_id
= g_strdup(server
? "server" : "client");