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
) {
1173 typedef NETIOAPI_API (WINAPI
*GetIfEntry2Func
)(PMIB_IF_ROW2 Row
);
1175 static int guest_get_network_stats(const char *name
,
1176 GuestNetworkInterfaceStat
*stats
)
1178 OSVERSIONINFO os_ver
;
1180 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1181 GetVersionEx(&os_ver
);
1182 if (os_ver
.dwMajorVersion
>= 6) {
1183 MIB_IF_ROW2 a_mid_ifrow
;
1184 GetIfEntry2Func getifentry2_ex
;
1186 HMODULE module
= GetModuleHandle("iphlpapi");
1187 PVOID func
= GetProcAddress(module
, "GetIfEntry2");
1193 getifentry2_ex
= (GetIfEntry2Func
)func
;
1194 if_index
= get_interface_index(name
);
1195 if (if_index
== (DWORD
)~0) {
1199 memset(&a_mid_ifrow
, 0, sizeof(a_mid_ifrow
));
1200 a_mid_ifrow
.InterfaceIndex
= if_index
;
1201 if (NO_ERROR
== getifentry2_ex(&a_mid_ifrow
)) {
1202 stats
->rx_bytes
= a_mid_ifrow
.InOctets
;
1203 stats
->rx_packets
= a_mid_ifrow
.InUcastPkts
;
1204 stats
->rx_errs
= a_mid_ifrow
.InErrors
;
1205 stats
->rx_dropped
= a_mid_ifrow
.InDiscards
;
1206 stats
->tx_bytes
= a_mid_ifrow
.OutOctets
;
1207 stats
->tx_packets
= a_mid_ifrow
.OutUcastPkts
;
1208 stats
->tx_errs
= a_mid_ifrow
.OutErrors
;
1209 stats
->tx_dropped
= a_mid_ifrow
.OutDiscards
;
1216 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1218 IP_ADAPTER_ADDRESSES
*adptr_addrs
, *addr
;
1219 IP_ADAPTER_UNICAST_ADDRESS
*ip_addr
= NULL
;
1220 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1221 GuestIpAddressList
*head_addr
, *cur_addr
;
1222 GuestNetworkInterfaceList
*info
;
1223 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1224 GuestIpAddressList
*address_item
= NULL
;
1225 unsigned char *mac_addr
;
1231 adptr_addrs
= guest_get_adapters_addresses(errp
);
1232 if (adptr_addrs
== NULL
) {
1236 /* Make WSA APIs available. */
1237 wsa_version
= MAKEWORD(2, 2);
1238 ret
= WSAStartup(wsa_version
, &wsa_data
);
1240 error_setg_win32(errp
, ret
, "failed socket startup");
1244 for (addr
= adptr_addrs
; addr
; addr
= addr
->Next
) {
1245 info
= g_malloc0(sizeof(*info
));
1247 if (cur_item
== NULL
) {
1248 head
= cur_item
= info
;
1250 cur_item
->next
= info
;
1254 info
->value
= g_malloc0(sizeof(*info
->value
));
1255 info
->value
->name
= guest_wctomb_dup(addr
->FriendlyName
);
1257 if (addr
->PhysicalAddressLength
!= 0) {
1258 mac_addr
= addr
->PhysicalAddress
;
1260 info
->value
->hardware_address
=
1261 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1262 (int) mac_addr
[0], (int) mac_addr
[1],
1263 (int) mac_addr
[2], (int) mac_addr
[3],
1264 (int) mac_addr
[4], (int) mac_addr
[5]);
1266 info
->value
->has_hardware_address
= true;
1271 for (ip_addr
= addr
->FirstUnicastAddress
;
1273 ip_addr
= ip_addr
->Next
) {
1274 addr_str
= guest_addr_to_str(ip_addr
, errp
);
1275 if (addr_str
== NULL
) {
1279 address_item
= g_malloc0(sizeof(*address_item
));
1282 head_addr
= cur_addr
= address_item
;
1284 cur_addr
->next
= address_item
;
1285 cur_addr
= address_item
;
1288 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1289 address_item
->value
->ip_address
= addr_str
;
1290 address_item
->value
->prefix
= guest_ip_prefix(ip_addr
);
1291 if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET
) {
1292 address_item
->value
->ip_address_type
=
1293 GUEST_IP_ADDRESS_TYPE_IPV4
;
1294 } else if (ip_addr
->Address
.lpSockaddr
->sa_family
== AF_INET6
) {
1295 address_item
->value
->ip_address_type
=
1296 GUEST_IP_ADDRESS_TYPE_IPV6
;
1300 info
->value
->has_ip_addresses
= true;
1301 info
->value
->ip_addresses
= head_addr
;
1303 if (!info
->value
->has_statistics
) {
1304 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1305 if (guest_get_network_stats(addr
->AdapterName
,
1306 interface_stat
) == -1) {
1307 info
->value
->has_statistics
= false;
1308 g_free(interface_stat
);
1310 info
->value
->statistics
= interface_stat
;
1311 info
->value
->has_statistics
= true;
1317 g_free(adptr_addrs
);
1321 int64_t qmp_guest_get_time(Error
**errp
)
1323 SYSTEMTIME ts
= {0};
1327 if (ts
.wYear
< 1601 || ts
.wYear
> 30827) {
1328 error_setg(errp
, "Failed to get time");
1332 if (!SystemTimeToFileTime(&ts
, &tf
)) {
1333 error_setg(errp
, "Failed to convert system time: %d", (int)GetLastError());
1337 return ((((int64_t)tf
.dwHighDateTime
<< 32) | tf
.dwLowDateTime
)
1338 - W32_FT_OFFSET
) * 100;
1341 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
1343 Error
*local_err
= NULL
;
1349 /* Unfortunately, Windows libraries don't provide an easy way to access
1352 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1354 * Instead, a workaround is to use the Windows win32tm command to
1355 * resync the time using the Windows Time service.
1360 HRESULT hr
= system("w32tm /resync /nowait");
1362 if (GetLastError() != 0) {
1363 strerror_s((LPTSTR
) & msg_buffer
, 0, errno
);
1364 error_setg(errp
, "system(...) failed: %s", (LPCTSTR
)msg_buffer
);
1365 } else if (hr
!= 0) {
1366 if (hr
== HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE
)) {
1367 error_setg(errp
, "Windows Time service not running on the "
1370 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1371 FORMAT_MESSAGE_FROM_SYSTEM
|
1372 FORMAT_MESSAGE_IGNORE_INSERTS
, NULL
,
1373 (DWORD
)hr
, MAKELANGID(LANG_NEUTRAL
,
1374 SUBLANG_DEFAULT
), (LPTSTR
) & msg_buffer
, 0,
1376 error_setg(errp
, "w32tm failed with error (0x%lx), couldn'"
1377 "t retrieve error message", hr
);
1379 error_setg(errp
, "w32tm failed with error (0x%lx): %s", hr
,
1380 (LPCTSTR
)msg_buffer
);
1381 LocalFree(msg_buffer
);
1384 } else if (!InternetGetConnectedState(&ret_flags
, 0)) {
1385 error_setg(errp
, "No internet connection on guest, sync not "
1391 /* Validate time passed by user. */
1392 if (time_ns
< 0 || time_ns
/ 100 > INT64_MAX
- W32_FT_OFFSET
) {
1393 error_setg(errp
, "Time %" PRId64
"is invalid", time_ns
);
1397 time
= time_ns
/ 100 + W32_FT_OFFSET
;
1399 tf
.dwLowDateTime
= (DWORD
) time
;
1400 tf
.dwHighDateTime
= (DWORD
) (time
>> 32);
1402 if (!FileTimeToSystemTime(&tf
, &ts
)) {
1403 error_setg(errp
, "Failed to convert system time %d",
1404 (int)GetLastError());
1408 acquire_privilege(SE_SYSTEMTIME_NAME
, &local_err
);
1410 error_propagate(errp
, local_err
);
1414 if (!SetSystemTime(&ts
)) {
1415 error_setg(errp
, "Failed to set time to guest: %d", (int)GetLastError());
1420 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1422 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi
, ptr
;
1424 GuestLogicalProcessorList
*head
, **link
;
1425 Error
*local_err
= NULL
;
1434 if ((GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) &&
1435 (GetLastError() == ERROR_INSUFFICIENT_BUFFER
) &&
1436 (length
> sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
))) {
1437 ptr
= pslpi
= g_malloc0(length
);
1438 if (GetLogicalProcessorInformation(pslpi
, &length
) == FALSE
) {
1439 error_setg(&local_err
, "Failed to get processor information: %d",
1440 (int)GetLastError());
1443 error_setg(&local_err
,
1444 "Failed to get processor information buffer length: %d",
1445 (int)GetLastError());
1448 while ((local_err
== NULL
) && (length
> 0)) {
1449 if (pslpi
->Relationship
== RelationProcessorCore
) {
1450 ULONG_PTR cpu_bits
= pslpi
->ProcessorMask
;
1452 while (cpu_bits
> 0) {
1453 if (!!(cpu_bits
& 1)) {
1454 GuestLogicalProcessor
*vcpu
;
1455 GuestLogicalProcessorList
*entry
;
1457 vcpu
= g_malloc0(sizeof *vcpu
);
1458 vcpu
->logical_id
= current
++;
1459 vcpu
->online
= true;
1460 vcpu
->has_can_offline
= true;
1462 entry
= g_malloc0(sizeof *entry
);
1463 entry
->value
= vcpu
;
1466 link
= &entry
->next
;
1471 length
-= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION
);
1472 pslpi
++; /* next entry */
1477 if (local_err
== NULL
) {
1481 /* there's no guest with zero VCPUs */
1482 error_setg(&local_err
, "Guest reported zero VCPUs");
1485 qapi_free_GuestLogicalProcessorList(head
);
1486 error_propagate(errp
, local_err
);
1490 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1492 error_setg(errp
, QERR_UNSUPPORTED
);
1497 get_net_error_message(gint error
)
1499 HMODULE module
= NULL
;
1500 gchar
*retval
= NULL
;
1501 wchar_t *msg
= NULL
;
1505 flags
= FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1506 FORMAT_MESSAGE_IGNORE_INSERTS
|
1507 FORMAT_MESSAGE_FROM_SYSTEM
;
1509 if (error
>= NERR_BASE
&& error
<= MAX_NERR
) {
1510 module
= LoadLibraryExW(L
"netmsg.dll", NULL
, LOAD_LIBRARY_AS_DATAFILE
);
1512 if (module
!= NULL
) {
1513 flags
|= FORMAT_MESSAGE_FROM_HMODULE
;
1517 FormatMessageW(flags
, module
, error
, 0, (LPWSTR
)&msg
, 0, NULL
);
1520 nchars
= wcslen(msg
);
1523 msg
[nchars
- 1] == L
'\n' &&
1524 msg
[nchars
- 2] == L
'\r') {
1525 msg
[nchars
- 2] = L
'\0';
1528 retval
= g_utf16_to_utf8(msg
, -1, NULL
, NULL
, NULL
);
1533 if (module
!= NULL
) {
1534 FreeLibrary(module
);
1540 void qmp_guest_set_user_password(const char *username
,
1541 const char *password
,
1546 char *rawpasswddata
= NULL
;
1547 size_t rawpasswdlen
;
1548 wchar_t *user
= NULL
, *wpass
= NULL
;
1549 USER_INFO_1003 pi1003
= { 0, };
1550 GError
*gerr
= NULL
;
1553 error_setg(errp
, QERR_UNSUPPORTED
);
1557 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1558 if (!rawpasswddata
) {
1561 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1562 rawpasswddata
[rawpasswdlen
] = '\0';
1564 user
= g_utf8_to_utf16(username
, -1, NULL
, NULL
, &gerr
);
1569 wpass
= g_utf8_to_utf16(rawpasswddata
, -1, NULL
, NULL
, &gerr
);
1574 pi1003
.usri1003_password
= wpass
;
1575 nas
= NetUserSetInfo(NULL
, user
,
1576 1003, (LPBYTE
)&pi1003
,
1579 if (nas
!= NERR_Success
) {
1580 gchar
*msg
= get_net_error_message(nas
);
1581 error_setg(errp
, "failed to set password: %s", msg
);
1587 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
1592 g_free(rawpasswddata
);
1595 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
1597 error_setg(errp
, QERR_UNSUPPORTED
);
1601 GuestMemoryBlockResponseList
*
1602 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
1604 error_setg(errp
, QERR_UNSUPPORTED
);
1608 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
1610 error_setg(errp
, QERR_UNSUPPORTED
);
1614 /* add unsupported commands to the blacklist */
1615 GList
*ga_command_blacklist_init(GList
*blacklist
)
1617 const char *list_unsupported
[] = {
1618 "guest-suspend-hybrid",
1620 "guest-get-memory-blocks", "guest-set-memory-blocks",
1621 "guest-get-memory-block-size",
1622 "guest-fsfreeze-freeze-list",
1624 char **p
= (char **)list_unsupported
;
1627 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1630 if (!vss_init(true)) {
1631 g_debug("vss_init failed, vss commands are going to be disabled");
1632 const char *list
[] = {
1633 "guest-get-fsinfo", "guest-fsfreeze-status",
1634 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL
};
1638 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
1645 /* register init/cleanup routines for stateful command groups */
1646 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1648 if (!vss_initialized()) {
1649 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1653 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1654 typedef struct _GA_WTSINFOA
{
1655 WTS_CONNECTSTATE_CLASS State
;
1657 DWORD IncomingBytes
;
1658 DWORD OutgoingBytes
;
1659 DWORD IncomingFrames
;
1660 DWORD OutgoingFrames
;
1661 DWORD IncomingCompressedBytes
;
1662 DWORD OutgoingCompressedBy
;
1663 CHAR WinStationName
[WINSTATIONNAME_LENGTH
];
1664 CHAR Domain
[DOMAIN_LENGTH
];
1665 CHAR UserName
[USERNAME_LENGTH
+ 1];
1666 LARGE_INTEGER ConnectTime
;
1667 LARGE_INTEGER DisconnectTime
;
1668 LARGE_INTEGER LastInputTime
;
1669 LARGE_INTEGER LogonTime
;
1670 LARGE_INTEGER CurrentTime
;
1674 GuestUserList
*qmp_guest_get_users(Error
**err
)
1676 #if (_WIN32_WINNT >= 0x0600)
1677 #define QGA_NANOSECONDS 10000000
1679 GHashTable
*cache
= NULL
;
1680 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
1682 DWORD buffer_size
= 0, count
= 0, i
= 0;
1683 GA_WTSINFOA
*info
= NULL
;
1684 WTS_SESSION_INFOA
*entries
= NULL
;
1685 GuestUserList
*item
= NULL
;
1686 GuestUser
*user
= NULL
;
1687 gpointer value
= NULL
;
1689 double login_time
= 0;
1691 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
1693 if (WTSEnumerateSessionsA(NULL
, 0, 1, &entries
, &count
)) {
1694 for (i
= 0; i
< count
; ++i
) {
1697 if (WTSQuerySessionInformationA(
1699 entries
[i
].SessionId
,
1705 if (strlen(info
->UserName
) == 0) {
1706 WTSFreeMemory(info
);
1710 login
= info
->LogonTime
.QuadPart
;
1711 login
-= W32_FT_OFFSET
;
1712 login_time
= ((double)login
) / QGA_NANOSECONDS
;
1714 if (g_hash_table_contains(cache
, info
->UserName
)) {
1715 value
= g_hash_table_lookup(cache
, info
->UserName
);
1716 user
= (GuestUser
*)value
;
1717 if (user
->login_time
> login_time
) {
1718 user
->login_time
= login_time
;
1721 item
= g_new0(GuestUserList
, 1);
1722 item
->value
= g_new0(GuestUser
, 1);
1724 item
->value
->user
= g_strdup(info
->UserName
);
1725 item
->value
->domain
= g_strdup(info
->Domain
);
1726 item
->value
->has_domain
= true;
1728 item
->value
->login_time
= login_time
;
1730 g_hash_table_add(cache
, item
->value
->user
);
1733 head
= cur_item
= item
;
1735 cur_item
->next
= item
;
1740 WTSFreeMemory(info
);
1742 WTSFreeMemory(entries
);
1744 g_hash_table_destroy(cache
);
1747 error_setg(err
, QERR_UNSUPPORTED
);
1752 typedef struct _ga_matrix_lookup_t
{
1755 char const *version
;
1756 char const *version_id
;
1757 } ga_matrix_lookup_t
;
1759 static ga_matrix_lookup_t
const WIN_VERSION_MATRIX
[2][8] = {
1761 /* Desktop editions */
1762 { 5, 0, "Microsoft Windows 2000", "2000"},
1763 { 5, 1, "Microsoft Windows XP", "xp"},
1764 { 6, 0, "Microsoft Windows Vista", "vista"},
1765 { 6, 1, "Microsoft Windows 7" "7"},
1766 { 6, 2, "Microsoft Windows 8", "8"},
1767 { 6, 3, "Microsoft Windows 8.1", "8.1"},
1768 {10, 0, "Microsoft Windows 10", "10"},
1771 /* Server editions */
1772 { 5, 2, "Microsoft Windows Server 2003", "2003"},
1773 { 6, 0, "Microsoft Windows Server 2008", "2008"},
1774 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
1775 { 6, 2, "Microsoft Windows Server 2012", "2012"},
1776 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
1777 {10, 0, "Microsoft Windows Server 2016", "2016"},
1783 static void ga_get_win_version(RTL_OSVERSIONINFOEXW
*info
, Error
**errp
)
1785 typedef NTSTATUS(WINAPI
* rtl_get_version_t
)(
1786 RTL_OSVERSIONINFOEXW
*os_version_info_ex
);
1788 info
->dwOSVersionInfoSize
= sizeof(RTL_OSVERSIONINFOEXW
);
1790 HMODULE module
= GetModuleHandle("ntdll");
1791 PVOID fun
= GetProcAddress(module
, "RtlGetVersion");
1793 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
1794 "Failed to get address of RtlGetVersion");
1798 rtl_get_version_t rtl_get_version
= (rtl_get_version_t
)fun
;
1799 rtl_get_version(info
);
1803 static char *ga_get_win_name(OSVERSIONINFOEXW
const *os_version
, bool id
)
1805 DWORD major
= os_version
->dwMajorVersion
;
1806 DWORD minor
= os_version
->dwMinorVersion
;
1807 int tbl_idx
= (os_version
->wProductType
!= VER_NT_WORKSTATION
);
1808 ga_matrix_lookup_t
const *table
= WIN_VERSION_MATRIX
[tbl_idx
];
1809 while (table
->version
!= NULL
) {
1810 if (major
== table
->major
&& minor
== table
->minor
) {
1812 return g_strdup(table
->version_id
);
1814 return g_strdup(table
->version
);
1819 slog("failed to lookup Windows version: major=%lu, minor=%lu",
1821 return g_strdup("N/A");
1824 static char *ga_get_win_product_name(Error
**errp
)
1828 char *result
= g_malloc0(size
);
1829 LONG err
= ERROR_SUCCESS
;
1831 err
= RegOpenKeyA(HKEY_LOCAL_MACHINE
,
1832 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
1834 if (err
!= ERROR_SUCCESS
) {
1835 error_setg_win32(errp
, err
, "failed to open registry key");
1839 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
1840 (LPBYTE
)result
, &size
);
1841 if (err
== ERROR_MORE_DATA
) {
1842 slog("ProductName longer than expected (%lu bytes), retrying",
1847 result
= g_malloc0(size
);
1848 err
= RegQueryValueExA(key
, "ProductName", NULL
, NULL
,
1849 (LPBYTE
)result
, &size
);
1852 if (err
!= ERROR_SUCCESS
) {
1853 error_setg_win32(errp
, err
, "failed to retrive ProductName");
1864 static char *ga_get_current_arch(void)
1867 GetNativeSystemInfo(&info
);
1868 char *result
= NULL
;
1869 switch (info
.wProcessorArchitecture
) {
1870 case PROCESSOR_ARCHITECTURE_AMD64
:
1871 result
= g_strdup("x86_64");
1873 case PROCESSOR_ARCHITECTURE_ARM
:
1874 result
= g_strdup("arm");
1876 case PROCESSOR_ARCHITECTURE_IA64
:
1877 result
= g_strdup("ia64");
1879 case PROCESSOR_ARCHITECTURE_INTEL
:
1880 result
= g_strdup("x86");
1882 case PROCESSOR_ARCHITECTURE_UNKNOWN
:
1884 slog("unknown processor architecture 0x%0x",
1885 info
.wProcessorArchitecture
);
1886 result
= g_strdup("unknown");
1892 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
1894 Error
*local_err
= NULL
;
1895 OSVERSIONINFOEXW os_version
= {0};
1900 ga_get_win_version(&os_version
, &local_err
);
1902 error_propagate(errp
, local_err
);
1906 server
= os_version
.wProductType
!= VER_NT_WORKSTATION
;
1907 product_name
= ga_get_win_product_name(&local_err
);
1908 if (product_name
== NULL
) {
1909 error_propagate(errp
, local_err
);
1913 info
= g_new0(GuestOSInfo
, 1);
1915 info
->has_kernel_version
= true;
1916 info
->kernel_version
= g_strdup_printf("%lu.%lu",
1917 os_version
.dwMajorVersion
,
1918 os_version
.dwMinorVersion
);
1919 info
->has_kernel_release
= true;
1920 info
->kernel_release
= g_strdup_printf("%lu",
1921 os_version
.dwBuildNumber
);
1922 info
->has_machine
= true;
1923 info
->machine
= ga_get_current_arch();
1925 info
->has_id
= true;
1926 info
->id
= g_strdup("mswindows");
1927 info
->has_name
= true;
1928 info
->name
= g_strdup("Microsoft Windows");
1929 info
->has_pretty_name
= true;
1930 info
->pretty_name
= product_name
;
1931 info
->has_version
= true;
1932 info
->version
= ga_get_win_name(&os_version
, false);
1933 info
->has_version_id
= true;
1934 info
->version_id
= ga_get_win_name(&os_version
, true);
1935 info
->has_variant
= true;
1936 info
->variant
= g_strdup(server
? "server" : "client");
1937 info
->has_variant_id
= true;
1938 info
->variant_id
= g_strdup(server
? "server" : "client");