ui: refactor code for determining if an update should be sent to the client
[qemu/ar7.git] / qga / commands-win32.c
blobd79974f2120626a62d9e95c160c9bf3c9e9925ec
1 /*
2 * QEMU Guest Agent win32-specific command implementations
4 * Copyright IBM Corp. 2012
6 * Authors:
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.
14 #ifndef _WIN32_WINNT
15 # define _WIN32_WINNT 0x0600
16 #endif
17 #include "qemu/osdep.h"
18 #include <wtypes.h>
19 #include <powrprof.h>
20 #include <winsock2.h>
21 #include <ws2tcpip.h>
22 #include <iptypes.h>
23 #include <iphlpapi.h>
24 #ifdef CONFIG_QGA_NTDDSCSI
25 #include <winioctl.h>
26 #include <ntddscsi.h>
27 #include <setupapi.h>
28 #include <initguid.h>
29 #endif
30 #include <lm.h>
31 #include <wtsapi32.h>
32 #include <wininet.h>
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
44 #endif
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 {
55 int64_t id;
56 HANDLE fh;
57 QTAILQ_ENTRY(GuestFileHandle) next;
58 } GuestFileHandle;
60 static struct {
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 {
69 const char *forms;
70 DWORD desired_access;
71 DWORD creation_disposition;
72 } OpenFlags;
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)
92 int mode;
93 Error **errp = NULL;
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) {
99 return flags;
103 error_setg(errp, "invalid file open mode '%s'", mode_str);
104 return NULL;
107 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
109 GuestFileHandle *gfh;
110 int64_t handle;
112 handle = ga_get_fd_handle(ga_state, errp);
113 if (handle < 0) {
114 return -1;
116 gfh = g_new0(GuestFileHandle, 1);
117 gfh->id = handle;
118 gfh->fh = fh;
119 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
121 return handle;
124 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
126 GuestFileHandle *gfh;
127 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
128 if (gfh->id == id) {
129 return gfh;
132 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
133 return NULL;
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) {
141 return;
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)) {
147 return;
149 /* The fd is named pipe fd */
150 if (pipe_state & PIPE_NOWAIT) {
151 return;
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)
161 int64_t fd;
162 HANDLE fh;
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;
169 if (!has_mode) {
170 mode = "r";
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");
176 return -1;
179 fh = CreateFile(path, guest_flags->desired_access, share_mode, sa_attr,
180 guest_flags->creation_disposition, flags_and_attr,
181 templ_file);
182 if (fh == INVALID_HANDLE_VALUE) {
183 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
184 path);
185 return -1;
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);
194 if (fd < 0) {
195 CloseHandle(fh);
196 error_setg(errp, "failed to add handle to qmp handle table");
197 return -1;
200 slog("guest-file-open, handle: % " PRId64, fd);
201 return fd;
204 void qmp_guest_file_close(int64_t handle, Error **errp)
206 bool ret;
207 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
208 slog("guest-file-close called, handle: %" PRId64, handle);
209 if (gfh == NULL) {
210 return;
212 ret = CloseHandle(gfh->fh);
213 if (!ret) {
214 error_setg_win32(errp, GetLastError(), "failed close handle");
215 return;
218 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
219 g_free(gfh);
222 static void acquire_privilege(const char *name, Error **errp)
224 HANDLE token = NULL;
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");
234 goto out;
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");
243 goto out;
246 } else {
247 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
248 "failed to open privilege token");
251 out:
252 if (token) {
253 CloseHandle(token);
255 error_propagate(errp, local_err);
258 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
259 Error **errp)
261 Error *local_err = NULL;
263 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
264 if (!thread) {
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;
284 } else {
285 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
286 "halt|powerdown|reboot");
287 return;
290 /* Request a shutdown privilege, but try to shut down the system
291 anyway. */
292 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
293 if (local_err) {
294 error_propagate(errp, local_err);
295 return;
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;
308 guchar *buf;
309 HANDLE fh;
310 bool is_ok;
311 DWORD read_count;
312 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
314 if (!gfh) {
315 return NULL;
317 if (!has_count) {
318 count = QGA_READ_COUNT_DEFAULT;
319 } else if (count < 0) {
320 error_setg(errp, "value '%" PRId64
321 "' is invalid for argument count", count);
322 return NULL;
325 fh = gfh->fh;
326 buf = g_malloc0(count+1);
327 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
328 if (!is_ok) {
329 error_setg_win32(errp, GetLastError(), "failed to read file");
330 slog("guest-file-read failed, handle %" PRId64, handle);
331 } else {
332 buf[read_count] = 0;
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);
341 g_free(buf);
343 return read_data;
346 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
347 bool has_count, int64_t count,
348 Error **errp)
350 GuestFileWrite *write_data = NULL;
351 guchar *buf;
352 gsize buf_len;
353 bool is_ok;
354 DWORD write_count;
355 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
356 HANDLE fh;
358 if (!gfh) {
359 return NULL;
361 fh = gfh->fh;
362 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
363 if (!buf) {
364 return NULL;
367 if (!has_count) {
368 count = buf_len;
369 } else if (count < 0 || count > buf_len) {
370 error_setg(errp, "value '%" PRId64
371 "' is invalid for argument count", count);
372 goto done;
375 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
376 if (!is_ok) {
377 error_setg_win32(errp, GetLastError(), "failed to write to file");
378 slog("guest-file-write-failed, handle: %" PRId64, handle);
379 } else {
380 write_data = g_new0(GuestFileWrite, 1);
381 write_data->count = (size_t) write_count;
384 done:
385 g_free(buf);
386 return write_data;
389 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
390 GuestFileWhence *whence_code,
391 Error **errp)
393 GuestFileHandle *gfh;
394 GuestFileSeek *seek_data;
395 HANDLE fh;
396 LARGE_INTEGER new_pos, off_pos;
397 off_pos.QuadPart = offset;
398 BOOL res;
399 int whence;
400 Error *err = NULL;
402 gfh = guest_file_handle_find(handle, errp);
403 if (!gfh) {
404 return NULL;
407 /* We stupidly exposed 'whence':'int' in our qapi */
408 whence = ga_parse_whence(whence_code, &err);
409 if (err) {
410 error_propagate(errp, err);
411 return NULL;
414 fh = gfh->fh;
415 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
416 if (!res) {
417 error_setg_win32(errp, GetLastError(), "failed to seek file");
418 return NULL;
420 seek_data = g_new0(GuestFileSeek, 1);
421 seek_data->position = new_pos.QuadPart;
422 return seek_data;
425 void qmp_guest_file_flush(int64_t handle, Error **errp)
427 HANDLE fh;
428 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
429 if (!gfh) {
430 return;
433 fh = gfh->fh;
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,
457 #endif
458 #if (_WIN32_WINNT >= 0x0601)
459 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
460 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
461 #endif
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)
478 HDEVINFO dev_info;
479 SP_DEVINFO_DATA dev_info_data;
480 DWORD size = 0;
481 int i;
482 char dev_name[MAX_PATH];
483 char *buffer = NULL;
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");
489 goto out;
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");
496 goto out;
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,
505 &size2)) {
506 size = MAX(size, size2);
507 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
508 g_free(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);
513 } else {
514 error_setg_win32(errp, GetLastError(),
515 "failed to get device name");
516 goto free_dev_info;
520 if (g_strcmp0(buffer, dev_name)) {
521 continue;
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)) {
531 break;
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)) {
538 break;
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)) {
545 break;
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));
558 pci->domain = dev;
559 pci->slot = slot;
560 pci->function = func;
561 pci->bus = bus;
562 break;
565 free_dev_info:
566 SetupDiDestroyDeviceInfoList(dev_info);
567 out:
568 g_free(buffer);
569 g_free(name);
570 return pci;
573 static int get_disk_bus_type(HANDLE vol_h, Error **errp)
575 STORAGE_PROPERTY_QUERY query;
576 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
577 DWORD received;
579 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");
588 return -1;
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;
602 DWORD len;
603 int bus;
604 HANDLE vol_h;
606 scsi_ad = &addr;
607 char *name = g_strndup(guid, strlen(guid)-1);
609 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
610 0, NULL);
611 if (vol_h == INVALID_HANDLE_VALUE) {
612 error_setg_win32(errp, GetLastError(), "failed to open volume");
613 goto out_free;
616 bus = get_disk_bus_type(vol_h, errp);
617 if (bus < 0) {
618 goto out_close;
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 */
626 || bus == BusTypeSas
627 #endif
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. */
641 } else {
642 disk->pci_controller = NULL;
645 list = g_malloc0(sizeof(*list));
646 list->value = disk;
647 list->next = NULL;
648 out_close:
649 CloseHandle(vol_h);
650 out_free:
651 g_free(name);
652 return list;
655 #else
657 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
659 return NULL;
662 #endif /* CONFIG_QGA_NTDDSCSI */
664 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
666 DWORD info_size;
667 char mnt, *mnt_point;
668 char fs_name[32];
669 char vol_info[MAX_PATH+1];
670 size_t len;
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");
676 return NULL;
679 mnt_point = g_malloc(info_size + 1);
680 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
681 &info_size)) {
682 error_setg_win32(errp, GetLastError(), "failed to get volume name");
683 goto free;
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");
694 goto free;
697 fs_name[sizeof(fs_name) - 1] = 0;
698 fs = g_malloc(sizeof(*fs));
699 fs->name = g_strdup(guid);
700 if (len == 0) {
701 fs->mountpoint = g_strdup("System Reserved");
702 } else {
703 fs->mountpoint = g_strndup(mnt_point, len);
705 fs->type = g_strdup(fs_name);
706 fs->disk = build_guest_disk_info(guid, errp);
707 free:
708 g_free(mnt_point);
709 return fs;
712 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
714 HANDLE vol_h;
715 GuestFilesystemInfoList *new, *ret = NULL;
716 char guid[256];
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");
721 return NULL;
724 do {
725 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
726 if (info == NULL) {
727 continue;
729 new = g_malloc(sizeof(*ret));
730 new->value = info;
731 new->next = ret;
732 ret = new;
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);
740 return ret;
744 * Return status of freeze/thaw
746 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
748 if (!vss_initialized()) {
749 error_setg(errp, QERR_UNSUPPORTED);
750 return 0;
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)
766 int i;
767 Error *local_err = NULL;
769 if (!vss_initialized()) {
770 error_setg(errp, QERR_UNSUPPORTED);
771 return 0;
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);
780 if (local_err) {
781 error_propagate(errp, local_err);
782 goto error;
785 return i;
787 error:
788 local_err = NULL;
789 qmp_guest_fsfreeze_thaw(&local_err);
790 if (local_err) {
791 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
792 error_free(local_err);
794 return 0;
797 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
798 strList *mountpoints,
799 Error **errp)
801 error_setg(errp, QERR_UNSUPPORTED);
803 return 0;
807 * Thaw local file systems using Volume Shadow-copy Service.
809 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
811 int i;
813 if (!vss_initialized()) {
814 error_setg(errp, QERR_UNSUPPORTED);
815 return 0;
818 qga_vss_fsfreeze(&i, false, errp);
820 ga_unset_frozen(ga_state);
821 return i;
824 static void guest_fsfreeze_cleanup(void)
826 Error *err = NULL;
828 if (!vss_initialized()) {
829 return;
832 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
833 qmp_guest_fsfreeze_thaw(&err);
834 if (err) {
835 slog("failed to clean up frozen filesystems: %s",
836 error_get_pretty(err));
837 error_free(err);
841 vss_deinit(true);
845 * Walk list of mounted file systems in the guest, and discard unused
846 * areas.
848 GuestFilesystemTrimResponse *
849 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
851 GuestFilesystemTrimResponse *resp;
852 HANDLE handle;
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");
858 return NULL;
861 resp = g_new0(GuestFilesystemTrimResponse, 1);
863 do {
864 GuestFilesystemTrimResult *res;
865 GuestFilesystemTrimResultList *list;
866 PWCHAR uc_path;
867 DWORD char_count = 0;
868 char *path, *out;
869 GError *gerr = NULL;
870 gchar * argv[4];
872 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
874 if (GetLastError() != ERROR_MORE_DATA) {
875 continue;
877 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
878 continue;
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 */
885 g_free(uc_path);
886 continue;
889 res = g_new0(GuestFilesystemTrimResult, 1);
891 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
893 g_free(uc_path);
895 if (!path) {
896 res->has_error = true;
897 res->error = g_strdup(gerr->message);
898 g_error_free(gerr);
899 break;
902 res->path = path;
904 list = g_new0(GuestFilesystemTrimResultList, 1);
905 list->value = res;
906 list->next = resp->paths;
908 resp->paths = list;
910 memset(argv, 0, sizeof(argv));
911 argv[0] = (gchar *)"defrag.exe";
912 argv[1] = (gchar *)"/L";
913 argv[2] = path;
915 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
916 &out /* stdout */, NULL /* stdin */,
917 NULL, &gerr)) {
918 res->has_error = true;
919 res->error = g_strdup(gerr->message);
920 g_error_free(gerr);
921 } else {
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 */
926 int i;
927 gchar **lines = g_strsplit(out, "\r\n", 0);
928 g_free(out);
930 for (i = 0; lines[i] != NULL; i++) {
931 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
932 continue;
934 res->has_error = true;
935 res->error = g_strdup(lines[i]);
936 break;
938 g_strfreev(lines);
940 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
942 FindVolumeClose(handle);
943 return resp;
946 typedef enum {
947 GUEST_SUSPEND_MODE_DISK,
948 GUEST_SUSPEND_MODE_RAM
949 } GuestSuspendMode;
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");
960 goto out;
963 switch (mode) {
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");
969 break;
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");
975 break;
976 default:
977 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
978 "GuestSuspendMode");
981 out:
982 error_propagate(errp, local_err);
985 static DWORD WINAPI do_suspend(LPVOID opaque)
987 GuestSuspendMode *mode = opaque;
988 DWORD ret = 0;
990 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
991 slog("failed to suspend guest, %lu", GetLastError());
992 ret = -1;
994 g_free(mode);
995 return ret;
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);
1008 if (local_err) {
1009 error_propagate(errp, local_err);
1010 g_free(mode);
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);
1024 if (local_err) {
1025 error_propagate(errp, local_err);
1026 g_free(mode);
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;
1039 DWORD ret;
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);
1051 adptr_addrs = NULL;
1053 return adptr_addrs;
1056 static char *guest_wctomb_dup(WCHAR *wstr)
1058 char *str;
1059 size_t i;
1061 i = wcslen(wstr) + 1;
1062 str = g_malloc(i);
1063 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
1064 wstr, -1, str, i, NULL, NULL);
1065 return str;
1068 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1069 Error **errp)
1071 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1072 DWORD len;
1073 int ret;
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,
1080 NULL,
1081 addr_str,
1082 &len);
1083 if (ret != 0) {
1084 error_setg_win32(errp, WSAGetLastError(),
1085 "failed address presentation form conversion");
1086 return NULL;
1088 return g_strdup(addr_str);
1090 return NULL;
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;
1101 #else
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;
1109 DWORD ret;
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) {
1117 g_free(adptr_info);
1118 adptr_info = NULL;
1120 return adptr_info;
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;
1127 IP_ADDR_STRING *ip;
1128 struct in_addr *p;
1130 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
1131 return prefix;
1133 adptr_info = guest_get_adapters_info();
1134 if (adptr_info == NULL) {
1135 return prefix;
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));
1146 goto out;
1150 out:
1151 g_free(adptr_info);
1152 return prefix;
1154 #endif
1156 #define INTERFACE_PATH_BUF_SZ 512
1158 static DWORD get_interface_index(const char *guid)
1160 ULONG index;
1161 DWORD status;
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) {
1167 return (DWORD)~0;
1168 } else {
1169 return index;
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;
1185 DWORD if_index = 0;
1186 HMODULE module = GetModuleHandle("iphlpapi");
1187 PVOID func = GetProcAddress(module, "GetIfEntry2");
1189 if (func == NULL) {
1190 return -1;
1193 getifentry2_ex = (GetIfEntry2Func)func;
1194 if_index = get_interface_index(name);
1195 if (if_index == (DWORD)~0) {
1196 return -1;
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;
1210 return 0;
1213 return -1;
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;
1226 char *addr_str;
1227 WORD wsa_version;
1228 WSADATA wsa_data;
1229 int ret;
1231 adptr_addrs = guest_get_adapters_addresses(errp);
1232 if (adptr_addrs == NULL) {
1233 return NULL;
1236 /* Make WSA APIs available. */
1237 wsa_version = MAKEWORD(2, 2);
1238 ret = WSAStartup(wsa_version, &wsa_data);
1239 if (ret != 0) {
1240 error_setg_win32(errp, ret, "failed socket startup");
1241 goto out;
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;
1249 } else {
1250 cur_item->next = info;
1251 cur_item = 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;
1269 head_addr = NULL;
1270 cur_addr = NULL;
1271 for (ip_addr = addr->FirstUnicastAddress;
1272 ip_addr;
1273 ip_addr = ip_addr->Next) {
1274 addr_str = guest_addr_to_str(ip_addr, errp);
1275 if (addr_str == NULL) {
1276 continue;
1279 address_item = g_malloc0(sizeof(*address_item));
1281 if (!cur_addr) {
1282 head_addr = cur_addr = address_item;
1283 } else {
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;
1299 if (head_addr) {
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);
1309 } else {
1310 info->value->statistics = interface_stat;
1311 info->value->has_statistics = true;
1315 WSACleanup();
1316 out:
1317 g_free(adptr_addrs);
1318 return head;
1321 int64_t qmp_guest_get_time(Error **errp)
1323 SYSTEMTIME ts = {0};
1324 FILETIME tf;
1326 GetSystemTime(&ts);
1327 if (ts.wYear < 1601 || ts.wYear > 30827) {
1328 error_setg(errp, "Failed to get time");
1329 return -1;
1332 if (!SystemTimeToFileTime(&ts, &tf)) {
1333 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1334 return -1;
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;
1344 SYSTEMTIME ts;
1345 FILETIME tf;
1346 LONGLONG time;
1348 if (!has_time) {
1349 /* Unfortunately, Windows libraries don't provide an easy way to access
1350 * RTC yet:
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.
1357 LPVOID msg_buffer;
1358 DWORD ret_flags;
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 "
1368 "guest");
1369 } else {
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,
1375 NULL)) {
1376 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1377 "t retrieve error message", hr);
1378 } else {
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 "
1386 "accurate");
1388 return;
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);
1394 return;
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());
1405 return;
1408 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1409 if (local_err) {
1410 error_propagate(errp, local_err);
1411 return;
1414 if (!SetSystemTime(&ts)) {
1415 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1416 return;
1420 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1422 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1423 DWORD length;
1424 GuestLogicalProcessorList *head, **link;
1425 Error *local_err = NULL;
1426 int64_t current;
1428 ptr = pslpi = NULL;
1429 length = 0;
1430 current = 0;
1431 head = NULL;
1432 link = &head;
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());
1442 } else {
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;
1465 *link = entry;
1466 link = &entry->next;
1468 cpu_bits >>= 1;
1471 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1472 pslpi++; /* next entry */
1475 g_free(ptr);
1477 if (local_err == NULL) {
1478 if (head != NULL) {
1479 return head;
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);
1487 return NULL;
1490 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1492 error_setg(errp, QERR_UNSUPPORTED);
1493 return -1;
1496 static gchar *
1497 get_net_error_message(gint error)
1499 HMODULE module = NULL;
1500 gchar *retval = NULL;
1501 wchar_t *msg = NULL;
1502 int flags;
1503 size_t nchars;
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);
1519 if (msg != NULL) {
1520 nchars = wcslen(msg);
1522 if (nchars >= 2 &&
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);
1530 LocalFree(msg);
1533 if (module != NULL) {
1534 FreeLibrary(module);
1537 return retval;
1540 void qmp_guest_set_user_password(const char *username,
1541 const char *password,
1542 bool crypted,
1543 Error **errp)
1545 NET_API_STATUS nas;
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;
1552 if (crypted) {
1553 error_setg(errp, QERR_UNSUPPORTED);
1554 return;
1557 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1558 if (!rawpasswddata) {
1559 return;
1561 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1562 rawpasswddata[rawpasswdlen] = '\0';
1564 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1565 if (!user) {
1566 goto done;
1569 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1570 if (!wpass) {
1571 goto done;
1574 pi1003.usri1003_password = wpass;
1575 nas = NetUserSetInfo(NULL, user,
1576 1003, (LPBYTE)&pi1003,
1577 NULL);
1579 if (nas != NERR_Success) {
1580 gchar *msg = get_net_error_message(nas);
1581 error_setg(errp, "failed to set password: %s", msg);
1582 g_free(msg);
1585 done:
1586 if (gerr) {
1587 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1588 g_error_free(gerr);
1590 g_free(user);
1591 g_free(wpass);
1592 g_free(rawpasswddata);
1595 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1597 error_setg(errp, QERR_UNSUPPORTED);
1598 return NULL;
1601 GuestMemoryBlockResponseList *
1602 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1604 error_setg(errp, QERR_UNSUPPORTED);
1605 return NULL;
1608 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1610 error_setg(errp, QERR_UNSUPPORTED);
1611 return NULL;
1614 /* add unsupported commands to the blacklist */
1615 GList *ga_command_blacklist_init(GList *blacklist)
1617 const char *list_unsupported[] = {
1618 "guest-suspend-hybrid",
1619 "guest-set-vcpus",
1620 "guest-get-memory-blocks", "guest-set-memory-blocks",
1621 "guest-get-memory-block-size",
1622 "guest-fsfreeze-freeze-list",
1623 NULL};
1624 char **p = (char **)list_unsupported;
1626 while (*p) {
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};
1635 p = (char **)list;
1637 while (*p) {
1638 blacklist = g_list_append(blacklist, g_strdup(*p++));
1642 return blacklist;
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;
1656 DWORD SessionId;
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;
1672 } GA_WTSINFOA;
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;
1688 INT64 login = 0;
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) {
1695 buffer_size = 0;
1696 info = NULL;
1697 if (WTSQuerySessionInformationA(
1698 NULL,
1699 entries[i].SessionId,
1700 WTSSessionInfo,
1701 (LPSTR *)&info,
1702 &buffer_size
1703 )) {
1705 if (strlen(info->UserName) == 0) {
1706 WTSFreeMemory(info);
1707 continue;
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;
1720 } else {
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);
1732 if (!cur_item) {
1733 head = cur_item = item;
1734 } else {
1735 cur_item->next = item;
1736 cur_item = item;
1740 WTSFreeMemory(info);
1742 WTSFreeMemory(entries);
1744 g_hash_table_destroy(cache);
1745 return head;
1746 #else
1747 error_setg(err, QERR_UNSUPPORTED);
1748 return NULL;
1749 #endif
1752 typedef struct _ga_matrix_lookup_t {
1753 int major;
1754 int minor;
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"},
1769 { 0, 0, 0}
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"},
1778 { 0, 0, 0},
1779 { 0, 0, 0}
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");
1792 if (fun == NULL) {
1793 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1794 "Failed to get address of RtlGetVersion");
1795 return;
1798 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
1799 rtl_get_version(info);
1800 return;
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) {
1811 if (id) {
1812 return g_strdup(table->version_id);
1813 } else {
1814 return g_strdup(table->version);
1817 ++table;
1819 slog("failed to lookup Windows version: major=%lu, minor=%lu",
1820 major, minor);
1821 return g_strdup("N/A");
1824 static char *ga_get_win_product_name(Error **errp)
1826 HKEY key = NULL;
1827 DWORD size = 128;
1828 char *result = g_malloc0(size);
1829 LONG err = ERROR_SUCCESS;
1831 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
1832 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
1833 &key);
1834 if (err != ERROR_SUCCESS) {
1835 error_setg_win32(errp, err, "failed to open registry key");
1836 goto fail;
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",
1843 size);
1844 g_free(result);
1845 result = NULL;
1846 if (size > 0) {
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");
1854 goto fail;
1857 return result;
1859 fail:
1860 g_free(result);
1861 return NULL;
1864 static char *ga_get_current_arch(void)
1866 SYSTEM_INFO info;
1867 GetNativeSystemInfo(&info);
1868 char *result = NULL;
1869 switch (info.wProcessorArchitecture) {
1870 case PROCESSOR_ARCHITECTURE_AMD64:
1871 result = g_strdup("x86_64");
1872 break;
1873 case PROCESSOR_ARCHITECTURE_ARM:
1874 result = g_strdup("arm");
1875 break;
1876 case PROCESSOR_ARCHITECTURE_IA64:
1877 result = g_strdup("ia64");
1878 break;
1879 case PROCESSOR_ARCHITECTURE_INTEL:
1880 result = g_strdup("x86");
1881 break;
1882 case PROCESSOR_ARCHITECTURE_UNKNOWN:
1883 default:
1884 slog("unknown processor architecture 0x%0x",
1885 info.wProcessorArchitecture);
1886 result = g_strdup("unknown");
1887 break;
1889 return result;
1892 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
1894 Error *local_err = NULL;
1895 OSVERSIONINFOEXW os_version = {0};
1896 bool server;
1897 char *product_name;
1898 GuestOSInfo *info;
1900 ga_get_win_version(&os_version, &local_err);
1901 if (local_err) {
1902 error_propagate(errp, local_err);
1903 return NULL;
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);
1910 return NULL;
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");
1940 return info;