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.
15 # define _WIN32_WINNT 0x0600
17 #include "qemu/osdep.h"
24 #ifdef CONFIG_QGA_NTDDSCSI
34 #include "qga/guest-agent-core.h"
35 #include "qga/vss-win32.h"
36 #include "qga-qmp-commands.h"
37 #include "qapi/qmp/qerror.h"
38 #include "qemu/queue.h"
39 #include "qemu/host-utils.h"
40 #include "qemu/base64.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 typedef 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 static OpenFlags
*find_open_flag(const char *mode_str
)
95 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
96 OpenFlags
*flags
= guest_file_open_modes
+ mode
;
98 if (strcmp(flags
->forms
, mode_str
) == 0) {
103 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
107 static int64_t guest_file_handle_add(HANDLE fh
, Error
**errp
)
109 GuestFileHandle
*gfh
;
112 handle
= ga_get_fd_handle(ga_state
, errp
);
116 gfh
= g_new0(GuestFileHandle
, 1);
119 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
124 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
126 GuestFileHandle
*gfh
;
127 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
) {
132 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
136 static void handle_set_nonblocking(HANDLE fh
)
138 DWORD file_type
, pipe_state
;
139 file_type
= GetFileType(fh
);
140 if (file_type
!= FILE_TYPE_PIPE
) {
143 /* If file_type == FILE_TYPE_PIPE, according to MSDN
144 * the specified file is socket or named pipe */
145 if (!GetNamedPipeHandleState(fh
, &pipe_state
, NULL
,
146 NULL
, NULL
, NULL
, 0)) {
149 /* The fd is named pipe fd */
150 if (pipe_state
& PIPE_NOWAIT
) {
154 pipe_state
|= PIPE_NOWAIT
;
155 SetNamedPipeHandleState(fh
, &pipe_state
, NULL
, NULL
);
158 int64_t qmp_guest_file_open(const char *path
, bool has_mode
,
159 const char *mode
, Error
**errp
)
163 HANDLE templ_file
= NULL
;
164 DWORD share_mode
= FILE_SHARE_READ
;
165 DWORD flags_and_attr
= FILE_ATTRIBUTE_NORMAL
;
166 LPSECURITY_ATTRIBUTES sa_attr
= NULL
;
167 OpenFlags
*guest_flags
;
172 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
173 guest_flags
= find_open_flag(mode
);
174 if (guest_flags
== NULL
) {
175 error_setg(errp
, "invalid file open mode");
179 fh
= CreateFile(path
, guest_flags
->desired_access
, share_mode
, sa_attr
,
180 guest_flags
->creation_disposition
, flags_and_attr
,
182 if (fh
== INVALID_HANDLE_VALUE
) {
183 error_setg_win32(errp
, GetLastError(), "failed to open file '%s'",
188 /* set fd non-blocking to avoid common use cases (like reading from a
189 * named pipe) from hanging the agent
191 handle_set_nonblocking(fh
);
193 fd
= guest_file_handle_add(fh
, errp
);
196 error_setg(errp
, "failed to add handle to qmp handle table");
200 slog("guest-file-open, handle: % " PRId64
, fd
);
204 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
207 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
208 slog("guest-file-close called, handle: %" PRId64
, handle
);
212 ret
= CloseHandle(gfh
->fh
);
214 error_setg_win32(errp
, GetLastError(), "failed close handle");
218 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
222 static void acquire_privilege(const char *name
, Error
**errp
)
225 TOKEN_PRIVILEGES priv
;
226 Error
*local_err
= NULL
;
228 if (OpenProcessToken(GetCurrentProcess(),
229 TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY
, &token
))
231 if (!LookupPrivilegeValue(NULL
, name
, &priv
.Privileges
[0].Luid
)) {
232 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
233 "no luid for requested privilege");
237 priv
.PrivilegeCount
= 1;
238 priv
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
240 if (!AdjustTokenPrivileges(token
, FALSE
, &priv
, 0, NULL
, 0)) {
241 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
242 "unable to acquire requested privilege");
247 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
248 "failed to open privilege token");
255 error_propagate(errp
, local_err
);
258 static void execute_async(DWORD
WINAPI (*func
)(LPVOID
), LPVOID opaque
,
261 Error
*local_err
= NULL
;
263 HANDLE thread
= CreateThread(NULL
, 0, func
, opaque
, 0, NULL
);
265 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
266 "failed to dispatch asynchronous command");
267 error_propagate(errp
, local_err
);
271 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
273 Error
*local_err
= NULL
;
274 UINT shutdown_flag
= EWX_FORCE
;
276 slog("guest-shutdown called, mode: %s", mode
);
278 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
279 shutdown_flag
|= EWX_POWEROFF
;
280 } else if (strcmp(mode
, "halt") == 0) {
281 shutdown_flag
|= EWX_SHUTDOWN
;
282 } else if (strcmp(mode
, "reboot") == 0) {
283 shutdown_flag
|= EWX_REBOOT
;
285 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "mode",
286 "halt|powerdown|reboot");
290 /* Request a shutdown privilege, but try to shut down the system
292 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
294 error_propagate(errp
, local_err
);
298 if (!ExitWindowsEx(shutdown_flag
, SHTDN_REASON_FLAG_PLANNED
)) {
299 slog("guest-shutdown failed: %lu", GetLastError());
300 error_setg(errp
, QERR_UNDEFINED_ERROR
);
304 GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
305 int64_t count
, Error
**errp
)
307 GuestFileRead
*read_data
= NULL
;
312 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
318 count
= QGA_READ_COUNT_DEFAULT
;
319 } else if (count
< 0) {
320 error_setg(errp
, "value '%" PRId64
321 "' is invalid for argument count", count
);
326 buf
= g_malloc0(count
+1);
327 is_ok
= ReadFile(fh
, buf
, count
, &read_count
, NULL
);
329 error_setg_win32(errp
, GetLastError(), "failed to read file");
330 slog("guest-file-read failed, handle %" PRId64
, handle
);
333 read_data
= g_new0(GuestFileRead
, 1);
334 read_data
->count
= (size_t)read_count
;
335 read_data
->eof
= read_count
== 0;
337 if (read_count
!= 0) {
338 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
346 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
347 bool has_count
, int64_t count
,
350 GuestFileWrite
*write_data
= NULL
;
355 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
362 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
369 } else if (count
< 0 || count
> buf_len
) {
370 error_setg(errp
, "value '%" PRId64
371 "' is invalid for argument count", count
);
375 is_ok
= WriteFile(fh
, buf
, count
, &write_count
, NULL
);
377 error_setg_win32(errp
, GetLastError(), "failed to write to file");
378 slog("guest-file-write-failed, handle: %" PRId64
, handle
);
380 write_data
= g_new0(GuestFileWrite
, 1);
381 write_data
->count
= (size_t) write_count
;
389 GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
390 GuestFileWhence
*whence_code
,
393 GuestFileHandle
*gfh
;
394 GuestFileSeek
*seek_data
;
396 LARGE_INTEGER new_pos
, off_pos
;
397 off_pos
.QuadPart
= offset
;
402 gfh
= guest_file_handle_find(handle
, errp
);
407 /* We stupidly exposed 'whence':'int' in our qapi */
408 whence
= ga_parse_whence(whence_code
, &err
);
410 error_propagate(errp
, err
);
415 res
= SetFilePointerEx(fh
, off_pos
, &new_pos
, whence
);
417 error_setg_win32(errp
, GetLastError(), "failed to seek file");
420 seek_data
= g_new0(GuestFileSeek
, 1);
421 seek_data
->position
= new_pos
.QuadPart
;
425 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
428 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
434 if (!FlushFileBuffers(fh
)) {
435 error_setg_win32(errp
, GetLastError(), "failed to flush file");
439 #ifdef CONFIG_QGA_NTDDSCSI
441 static STORAGE_BUS_TYPE win2qemu
[] = {
442 [BusTypeUnknown
] = GUEST_DISK_BUS_TYPE_UNKNOWN
,
443 [BusTypeScsi
] = GUEST_DISK_BUS_TYPE_SCSI
,
444 [BusTypeAtapi
] = GUEST_DISK_BUS_TYPE_IDE
,
445 [BusTypeAta
] = GUEST_DISK_BUS_TYPE_IDE
,
446 [BusType1394
] = GUEST_DISK_BUS_TYPE_IEEE1394
,
447 [BusTypeSsa
] = GUEST_DISK_BUS_TYPE_SSA
,
448 [BusTypeFibre
] = GUEST_DISK_BUS_TYPE_SSA
,
449 [BusTypeUsb
] = GUEST_DISK_BUS_TYPE_USB
,
450 [BusTypeRAID
] = GUEST_DISK_BUS_TYPE_RAID
,
451 #if (_WIN32_WINNT >= 0x0600)
452 [BusTypeiScsi
] = GUEST_DISK_BUS_TYPE_ISCSI
,
453 [BusTypeSas
] = GUEST_DISK_BUS_TYPE_SAS
,
454 [BusTypeSata
] = GUEST_DISK_BUS_TYPE_SATA
,
455 [BusTypeSd
] = GUEST_DISK_BUS_TYPE_SD
,
456 [BusTypeMmc
] = GUEST_DISK_BUS_TYPE_MMC
,
458 #if (_WIN32_WINNT >= 0x0601)
459 [BusTypeVirtual
] = GUEST_DISK_BUS_TYPE_VIRTUAL
,
460 [BusTypeFileBackedVirtual
] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL
,
464 static GuestDiskBusType
find_bus_type(STORAGE_BUS_TYPE bus
)
466 if (bus
> ARRAY_SIZE(win2qemu
) || (int)bus
< 0) {
467 return GUEST_DISK_BUS_TYPE_UNKNOWN
;
469 return win2qemu
[(int)bus
];
472 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME
,
473 0x53f5630dL
, 0xb6bf, 0x11d0, 0x94, 0xf2,
474 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
476 static GuestPCIAddress
*get_pci_info(char *guid
, Error
**errp
)
479 SP_DEVINFO_DATA dev_info_data
;
482 char dev_name
[MAX_PATH
];
484 GuestPCIAddress
*pci
= NULL
;
485 char *name
= g_strdup(&guid
[4]);
487 if (!QueryDosDevice(name
, dev_name
, ARRAY_SIZE(dev_name
))) {
488 error_setg_win32(errp
, GetLastError(), "failed to get dos device name");
492 dev_info
= SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME
, 0, 0,
493 DIGCF_PRESENT
| DIGCF_DEVICEINTERFACE
);
494 if (dev_info
== INVALID_HANDLE_VALUE
) {
495 error_setg_win32(errp
, GetLastError(), "failed to get devices tree");
499 dev_info_data
.cbSize
= sizeof(SP_DEVINFO_DATA
);
500 for (i
= 0; SetupDiEnumDeviceInfo(dev_info
, i
, &dev_info_data
); i
++) {
501 DWORD addr
, bus
, slot
, func
, dev
, data
, size2
;
502 while (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
503 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME
,
504 &data
, (PBYTE
)buffer
, size
,
506 size
= MAX(size
, size2
);
507 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) {
509 /* Double the size to avoid problems on
510 * W2k MBCS systems per KB 888609.
511 * https://support.microsoft.com/en-us/kb/259695 */
512 buffer
= g_malloc(size
* 2);
514 error_setg_win32(errp
, GetLastError(),
515 "failed to get device name");
520 if (g_strcmp0(buffer
, dev_name
)) {
524 /* There is no need to allocate buffer in the next functions. The size
525 * is known and ULONG according to
526 * https://support.microsoft.com/en-us/kb/253232
527 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
529 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
530 SPDRP_BUSNUMBER
, &data
, (PBYTE
)&bus
, size
, NULL
)) {
534 /* The function retrieves the device's address. This value will be
535 * transformed into device function and number */
536 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
537 SPDRP_ADDRESS
, &data
, (PBYTE
)&addr
, size
, NULL
)) {
541 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
542 * This number is typically a user-perceived slot number. */
543 if (!SetupDiGetDeviceRegistryProperty(dev_info
, &dev_info_data
,
544 SPDRP_UI_NUMBER
, &data
, (PBYTE
)&slot
, size
, NULL
)) {
548 /* SetupApi gives us the same information as driver with
549 * IoGetDeviceProperty. According to Microsoft
550 * https://support.microsoft.com/en-us/kb/253232
551 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
552 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
553 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
555 func
= addr
& 0x0000FFFF;
556 dev
= (addr
>> 16) & 0x0000FFFF;
557 pci
= g_malloc0(sizeof(*pci
));
560 pci
->function
= func
;
566 SetupDiDestroyDeviceInfoList(dev_info
);
573 static int get_disk_bus_type(HANDLE vol_h
, Error
**errp
)
575 STORAGE_PROPERTY_QUERY query
;
576 STORAGE_DEVICE_DESCRIPTOR
*dev_desc
, buf
;
580 dev_desc
->Size
= sizeof(buf
);
581 query
.PropertyId
= StorageDeviceProperty
;
582 query
.QueryType
= PropertyStandardQuery
;
584 if (!DeviceIoControl(vol_h
, IOCTL_STORAGE_QUERY_PROPERTY
, &query
,
585 sizeof(STORAGE_PROPERTY_QUERY
), dev_desc
,
586 dev_desc
->Size
, &received
, NULL
)) {
587 error_setg_win32(errp
, GetLastError(), "failed to get bus type");
591 return dev_desc
->BusType
;
594 /* VSS provider works with volumes, thus there is no difference if
595 * the volume consist of spanned disks. Info about the first disk in the
596 * volume is returned for the spanned disk group (LVM) */
597 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
599 GuestDiskAddressList
*list
= NULL
;
600 GuestDiskAddress
*disk
;
601 SCSI_ADDRESS addr
, *scsi_ad
;
607 char *name
= g_strndup(guid
, strlen(guid
)-1);
609 vol_h
= CreateFile(name
, 0, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
611 if (vol_h
== INVALID_HANDLE_VALUE
) {
612 error_setg_win32(errp
, GetLastError(), "failed to open volume");
616 bus
= get_disk_bus_type(vol_h
, errp
);
621 disk
= g_malloc0(sizeof(*disk
));
622 disk
->bus_type
= find_bus_type(bus
);
623 if (bus
== BusTypeScsi
|| bus
== BusTypeAta
|| bus
== BusTypeRAID
624 #if (_WIN32_WINNT >= 0x0600)
625 /* This bus type is not supported before Windows Server 2003 SP1 */
629 /* We are able to use the same ioctls for different bus types
630 * according to Microsoft docs
631 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
632 if (DeviceIoControl(vol_h
, IOCTL_SCSI_GET_ADDRESS
, NULL
, 0, scsi_ad
,
633 sizeof(SCSI_ADDRESS
), &len
, NULL
)) {
634 disk
->unit
= addr
.Lun
;
635 disk
->target
= addr
.TargetId
;
636 disk
->bus
= addr
.PathId
;
637 disk
->pci_controller
= get_pci_info(name
, errp
);
639 /* We do not set error in this case, because we still have enough
640 * information about volume. */
642 disk
->pci_controller
= NULL
;
645 list
= g_malloc0(sizeof(*list
));
657 static GuestDiskAddressList
*build_guest_disk_info(char *guid
, Error
**errp
)
662 #endif /* CONFIG_QGA_NTDDSCSI */
664 static GuestFilesystemInfo
*build_guest_fsinfo(char *guid
, Error
**errp
)
667 char mnt
, *mnt_point
;
669 char vol_info
[MAX_PATH
+1];
671 GuestFilesystemInfo
*fs
= NULL
;
673 GetVolumePathNamesForVolumeName(guid
, (LPCH
)&mnt
, 0, &info_size
);
674 if (GetLastError() != ERROR_MORE_DATA
) {
675 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
679 mnt_point
= g_malloc(info_size
+ 1);
680 if (!GetVolumePathNamesForVolumeName(guid
, mnt_point
, info_size
,
682 error_setg_win32(errp
, GetLastError(), "failed to get volume name");
686 len
= strlen(mnt_point
);
687 mnt_point
[len
] = '\\';
688 mnt_point
[len
+1] = 0;
689 if (!GetVolumeInformation(mnt_point
, vol_info
, sizeof(vol_info
), NULL
, NULL
,
690 NULL
, (LPSTR
)&fs_name
, sizeof(fs_name
))) {
691 if (GetLastError() != ERROR_NOT_READY
) {
692 error_setg_win32(errp
, GetLastError(), "failed to get volume info");
697 fs_name
[sizeof(fs_name
) - 1] = 0;
698 fs
= g_malloc(sizeof(*fs
));
699 fs
->name
= g_strdup(guid
);
701 fs
->mountpoint
= g_strdup("System Reserved");
703 fs
->mountpoint
= g_strndup(mnt_point
, len
);
705 fs
->type
= g_strdup(fs_name
);
706 fs
->disk
= build_guest_disk_info(guid
, errp
);
712 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
715 GuestFilesystemInfoList
*new, *ret
= NULL
;
718 vol_h
= FindFirstVolume(guid
, sizeof(guid
));
719 if (vol_h
== INVALID_HANDLE_VALUE
) {
720 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
725 GuestFilesystemInfo
*info
= build_guest_fsinfo(guid
, errp
);
729 new = g_malloc(sizeof(*ret
));
733 } while (FindNextVolume(vol_h
, guid
, sizeof(guid
)));
735 if (GetLastError() != ERROR_NO_MORE_FILES
) {
736 error_setg_win32(errp
, GetLastError(), "failed to find next volume");
739 FindVolumeClose(vol_h
);
744 * Return status of freeze/thaw
746 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
748 if (!vss_initialized()) {
749 error_setg(errp
, QERR_UNSUPPORTED
);
753 if (ga_is_frozen(ga_state
)) {
754 return GUEST_FSFREEZE_STATUS_FROZEN
;
757 return GUEST_FSFREEZE_STATUS_THAWED
;
761 * Freeze local file systems using Volume Shadow-copy Service.
762 * The frozen state is limited for up to 10 seconds by VSS.
764 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
767 Error
*local_err
= NULL
;
769 if (!vss_initialized()) {
770 error_setg(errp
, QERR_UNSUPPORTED
);
774 slog("guest-fsfreeze called");
776 /* cannot risk guest agent blocking itself on a write in this state */
777 ga_set_frozen(ga_state
);
779 qga_vss_fsfreeze(&i
, true, &local_err
);
781 error_propagate(errp
, local_err
);
789 qmp_guest_fsfreeze_thaw(&local_err
);
791 g_debug("cleanup thaw: %s", error_get_pretty(local_err
));
792 error_free(local_err
);
797 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
798 strList
*mountpoints
,
801 error_setg(errp
, QERR_UNSUPPORTED
);
807 * Thaw local file systems using Volume Shadow-copy Service.
809 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
813 if (!vss_initialized()) {
814 error_setg(errp
, QERR_UNSUPPORTED
);
818 qga_vss_fsfreeze(&i
, false, errp
);
820 ga_unset_frozen(ga_state
);
824 static void guest_fsfreeze_cleanup(void)
828 if (!vss_initialized()) {
832 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
833 qmp_guest_fsfreeze_thaw(&err
);
835 slog("failed to clean up frozen filesystems: %s",
836 error_get_pretty(err
));
845 * Walk list of mounted file systems in the guest, and discard unused
848 GuestFilesystemTrimResponse
*
849 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
851 GuestFilesystemTrimResponse
*resp
;
853 WCHAR guid
[MAX_PATH
] = L
"";
855 handle
= FindFirstVolumeW(guid
, ARRAYSIZE(guid
));
856 if (handle
== INVALID_HANDLE_VALUE
) {
857 error_setg_win32(errp
, GetLastError(), "failed to find any volume");
861 resp
= g_new0(GuestFilesystemTrimResponse
, 1);
864 GuestFilesystemTrimResult
*res
;
865 GuestFilesystemTrimResultList
*list
;
867 DWORD char_count
= 0;
872 GetVolumePathNamesForVolumeNameW(guid
, NULL
, 0, &char_count
);
874 if (GetLastError() != ERROR_MORE_DATA
) {
877 if (GetDriveTypeW(guid
) != DRIVE_FIXED
) {
881 uc_path
= g_malloc(sizeof(WCHAR
) * char_count
);
882 if (!GetVolumePathNamesForVolumeNameW(guid
, uc_path
, char_count
,
883 &char_count
) || !*uc_path
) {
884 /* strange, but this condition could be faced even with size == 2 */
889 res
= g_new0(GuestFilesystemTrimResult
, 1);
891 path
= g_utf16_to_utf8(uc_path
, char_count
, NULL
, NULL
, &gerr
);
896 res
->has_error
= true;
897 res
->error
= g_strdup(gerr
->message
);
904 list
= g_new0(GuestFilesystemTrimResultList
, 1);
906 list
->next
= resp
->paths
;
910 memset(argv
, 0, sizeof(argv
));
911 argv
[0] = (gchar
*)"defrag.exe";
912 argv
[1] = (gchar
*)"/L";
915 if (!g_spawn_sync(NULL
, argv
, NULL
, G_SPAWN_SEARCH_PATH
, NULL
, NULL
,
916 &out
/* stdout */, NULL
/* stdin */,
918 res
->has_error
= true;
919 res
->error
= g_strdup(gerr
->message
);
922 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
923 Error is reported in the output with something like
924 (x89000020) etc code in the stdout */
927 gchar
**lines
= g_strsplit(out
, "\r\n", 0);
930 for (i
= 0; lines
[i
] != NULL
; i
++) {
931 if (g_strstr_len(lines
[i
], -1, "(0x") == NULL
) {
934 res
->has_error
= true;
935 res
->error
= g_strdup(lines
[i
]);
940 } while (FindNextVolumeW(handle
, guid
, ARRAYSIZE(guid
)));
942 FindVolumeClose(handle
);
947 GUEST_SUSPEND_MODE_DISK
,
948 GUEST_SUSPEND_MODE_RAM
951 static void check_suspend_mode(GuestSuspendMode mode
, Error
**errp
)
953 SYSTEM_POWER_CAPABILITIES sys_pwr_caps
;
954 Error
*local_err
= NULL
;
956 ZeroMemory(&sys_pwr_caps
, sizeof(sys_pwr_caps
));
957 if (!GetPwrCapabilities(&sys_pwr_caps
)) {
958 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
959 "failed to determine guest suspend capabilities");
964 case GUEST_SUSPEND_MODE_DISK
:
965 if (!sys_pwr_caps
.SystemS4
) {
966 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
967 "suspend-to-disk not supported by OS");
970 case GUEST_SUSPEND_MODE_RAM
:
971 if (!sys_pwr_caps
.SystemS3
) {
972 error_setg(&local_err
, QERR_QGA_COMMAND_FAILED
,
973 "suspend-to-ram not supported by OS");
977 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "mode",
982 error_propagate(errp
, local_err
);
985 static DWORD WINAPI
do_suspend(LPVOID opaque
)
987 GuestSuspendMode
*mode
= opaque
;
990 if (!SetSuspendState(*mode
== GUEST_SUSPEND_MODE_DISK
, TRUE
, TRUE
)) {
991 slog("failed to suspend guest, %lu", GetLastError());
998 void qmp_guest_suspend_disk(Error
**errp
)
1000 Error
*local_err
= NULL
;
1001 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1003 *mode
= GUEST_SUSPEND_MODE_DISK
;
1004 check_suspend_mode(*mode
, &local_err
);
1005 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1006 execute_async(do_suspend
, mode
, &local_err
);
1009 error_propagate(errp
, local_err
);
1014 void qmp_guest_suspend_ram(Error
**errp
)
1016 Error
*local_err
= NULL
;
1017 GuestSuspendMode
*mode
= g_new(GuestSuspendMode
, 1);
1019 *mode
= GUEST_SUSPEND_MODE_RAM
;
1020 check_suspend_mode(*mode
, &local_err
);
1021 acquire_privilege(SE_SHUTDOWN_NAME
, &local_err
);
1022 execute_async(do_suspend
, mode
, &local_err
);
1025 error_propagate(errp
, local_err
);
1030 void qmp_guest_suspend_hybrid(Error
**errp
)
1032 error_setg(errp
, QERR_UNSUPPORTED
);
1035 static IP_ADAPTER_ADDRESSES
*guest_get_adapters_addresses(Error
**errp
)
1037 IP_ADAPTER_ADDRESSES
*adptr_addrs
= NULL
;
1038 ULONG adptr_addrs_len
= 0;
1041 /* Call the first time to get the adptr_addrs_len. */
1042 GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1043 NULL
, adptr_addrs
, &adptr_addrs_len
);
1045 adptr_addrs
= g_malloc(adptr_addrs_len
);
1046 ret
= GetAdaptersAddresses(AF_UNSPEC
, GAA_FLAG_INCLUDE_PREFIX
,
1047 NULL
, adptr_addrs
, &adptr_addrs_len
);
1048 if (ret
!= ERROR_SUCCESS
) {
1049 error_setg_win32(errp
, ret
, "failed to get adapters addresses");
1050 g_free(adptr_addrs
);
1056 static char *guest_wctomb_dup(WCHAR
*wstr
)
1061 i
= wcslen(wstr
) + 1;
1063 WideCharToMultiByte(CP_ACP
, WC_COMPOSITECHECK
,
1064 wstr
, -1, str
, i
, NULL
, NULL
);
1068 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
,
1071 char addr_str
[INET6_ADDRSTRLEN
+ INET_ADDRSTRLEN
];
1075 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
||
1076 ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1077 len
= sizeof(addr_str
);
1078 ret
= WSAAddressToString(ip_addr
->Address
.lpSockaddr
,
1079 ip_addr
->Address
.iSockaddrLength
,
1084 error_setg_win32(errp
, WSAGetLastError(),
1085 "failed address presentation form conversion");
1088 return g_strdup(addr_str
);
1093 #if (_WIN32_WINNT >= 0x0600)
1094 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1096 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1097 * field to obtain the prefix.
1099 return ip_addr
->OnLinkPrefixLength
;
1102 /* When using the Windows XP and 2003 build environment, do the best we can to
1103 * figure out the prefix.
1105 static IP_ADAPTER_INFO
*guest_get_adapters_info(void)
1107 IP_ADAPTER_INFO
*adptr_info
= NULL
;
1108 ULONG adptr_info_len
= 0;
1111 /* Call the first time to get the adptr_info_len. */
1112 GetAdaptersInfo(adptr_info
, &adptr_info_len
);
1114 adptr_info
= g_malloc(adptr_info_len
);
1115 ret
= GetAdaptersInfo(adptr_info
, &adptr_info_len
);
1116 if (ret
!= ERROR_SUCCESS
) {
1123 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
)
1125 int64_t prefix
= -1; /* Use for AF_INET6 and unknown/undetermined values. */
1126 IP_ADAPTER_INFO
*adptr_info
, *info
;
1130 if (ip_addr
->Address
.lpSockaddr
->sa_family
!= AF_INET
) {
1133 adptr_info
= guest_get_adapters_info();
1134 if (adptr_info
== NULL
) {
1138 /* Match up the passed in ip_addr with one found in adaptr_info.
1139 * The matching one in adptr_info will have the netmask.
1141 p
= &((struct sockaddr_in
*)ip_addr
->Address
.lpSockaddr
)->sin_addr
;
1142 for (info
= adptr_info
; info
; info
= info
->Next
) {
1143 for (ip
= &info
->IpAddressList
; ip
; ip
= ip
->Next
) {
1144 if (p
->S_un
.S_addr
== inet_addr(ip
->IpAddress
.String
)) {
1145 prefix
= ctpop32(inet_addr(ip
->IpMask
.String
));
1156 #define INTERFACE_PATH_BUF_SZ 512
1158 static DWORD
get_interface_index(const char *guid
)
1162 wchar_t wbuf
[INTERFACE_PATH_BUF_SZ
];
1163 snwprintf(wbuf
, INTERFACE_PATH_BUF_SZ
, L
"\\device\\tcpip_%s", guid
);
1164 wbuf
[INTERFACE_PATH_BUF_SZ
- 1] = 0;
1165 status
= GetAdapterIndex (wbuf
, &index
);
1166 if (status
!= NO_ERROR
) {
1172 static int guest_get_network_stats(const char *name
,
1173 GuestNetworkInterfaceStat
*stats
)
1176 MIB_IFROW a_mid_ifrow
;
1177 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1178 if_index
= get_interface_index(name
);
1179 a_mid_ifrow
.dwIndex
= if_index
;
1180 if (NO_ERROR
== GetIfEntry(&a_mid_ifrow
)) {
1181 stats
->rx_bytes
= a_mid_ifrow
.dwInOctets
;
1182 stats
->rx_packets
= a_mid_ifrow
.dwInUcastPkts
;
1183 stats
->rx_errs
= a_mid_ifrow
.dwInErrors
;
1184 stats
->rx_dropped
= a_mid_ifrow
.dwInDiscards
;
1185 stats
->tx_bytes
= a_mid_ifrow
.dwOutOctets
;
1186 stats
->tx_packets
= a_mid_ifrow
.dwOutUcastPkts
;
1187 stats
->tx_errs
= a_mid_ifrow
.dwOutErrors
;
1188 stats
->tx_dropped
= a_mid_ifrow
.dwOutDiscards
;
1194 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1196 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1197 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1198 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1199 GuestIpAddressList
*head_addr
, *cur_addr
;
1200 GuestNetworkInterfaceList
*info
;
1201 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1202 GuestIpAddressList
*address_item
= NULL
;
1203 unsigned char *mac_addr
;
1209 adptr_addrs
= guest_get_adapters_addresses(errp
);
1210 if (adptr_addrs
== NULL
) {
1214 /* Make WSA APIs available. */
1215 wsa_version
= MAKEWORD(2, 2);
1216 ret
= WSAStartup(wsa_version
, &wsa_data
);
1218 error_setg_win32(errp
, ret
, "failed socket startup");
1222 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1223 info
= g_malloc0(sizeof(*info
));
1225 if (cur_item
== NULL
) {
1226 head
= cur_item
= info
;
1228 cur_item
->next
= info
;
1232 info
->value
= g_malloc0(sizeof(*info
->value
));
1233 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1235 if (addr
->PhysicalAddressLength
!= 0) {
1236 mac_addr
= addr
->PhysicalAddress
;
1238 info
->value
->hardware_address
=
1239 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1240 (int) mac_addr
[0], (int) mac_addr
[1],
1241 (int) mac_addr
[2], (int) mac_addr
[3],
1242 (int) mac_addr
[4], (int) mac_addr
[5]);
1244 info
->value
->has_hardware_address
= true;
1249 for (ip_addr
= addr
->FirstUnicastAddress
;
1251 ip_addr
= ip_addr
->Next
) {
1252 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1253 if (addr_str
== NULL
) {
1257 address_item
= g_malloc0(sizeof(*address_item
));
1260 head_addr
= cur_addr
= address_item
;
1262 cur_addr
->next
= address_item
;
1263 cur_addr
= address_item
;
1266 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1267 address_item
->value
->ip_address
= addr_str
;
1268 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1269 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1270 address_item
->value
->ip_address_type
=
1271 GUEST_IP_ADDRESS_TYPE_IPV4
;
1272 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1273 address_item
->value
->ip_address_type
=
1274 GUEST_IP_ADDRESS_TYPE_IPV6
;
1278 info
->value
->has_ip_addresses
= true;
1279 info
->value
->ip_addresses
= head_addr
;
1281 if (!info
->value
->has_statistics
) {
1282 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1283 if (guest_get_network_stats(addr
->AdapterName
,
1284 interface_stat
) == -1) {
1285 info
->value
->has_statistics
= false;
1286 g_free(interface_stat
);
1288 info
->value
->statistics
= interface_stat
;
1289 info
->value
->has_statistics
= true;
1295 g_free(adptr_addrs
);
1299 int64_t qmp_guest_get_time(Error
**errp
)
1301 SYSTEMTIME ts
= {0};
1305 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1306 error_setg(errp
, "Failed to get time");
1310 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1311 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1315 return ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1316 - W32_FT_OFFSET
) * 100;
1319 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1321 Error
*local_err
= NULL
;
1327 /* Unfortunately, Windows libraries don't provide an easy way to access
1330 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1332 * Instead, a workaround is to use the Windows win32tm command to
1333 * resync the time using the Windows Time service.
1338 HRESULT hr
= system("w32tm /resync /nowait");
1340 if (GetLastError() != 0) {
1341 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1342 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1343 } else if (hr
!= 0) {
1344 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1345 error_setg(errp
, "Windows Time service not running on the "
1348 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1349 FORMAT_MESSAGE_FROM_SYSTEM
|
1350 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1351 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1352 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1354 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1355 "t retrieve error message", hr
);
1357 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1358 (LPCTSTR
)msg_buffer
);
1359 LocalFree(msg_buffer
);
1362 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1363 error_setg(errp
, "No internet connection on guest, sync not "
1369 /* Validate time passed by user. */
1370 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1371 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1375 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1377 tf
.dwLowDateTime
= (DWORD
) time
;
1378 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1380 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1381 error_setg(errp
, "Failed to convert system time %d",
1382 (int)GetLastError());
1386 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1388 error_propagate(errp
, local_err
);
1392 if (!SetSystemTime(&ts
)) {
1393 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1398 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1400 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1402 GuestLogicalProcessorList
*head
, **link
;
1403 Error
*local_err
= NULL
;
1412 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1413 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1414 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1415 ptr
= pslpi
= g_malloc0(length
);
1416 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1417 error_setg(&local_err
, "Failed to get processor information: %d",
1418 (int)GetLastError());
1421 error_setg(&local_err
,
1422 "Failed to get processor information buffer length: %d",
1423 (int)GetLastError());
1426 while ((local_err
== NULL
) && (length
> 0)) {
1427 if (pslpi
->Relationship
== RelationProcessorCore
) {
1428 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1430 while (cpu_bits
> 0) {
1431 if (!!(cpu_bits
& 1)) {
1432 GuestLogicalProcessor
*vcpu
;
1433 GuestLogicalProcessorList
*entry
;
1435 vcpu
= g_malloc0(sizeof *vcpu
);
1436 vcpu
->logical_id
= current
++;
1437 vcpu
->online
= true;
1438 vcpu
->has_can_offline
= true;
1440 entry
= g_malloc0(sizeof *entry
);
1441 entry
->value
= vcpu
;
1444 link
= &entry
->next
;
1449 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1450 pslpi
++; /* next entry */
1455 if (local_err
== NULL
) {
1459 /* there's no guest with zero VCPUs */
1460 error_setg(&local_err
, "Guest reported zero VCPUs");
1463 qapi_free_GuestLogicalProcessorList(head
);
1464 error_propagate(errp
, local_err
);
1468 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1470 error_setg(errp
, QERR_UNSUPPORTED
);
1475 get_net_error_message(gint error
)
1477 HMODULE module
= NULL
;
1478 gchar
*retval
= NULL
;
1479 wchar_t *msg
= NULL
;
1483 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1484 FORMAT_MESSAGE_IGNORE_INSERTS
|
1485 FORMAT_MESSAGE_FROM_SYSTEM
;
1487 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1488 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1490 if (module
!= NULL
) {
1491 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1495 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1498 nchars
= wcslen(msg
);
1501 msg
[nchars
- 1] == L
'\n' &&
1502 msg
[nchars
- 2] == L
'\r') {
1503 msg
[nchars
- 2] = L
'\0';
1506 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1511 if (module
!= NULL
) {
1512 FreeLibrary(module
);
1518 void qmp_guest_set_user_password(const char *username
,
1519 const char *password
,
1524 char *rawpasswddata
= NULL
;
1525 size_t rawpasswdlen
;
1526 wchar_t *user
= NULL
, *wpass
= NULL
;
1527 USER_INFO_1003 pi1003
= { 0, };
1528 GError
*gerr
= NULL
;
1531 error_setg(errp
, QERR_UNSUPPORTED
);
1535 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1536 if (!rawpasswddata
) {
1539 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1540 rawpasswddata
[rawpasswdlen
] = '\0';
1542 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1547 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1552 pi1003
.usri1003_password
= wpass
;
1553 nas
= NetUserSetInfo(NULL
, user
,
1554 1003, (LPBYTE
)&pi1003
,
1557 if (nas
!= NERR_Success
) {
1558 gchar
*msg
= get_net_error_message(nas
);
1559 error_setg(errp
, "failed to set password: %s", msg
);
1565 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1570 g_free(rawpasswddata
);
1573 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1575 error_setg(errp
, QERR_UNSUPPORTED
);
1579 GuestMemoryBlockResponseList
*
1580 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1582 error_setg(errp
, QERR_UNSUPPORTED
);
1586 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1588 error_setg(errp
, QERR_UNSUPPORTED
);
1592 /* add unsupported commands to the blacklist */
1593 GList
*ga_command_blacklist_init(GList
*blacklist
)
1595 const char *list_unsupported
[] = {
1596 "guest-suspend-hybrid",
1598 "guest-get-memory-blocks", "guest-set-memory-blocks",
1599 "guest-get-memory-block-size",
1600 "guest-fsfreeze-freeze-list",
1602 char **p
= (char **)list_unsupported
;
1605 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1608 if (!vss_init(true)) {
1609 g_debug("vss_init failed, vss commands are going to be disabled");
1610 const char *list
[] = {
1611 "guest-get-fsinfo", "guest-fsfreeze-status",
1612 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1616 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1623 /* register init/cleanup routines for stateful command groups */
1624 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1626 if (!vss_initialized()) {
1627 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1631 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1632 typedef struct _GA_WTSINFOA
{
1633 WTS_CONNECTSTATE_CLASS State
;
1635 DWORD IncomingBytes
;
1636 DWORD OutgoingBytes
;
1637 DWORD IncomingFrames
;
1638 DWORD OutgoingFrames
;
1639 DWORD IncomingCompressedBytes
;
1640 DWORD OutgoingCompressedBy
;
1641 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
1642 CHAR Domain
[DOMAIN_LENGTH
];
1643 CHAR UserName
[USERNAME_LENGTH
+ 1];
1644 LARGE_INTEGER ConnectTime
;
1645 LARGE_INTEGER DisconnectTime
;
1646 LARGE_INTEGER LastInputTime
;
1647 LARGE_INTEGER LogonTime
;
1648 LARGE_INTEGER CurrentTime
;
1652 GuestUserList
*qmp_guest_get_users(Error
**err
)
1654 #if (_WIN32_WINNT >= 0x0600)
1655 #define QGA_NANOSECONDS 10000000
1657 GHashTable
*cache
= NULL
;
1658 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
1660 DWORD buffer_size
= 0, count
= 0, i
= 0;
1661 GA_WTSINFOA
*info
= NULL
;
1662 WTS_SESSION_INFOA
*entries
= NULL
;
1663 GuestUserList
*item
= NULL
;
1664 GuestUser
*user
= NULL
;
1665 gpointer value
= NULL
;
1667 double login_time
= 0;
1669 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
1671 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
1672 for (i
= 0; i
< count
; ++i
) {
1675 if (WTSQuerySessionInformationA(
1677 entries
[i
].SessionId
,
1683 if (strlen(info
->UserName
) == 0) {
1684 WTSFreeMemory(info
);
1688 login
= info
->LogonTime
.QuadPart
;
1689 login
-= W32_FT_OFFSET
;
1690 login_time
= ((double)login
) / QGA_NANOSECONDS
;
1692 if (g_hash_table_contains(cache
, info
->UserName
)) {
1693 value
= g_hash_table_lookup(cache
, info
->UserName
);
1694 user
= (GuestUser
*)value
;
1695 if (user
->login_time
> login_time
) {
1696 user
->login_time
= login_time
;
1699 item
= g_new0(GuestUserList
, 1);
1700 item
->value
= g_new0(GuestUser
, 1);
1702 item
->value
->user
= g_strdup(info
->UserName
);
1703 item
->value
->domain
= g_strdup(info
->Domain
);
1704 item
->value
->has_domain
= true;
1706 item
->value
->login_time
= login_time
;
1708 g_hash_table_add(cache
, item
->value
->user
);
1711 head
= cur_item
= item
;
1713 cur_item
->next
= item
;
1718 WTSFreeMemory(info
);
1720 WTSFreeMemory(entries
);
1722 g_hash_table_destroy(cache
);
1725 error_setg(err
, QERR_UNSUPPORTED
);
1730 typedef struct _ga_matrix_lookup_t
{
1733 char const *version
;
1734 char const *version_id
;
1735 } ga_matrix_lookup_t
;
1737 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][8] = {
1739 /* Desktop editions */
1740 { 5, 0, "Microsoft Windows 2000", "2000"},
1741 { 5, 1, "Microsoft Windows XP", "xp"},
1742 { 6, 0, "Microsoft Windows Vista", "vista"},
1743 { 6, 1, "Microsoft Windows 7" "7"},
1744 { 6, 2, "Microsoft Windows 8", "8"},
1745 { 6, 3, "Microsoft Windows 8.1", "8.1"},
1746 {10, 0, "Microsoft Windows 10", "10"},
1749 /* Server editions */
1750 { 5, 2, "Microsoft Windows Server 2003", "2003"},
1751 { 6, 0, "Microsoft Windows Server 2008", "2008"},
1752 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
1753 { 6, 2, "Microsoft Windows Server 2012", "2012"},
1754 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
1755 {10, 0, "Microsoft Windows Server 2016", "2016"},
1761 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
1763 typedef NTSTATUS(WINAPI
* rtl_get_version_t
)(
1764 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
1766 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
1768 HMODULE module
= GetModuleHandle("ntdll");
1769 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
1771 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1772 "Failed to get address of RtlGetVersion");
1776 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
1777 rtl_get_version(info
);
1781 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
1783 DWORD major
= os_version
->dwMajorVersion
;
1784 DWORD minor
= os_version
->dwMinorVersion
;
1785 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
1786 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
1787 while (table
->version
!= NULL
) {
1788 if (major
== table
->major
&& minor
== table
->minor
) {
1790 return g_strdup(table
->version_id
);
1792 return g_strdup(table
->version
);
1797 slog("failed to lookup Windows version: major=%lu, minor=%lu",
1799 return g_strdup("N/A");
1802 static char *ga_get_win_product_name(Error
**errp
)
1806 char *result
= g_malloc0(size
);
1807 LONG err
= ERROR_SUCCESS
;
1809 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
1810 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
1812 if (err
!= ERROR_SUCCESS
) {
1813 error_setg_win32(errp
, err
, "failed to open registry key");
1817 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
1818 (LPBYTE
)result
, &size
);
1819 if (err
== ERROR_MORE_DATA
) {
1820 slog("ProductName longer than expected (%lu bytes), retrying",
1825 result
= g_malloc0(size
);
1826 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
1827 (LPBYTE
)result
, &size
);
1830 if (err
!= ERROR_SUCCESS
) {
1831 error_setg_win32(errp
, err
, "failed to retrive ProductName");
1842 static char *ga_get_current_arch(void)
1845 GetNativeSystemInfo(&info
);
1846 char *result
= NULL
;
1847 switch (info
.wProcessorArchitecture
) {
1848 case PROCESSOR_ARCHITECTURE_AMD64
:
1849 result
= g_strdup("x86_64");
1851 case PROCESSOR_ARCHITECTURE_ARM
:
1852 result
= g_strdup("arm");
1854 case PROCESSOR_ARCHITECTURE_IA64
:
1855 result
= g_strdup("ia64");
1857 case PROCESSOR_ARCHITECTURE_INTEL
:
1858 result
= g_strdup("x86");
1860 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
1862 slog("unknown processor architecture 0x%0x",
1863 info
.wProcessorArchitecture
);
1864 result
= g_strdup("unknown");
1870 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
1872 Error
*local_err
= NULL
;
1873 OSVERSIONINFOEXW os_version
= {0};
1878 ga_get_win_version(&os_version
, &local_err
);
1880 error_propagate(errp
, local_err
);
1884 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
1885 product_name
= ga_get_win_product_name(&local_err
);
1886 if (product_name
== NULL
) {
1887 error_propagate(errp
, local_err
);
1891 info
= g_new0(GuestOSInfo
, 1);
1893 info
->has_kernel_version
= true;
1894 info
->kernel_version
= g_strdup_printf("%lu.%lu",
1895 os_version
.dwMajorVersion
,
1896 os_version
.dwMinorVersion
);
1897 info
->has_kernel_release
= true;
1898 info
->kernel_release
= g_strdup_printf("%lu",
1899 os_version
.dwBuildNumber
);
1900 info
->has_machine
= true;
1901 info
->machine
= ga_get_current_arch();
1903 info
->has_id
= true;
1904 info
->id
= g_strdup("mswindows");
1905 info
->has_name
= true;
1906 info
->name
= g_strdup("Microsoft Windows");
1907 info
->has_pretty_name
= true;
1908 info
->pretty_name
= product_name
;
1909 info
->has_version
= true;
1910 info
->version
= ga_get_win_name(&os_version
, false);
1911 info
->has_version_id
= true;
1912 info
->version_id
= ga_get_win_name(&os_version
, true);
1913 info
->has_variant
= true;
1914 info
->variant
= g_strdup(server
? "server" : "client");
1915 info
->has_variant_id
= true;
1916 info
->variant_id
= g_strdup(server
? "server" : "client");