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.
23 #ifdef CONFIG_QGA_NTDDSCSI
31 #include "qga/guest-agent-core.h"
32 #include "qga/vss-win32.h"
33 #include "qga-qmp-commands.h"
34 #include "qapi/qmp/qerror.h"
35 #include "qemu/queue.h"
36 #include "qemu/host-utils.h"
38 #ifndef SHTDN_REASON_FLAG_PLANNED
39 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
42 /* multiple of 100 nanoseconds elapsed between windows baseline
43 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
44 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
45 (365 * (1970 - 1601) + \
46 (1970 - 1601) / 4 - 3))
48 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
50 typedef struct GuestFileHandle
{
53 QTAILQ_ENTRY(GuestFileHandle
) next
;
57 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
61 typedef struct OpenFlags
{
64 DWORD creation_disposition
;
66 static OpenFlags guest_file_open_modes
[] = {
67 {"r", GENERIC_READ
, OPEN_EXISTING
},
68 {"rb", GENERIC_READ
, OPEN_EXISTING
},
69 {"w", GENERIC_WRITE
, CREATE_ALWAYS
},
70 {"wb", GENERIC_WRITE
, CREATE_ALWAYS
},
71 {"a", GENERIC_WRITE
, OPEN_ALWAYS
},
72 {"r+", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
73 {"rb+", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
74 {"r+b", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
75 {"w+", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
76 {"wb+", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
77 {"w+b", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
78 {"a+", GENERIC_WRITE
|GENERIC_READ
, OPEN_ALWAYS
},
79 {"ab+", GENERIC_WRITE
|GENERIC_READ
, OPEN_ALWAYS
},
80 {"a+b", GENERIC_WRITE
|GENERIC_READ
, OPEN_ALWAYS
}
83 static OpenFlags
*find_open_flag(const char *mode_str
)
88 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
89 OpenFlags
*flags
= guest_file_open_modes
+ mode
;
91 if (strcmp(flags
->forms
, mode_str
) == 0) {
96 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
100 static int64_t guest_file_handle_add(HANDLE fh
, Error
**errp
)
102 GuestFileHandle
*gfh
;
105 handle
= ga_get_fd_handle(ga_state
, errp
);
109 gfh
= g_malloc0(sizeof(GuestFileHandle
));
112 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
117 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
119 GuestFileHandle
*gfh
;
120 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
) {
125 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
129 int64_t qmp_guest_file_open(const char *path
, bool has_mode
,
130 const char *mode
, Error
**errp
)
134 HANDLE templ_file
= NULL
;
135 DWORD share_mode
= FILE_SHARE_READ
;
136 DWORD flags_and_attr
= FILE_ATTRIBUTE_NORMAL
;
137 LPSECURITY_ATTRIBUTES sa_attr
= NULL
;
138 OpenFlags
*guest_flags
;
143 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
144 guest_flags
= find_open_flag(mode
);
145 if (guest_flags
== NULL
) {
146 error_setg(errp
, "invalid file open mode");
150 fh
= CreateFile(path
, guest_flags
->desired_access
, share_mode
, sa_attr
,
151 guest_flags
->creation_disposition
, flags_and_attr
,
153 if (fh
== INVALID_HANDLE_VALUE
) {
154 error_setg_win32(errp
, GetLastError(), "failed to open file '%s'",
159 fd
= guest_file_handle_add(fh
, errp
);
162 error_setg(errp
, "failed to add handle to qmp handle table");
166 slog("guest-file-open, handle: % " PRId64
, fd
);
170 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
173 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
174 slog("guest-file-close called, handle: %" PRId64
, handle
);
178 ret
= CloseHandle(gfh
->fh
);
180 error_setg_win32(errp
, GetLastError(), "failed close handle");
184 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
188 static void acquire_privilege(const char *name
, Error
**errp
)
191 TOKEN_PRIVILEGES priv
;
192 Error
*local_err
= NULL
;
194 if (OpenProcessToken(GetCurrentProcess(),
195 TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY
, &token
))
197 if (!LookupPrivilegeValue(NULL
, name
, &priv
.Privileges
[0].Luid
)) {
198 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
199 "no luid for requested privilege");
203 priv
.PrivilegeCount
= 1;
204 priv
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
206 if (!AdjustTokenPrivileges(token
, FALSE
, &priv
, 0, NULL
, 0)) {
207 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
208 "unable to acquire requested privilege");
213 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
214 "failed to open privilege token");
222 error_propagate(errp
, local_err
);
226 static void execute_async(DWORD
WINAPI (*func
)(LPVOID
), LPVOID opaque
,
229 Error
*local_err
= NULL
;
231 HANDLE thread
= CreateThread(NULL
, 0, func
, opaque
, 0, NULL
);
233 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
234 "failed to dispatch asynchronous command");
235 error_propagate(errp
, local_err
);
239 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
241 Error
*local_err
= NULL
;
242 UINT shutdown_flag
= EWX_FORCE
;
244 slog("guest-shutdown called, mode: %s", mode
);
246 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
247 shutdown_flag
|= EWX_POWEROFF
;
248 } else if (strcmp(mode
, "halt") == 0) {
249 shutdown_flag
|= EWX_SHUTDOWN
;
250 } else if (strcmp(mode
, "reboot") == 0) {
251 shutdown_flag
|= EWX_REBOOT
;
253 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "mode",
254 "halt|powerdown|reboot");
258 /* Request a shutdown privilege, but try to shut down the system
260 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
262 error_propagate(errp
, local_err
);
266 if (!ExitWindowsEx(shutdown_flag
, SHTDN_REASON_FLAG_PLANNED
)) {
267 slog("guest-shutdown failed: %lu", GetLastError());
268 error_setg(errp
, QERR_UNDEFINED_ERROR
);
272 GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
273 int64_t count
, Error
**errp
)
275 GuestFileRead
*read_data
= NULL
;
280 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
286 count
= QGA_READ_COUNT_DEFAULT
;
287 } else if (count
< 0) {
288 error_setg(errp
, "value '%" PRId64
289 "' is invalid for argument count", count
);
294 buf
= g_malloc0(count
+1);
295 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
297 error_setg_win32(errp
, GetLastError(), "failed to read file");
298 slog("guest-file-read failed, handle %" PRId64
, handle
);
301 read_data
= g_malloc0(sizeof(GuestFileRead
));
302 read_data
->count
= (size_t)read_count
;
303 read_data
->eof
= read_count
== 0;
305 if (read_count
!= 0) {
306 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
314 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
315 bool has_count
, int64_t count
,
318 GuestFileWrite
*write_data
= NULL
;
323 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
330 buf
= g_base64_decode(buf_b64
, &buf_len
);
334 } else if (count
< 0 || count
> buf_len
) {
335 error_setg(errp
, "value '%" PRId64
336 "' is invalid for argument count", count
);
340 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
342 error_setg_win32(errp
, GetLastError(), "failed to write to file");
343 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
345 write_data
= g_malloc0(sizeof(GuestFileWrite
));
346 write_data
->count
= (size_t) write_count
;
354 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
355 int64_t whence
, Error
**errp
)
357 GuestFileHandle
*gfh
;
358 GuestFileSeek
*seek_data
;
360 LARGE_INTEGER new_pos
, off_pos
;
361 off_pos
.QuadPart
= offset
;
363 gfh
= guest_file_handle_find(handle
, errp
);
369 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
371 error_setg_win32(errp
, GetLastError(), "failed to seek file");
374 seek_data
= g_new0(GuestFileSeek
, 1);
375 seek_data
->position
= new_pos
.QuadPart
;
379 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
382 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
388 if (!FlushFileBuffers(fh
)) {
389 error_setg_win32(errp
, GetLastError(), "failed to flush file");
393 static void guest_file_init(void)
395 QTAILQ_INIT(&guest_file_state
.filehandles
);
398 #ifdef CONFIG_QGA_NTDDSCSI
400 static STORAGE_BUS_TYPE win2qemu
[] = {
401 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
402 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
403 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
404 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
405 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
406 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
407 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
408 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
409 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
410 #if (_WIN32_WINNT >= 0x0600)
411 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
412 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
413 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
414 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
415 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
417 #if (_WIN32_WINNT >= 0x0601)
418 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
419 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
423 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
425 if (bus
> ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
426 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
428 return win2qemu
[(int)bus
];
431 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME
,
432 0x53f5630dL
, 0xb6bf, 0x11d0, 0x94, 0xf2,
433 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
435 static GuestPCIAddress
*get_pci_info(char *guid
, Error
**errp
)
438 SP_DEVINFO_DATA dev_info_data
;
441 char dev_name
[MAX_PATH
];
443 GuestPCIAddress
*pci
= NULL
;
444 char *name
= g_strdup(&guid
[4]);
446 if (!QueryDosDevice(name
, dev_name
, ARRAY_SIZE(dev_name
))) {
447 error_setg_win32(errp
, GetLastError(), "failed to get dos device name");
451 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME
, 0, 0,
452 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
453 if (dev_info
== INVALID_HANDLE_VALUE
) {
454 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
458 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
459 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
460 DWORD addr
, bus
, slot
, func
, dev
, data
, size2
;
461 while (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
462 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME
,
463 &data
, (PBYTE
)buffer
, size
,
465 size
= MAX(size
, size2
);
466 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
468 /* Double the size to avoid problems on
469 * W2k MBCS systems per KB 888609.
470 * https://support.microsoft.com/en-us/kb/259695 */
471 buffer
= g_malloc(size
* 2);
473 error_setg_win32(errp
, GetLastError(),
474 "failed to get device name");
479 if (g_strcmp0(buffer
, dev_name
)) {
483 /* There is no need to allocate buffer in the next functions. The size
484 * is known and ULONG according to
485 * https://support.microsoft.com/en-us/kb/253232
486 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
488 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
489 SPDRP_BUSNUMBER
, &data
, (PBYTE
)&bus
, size
, NULL
)) {
493 /* The function retrieves the device's address. This value will be
494 * transformed into device function and number */
495 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
496 SPDRP_ADDRESS
, &data
, (PBYTE
)&addr
, size
, NULL
)) {
500 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
501 * This number is typically a user-perceived slot number. */
502 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
503 SPDRP_UI_NUMBER
, &data
, (PBYTE
)&slot
, size
, NULL
)) {
507 /* SetupApi gives us the same information as driver with
508 * IoGetDeviceProperty. According to Microsoft
509 * https://support.microsoft.com/en-us/kb/253232
510 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
511 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
512 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
514 func
= addr
& 0x0000FFFF;
515 dev
= (addr
>> 16) & 0x0000FFFF;
516 pci
= g_malloc0(sizeof(*pci
));
519 pci
->function
= func
;
529 static int get_disk_bus_type(HANDLE vol_h
, Error
**errp
)
531 STORAGE_PROPERTY_QUERY query
;
532 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
536 dev_desc
->Size
= sizeof(buf
);
537 query
.PropertyId
= StorageDeviceProperty
;
538 query
.QueryType
= PropertyStandardQuery
;
540 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
541 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
542 dev_desc
->Size
, &received
, NULL
)) {
543 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
547 return dev_desc
->BusType
;
550 /* VSS provider works with volumes, thus there is no difference if
551 * the volume consist of spanned disks. Info about the first disk in the
552 * volume is returned for the spanned disk group (LVM) */
553 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
555 GuestDiskAddressList
*list
= NULL
;
556 GuestDiskAddress
*disk
;
557 SCSI_ADDRESS addr
, *scsi_ad
;
563 char *name
= g_strndup(guid
, strlen(guid
)-1);
565 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
567 if (vol_h
== INVALID_HANDLE_VALUE
) {
568 error_setg_win32(errp
, GetLastError(), "failed to open volume");
572 bus
= get_disk_bus_type(vol_h
, errp
);
577 disk
= g_malloc0(sizeof(*disk
));
578 disk
->bus_type
= find_bus_type(bus
);
579 if (bus
== BusTypeScsi
|| bus
== BusTypeAta
|| bus
== BusTypeRAID
580 #if (_WIN32_WINNT >= 0x0600)
581 /* This bus type is not supported before Windows Server 2003 SP1 */
585 /* We are able to use the same ioctls for different bus types
586 * according to Microsoft docs
587 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
588 if (DeviceIoControl(vol_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
589 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
590 disk
->unit
= addr
.Lun
;
591 disk
->target
= addr
.TargetId
;
592 disk
->bus
= addr
.PathId
;
593 disk
->pci_controller
= get_pci_info(name
, errp
);
595 /* We do not set error in this case, because we still have enough
596 * information about volume. */
598 disk
->pci_controller
= NULL
;
601 list
= g_malloc0(sizeof(*list
));
613 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
618 #endif /* CONFIG_QGA_NTDDSCSI */
620 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
623 char mnt
, *mnt_point
;
625 char vol_info
[MAX_PATH
+1];
627 GuestFilesystemInfo
*fs
= NULL
;
629 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
630 if (GetLastError() != ERROR_MORE_DATA
) {
631 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
635 mnt_point
= g_malloc(info_size
+ 1);
636 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
638 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
642 len
= strlen(mnt_point
);
643 mnt_point
[len
] = '\\';
644 mnt_point
[len
+1] = 0;
645 if (!GetVolumeInformation(mnt_point
, vol_info
, sizeof(vol_info
), NULL
, NULL
,
646 NULL
, (LPSTR
)&fs_name
, sizeof(fs_name
))) {
647 if (GetLastError() != ERROR_NOT_READY
) {
648 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
653 fs_name
[sizeof(fs_name
) - 1] = 0;
654 fs
= g_malloc(sizeof(*fs
));
655 fs
->name
= g_strdup(guid
);
657 fs
->mountpoint
= g_strdup("System Reserved");
659 fs
->mountpoint
= g_strndup(mnt_point
, len
);
661 fs
->type
= g_strdup(fs_name
);
662 fs
->disk
= build_guest_disk_info(guid
, errp
);
668 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
671 GuestFilesystemInfoList
*new, *ret
= NULL
;
674 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
675 if (vol_h
== INVALID_HANDLE_VALUE
) {
676 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
681 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, errp
);
685 new = g_malloc(sizeof(*ret
));
689 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
691 if (GetLastError() != ERROR_NO_MORE_FILES
) {
692 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
695 FindVolumeClose(vol_h
);
700 * Return status of freeze/thaw
702 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
704 if (!vss_initialized()) {
705 error_setg(errp
, QERR_UNSUPPORTED
);
709 if (ga_is_frozen(ga_state
)) {
710 return GUEST_FSFREEZE_STATUS_FROZEN
;
713 return GUEST_FSFREEZE_STATUS_THAWED
;
717 * Freeze local file systems using Volume Shadow-copy Service.
718 * The frozen state is limited for up to 10 seconds by VSS.
720 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
723 Error
*local_err
= NULL
;
725 if (!vss_initialized()) {
726 error_setg(errp
, QERR_UNSUPPORTED
);
730 slog("guest-fsfreeze called");
732 /* cannot risk guest agent blocking itself on a write in this state */
733 ga_set_frozen(ga_state
);
735 qga_vss_fsfreeze(&i
, &local_err
, true);
737 error_propagate(errp
, local_err
);
745 qmp_guest_fsfreeze_thaw(&local_err
);
747 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
748 error_free(local_err
);
753 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
754 strList
*mountpoints
,
757 error_setg(errp
, QERR_UNSUPPORTED
);
763 * Thaw local file systems using Volume Shadow-copy Service.
765 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
769 if (!vss_initialized()) {
770 error_setg(errp
, QERR_UNSUPPORTED
);
774 qga_vss_fsfreeze(&i
, errp
, false);
776 ga_unset_frozen(ga_state
);
780 static void guest_fsfreeze_cleanup(void)
784 if (!vss_initialized()) {
788 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
789 qmp_guest_fsfreeze_thaw(&err
);
791 slog("failed to clean up frozen filesystems: %s",
792 error_get_pretty(err
));
801 * Walk list of mounted file systems in the guest, and discard unused
804 GuestFilesystemTrimResponse
*
805 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
807 error_setg(errp
, QERR_UNSUPPORTED
);
812 GUEST_SUSPEND_MODE_DISK
,
813 GUEST_SUSPEND_MODE_RAM
816 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
818 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
819 Error
*local_err
= NULL
;
821 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
822 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
823 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
824 "failed to determine guest suspend capabilities");
829 case GUEST_SUSPEND_MODE_DISK
:
830 if (!sys_pwr_caps
.SystemS4
) {
831 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
832 "suspend-to-disk not supported by OS");
835 case GUEST_SUSPEND_MODE_RAM
:
836 if (!sys_pwr_caps
.SystemS3
) {
837 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
838 "suspend-to-ram not supported by OS");
842 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "mode",
848 error_propagate(errp
, local_err
);
852 static DWORD WINAPI
do_suspend(LPVOID opaque
)
854 GuestSuspendMode
*mode
= opaque
;
857 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
858 slog("failed to suspend guest, %lu", GetLastError());
865 void qmp_guest_suspend_disk(Error
**errp
)
867 Error
*local_err
= NULL
;
868 GuestSuspendMode
*mode
= g_malloc(sizeof(GuestSuspendMode
));
870 *mode
= GUEST_SUSPEND_MODE_DISK
;
871 check_suspend_mode(*mode
, &local_err
);
872 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
873 execute_async(do_suspend
, mode
, &local_err
);
876 error_propagate(errp
, local_err
);
881 void qmp_guest_suspend_ram(Error
**errp
)
883 Error
*local_err
= NULL
;
884 GuestSuspendMode
*mode
= g_malloc(sizeof(GuestSuspendMode
));
886 *mode
= GUEST_SUSPEND_MODE_RAM
;
887 check_suspend_mode(*mode
, &local_err
);
888 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
889 execute_async(do_suspend
, mode
, &local_err
);
892 error_propagate(errp
, local_err
);
897 void qmp_guest_suspend_hybrid(Error
**errp
)
899 error_setg(errp
, QERR_UNSUPPORTED
);
902 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
904 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
905 ULONG adptr_addrs_len
= 0;
908 /* Call the first time to get the adptr_addrs_len. */
909 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
910 NULL
, adptr_addrs
, &adptr_addrs_len
);
912 adptr_addrs
= g_malloc(adptr_addrs_len
);
913 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
914 NULL
, adptr_addrs
, &adptr_addrs_len
);
915 if (ret
!= ERROR_SUCCESS
) {
916 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
923 static char *guest_wctomb_dup(WCHAR
*wstr
)
928 i
= wcslen(wstr
) + 1;
930 WideCharToMultiByte(CP_ACP
, WC_COMPOSITECHECK
,
931 wstr
, -1, str
, i
, NULL
, NULL
);
935 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
938 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
942 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
943 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
944 len
= sizeof(addr_str
);
945 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
946 ip_addr
->Address
.iSockaddrLength
,
951 error_setg_win32(errp
, WSAGetLastError(),
952 "failed address presentation form conversion");
955 return g_strdup(addr_str
);
960 #if (_WIN32_WINNT >= 0x0600)
961 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
963 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
964 * field to obtain the prefix.
966 return ip_addr
->OnLinkPrefixLength
;
969 /* When using the Windows XP and 2003 build environment, do the best we can to
970 * figure out the prefix.
972 static IP_ADAPTER_INFO
*guest_get_adapters_info(void)
974 IP_ADAPTER_INFO
*adptr_info
= NULL
;
975 ULONG adptr_info_len
= 0;
978 /* Call the first time to get the adptr_info_len. */
979 GetAdaptersInfo(adptr_info
, &adptr_info_len
);
981 adptr_info
= g_malloc(adptr_info_len
);
982 ret
= GetAdaptersInfo(adptr_info
, &adptr_info_len
);
983 if (ret
!= ERROR_SUCCESS
) {
990 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
992 int64_t prefix
= -1; /* Use for AF_INET6 and unknown/undetermined values. */
993 IP_ADAPTER_INFO
*adptr_info
, *info
;
997 if (ip_addr
->Address
.lpSockaddr
->sa_family
!= AF_INET
) {
1000 adptr_info
= guest_get_adapters_info();
1001 if (adptr_info
== NULL
) {
1005 /* Match up the passed in ip_addr with one found in adaptr_info.
1006 * The matching one in adptr_info will have the netmask.
1008 p
= &((struct sockaddr_in
*)ip_addr
->Address
.lpSockaddr
)->sin_addr
;
1009 for (info
= adptr_info
; info
; info
= info
->Next
) {
1010 for (ip
= &info
->IpAddressList
; ip
; ip
= ip
->Next
) {
1011 if (p
->S_un
.S_addr
== inet_addr(ip
->IpAddress
.String
)) {
1012 prefix
= ctpop32(inet_addr(ip
->IpMask
.String
));
1023 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1025 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1026 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1027 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1028 GuestIpAddressList
*head_addr
, *cur_addr
;
1029 GuestNetworkInterfaceList
*info
;
1030 GuestIpAddressList
*address_item
= NULL
;
1031 unsigned char *mac_addr
;
1037 adptr_addrs
= guest_get_adapters_addresses(errp
);
1038 if (adptr_addrs
== NULL
) {
1042 /* Make WSA APIs available. */
1043 wsa_version
= MAKEWORD(2, 2);
1044 ret
= WSAStartup(wsa_version
, &wsa_data
);
1046 error_setg_win32(errp
, ret
, "failed socket startup");
1050 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1051 info
= g_malloc0(sizeof(*info
));
1053 if (cur_item
== NULL
) {
1054 head
= cur_item
= info
;
1056 cur_item
->next
= info
;
1060 info
->value
= g_malloc0(sizeof(*info
->value
));
1061 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1063 if (addr
->PhysicalAddressLength
!= 0) {
1064 mac_addr
= addr
->PhysicalAddress
;
1066 info
->value
->hardware_address
=
1067 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1068 (int) mac_addr
[0], (int) mac_addr
[1],
1069 (int) mac_addr
[2], (int) mac_addr
[3],
1070 (int) mac_addr
[4], (int) mac_addr
[5]);
1072 info
->value
->has_hardware_address
= true;
1077 for (ip_addr
= addr
->FirstUnicastAddress
;
1079 ip_addr
= ip_addr
->Next
) {
1080 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1081 if (addr_str
== NULL
) {
1085 address_item
= g_malloc0(sizeof(*address_item
));
1088 head_addr
= cur_addr
= address_item
;
1090 cur_addr
->next
= address_item
;
1091 cur_addr
= address_item
;
1094 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1095 address_item
->value
->ip_address
= addr_str
;
1096 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1097 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1098 address_item
->value
->ip_address_type
=
1099 GUEST_IP_ADDRESS_TYPE_IPV4
;
1100 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1101 address_item
->value
->ip_address_type
=
1102 GUEST_IP_ADDRESS_TYPE_IPV6
;
1106 info
->value
->has_ip_addresses
= true;
1107 info
->value
->ip_addresses
= head_addr
;
1112 g_free(adptr_addrs
);
1116 int64_t qmp_guest_get_time(Error
**errp
)
1118 SYSTEMTIME ts
= {0};
1123 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1124 error_setg(errp
, "Failed to get time");
1128 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1129 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1133 time_ns
= ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1134 - W32_FT_OFFSET
) * 100;
1139 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1141 Error
*local_err
= NULL
;
1147 /* Unfortunately, Windows libraries don't provide an easy way to access
1150 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1152 error_setg(errp
, "Time argument is required on this platform");
1156 /* Validate time passed by user. */
1157 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1158 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1162 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1164 tf
.dwLowDateTime
= (DWORD
) time
;
1165 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1167 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1168 error_setg(errp
, "Failed to convert system time %d",
1169 (int)GetLastError());
1173 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1175 error_propagate(errp
, local_err
);
1179 if (!SetSystemTime(&ts
)) {
1180 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1185 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1187 error_setg(errp
, QERR_UNSUPPORTED
);
1191 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1193 error_setg(errp
, QERR_UNSUPPORTED
);
1198 get_net_error_message(gint error
)
1200 HMODULE module
= NULL
;
1201 gchar
*retval
= NULL
;
1202 wchar_t *msg
= NULL
;
1205 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
1206 |FORMAT_MESSAGE_IGNORE_INSERTS
1207 |FORMAT_MESSAGE_FROM_SYSTEM
;
1209 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1210 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1212 if (module
!= NULL
) {
1213 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1217 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1220 nchars
= wcslen(msg
);
1222 if (nchars
> 2 && msg
[nchars
-1] == '\n' && msg
[nchars
-2] == '\r') {
1223 msg
[nchars
-2] = '\0';
1226 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1231 if (module
!= NULL
) {
1232 FreeLibrary(module
);
1238 void qmp_guest_set_user_password(const char *username
,
1239 const char *password
,
1244 char *rawpasswddata
= NULL
;
1245 size_t rawpasswdlen
;
1246 wchar_t *user
, *wpass
;
1247 USER_INFO_1003 pi1003
= { 0, };
1250 error_setg(errp
, QERR_UNSUPPORTED
);
1254 rawpasswddata
= (char *)g_base64_decode(password
, &rawpasswdlen
);
1255 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1256 rawpasswddata
[rawpasswdlen
] = '\0';
1258 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, NULL
);
1259 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, NULL
);
1261 pi1003
.usri1003_password
= wpass
;
1262 nas
= NetUserSetInfo(NULL
, user
,
1263 1003, (LPBYTE
)&pi1003
,
1266 if (nas
!= NERR_Success
) {
1267 gchar
*msg
= get_net_error_message(nas
);
1268 error_setg(errp
, "failed to set password: %s", msg
);
1274 g_free(rawpasswddata
);
1277 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1279 error_setg(errp
, QERR_UNSUPPORTED
);
1283 GuestMemoryBlockResponseList
*
1284 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1286 error_setg(errp
, QERR_UNSUPPORTED
);
1290 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1292 error_setg(errp
, QERR_UNSUPPORTED
);
1296 /* add unsupported commands to the blacklist */
1297 GList
*ga_command_blacklist_init(GList
*blacklist
)
1299 const char *list_unsupported
[] = {
1300 "guest-suspend-hybrid",
1301 "guest-get-vcpus", "guest-set-vcpus",
1302 "guest-get-memory-blocks", "guest-set-memory-blocks",
1303 "guest-get-memory-block-size",
1304 "guest-fsfreeze-freeze-list",
1305 "guest-fstrim", NULL
};
1306 char **p
= (char **)list_unsupported
;
1309 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1312 if (!vss_init(true)) {
1313 g_debug("vss_init failed, vss commands are going to be disabled");
1314 const char *list
[] = {
1315 "guest-get-fsinfo", "guest-fsfreeze-status",
1316 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1320 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1327 /* register init/cleanup routines for stateful command groups */
1328 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1330 if (!vss_initialized()) {
1331 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1333 ga_command_state_add(cs
, guest_file_init
, NULL
);