2 * QEMU Guest Agent win32-specific command implementations
4 * Copyright IBM Corp. 2012
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
18 #include "qemu/osdep.h"
25 #ifdef CONFIG_QGA_NTDDSCSI
35 #include "guest-agent-core.h"
36 #include "vss-win32.h"
37 #include "qga-qapi-commands.h"
38 #include "qapi/error.h"
39 #include "qapi/qmp/qerror.h"
40 #include "qemu/queue.h"
41 #include "qemu/host-utils.h"
42 #include "qemu/base64.h"
44 #ifndef SHTDN_REASON_FLAG_PLANNED
45 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
48 /* multiple of 100 nanoseconds elapsed between windows baseline
49 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
50 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
51 (365 * (1970 - 1601) + \
52 (1970 - 1601) / 4 - 3))
54 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
56 typedef struct GuestFileHandle {
59 QTAILQ_ENTRY(GuestFileHandle) next;
63 QTAILQ_HEAD(, GuestFileHandle) filehandles;
64 } guest_file_state = {
65 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
68 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
70 typedef struct OpenFlags {
73 DWORD creation_disposition;
75 static OpenFlags guest_file_open_modes[] = {
76 {"r", GENERIC_READ, OPEN_EXISTING},
77 {"rb", GENERIC_READ, OPEN_EXISTING},
78 {"w", GENERIC_WRITE, CREATE_ALWAYS},
79 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
80 {"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
81 {"r+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
82 {"rb+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
83 {"r+b", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
84 {"w+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
85 {"wb+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
86 {"w+b", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
87 {"a+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
88 {"ab+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
89 {"a+b", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS }
92 #define debug_error(msg) do { \
93 char *suffix = g_win32_error_message(GetLastError()); \
94 g_debug("%s: %s", (msg), suffix); \
98 static OpenFlags *find_open_flag(const char *mode_str)
103 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
104 OpenFlags *flags = guest_file_open_modes + mode;
106 if (strcmp(flags->forms, mode_str) == 0) {
111 error_setg(errp, "invalid file open mode '%s'", mode_str);
115 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
117 GuestFileHandle *gfh;
120 handle = ga_get_fd_handle(ga_state, errp);
124 gfh = g_new0(GuestFileHandle, 1);
127 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
132 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
134 GuestFileHandle *gfh;
135 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
140 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
144 static void handle_set_nonblocking(HANDLE fh)
146 DWORD file_type, pipe_state;
147 file_type = GetFileType(fh);
148 if (file_type != FILE_TYPE_PIPE) {
151 /* If file_type == FILE_TYPE_PIPE, according to MSDN
152 * the specified file is socket or named pipe */
153 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
154 NULL, NULL, NULL, 0)) {
157 /* The fd is named pipe fd */
158 if (pipe_state & PIPE_NOWAIT) {
162 pipe_state |= PIPE_NOWAIT;
163 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
166 int64_t qmp_guest_file_open(const char *path, bool has_mode,
167 const char *mode, Error **errp)
171 HANDLE templ_file = NULL;
172 DWORD share_mode = FILE_SHARE_READ;
173 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
174 LPSECURITY_ATTRIBUTES sa_attr = NULL;
175 OpenFlags *guest_flags;
177 wchar_t *w_path = NULL;
182 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
183 guest_flags = find_open_flag(mode);
184 if (guest_flags == NULL) {
185 error_setg(errp, "invalid file open mode");
189 w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
194 fh = CreateFileW(w_path, guest_flags->desired_access, share_mode, sa_attr,
195 guest_flags->creation_disposition, flags_and_attr,
197 if (fh == INVALID_HANDLE_VALUE) {
198 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
203 /* set fd non-blocking to avoid common use cases (like reading from a
204 * named pipe) from hanging the agent
206 handle_set_nonblocking(fh);
208 fd = guest_file_handle_add(fh, errp);
211 error_setg(errp, "failed to add handle to qmp handle table");
215 slog("guest-file-open, handle: % " PRId64, fd);
219 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
226 void qmp_guest_file_close(int64_t handle, Error **errp)
229 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
230 slog("guest-file-close called, handle: %" PRId64, handle);
234 ret = CloseHandle(gfh->fh);
236 error_setg_win32(errp, GetLastError(), "failed close handle");
240 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
244 static void acquire_privilege(const char *name, Error **errp)
247 TOKEN_PRIVILEGES priv;
248 Error *local_err = NULL;
250 if (OpenProcessToken(GetCurrentProcess(),
251 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
253 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
254 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
255 "no luid for requested privilege");
259 priv.PrivilegeCount = 1;
260 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
262 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
263 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
264 "unable to acquire requested privilege");
269 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
270 "failed to open privilege token");
277 error_propagate(errp, local_err);
280 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
283 Error *local_err = NULL;
285 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
287 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
288 "failed to dispatch asynchronous command");
289 error_propagate(errp, local_err);
293 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
295 Error *local_err = NULL;
296 UINT shutdown_flag = EWX_FORCE;
298 slog("guest-shutdown called, mode: %s", mode);
300 if (!has_mode || strcmp(mode, "powerdown") == 0) {
301 shutdown_flag |= EWX_POWEROFF;
302 } else if (strcmp(mode, "halt") == 0) {
303 shutdown_flag |= EWX_SHUTDOWN;
304 } else if (strcmp(mode, "reboot") == 0) {
305 shutdown_flag |= EWX_REBOOT;
307 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
308 "halt|powerdown|reboot");
312 /* Request a shutdown privilege, but try to shut down the system
314 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
316 error_propagate(errp, local_err);
320 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
321 slog("guest-shutdown failed: %lu", GetLastError());
322 error_setg(errp, QERR_UNDEFINED_ERROR);
326 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
327 int64_t count, Error **errp)
329 GuestFileRead *read_data = NULL;
334 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
340 count = QGA_READ_COUNT_DEFAULT;
341 } else if (count < 0 || count >= UINT32_MAX) {
342 error_setg(errp, "value '%" PRId64
343 "' is invalid for argument count", count);
348 buf = g_malloc0(count+1);
349 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
351 error_setg_win32(errp, GetLastError(), "failed to read file");
352 slog("guest-file-read failed, handle %" PRId64, handle);
355 read_data = g_new0(GuestFileRead, 1);
356 read_data->count = (size_t)read_count;
357 read_data->eof = read_count == 0;
359 if (read_count != 0) {
360 read_data->buf_b64 = g_base64_encode(buf, read_count);
368 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
369 bool has_count, int64_t count,
372 GuestFileWrite *write_data = NULL;
377 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
384 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
391 } else if (count < 0 || count > buf_len) {
392 error_setg(errp, "value '%" PRId64
393 "' is invalid for argument count", count);
397 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
399 error_setg_win32(errp, GetLastError(), "failed to write to file");
400 slog("guest-file-write-failed, handle: %" PRId64, handle);
402 write_data = g_new0(GuestFileWrite, 1);
403 write_data->count = (size_t) write_count;
411 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
412 GuestFileWhence *whence_code,
415 GuestFileHandle *gfh;
416 GuestFileSeek *seek_data;
418 LARGE_INTEGER new_pos, off_pos;
419 off_pos.QuadPart = offset;
424 gfh = guest_file_handle_find(handle, errp);
429 /* We stupidly exposed 'whence':'int' in our qapi */
430 whence = ga_parse_whence(whence_code, &err);
432 error_propagate(errp, err);
437 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
439 error_setg_win32(errp, GetLastError(), "failed to seek file");
442 seek_data = g_new0(GuestFileSeek, 1);
443 seek_data->position = new_pos.QuadPart;
447 void qmp_guest_file_flush(int64_t handle, Error **errp)
450 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
456 if (!FlushFileBuffers(fh)) {
457 error_setg_win32(errp, GetLastError(), "failed to flush file");
461 #ifdef CONFIG_QGA_NTDDSCSI
463 static STORAGE_BUS_TYPE win2qemu[] = {
464 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
465 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
466 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
467 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
468 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
469 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
470 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
471 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
472 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
473 #if (_WIN32_WINNT >= 0x0600)
474 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
475 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
476 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
477 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
478 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
480 #if (_WIN32_WINNT >= 0x0601)
481 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
482 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
486 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
488 if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
489 return GUEST_DISK_BUS_TYPE_UNKNOWN;
491 return win2qemu[(int)bus];
494 /* XXX: The following function is BROKEN!
496 * It does not work and probably has never worked. When we query for list of
497 * disks we get cryptic names like "\Device\0000001d" instead of
498 * "\PhysicalDriveX" or "\HarddiskX". Whether the names can be translated one
499 * way or the other for comparison is an open question.
501 * When we query volume names (the original version) we are able to match those
502 * but then the property queries report error "Invalid function". (duh!)
506 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME,
507 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2,
508 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
510 DEFINE_GUID(GUID_DEVINTERFACE_DISK,
511 0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2,
512 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
515 static GuestPCIAddress *get_pci_info(char *guid, Error **errp)
518 SP_DEVINFO_DATA dev_info_data;
521 char dev_name[MAX_PATH];
523 GuestPCIAddress *pci = NULL;
525 bool partial_pci = false;
526 pci = g_malloc0(sizeof(*pci));
532 if (g_str_has_prefix(guid, "\\\\.\\") ||
533 g_str_has_prefix(guid, "\\\\?\\")) {
534 name = g_strdup(guid + 4);
536 name = g_strdup(guid);
539 if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {
540 error_setg_win32(errp, GetLastError(), "failed to get dos device name");
544 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
545 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
546 if (dev_info == INVALID_HANDLE_VALUE) {
547 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
551 g_debug("enumerating devices");
552 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
553 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
554 DWORD addr, bus, slot, data, size2;
556 while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
557 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
558 &data, (PBYTE)buffer, size,
560 size = MAX(size, size2);
561 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
563 /* Double the size to avoid problems on
564 * W2k MBCS systems per KB 888609.
565 * https://support.microsoft.com/en-us/kb/259695 */
566 buffer = g_malloc(size * 2);
568 error_setg_win32(errp, GetLastError(),
569 "failed to get device name");
574 if (g_strcmp0(buffer, dev_name)) {
577 g_debug("found device %s", dev_name);
579 /* There is no need to allocate buffer in the next functions. The size
580 * is known and ULONG according to
581 * https://support.microsoft.com/en-us/kb/253232
582 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
584 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
585 SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {
586 debug_error("failed to get bus");
591 /* The function retrieves the device's address. This value will be
592 * transformed into device function and number */
593 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
594 SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {
595 debug_error("failed to get address");
600 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
601 * This number is typically a user-perceived slot number. */
602 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
603 SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {
604 debug_error("failed to get slot");
609 /* SetupApi gives us the same information as driver with
610 * IoGetDeviceProperty. According to Microsoft
611 * https://support.microsoft.com/en-us/kb/253232
612 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
613 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
614 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
622 func = ((int) addr == -1) ? -1 : addr & 0x0000FFFF;
623 dev = ((int) addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
625 pci->slot = (int) slot;
626 pci->function = func;
627 pci->bus = (int) bus;
633 SetupDiDestroyDeviceInfoList(dev_info);
640 static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
643 STORAGE_PROPERTY_QUERY query;
644 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
646 ULONG size = sizeof(buf);
649 query.PropertyId = StorageDeviceProperty;
650 query.QueryType = PropertyStandardQuery;
652 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
653 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
654 size, &received, NULL)) {
655 error_setg_win32(errp, GetLastError(), "failed to get bus type");
658 disk->bus_type = find_bus_type(dev_desc->BusType);
659 g_debug("bus type %d", disk->bus_type);
661 /* Query once more. Now with long enough buffer. */
662 size = dev_desc->Size;
663 dev_desc = g_malloc0(size);
664 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
665 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
666 size, &received, NULL)) {
667 error_setg_win32(errp, GetLastError(), "failed to get serial number");
668 g_debug("failed to get serial number");
671 if (dev_desc->SerialNumberOffset > 0) {
675 if (dev_desc->SerialNumberOffset >= received) {
676 error_setg(errp, "failed to get serial number: offset outside the buffer");
677 g_debug("serial number offset outside the buffer");
680 serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
681 len = received - dev_desc->SerialNumberOffset;
682 g_debug("serial number \"%s\"", serial);
684 disk->serial = g_strndup(serial, len);
685 disk->has_serial = true;
694 static void get_single_disk_info(GuestDiskAddress *disk, Error **errp)
696 SCSI_ADDRESS addr, *scsi_ad;
699 Error *local_err = NULL;
703 g_debug("getting disk info for: %s", disk->dev);
704 disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
706 if (disk_h == INVALID_HANDLE_VALUE) {
707 error_setg_win32(errp, GetLastError(), "failed to open disk");
711 get_disk_properties(disk_h, disk, &local_err);
713 error_propagate(errp, local_err);
717 g_debug("bus type %d", disk->bus_type);
718 /* always set pci_controller as required by schema. get_pci_info() should
719 * report -1 values for non-PCI buses rather than fail. fail the command
720 * if that doesn't hold since that suggests some other unexpected
723 disk->pci_controller = get_pci_info(disk->dev, &local_err);
725 error_propagate(errp, local_err);
728 if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
729 || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
730 || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
731 #if (_WIN32_WINNT >= 0x0600)
732 /* This bus type is not supported before Windows Server 2003 SP1 */
733 || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
736 /* We are able to use the same ioctls for different bus types
737 * according to Microsoft docs
738 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
739 g_debug("getting pci-controller info");
740 if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
741 sizeof(SCSI_ADDRESS), &len, NULL)) {
742 disk->unit = addr.Lun;
743 disk->target = addr.TargetId;
744 disk->bus = addr.PathId;
746 /* We do not set error in this case, because we still have enough
747 * information about volume. */
755 /* VSS provider works with volumes, thus there is no difference if
756 * the volume consist of spanned disks. Info about the first disk in the
757 * volume is returned for the spanned disk group (LVM) */
758 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
760 Error *local_err = NULL;
761 GuestDiskAddressList *list = NULL, *cur_item = NULL;
762 GuestDiskAddress *disk = NULL;
766 PVOLUME_DISK_EXTENTS extents = NULL;
768 /* strip final backslash */
769 char *name = g_strdup(guid);
770 if (g_str_has_suffix(name, "\\")) {
771 name[strlen(name) - 1] = 0;
774 g_debug("opening %s", name);
775 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
777 if (vol_h == INVALID_HANDLE_VALUE) {
778 error_setg_win32(errp, GetLastError(), "failed to open volume");
782 /* Get list of extents */
783 g_debug("getting disk extents");
784 size = sizeof(VOLUME_DISK_EXTENTS);
785 extents = g_malloc0(size);
786 if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
787 0, extents, size, NULL, NULL)) {
788 DWORD last_err = GetLastError();
789 if (last_err == ERROR_MORE_DATA) {
790 /* Try once more with big enough buffer */
791 size = sizeof(VOLUME_DISK_EXTENTS)
792 + extents->NumberOfDiskExtents*sizeof(DISK_EXTENT);
794 extents = g_malloc0(size);
795 if (!DeviceIoControl(
796 vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
797 0, extents, size, NULL, NULL)) {
798 error_setg_win32(errp, GetLastError(),
799 "failed to get disk extents");
802 } else if (last_err == ERROR_INVALID_FUNCTION) {
803 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
804 g_debug("volume not on disk");
805 disk = g_malloc0(sizeof(GuestDiskAddress));
806 disk->has_dev = true;
807 disk->dev = g_strdup(name);
808 get_single_disk_info(disk, &local_err);
810 g_debug("failed to get disk info, ignoring error: %s",
811 error_get_pretty(local_err));
812 error_free(local_err);
815 list = g_malloc0(sizeof(*list));
821 error_setg_win32(errp, GetLastError(),
822 "failed to get disk extents");
826 g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
828 /* Go through each extent */
829 for (i = 0; i < extents->NumberOfDiskExtents; i++) {
830 disk = g_malloc0(sizeof(GuestDiskAddress));
832 /* Disk numbers directly correspond to numbers used in UNCs
834 * See documentation for DISK_EXTENT:
835 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
837 * See also Naming Files, Paths and Namespaces:
838 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
840 disk->has_dev = true;
841 disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
842 extents->Extents[i].DiskNumber);
844 get_single_disk_info(disk, &local_err);
846 error_propagate(errp, local_err);
849 cur_item = g_malloc0(sizeof(*list));
850 cur_item->value = disk;
852 cur_item->next = list;
858 qapi_free_GuestDiskAddress(disk);
867 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
872 #endif /* CONFIG_QGA_NTDDSCSI */
874 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
877 char mnt, *mnt_point;
879 char vol_info[MAX_PATH+1];
881 uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
882 GuestFilesystemInfo *fs = NULL;
884 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
885 if (GetLastError() != ERROR_MORE_DATA) {
886 error_setg_win32(errp, GetLastError(), "failed to get volume name");
890 mnt_point = g_malloc(info_size + 1);
891 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
893 error_setg_win32(errp, GetLastError(), "failed to get volume name");
897 len = strlen(mnt_point);
898 mnt_point[len] = '\\';
899 mnt_point[len+1] = 0;
900 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
901 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
902 if (GetLastError() != ERROR_NOT_READY) {
903 error_setg_win32(errp, GetLastError(), "failed to get volume info");
908 fs_name[sizeof(fs_name) - 1] = 0;
909 fs = g_malloc(sizeof(*fs));
910 fs->name = g_strdup(guid);
911 fs->has_total_bytes = false;
912 fs->has_used_bytes = false;
914 fs->mountpoint = g_strdup("System Reserved");
916 fs->mountpoint = g_strndup(mnt_point, len);
917 if (GetDiskFreeSpaceEx(fs->mountpoint,
918 (PULARGE_INTEGER) & i64FreeBytesToCaller,
919 (PULARGE_INTEGER) & i64TotalBytes,
920 (PULARGE_INTEGER) & i64FreeBytes)) {
921 fs->used_bytes = i64TotalBytes - i64FreeBytes;
922 fs->total_bytes = i64TotalBytes;
923 fs->has_total_bytes = true;
924 fs->has_used_bytes = true;
927 fs->type = g_strdup(fs_name);
928 fs->disk = build_guest_disk_info(guid, errp);
934 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
937 GuestFilesystemInfoList *new, *ret = NULL;
940 vol_h = FindFirstVolume(guid, sizeof(guid));
941 if (vol_h == INVALID_HANDLE_VALUE) {
942 error_setg_win32(errp, GetLastError(), "failed to find any volume");
947 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
951 new = g_malloc(sizeof(*ret));
955 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
957 if (GetLastError() != ERROR_NO_MORE_FILES) {
958 error_setg_win32(errp, GetLastError(), "failed to find next volume");
961 FindVolumeClose(vol_h);
966 * Return status of freeze/thaw
968 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
970 if (!vss_initialized()) {
971 error_setg(errp, QERR_UNSUPPORTED);
975 if (ga_is_frozen(ga_state)) {
976 return GUEST_FSFREEZE_STATUS_FROZEN;
979 return GUEST_FSFREEZE_STATUS_THAWED;
983 * Freeze local file systems using Volume Shadow-copy Service.
984 * The frozen state is limited for up to 10 seconds by VSS.
986 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
988 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
991 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
992 strList *mountpoints,
996 Error *local_err = NULL;
998 if (!vss_initialized()) {
999 error_setg(errp, QERR_UNSUPPORTED);
1003 slog("guest-fsfreeze called");
1005 /* cannot risk guest agent blocking itself on a write in this state */
1006 ga_set_frozen(ga_state);
1008 qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
1010 error_propagate(errp, local_err);
1018 qmp_guest_fsfreeze_thaw(&local_err);
1020 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
1021 error_free(local_err);
1027 * Thaw local file systems using Volume Shadow-copy Service.
1029 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1033 if (!vss_initialized()) {
1034 error_setg(errp, QERR_UNSUPPORTED);
1038 qga_vss_fsfreeze(&i, false, NULL, errp);
1040 ga_unset_frozen(ga_state);
1044 static void guest_fsfreeze_cleanup(void)
1048 if (!vss_initialized()) {
1052 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1053 qmp_guest_fsfreeze_thaw(&err);
1055 slog("failed to clean up frozen filesystems: %s",
1056 error_get_pretty(err));
1065 * Walk list of mounted file systems in the guest, and discard unused
1068 GuestFilesystemTrimResponse *
1069 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1071 GuestFilesystemTrimResponse *resp;
1073 WCHAR guid[MAX_PATH] = L"";
1077 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
1078 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1079 GetVersionEx(&osvi);
1080 win8_or_later = (osvi.dwMajorVersion > 6 ||
1081 ((osvi.dwMajorVersion == 6) &&
1082 (osvi.dwMinorVersion >= 2)));
1083 if (!win8_or_later) {
1084 error_setg(errp, "fstrim is only supported for Win8+");
1088 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
1089 if (handle == INVALID_HANDLE_VALUE) {
1090 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1094 resp = g_new0(GuestFilesystemTrimResponse, 1);
1097 GuestFilesystemTrimResult *res;
1098 GuestFilesystemTrimResultList *list;
1100 DWORD char_count = 0;
1102 GError *gerr = NULL;
1105 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1107 if (GetLastError() != ERROR_MORE_DATA) {
1110 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1114 uc_path = g_malloc(sizeof(WCHAR) * char_count);
1115 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1116 &char_count) || !*uc_path) {
1117 /* strange, but this condition could be faced even with size == 2 */
1122 res = g_new0(GuestFilesystemTrimResult, 1);
1124 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1129 res->has_error = true;
1130 res->error = g_strdup(gerr->message);
1137 list = g_new0(GuestFilesystemTrimResultList, 1);
1139 list->next = resp->paths;
1143 memset(argv, 0, sizeof(argv));
1144 argv[0] = (gchar *)"defrag.exe";
1145 argv[1] = (gchar *)"/L";
1148 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1149 &out /* stdout */, NULL /* stdin */,
1151 res->has_error = true;
1152 res->error = g_strdup(gerr->message);
1155 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1156 Error is reported in the output with something like
1157 (x89000020) etc code in the stdout */
1160 gchar **lines = g_strsplit(out, "\r\n", 0);
1163 for (i = 0; lines[i] != NULL; i++) {
1164 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1167 res->has_error = true;
1168 res->error = g_strdup(lines[i]);
1173 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1175 FindVolumeClose(handle);
1180 GUEST_SUSPEND_MODE_DISK,
1181 GUEST_SUSPEND_MODE_RAM
1184 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
1186 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1187 Error *local_err = NULL;
1189 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1190 if (!GetPwrCapabilities(&sys_pwr_caps)) {
1191 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1192 "failed to determine guest suspend capabilities");
1197 case GUEST_SUSPEND_MODE_DISK:
1198 if (!sys_pwr_caps.SystemS4) {
1199 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1200 "suspend-to-disk not supported by OS");
1203 case GUEST_SUSPEND_MODE_RAM:
1204 if (!sys_pwr_caps.SystemS3) {
1205 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1206 "suspend-to-ram not supported by OS");
1210 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
1211 "GuestSuspendMode");
1215 error_propagate(errp, local_err);
1218 static DWORD WINAPI do_suspend(LPVOID opaque)
1220 GuestSuspendMode *mode = opaque;
1223 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1224 slog("failed to suspend guest, %lu", GetLastError());
1231 void qmp_guest_suspend_disk(Error **errp)
1233 Error *local_err = NULL;
1234 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1236 *mode = GUEST_SUSPEND_MODE_DISK;
1237 check_suspend_mode(*mode, &local_err);
1238 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1239 execute_async(do_suspend, mode, &local_err);
1242 error_propagate(errp, local_err);
1247 void qmp_guest_suspend_ram(Error **errp)
1249 Error *local_err = NULL;
1250 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1252 *mode = GUEST_SUSPEND_MODE_RAM;
1253 check_suspend_mode(*mode, &local_err);
1254 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1255 execute_async(do_suspend, mode, &local_err);
1258 error_propagate(errp, local_err);
1263 void qmp_guest_suspend_hybrid(Error **errp)
1265 error_setg(errp, QERR_UNSUPPORTED);
1268 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1270 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1271 ULONG adptr_addrs_len = 0;
1274 /* Call the first time to get the adptr_addrs_len. */
1275 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1276 NULL, adptr_addrs, &adptr_addrs_len);
1278 adptr_addrs = g_malloc(adptr_addrs_len);
1279 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1280 NULL, adptr_addrs, &adptr_addrs_len);
1281 if (ret != ERROR_SUCCESS) {
1282 error_setg_win32(errp, ret, "failed to get adapters addresses");
1283 g_free(adptr_addrs);
1289 static char *guest_wctomb_dup(WCHAR *wstr)
1294 i = wcslen(wstr) + 1;
1296 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
1297 wstr, -1, str, i, NULL, NULL);
1301 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1304 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1308 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1309 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1310 len = sizeof(addr_str);
1311 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1312 ip_addr->Address.iSockaddrLength,
1317 error_setg_win32(errp, WSAGetLastError(),
1318 "failed address presentation form conversion");
1321 return g_strdup(addr_str);
1326 #if (_WIN32_WINNT >= 0x0600)
1327 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1329 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1330 * field to obtain the prefix.
1332 return ip_addr->OnLinkPrefixLength;
1335 /* When using the Windows XP and 2003 build environment, do the best we can to
1336 * figure out the prefix.
1338 static IP_ADAPTER_INFO *guest_get_adapters_info(void)
1340 IP_ADAPTER_INFO *adptr_info = NULL;
1341 ULONG adptr_info_len = 0;
1344 /* Call the first time to get the adptr_info_len. */
1345 GetAdaptersInfo(adptr_info, &adptr_info_len);
1347 adptr_info = g_malloc(adptr_info_len);
1348 ret = GetAdaptersInfo(adptr_info, &adptr_info_len);
1349 if (ret != ERROR_SUCCESS) {
1356 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1358 int64_t prefix = -1; /* Use for AF_INET6 and unknown/undetermined values. */
1359 IP_ADAPTER_INFO *adptr_info, *info;
1363 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
1366 adptr_info = guest_get_adapters_info();
1367 if (adptr_info == NULL) {
1371 /* Match up the passed in ip_addr with one found in adaptr_info.
1372 * The matching one in adptr_info will have the netmask.
1374 p = &((struct sockaddr_in *)ip_addr->Address.lpSockaddr)->sin_addr;
1375 for (info = adptr_info; info; info = info->Next) {
1376 for (ip = &info->IpAddressList; ip; ip = ip->Next) {
1377 if (p->S_un.S_addr == inet_addr(ip->IpAddress.String)) {
1378 prefix = ctpop32(inet_addr(ip->IpMask.String));
1389 #define INTERFACE_PATH_BUF_SZ 512
1391 static DWORD get_interface_index(const char *guid)
1395 wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1396 snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1397 wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1398 status = GetAdapterIndex (wbuf, &index);
1399 if (status != NO_ERROR) {
1406 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1408 static int guest_get_network_stats(const char *name,
1409 GuestNetworkInterfaceStat *stats)
1411 OSVERSIONINFO os_ver;
1413 os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1414 GetVersionEx(&os_ver);
1415 if (os_ver.dwMajorVersion >= 6) {
1416 MIB_IF_ROW2 a_mid_ifrow;
1417 GetIfEntry2Func getifentry2_ex;
1419 HMODULE module = GetModuleHandle("iphlpapi");
1420 PVOID func = GetProcAddress(module, "GetIfEntry2");
1426 getifentry2_ex = (GetIfEntry2Func)func;
1427 if_index = get_interface_index(name);
1428 if (if_index == (DWORD)~0) {
1432 memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1433 a_mid_ifrow.InterfaceIndex = if_index;
1434 if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1435 stats->rx_bytes = a_mid_ifrow.InOctets;
1436 stats->rx_packets = a_mid_ifrow.InUcastPkts;
1437 stats->rx_errs = a_mid_ifrow.InErrors;
1438 stats->rx_dropped = a_mid_ifrow.InDiscards;
1439 stats->tx_bytes = a_mid_ifrow.OutOctets;
1440 stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1441 stats->tx_errs = a_mid_ifrow.OutErrors;
1442 stats->tx_dropped = a_mid_ifrow.OutDiscards;
1449 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1451 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1452 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1453 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1454 GuestIpAddressList *head_addr, *cur_addr;
1455 GuestNetworkInterfaceList *info;
1456 GuestNetworkInterfaceStat *interface_stat = NULL;
1457 GuestIpAddressList *address_item = NULL;
1458 unsigned char *mac_addr;
1464 adptr_addrs = guest_get_adapters_addresses(errp);
1465 if (adptr_addrs == NULL) {
1469 /* Make WSA APIs available. */
1470 wsa_version = MAKEWORD(2, 2);
1471 ret = WSAStartup(wsa_version, &wsa_data);
1473 error_setg_win32(errp, ret, "failed socket startup");
1477 for (addr = adptr_addrs; addr; addr = addr->Next) {
1478 info = g_malloc0(sizeof(*info));
1480 if (cur_item == NULL) {
1481 head = cur_item = info;
1483 cur_item->next = info;
1487 info->value = g_malloc0(sizeof(*info->value));
1488 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1490 if (addr->PhysicalAddressLength != 0) {
1491 mac_addr = addr->PhysicalAddress;
1493 info->value->hardware_address =
1494 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1495 (int) mac_addr[0], (int) mac_addr[1],
1496 (int) mac_addr[2], (int) mac_addr[3],
1497 (int) mac_addr[4], (int) mac_addr[5]);
1499 info->value->has_hardware_address = true;
1504 for (ip_addr = addr->FirstUnicastAddress;
1506 ip_addr = ip_addr->Next) {
1507 addr_str = guest_addr_to_str(ip_addr, errp);
1508 if (addr_str == NULL) {
1512 address_item = g_malloc0(sizeof(*address_item));
1515 head_addr = cur_addr = address_item;
1517 cur_addr->next = address_item;
1518 cur_addr = address_item;
1521 address_item->value = g_malloc0(sizeof(*address_item->value));
1522 address_item->value->ip_address = addr_str;
1523 address_item->value->prefix = guest_ip_prefix(ip_addr);
1524 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1525 address_item->value->ip_address_type =
1526 GUEST_IP_ADDRESS_TYPE_IPV4;
1527 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1528 address_item->value->ip_address_type =
1529 GUEST_IP_ADDRESS_TYPE_IPV6;
1533 info->value->has_ip_addresses = true;
1534 info->value->ip_addresses = head_addr;
1536 if (!info->value->has_statistics) {
1537 interface_stat = g_malloc0(sizeof(*interface_stat));
1538 if (guest_get_network_stats(addr->AdapterName,
1539 interface_stat) == -1) {
1540 info->value->has_statistics = false;
1541 g_free(interface_stat);
1543 info->value->statistics = interface_stat;
1544 info->value->has_statistics = true;
1550 g_free(adptr_addrs);
1554 int64_t qmp_guest_get_time(Error **errp)
1556 SYSTEMTIME ts = {0};
1560 if (ts.wYear < 1601 || ts.wYear > 30827) {
1561 error_setg(errp, "Failed to get time");
1565 if (!SystemTimeToFileTime(&ts, &tf)) {
1566 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1570 return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1571 - W32_FT_OFFSET) * 100;
1574 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1576 Error *local_err = NULL;
1582 /* Unfortunately, Windows libraries don't provide an easy way to access
1585 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1587 * Instead, a workaround is to use the Windows win32tm command to
1588 * resync the time using the Windows Time service.
1593 HRESULT hr = system("w32tm /resync /nowait");
1595 if (GetLastError() != 0) {
1596 strerror_s((LPTSTR) & msg_buffer, 0, errno);
1597 error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1598 } else if (hr != 0) {
1599 if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1600 error_setg(errp, "Windows Time service not running on the "
1603 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1604 FORMAT_MESSAGE_FROM_SYSTEM |
1605 FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1606 (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1607 SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1609 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1610 "t retrieve error message", hr);
1612 error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1613 (LPCTSTR)msg_buffer);
1614 LocalFree(msg_buffer);
1617 } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1618 error_setg(errp, "No internet connection on guest, sync not "
1624 /* Validate time passed by user. */
1625 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1626 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1630 time = time_ns / 100 + W32_FT_OFFSET;
1632 tf.dwLowDateTime = (DWORD) time;
1633 tf.dwHighDateTime = (DWORD) (time >> 32);
1635 if (!FileTimeToSystemTime(&tf, &ts)) {
1636 error_setg(errp, "Failed to convert system time %d",
1637 (int)GetLastError());
1641 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1643 error_propagate(errp, local_err);
1647 if (!SetSystemTime(&ts)) {
1648 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1653 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1655 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1657 GuestLogicalProcessorList *head, **link;
1658 Error *local_err = NULL;
1667 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1668 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1669 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1670 ptr = pslpi = g_malloc0(length);
1671 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1672 error_setg(&local_err, "Failed to get processor information: %d",
1673 (int)GetLastError());
1676 error_setg(&local_err,
1677 "Failed to get processor information buffer length: %d",
1678 (int)GetLastError());
1681 while ((local_err == NULL) && (length > 0)) {
1682 if (pslpi->Relationship == RelationProcessorCore) {
1683 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1685 while (cpu_bits > 0) {
1686 if (!!(cpu_bits & 1)) {
1687 GuestLogicalProcessor *vcpu;
1688 GuestLogicalProcessorList *entry;
1690 vcpu = g_malloc0(sizeof *vcpu);
1691 vcpu->logical_id = current++;
1692 vcpu->online = true;
1693 vcpu->has_can_offline = true;
1695 entry = g_malloc0(sizeof *entry);
1696 entry->value = vcpu;
1699 link = &entry->next;
1704 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1705 pslpi++; /* next entry */
1710 if (local_err == NULL) {
1714 /* there's no guest with zero VCPUs */
1715 error_setg(&local_err, "Guest reported zero VCPUs");
1718 qapi_free_GuestLogicalProcessorList(head);
1719 error_propagate(errp, local_err);
1723 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1725 error_setg(errp, QERR_UNSUPPORTED);
1730 get_net_error_message(gint error)
1732 HMODULE module = NULL;
1733 gchar *retval = NULL;
1734 wchar_t *msg = NULL;
1738 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1739 FORMAT_MESSAGE_IGNORE_INSERTS |
1740 FORMAT_MESSAGE_FROM_SYSTEM;
1742 if (error >= NERR_BASE && error <= MAX_NERR) {
1743 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1745 if (module != NULL) {
1746 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1750 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1753 nchars = wcslen(msg);
1756 msg[nchars - 1] == L'\n' &&
1757 msg[nchars - 2] == L'\r') {
1758 msg[nchars - 2] = L'\0';
1761 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1766 if (module != NULL) {
1767 FreeLibrary(module);
1773 void qmp_guest_set_user_password(const char *username,
1774 const char *password,
1779 char *rawpasswddata = NULL;
1780 size_t rawpasswdlen;
1781 wchar_t *user = NULL, *wpass = NULL;
1782 USER_INFO_1003 pi1003 = { 0, };
1783 GError *gerr = NULL;
1786 error_setg(errp, QERR_UNSUPPORTED);
1790 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1791 if (!rawpasswddata) {
1794 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1795 rawpasswddata[rawpasswdlen] = '\0';
1797 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1802 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1807 pi1003.usri1003_password = wpass;
1808 nas = NetUserSetInfo(NULL, user,
1809 1003, (LPBYTE)&pi1003,
1812 if (nas != NERR_Success) {
1813 gchar *msg = get_net_error_message(nas);
1814 error_setg(errp, "failed to set password: %s", msg);
1820 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1825 g_free(rawpasswddata);
1828 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1830 error_setg(errp, QERR_UNSUPPORTED);
1834 GuestMemoryBlockResponseList *
1835 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1837 error_setg(errp, QERR_UNSUPPORTED);
1841 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1843 error_setg(errp, QERR_UNSUPPORTED);
1847 /* add unsupported commands to the blacklist */
1848 GList *ga_command_blacklist_init(GList *blacklist)
1850 const char *list_unsupported[] = {
1851 "guest-suspend-hybrid",
1853 "guest-get-memory-blocks", "guest-set-memory-blocks",
1854 "guest-get-memory-block-size",
1856 char **p = (char **)list_unsupported;
1859 blacklist = g_list_append(blacklist, g_strdup(*p++));
1862 if (!vss_init(true)) {
1863 g_debug("vss_init failed, vss commands are going to be disabled");
1864 const char *list[] = {
1865 "guest-get-fsinfo", "guest-fsfreeze-status",
1866 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1870 blacklist = g_list_append(blacklist, g_strdup(*p++));
1877 /* register init/cleanup routines for stateful command groups */
1878 void ga_command_state_init(GAState *s, GACommandState *cs)
1880 if (!vss_initialized()) {
1881 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1885 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1886 typedef struct _GA_WTSINFOA {
1887 WTS_CONNECTSTATE_CLASS State;
1889 DWORD IncomingBytes;
1890 DWORD OutgoingBytes;
1891 DWORD IncomingFrames;
1892 DWORD OutgoingFrames;
1893 DWORD IncomingCompressedBytes;
1894 DWORD OutgoingCompressedBy;
1895 CHAR WinStationName[WINSTATIONNAME_LENGTH];
1896 CHAR Domain[DOMAIN_LENGTH];
1897 CHAR UserName[USERNAME_LENGTH + 1];
1898 LARGE_INTEGER ConnectTime;
1899 LARGE_INTEGER DisconnectTime;
1900 LARGE_INTEGER LastInputTime;
1901 LARGE_INTEGER LogonTime;
1902 LARGE_INTEGER CurrentTime;
1906 GuestUserList *qmp_guest_get_users(Error **err)
1908 #if (_WIN32_WINNT >= 0x0600)
1909 #define QGA_NANOSECONDS 10000000
1911 GHashTable *cache = NULL;
1912 GuestUserList *head = NULL, *cur_item = NULL;
1914 DWORD buffer_size = 0, count = 0, i = 0;
1915 GA_WTSINFOA *info = NULL;
1916 WTS_SESSION_INFOA *entries = NULL;
1917 GuestUserList *item = NULL;
1918 GuestUser *user = NULL;
1919 gpointer value = NULL;
1921 double login_time = 0;
1923 cache = g_hash_table_new(g_str_hash, g_str_equal);
1925 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
1926 for (i = 0; i < count; ++i) {
1929 if (WTSQuerySessionInformationA(
1931 entries[i].SessionId,
1937 if (strlen(info->UserName) == 0) {
1938 WTSFreeMemory(info);
1942 login = info->LogonTime.QuadPart;
1943 login -= W32_FT_OFFSET;
1944 login_time = ((double)login) / QGA_NANOSECONDS;
1946 if (g_hash_table_contains(cache, info->UserName)) {
1947 value = g_hash_table_lookup(cache, info->UserName);
1948 user = (GuestUser *)value;
1949 if (user->login_time > login_time) {
1950 user->login_time = login_time;
1953 item = g_new0(GuestUserList, 1);
1954 item->value = g_new0(GuestUser, 1);
1956 item->value->user = g_strdup(info->UserName);
1957 item->value->domain = g_strdup(info->Domain);
1958 item->value->has_domain = true;
1960 item->value->login_time = login_time;
1962 g_hash_table_add(cache, item->value->user);
1965 head = cur_item = item;
1967 cur_item->next = item;
1972 WTSFreeMemory(info);
1974 WTSFreeMemory(entries);
1976 g_hash_table_destroy(cache);
1979 error_setg(err, QERR_UNSUPPORTED);
1984 typedef struct _ga_matrix_lookup_t {
1987 char const *version;
1988 char const *version_id;
1989 } ga_matrix_lookup_t;
1991 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
1993 /* Desktop editions */
1994 { 5, 0, "Microsoft Windows 2000", "2000"},
1995 { 5, 1, "Microsoft Windows XP", "xp"},
1996 { 6, 0, "Microsoft Windows Vista", "vista"},
1997 { 6, 1, "Microsoft Windows 7" "7"},
1998 { 6, 2, "Microsoft Windows 8", "8"},
1999 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2000 {10, 0, "Microsoft Windows 10", "10"},
2003 /* Server editions */
2004 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2005 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2006 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2007 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2008 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2009 {10, 0, "Microsoft Windows Server 2016", "2016"},
2015 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2017 typedef NTSTATUS(WINAPI * rtl_get_version_t)(
2018 RTL_OSVERSIONINFOEXW *os_version_info_ex);
2020 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2022 HMODULE module = GetModuleHandle("ntdll");
2023 PVOID fun = GetProcAddress(module, "RtlGetVersion");
2025 error_setg(errp, QERR_QGA_COMMAND_FAILED,
2026 "Failed to get address of RtlGetVersion");
2030 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2031 rtl_get_version(info);
2035 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
2037 DWORD major = os_version->dwMajorVersion;
2038 DWORD minor = os_version->dwMinorVersion;
2039 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2040 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
2041 while (table->version != NULL) {
2042 if (major == table->major && minor == table->minor) {
2044 return g_strdup(table->version_id);
2046 return g_strdup(table->version);
2051 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2053 return g_strdup("N/A");
2056 static char *ga_get_win_product_name(Error **errp)
2060 char *result = g_malloc0(size);
2061 LONG err = ERROR_SUCCESS;
2063 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2064 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2066 if (err != ERROR_SUCCESS) {
2067 error_setg_win32(errp, err, "failed to open registry key");
2071 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2072 (LPBYTE)result, &size);
2073 if (err == ERROR_MORE_DATA) {
2074 slog("ProductName longer than expected (%lu bytes), retrying",
2079 result = g_malloc0(size);
2080 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2081 (LPBYTE)result, &size);
2084 if (err != ERROR_SUCCESS) {
2085 error_setg_win32(errp, err, "failed to retrive ProductName");
2096 static char *ga_get_current_arch(void)
2099 GetNativeSystemInfo(&info);
2100 char *result = NULL;
2101 switch (info.wProcessorArchitecture) {
2102 case PROCESSOR_ARCHITECTURE_AMD64:
2103 result = g_strdup("x86_64");
2105 case PROCESSOR_ARCHITECTURE_ARM:
2106 result = g_strdup("arm");
2108 case PROCESSOR_ARCHITECTURE_IA64:
2109 result = g_strdup("ia64");
2111 case PROCESSOR_ARCHITECTURE_INTEL:
2112 result = g_strdup("x86");
2114 case PROCESSOR_ARCHITECTURE_UNKNOWN:
2116 slog("unknown processor architecture 0x%0x",
2117 info.wProcessorArchitecture);
2118 result = g_strdup("unknown");
2124 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2126 Error *local_err = NULL;
2127 OSVERSIONINFOEXW os_version = {0};
2132 ga_get_win_version(&os_version, &local_err);
2134 error_propagate(errp, local_err);
2138 server = os_version.wProductType != VER_NT_WORKSTATION;
2139 product_name = ga_get_win_product_name(&local_err);
2140 if (product_name == NULL) {
2141 error_propagate(errp, local_err);
2145 info = g_new0(GuestOSInfo, 1);
2147 info->has_kernel_version = true;
2148 info->kernel_version = g_strdup_printf("%lu.%lu",
2149 os_version.dwMajorVersion,
2150 os_version.dwMinorVersion);
2151 info->has_kernel_release = true;
2152 info->kernel_release = g_strdup_printf("%lu",
2153 os_version.dwBuildNumber);
2154 info->has_machine = true;
2155 info->machine = ga_get_current_arch();
2157 info->has_id = true;
2158 info->id = g_strdup("mswindows");
2159 info->has_name = true;
2160 info->name = g_strdup("Microsoft Windows");
2161 info->has_pretty_name = true;
2162 info->pretty_name = product_name;
2163 info->has_version = true;
2164 info->version = ga_get_win_name(&os_version, false);
2165 info->has_version_id = true;
2166 info->version_id = ga_get_win_name(&os_version, true);
2167 info->has_variant = true;
2168 info->variant = g_strdup(server ? "server" : "client");
2169 info->has_variant_id = true;
2170 info->variant_id = g_strdup(server ? "server" : "client");