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
;
58 } guest_file_state
= {
59 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
63 typedef struct OpenFlags
{
66 DWORD creation_disposition
;
68 static OpenFlags guest_file_open_modes
[] = {
69 {"r", GENERIC_READ
, OPEN_EXISTING
},
70 {"rb", GENERIC_READ
, OPEN_EXISTING
},
71 {"w", GENERIC_WRITE
, CREATE_ALWAYS
},
72 {"wb", GENERIC_WRITE
, CREATE_ALWAYS
},
73 {"a", GENERIC_WRITE
, OPEN_ALWAYS
},
74 {"r+", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
75 {"rb+", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
76 {"r+b", GENERIC_WRITE
|GENERIC_READ
, OPEN_EXISTING
},
77 {"w+", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
78 {"wb+", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
79 {"w+b", GENERIC_WRITE
|GENERIC_READ
, CREATE_ALWAYS
},
80 {"a+", GENERIC_WRITE
|GENERIC_READ
, OPEN_ALWAYS
},
81 {"ab+", GENERIC_WRITE
|GENERIC_READ
, OPEN_ALWAYS
},
82 {"a+b", GENERIC_WRITE
|GENERIC_READ
, OPEN_ALWAYS
}
85 static OpenFlags
*find_open_flag(const char *mode_str
)
90 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
91 OpenFlags
*flags
= guest_file_open_modes
+ mode
;
93 if (strcmp(flags
->forms
, mode_str
) == 0) {
98 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
102 static int64_t guest_file_handle_add(HANDLE fh
, Error
**errp
)
104 GuestFileHandle
*gfh
;
107 handle
= ga_get_fd_handle(ga_state
, errp
);
111 gfh
= g_new0(GuestFileHandle
, 1);
114 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
119 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
121 GuestFileHandle
*gfh
;
122 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
) {
127 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
131 int64_t qmp_guest_file_open(const char *path
, bool has_mode
,
132 const char *mode
, Error
**errp
)
136 HANDLE templ_file
= NULL
;
137 DWORD share_mode
= FILE_SHARE_READ
;
138 DWORD flags_and_attr
= FILE_ATTRIBUTE_NORMAL
;
139 LPSECURITY_ATTRIBUTES sa_attr
= NULL
;
140 OpenFlags
*guest_flags
;
145 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
146 guest_flags
= find_open_flag(mode
);
147 if (guest_flags
== NULL
) {
148 error_setg(errp
, "invalid file open mode");
152 fh
= CreateFile(path
, guest_flags
->desired_access
, share_mode
, sa_attr
,
153 guest_flags
->creation_disposition
, flags_and_attr
,
155 if (fh
== INVALID_HANDLE_VALUE
) {
156 error_setg_win32(errp
, GetLastError(), "failed to open file '%s'",
161 fd
= guest_file_handle_add(fh
, errp
);
164 error_setg(errp
, "failed to add handle to qmp handle table");
168 slog("guest-file-open, handle: % " PRId64
, fd
);
172 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
175 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
176 slog("guest-file-close called, handle: %" PRId64
, handle
);
180 ret
= CloseHandle(gfh
->fh
);
182 error_setg_win32(errp
, GetLastError(), "failed close handle");
186 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
190 static void acquire_privilege(const char *name
, Error
**errp
)
193 TOKEN_PRIVILEGES priv
;
194 Error
*local_err
= NULL
;
196 if (OpenProcessToken(GetCurrentProcess(),
197 TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY
, &token
))
199 if (!LookupPrivilegeValue(NULL
, name
, &priv
.Privileges
[0].Luid
)) {
200 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
201 "no luid for requested privilege");
205 priv
.PrivilegeCount
= 1;
206 priv
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
208 if (!AdjustTokenPrivileges(token
, FALSE
, &priv
, 0, NULL
, 0)) {
209 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
210 "unable to acquire requested privilege");
215 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
216 "failed to open privilege token");
224 error_propagate(errp
, local_err
);
228 static void execute_async(DWORD
WINAPI (*func
)(LPVOID
), LPVOID opaque
,
231 Error
*local_err
= NULL
;
233 HANDLE thread
= CreateThread(NULL
, 0, func
, opaque
, 0, NULL
);
235 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
236 "failed to dispatch asynchronous command");
237 error_propagate(errp
, local_err
);
241 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
243 Error
*local_err
= NULL
;
244 UINT shutdown_flag
= EWX_FORCE
;
246 slog("guest-shutdown called, mode: %s", mode
);
248 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
249 shutdown_flag
|= EWX_POWEROFF
;
250 } else if (strcmp(mode
, "halt") == 0) {
251 shutdown_flag
|= EWX_SHUTDOWN
;
252 } else if (strcmp(mode
, "reboot") == 0) {
253 shutdown_flag
|= EWX_REBOOT
;
255 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "mode",
256 "halt|powerdown|reboot");
260 /* Request a shutdown privilege, but try to shut down the system
262 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
264 error_propagate(errp
, local_err
);
268 if (!ExitWindowsEx(shutdown_flag
, SHTDN_REASON_FLAG_PLANNED
)) {
269 slog("guest-shutdown failed: %lu", GetLastError());
270 error_setg(errp
, QERR_UNDEFINED_ERROR
);
274 GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
275 int64_t count
, Error
**errp
)
277 GuestFileRead
*read_data
= NULL
;
282 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
288 count
= QGA_READ_COUNT_DEFAULT
;
289 } else if (count
< 0) {
290 error_setg(errp
, "value '%" PRId64
291 "' is invalid for argument count", count
);
296 buf
= g_malloc0(count
+1);
297 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
299 error_setg_win32(errp
, GetLastError(), "failed to read file");
300 slog("guest-file-read failed, handle %" PRId64
, handle
);
303 read_data
= g_new0(GuestFileRead
, 1);
304 read_data
->count
= (size_t)read_count
;
305 read_data
->eof
= read_count
== 0;
307 if (read_count
!= 0) {
308 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
316 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
317 bool has_count
, int64_t count
,
320 GuestFileWrite
*write_data
= NULL
;
325 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
332 buf
= g_base64_decode(buf_b64
, &buf_len
);
336 } else if (count
< 0 || count
> buf_len
) {
337 error_setg(errp
, "value '%" PRId64
338 "' is invalid for argument count", count
);
342 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
344 error_setg_win32(errp
, GetLastError(), "failed to write to file");
345 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
347 write_data
= g_new0(GuestFileWrite
, 1);
348 write_data
->count
= (size_t) write_count
;
356 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
357 int64_t whence
, Error
**errp
)
359 GuestFileHandle
*gfh
;
360 GuestFileSeek
*seek_data
;
362 LARGE_INTEGER new_pos
, off_pos
;
363 off_pos
.QuadPart
= offset
;
365 gfh
= guest_file_handle_find(handle
, errp
);
371 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
373 error_setg_win32(errp
, GetLastError(), "failed to seek file");
376 seek_data
= g_new0(GuestFileSeek
, 1);
377 seek_data
->position
= new_pos
.QuadPart
;
381 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
384 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
390 if (!FlushFileBuffers(fh
)) {
391 error_setg_win32(errp
, GetLastError(), "failed to flush file");
395 #ifdef CONFIG_QGA_NTDDSCSI
397 static STORAGE_BUS_TYPE win2qemu
[] = {
398 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
399 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
400 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
401 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
402 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
403 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
404 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
405 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
406 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
407 #if (_WIN32_WINNT >= 0x0600)
408 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
409 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
410 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
411 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
412 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
414 #if (_WIN32_WINNT >= 0x0601)
415 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
416 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
420 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
422 if (bus
> ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
423 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
425 return win2qemu
[(int)bus
];
428 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME
,
429 0x53f5630dL
, 0xb6bf, 0x11d0, 0x94, 0xf2,
430 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
432 static GuestPCIAddress
*get_pci_info(char *guid
, Error
**errp
)
435 SP_DEVINFO_DATA dev_info_data
;
438 char dev_name
[MAX_PATH
];
440 GuestPCIAddress
*pci
= NULL
;
441 char *name
= g_strdup(&guid
[4]);
443 if (!QueryDosDevice(name
, dev_name
, ARRAY_SIZE(dev_name
))) {
444 error_setg_win32(errp
, GetLastError(), "failed to get dos device name");
448 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME
, 0, 0,
449 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
450 if (dev_info
== INVALID_HANDLE_VALUE
) {
451 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
455 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
456 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
457 DWORD addr
, bus
, slot
, func
, dev
, data
, size2
;
458 while (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
459 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME
,
460 &data
, (PBYTE
)buffer
, size
,
462 size
= MAX(size
, size2
);
463 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
465 /* Double the size to avoid problems on
466 * W2k MBCS systems per KB 888609.
467 * https://support.microsoft.com/en-us/kb/259695 */
468 buffer
= g_malloc(size
* 2);
470 error_setg_win32(errp
, GetLastError(),
471 "failed to get device name");
476 if (g_strcmp0(buffer
, dev_name
)) {
480 /* There is no need to allocate buffer in the next functions. The size
481 * is known and ULONG according to
482 * https://support.microsoft.com/en-us/kb/253232
483 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
485 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
486 SPDRP_BUSNUMBER
, &data
, (PBYTE
)&bus
, size
, NULL
)) {
490 /* The function retrieves the device's address. This value will be
491 * transformed into device function and number */
492 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
493 SPDRP_ADDRESS
, &data
, (PBYTE
)&addr
, size
, NULL
)) {
497 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
498 * This number is typically a user-perceived slot number. */
499 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
500 SPDRP_UI_NUMBER
, &data
, (PBYTE
)&slot
, size
, NULL
)) {
504 /* SetupApi gives us the same information as driver with
505 * IoGetDeviceProperty. According to Microsoft
506 * https://support.microsoft.com/en-us/kb/253232
507 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
508 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
509 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
511 func
= addr
& 0x0000FFFF;
512 dev
= (addr
>> 16) & 0x0000FFFF;
513 pci
= g_malloc0(sizeof(*pci
));
516 pci
->function
= func
;
526 static int get_disk_bus_type(HANDLE vol_h
, Error
**errp
)
528 STORAGE_PROPERTY_QUERY query
;
529 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
533 dev_desc
->Size
= sizeof(buf
);
534 query
.PropertyId
= StorageDeviceProperty
;
535 query
.QueryType
= PropertyStandardQuery
;
537 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
538 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
539 dev_desc
->Size
, &received
, NULL
)) {
540 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
544 return dev_desc
->BusType
;
547 /* VSS provider works with volumes, thus there is no difference if
548 * the volume consist of spanned disks. Info about the first disk in the
549 * volume is returned for the spanned disk group (LVM) */
550 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
552 GuestDiskAddressList
*list
= NULL
;
553 GuestDiskAddress
*disk
;
554 SCSI_ADDRESS addr
, *scsi_ad
;
560 char *name
= g_strndup(guid
, strlen(guid
)-1);
562 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
564 if (vol_h
== INVALID_HANDLE_VALUE
) {
565 error_setg_win32(errp
, GetLastError(), "failed to open volume");
569 bus
= get_disk_bus_type(vol_h
, errp
);
574 disk
= g_malloc0(sizeof(*disk
));
575 disk
->bus_type
= find_bus_type(bus
);
576 if (bus
== BusTypeScsi
|| bus
== BusTypeAta
|| bus
== BusTypeRAID
577 #if (_WIN32_WINNT >= 0x0600)
578 /* This bus type is not supported before Windows Server 2003 SP1 */
582 /* We are able to use the same ioctls for different bus types
583 * according to Microsoft docs
584 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
585 if (DeviceIoControl(vol_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
586 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
587 disk
->unit
= addr
.Lun
;
588 disk
->target
= addr
.TargetId
;
589 disk
->bus
= addr
.PathId
;
590 disk
->pci_controller
= get_pci_info(name
, errp
);
592 /* We do not set error in this case, because we still have enough
593 * information about volume. */
595 disk
->pci_controller
= NULL
;
598 list
= g_malloc0(sizeof(*list
));
610 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
615 #endif /* CONFIG_QGA_NTDDSCSI */
617 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
620 char mnt
, *mnt_point
;
622 char vol_info
[MAX_PATH
+1];
624 GuestFilesystemInfo
*fs
= NULL
;
626 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
627 if (GetLastError() != ERROR_MORE_DATA
) {
628 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
632 mnt_point
= g_malloc(info_size
+ 1);
633 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
635 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
639 len
= strlen(mnt_point
);
640 mnt_point
[len
] = '\\';
641 mnt_point
[len
+1] = 0;
642 if (!GetVolumeInformation(mnt_point
, vol_info
, sizeof(vol_info
), NULL
, NULL
,
643 NULL
, (LPSTR
)&fs_name
, sizeof(fs_name
))) {
644 if (GetLastError() != ERROR_NOT_READY
) {
645 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
650 fs_name
[sizeof(fs_name
) - 1] = 0;
651 fs
= g_malloc(sizeof(*fs
));
652 fs
->name
= g_strdup(guid
);
654 fs
->mountpoint
= g_strdup("System Reserved");
656 fs
->mountpoint
= g_strndup(mnt_point
, len
);
658 fs
->type
= g_strdup(fs_name
);
659 fs
->disk
= build_guest_disk_info(guid
, errp
);
665 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
668 GuestFilesystemInfoList
*new, *ret
= NULL
;
671 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
672 if (vol_h
== INVALID_HANDLE_VALUE
) {
673 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
678 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, errp
);
682 new = g_malloc(sizeof(*ret
));
686 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
688 if (GetLastError() != ERROR_NO_MORE_FILES
) {
689 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
692 FindVolumeClose(vol_h
);
697 * Return status of freeze/thaw
699 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
701 if (!vss_initialized()) {
702 error_setg(errp
, QERR_UNSUPPORTED
);
706 if (ga_is_frozen(ga_state
)) {
707 return GUEST_FSFREEZE_STATUS_FROZEN
;
710 return GUEST_FSFREEZE_STATUS_THAWED
;
714 * Freeze local file systems using Volume Shadow-copy Service.
715 * The frozen state is limited for up to 10 seconds by VSS.
717 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
720 Error
*local_err
= NULL
;
722 if (!vss_initialized()) {
723 error_setg(errp
, QERR_UNSUPPORTED
);
727 slog("guest-fsfreeze called");
729 /* cannot risk guest agent blocking itself on a write in this state */
730 ga_set_frozen(ga_state
);
732 qga_vss_fsfreeze(&i
, &local_err
, true);
734 error_propagate(errp
, local_err
);
742 qmp_guest_fsfreeze_thaw(&local_err
);
744 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
745 error_free(local_err
);
750 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
751 strList
*mountpoints
,
754 error_setg(errp
, QERR_UNSUPPORTED
);
760 * Thaw local file systems using Volume Shadow-copy Service.
762 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
766 if (!vss_initialized()) {
767 error_setg(errp
, QERR_UNSUPPORTED
);
771 qga_vss_fsfreeze(&i
, errp
, false);
773 ga_unset_frozen(ga_state
);
777 static void guest_fsfreeze_cleanup(void)
781 if (!vss_initialized()) {
785 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
786 qmp_guest_fsfreeze_thaw(&err
);
788 slog("failed to clean up frozen filesystems: %s",
789 error_get_pretty(err
));
798 * Walk list of mounted file systems in the guest, and discard unused
801 GuestFilesystemTrimResponse
*
802 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
804 error_setg(errp
, QERR_UNSUPPORTED
);
809 GUEST_SUSPEND_MODE_DISK
,
810 GUEST_SUSPEND_MODE_RAM
813 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
815 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
816 Error
*local_err
= NULL
;
818 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
819 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
820 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
821 "failed to determine guest suspend capabilities");
826 case GUEST_SUSPEND_MODE_DISK
:
827 if (!sys_pwr_caps
.SystemS4
) {
828 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
829 "suspend-to-disk not supported by OS");
832 case GUEST_SUSPEND_MODE_RAM
:
833 if (!sys_pwr_caps
.SystemS3
) {
834 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
835 "suspend-to-ram not supported by OS");
839 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "mode",
845 error_propagate(errp
, local_err
);
849 static DWORD WINAPI
do_suspend(LPVOID opaque
)
851 GuestSuspendMode
*mode
= opaque
;
854 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
855 slog("failed to suspend guest, %lu", GetLastError());
862 void qmp_guest_suspend_disk(Error
**errp
)
864 Error
*local_err
= NULL
;
865 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
867 *mode
= GUEST_SUSPEND_MODE_DISK
;
868 check_suspend_mode(*mode
, &local_err
);
869 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
870 execute_async(do_suspend
, mode
, &local_err
);
873 error_propagate(errp
, local_err
);
878 void qmp_guest_suspend_ram(Error
**errp
)
880 Error
*local_err
= NULL
;
881 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
883 *mode
= GUEST_SUSPEND_MODE_RAM
;
884 check_suspend_mode(*mode
, &local_err
);
885 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
886 execute_async(do_suspend
, mode
, &local_err
);
889 error_propagate(errp
, local_err
);
894 void qmp_guest_suspend_hybrid(Error
**errp
)
896 error_setg(errp
, QERR_UNSUPPORTED
);
899 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
901 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
902 ULONG adptr_addrs_len
= 0;
905 /* Call the first time to get the adptr_addrs_len. */
906 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
907 NULL
, adptr_addrs
, &adptr_addrs_len
);
909 adptr_addrs
= g_malloc(adptr_addrs_len
);
910 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
911 NULL
, adptr_addrs
, &adptr_addrs_len
);
912 if (ret
!= ERROR_SUCCESS
) {
913 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
920 static char *guest_wctomb_dup(WCHAR
*wstr
)
925 i
= wcslen(wstr
) + 1;
927 WideCharToMultiByte(CP_ACP
, WC_COMPOSITECHECK
,
928 wstr
, -1, str
, i
, NULL
, NULL
);
932 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
935 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
939 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
940 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
941 len
= sizeof(addr_str
);
942 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
943 ip_addr
->Address
.iSockaddrLength
,
948 error_setg_win32(errp
, WSAGetLastError(),
949 "failed address presentation form conversion");
952 return g_strdup(addr_str
);
957 #if (_WIN32_WINNT >= 0x0600)
958 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
960 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
961 * field to obtain the prefix.
963 return ip_addr
->OnLinkPrefixLength
;
966 /* When using the Windows XP and 2003 build environment, do the best we can to
967 * figure out the prefix.
969 static IP_ADAPTER_INFO
*guest_get_adapters_info(void)
971 IP_ADAPTER_INFO
*adptr_info
= NULL
;
972 ULONG adptr_info_len
= 0;
975 /* Call the first time to get the adptr_info_len. */
976 GetAdaptersInfo(adptr_info
, &adptr_info_len
);
978 adptr_info
= g_malloc(adptr_info_len
);
979 ret
= GetAdaptersInfo(adptr_info
, &adptr_info_len
);
980 if (ret
!= ERROR_SUCCESS
) {
987 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
989 int64_t prefix
= -1; /* Use for AF_INET6 and unknown/undetermined values. */
990 IP_ADAPTER_INFO
*adptr_info
, *info
;
994 if (ip_addr
->Address
.lpSockaddr
->sa_family
!= AF_INET
) {
997 adptr_info
= guest_get_adapters_info();
998 if (adptr_info
== NULL
) {
1002 /* Match up the passed in ip_addr with one found in adaptr_info.
1003 * The matching one in adptr_info will have the netmask.
1005 p
= &((struct sockaddr_in
*)ip_addr
->Address
.lpSockaddr
)->sin_addr
;
1006 for (info
= adptr_info
; info
; info
= info
->Next
) {
1007 for (ip
= &info
->IpAddressList
; ip
; ip
= ip
->Next
) {
1008 if (p
->S_un
.S_addr
== inet_addr(ip
->IpAddress
.String
)) {
1009 prefix
= ctpop32(inet_addr(ip
->IpMask
.String
));
1020 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1022 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1023 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1024 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1025 GuestIpAddressList
*head_addr
, *cur_addr
;
1026 GuestNetworkInterfaceList
*info
;
1027 GuestIpAddressList
*address_item
= NULL
;
1028 unsigned char *mac_addr
;
1034 adptr_addrs
= guest_get_adapters_addresses(errp
);
1035 if (adptr_addrs
== NULL
) {
1039 /* Make WSA APIs available. */
1040 wsa_version
= MAKEWORD(2, 2);
1041 ret
= WSAStartup(wsa_version
, &wsa_data
);
1043 error_setg_win32(errp
, ret
, "failed socket startup");
1047 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1048 info
= g_malloc0(sizeof(*info
));
1050 if (cur_item
== NULL
) {
1051 head
= cur_item
= info
;
1053 cur_item
->next
= info
;
1057 info
->value
= g_malloc0(sizeof(*info
->value
));
1058 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1060 if (addr
->PhysicalAddressLength
!= 0) {
1061 mac_addr
= addr
->PhysicalAddress
;
1063 info
->value
->hardware_address
=
1064 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1065 (int) mac_addr
[0], (int) mac_addr
[1],
1066 (int) mac_addr
[2], (int) mac_addr
[3],
1067 (int) mac_addr
[4], (int) mac_addr
[5]);
1069 info
->value
->has_hardware_address
= true;
1074 for (ip_addr
= addr
->FirstUnicastAddress
;
1076 ip_addr
= ip_addr
->Next
) {
1077 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1078 if (addr_str
== NULL
) {
1082 address_item
= g_malloc0(sizeof(*address_item
));
1085 head_addr
= cur_addr
= address_item
;
1087 cur_addr
->next
= address_item
;
1088 cur_addr
= address_item
;
1091 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1092 address_item
->value
->ip_address
= addr_str
;
1093 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1094 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1095 address_item
->value
->ip_address_type
=
1096 GUEST_IP_ADDRESS_TYPE_IPV4
;
1097 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1098 address_item
->value
->ip_address_type
=
1099 GUEST_IP_ADDRESS_TYPE_IPV6
;
1103 info
->value
->has_ip_addresses
= true;
1104 info
->value
->ip_addresses
= head_addr
;
1109 g_free(adptr_addrs
);
1113 int64_t qmp_guest_get_time(Error
**errp
)
1115 SYSTEMTIME ts
= {0};
1120 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1121 error_setg(errp
, "Failed to get time");
1125 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1126 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1130 time_ns
= ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1131 - W32_FT_OFFSET
) * 100;
1136 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1138 Error
*local_err
= NULL
;
1144 /* Unfortunately, Windows libraries don't provide an easy way to access
1147 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1149 error_setg(errp
, "Time argument is required on this platform");
1153 /* Validate time passed by user. */
1154 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1155 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1159 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1161 tf
.dwLowDateTime
= (DWORD
) time
;
1162 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1164 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1165 error_setg(errp
, "Failed to convert system time %d",
1166 (int)GetLastError());
1170 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1172 error_propagate(errp
, local_err
);
1176 if (!SetSystemTime(&ts
)) {
1177 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1182 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1184 error_setg(errp
, QERR_UNSUPPORTED
);
1188 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1190 error_setg(errp
, QERR_UNSUPPORTED
);
1195 get_net_error_message(gint error
)
1197 HMODULE module
= NULL
;
1198 gchar
*retval
= NULL
;
1199 wchar_t *msg
= NULL
;
1202 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
1203 |FORMAT_MESSAGE_IGNORE_INSERTS
1204 |FORMAT_MESSAGE_FROM_SYSTEM
;
1206 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1207 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1209 if (module
!= NULL
) {
1210 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1214 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1217 nchars
= wcslen(msg
);
1219 if (nchars
> 2 && msg
[nchars
-1] == '\n' && msg
[nchars
-2] == '\r') {
1220 msg
[nchars
-2] = '\0';
1223 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1228 if (module
!= NULL
) {
1229 FreeLibrary(module
);
1235 void qmp_guest_set_user_password(const char *username
,
1236 const char *password
,
1241 char *rawpasswddata
= NULL
;
1242 size_t rawpasswdlen
;
1243 wchar_t *user
, *wpass
;
1244 USER_INFO_1003 pi1003
= { 0, };
1247 error_setg(errp
, QERR_UNSUPPORTED
);
1251 rawpasswddata
= (char *)g_base64_decode(password
, &rawpasswdlen
);
1252 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1253 rawpasswddata
[rawpasswdlen
] = '\0';
1255 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, NULL
);
1256 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, NULL
);
1258 pi1003
.usri1003_password
= wpass
;
1259 nas
= NetUserSetInfo(NULL
, user
,
1260 1003, (LPBYTE
)&pi1003
,
1263 if (nas
!= NERR_Success
) {
1264 gchar
*msg
= get_net_error_message(nas
);
1265 error_setg(errp
, "failed to set password: %s", msg
);
1271 g_free(rawpasswddata
);
1274 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1276 error_setg(errp
, QERR_UNSUPPORTED
);
1280 GuestMemoryBlockResponseList
*
1281 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1283 error_setg(errp
, QERR_UNSUPPORTED
);
1287 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1289 error_setg(errp
, QERR_UNSUPPORTED
);
1293 /* add unsupported commands to the blacklist */
1294 GList
*ga_command_blacklist_init(GList
*blacklist
)
1296 const char *list_unsupported
[] = {
1297 "guest-suspend-hybrid",
1298 "guest-get-vcpus", "guest-set-vcpus",
1299 "guest-get-memory-blocks", "guest-set-memory-blocks",
1300 "guest-get-memory-block-size",
1301 "guest-fsfreeze-freeze-list",
1302 "guest-fstrim", NULL
};
1303 char **p
= (char **)list_unsupported
;
1306 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1309 if (!vss_init(true)) {
1310 g_debug("vss_init failed, vss commands are going to be disabled");
1311 const char *list
[] = {
1312 "guest-get-fsinfo", "guest-fsfreeze-status",
1313 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1317 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1324 /* register init/cleanup routines for stateful command groups */
1325 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1327 if (!vss_initialized()) {
1328 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);