monitor: Fix tracepoint crash on JSON syntax error
[qemu/armbru.git] / qga / commands-win32.c
blob318d760a74f4959ff8f9326bff8cbf1ecdfd3957
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
18 #include "qemu/osdep.h"
19 #include <wtypes.h>
20 #include <powrprof.h>
21 #include <winsock2.h>
22 #include <ws2tcpip.h>
23 #include <iptypes.h>
24 #include <iphlpapi.h>
25 #ifdef CONFIG_QGA_NTDDSCSI
26 #include <winioctl.h>
27 #include <ntddscsi.h>
28 #include <setupapi.h>
29 #include <initguid.h>
30 #endif
31 #include <lm.h>
32 #include <wtsapi32.h>
33 #include <wininet.h>
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
46 #endif
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 {
57 int64_t id;
58 HANDLE fh;
59 QTAILQ_ENTRY(GuestFileHandle) next;
60 } GuestFileHandle;
62 static struct {
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 {
71 const char *forms;
72 DWORD desired_access;
73 DWORD creation_disposition;
74 } OpenFlags;
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 static OpenFlags *find_open_flag(const char *mode_str)
94 int mode;
95 Error **errp = NULL;
97 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
98 OpenFlags *flags = guest_file_open_modes + mode;
100 if (strcmp(flags->forms, mode_str) == 0) {
101 return flags;
105 error_setg(errp, "invalid file open mode '%s'", mode_str);
106 return NULL;
109 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
111 GuestFileHandle *gfh;
112 int64_t handle;
114 handle = ga_get_fd_handle(ga_state, errp);
115 if (handle < 0) {
116 return -1;
118 gfh = g_new0(GuestFileHandle, 1);
119 gfh->id = handle;
120 gfh->fh = fh;
121 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
123 return handle;
126 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
128 GuestFileHandle *gfh;
129 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
130 if (gfh->id == id) {
131 return gfh;
134 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
135 return NULL;
138 static void handle_set_nonblocking(HANDLE fh)
140 DWORD file_type, pipe_state;
141 file_type = GetFileType(fh);
142 if (file_type != FILE_TYPE_PIPE) {
143 return;
145 /* If file_type == FILE_TYPE_PIPE, according to MSDN
146 * the specified file is socket or named pipe */
147 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
148 NULL, NULL, NULL, 0)) {
149 return;
151 /* The fd is named pipe fd */
152 if (pipe_state & PIPE_NOWAIT) {
153 return;
156 pipe_state |= PIPE_NOWAIT;
157 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
160 int64_t qmp_guest_file_open(const char *path, bool has_mode,
161 const char *mode, Error **errp)
163 int64_t fd;
164 HANDLE fh;
165 HANDLE templ_file = NULL;
166 DWORD share_mode = FILE_SHARE_READ;
167 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
168 LPSECURITY_ATTRIBUTES sa_attr = NULL;
169 OpenFlags *guest_flags;
171 if (!has_mode) {
172 mode = "r";
174 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
175 guest_flags = find_open_flag(mode);
176 if (guest_flags == NULL) {
177 error_setg(errp, "invalid file open mode");
178 return -1;
181 fh = CreateFile(path, guest_flags->desired_access, share_mode, sa_attr,
182 guest_flags->creation_disposition, flags_and_attr,
183 templ_file);
184 if (fh == INVALID_HANDLE_VALUE) {
185 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
186 path);
187 return -1;
190 /* set fd non-blocking to avoid common use cases (like reading from a
191 * named pipe) from hanging the agent
193 handle_set_nonblocking(fh);
195 fd = guest_file_handle_add(fh, errp);
196 if (fd < 0) {
197 CloseHandle(fh);
198 error_setg(errp, "failed to add handle to qmp handle table");
199 return -1;
202 slog("guest-file-open, handle: % " PRId64, fd);
203 return fd;
206 void qmp_guest_file_close(int64_t handle, Error **errp)
208 bool ret;
209 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
210 slog("guest-file-close called, handle: %" PRId64, handle);
211 if (gfh == NULL) {
212 return;
214 ret = CloseHandle(gfh->fh);
215 if (!ret) {
216 error_setg_win32(errp, GetLastError(), "failed close handle");
217 return;
220 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
221 g_free(gfh);
224 static void acquire_privilege(const char *name, Error **errp)
226 HANDLE token = NULL;
227 TOKEN_PRIVILEGES priv;
228 Error *local_err = NULL;
230 if (OpenProcessToken(GetCurrentProcess(),
231 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
233 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
234 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
235 "no luid for requested privilege");
236 goto out;
239 priv.PrivilegeCount = 1;
240 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
242 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
243 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
244 "unable to acquire requested privilege");
245 goto out;
248 } else {
249 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
250 "failed to open privilege token");
253 out:
254 if (token) {
255 CloseHandle(token);
257 error_propagate(errp, local_err);
260 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
261 Error **errp)
263 Error *local_err = NULL;
265 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
266 if (!thread) {
267 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
268 "failed to dispatch asynchronous command");
269 error_propagate(errp, local_err);
273 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
275 Error *local_err = NULL;
276 UINT shutdown_flag = EWX_FORCE;
278 slog("guest-shutdown called, mode: %s", mode);
280 if (!has_mode || strcmp(mode, "powerdown") == 0) {
281 shutdown_flag |= EWX_POWEROFF;
282 } else if (strcmp(mode, "halt") == 0) {
283 shutdown_flag |= EWX_SHUTDOWN;
284 } else if (strcmp(mode, "reboot") == 0) {
285 shutdown_flag |= EWX_REBOOT;
286 } else {
287 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
288 "halt|powerdown|reboot");
289 return;
292 /* Request a shutdown privilege, but try to shut down the system
293 anyway. */
294 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
295 if (local_err) {
296 error_propagate(errp, local_err);
297 return;
300 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
301 slog("guest-shutdown failed: %lu", GetLastError());
302 error_setg(errp, QERR_UNDEFINED_ERROR);
306 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
307 int64_t count, Error **errp)
309 GuestFileRead *read_data = NULL;
310 guchar *buf;
311 HANDLE fh;
312 bool is_ok;
313 DWORD read_count;
314 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
316 if (!gfh) {
317 return NULL;
319 if (!has_count) {
320 count = QGA_READ_COUNT_DEFAULT;
321 } else if (count < 0 || count >= UINT32_MAX) {
322 error_setg(errp, "value '%" PRId64
323 "' is invalid for argument count", count);
324 return NULL;
327 fh = gfh->fh;
328 buf = g_malloc0(count+1);
329 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
330 if (!is_ok) {
331 error_setg_win32(errp, GetLastError(), "failed to read file");
332 slog("guest-file-read failed, handle %" PRId64, handle);
333 } else {
334 buf[read_count] = 0;
335 read_data = g_new0(GuestFileRead, 1);
336 read_data->count = (size_t)read_count;
337 read_data->eof = read_count == 0;
339 if (read_count != 0) {
340 read_data->buf_b64 = g_base64_encode(buf, read_count);
343 g_free(buf);
345 return read_data;
348 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
349 bool has_count, int64_t count,
350 Error **errp)
352 GuestFileWrite *write_data = NULL;
353 guchar *buf;
354 gsize buf_len;
355 bool is_ok;
356 DWORD write_count;
357 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
358 HANDLE fh;
360 if (!gfh) {
361 return NULL;
363 fh = gfh->fh;
364 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
365 if (!buf) {
366 return NULL;
369 if (!has_count) {
370 count = buf_len;
371 } else if (count < 0 || count > buf_len) {
372 error_setg(errp, "value '%" PRId64
373 "' is invalid for argument count", count);
374 goto done;
377 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
378 if (!is_ok) {
379 error_setg_win32(errp, GetLastError(), "failed to write to file");
380 slog("guest-file-write-failed, handle: %" PRId64, handle);
381 } else {
382 write_data = g_new0(GuestFileWrite, 1);
383 write_data->count = (size_t) write_count;
386 done:
387 g_free(buf);
388 return write_data;
391 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
392 GuestFileWhence *whence_code,
393 Error **errp)
395 GuestFileHandle *gfh;
396 GuestFileSeek *seek_data;
397 HANDLE fh;
398 LARGE_INTEGER new_pos, off_pos;
399 off_pos.QuadPart = offset;
400 BOOL res;
401 int whence;
402 Error *err = NULL;
404 gfh = guest_file_handle_find(handle, errp);
405 if (!gfh) {
406 return NULL;
409 /* We stupidly exposed 'whence':'int' in our qapi */
410 whence = ga_parse_whence(whence_code, &err);
411 if (err) {
412 error_propagate(errp, err);
413 return NULL;
416 fh = gfh->fh;
417 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
418 if (!res) {
419 error_setg_win32(errp, GetLastError(), "failed to seek file");
420 return NULL;
422 seek_data = g_new0(GuestFileSeek, 1);
423 seek_data->position = new_pos.QuadPart;
424 return seek_data;
427 void qmp_guest_file_flush(int64_t handle, Error **errp)
429 HANDLE fh;
430 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
431 if (!gfh) {
432 return;
435 fh = gfh->fh;
436 if (!FlushFileBuffers(fh)) {
437 error_setg_win32(errp, GetLastError(), "failed to flush file");
441 #ifdef CONFIG_QGA_NTDDSCSI
443 static STORAGE_BUS_TYPE win2qemu[] = {
444 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
445 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
446 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
447 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
448 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
449 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
450 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
451 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
452 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
453 #if (_WIN32_WINNT >= 0x0600)
454 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
455 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
456 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
457 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
458 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
459 #endif
460 #if (_WIN32_WINNT >= 0x0601)
461 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
462 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
463 #endif
466 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
468 if (bus > ARRAY_SIZE(win2qemu) || (int)bus < 0) {
469 return GUEST_DISK_BUS_TYPE_UNKNOWN;
471 return win2qemu[(int)bus];
474 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME,
475 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2,
476 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
478 static GuestPCIAddress *get_pci_info(char *guid, Error **errp)
480 HDEVINFO dev_info;
481 SP_DEVINFO_DATA dev_info_data;
482 DWORD size = 0;
483 int i;
484 char dev_name[MAX_PATH];
485 char *buffer = NULL;
486 GuestPCIAddress *pci = NULL;
487 char *name = g_strdup(&guid[4]);
489 if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {
490 error_setg_win32(errp, GetLastError(), "failed to get dos device name");
491 goto out;
494 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, 0, 0,
495 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
496 if (dev_info == INVALID_HANDLE_VALUE) {
497 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
498 goto out;
501 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
502 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
503 DWORD addr, bus, slot, func, dev, data, size2;
504 while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
505 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
506 &data, (PBYTE)buffer, size,
507 &size2)) {
508 size = MAX(size, size2);
509 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
510 g_free(buffer);
511 /* Double the size to avoid problems on
512 * W2k MBCS systems per KB 888609.
513 * https://support.microsoft.com/en-us/kb/259695 */
514 buffer = g_malloc(size * 2);
515 } else {
516 error_setg_win32(errp, GetLastError(),
517 "failed to get device name");
518 goto free_dev_info;
522 if (g_strcmp0(buffer, dev_name)) {
523 continue;
526 /* There is no need to allocate buffer in the next functions. The size
527 * is known and ULONG according to
528 * https://support.microsoft.com/en-us/kb/253232
529 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
531 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
532 SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {
533 break;
536 /* The function retrieves the device's address. This value will be
537 * transformed into device function and number */
538 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
539 SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {
540 break;
543 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
544 * This number is typically a user-perceived slot number. */
545 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
546 SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {
547 break;
550 /* SetupApi gives us the same information as driver with
551 * IoGetDeviceProperty. According to Microsoft
552 * https://support.microsoft.com/en-us/kb/253232
553 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
554 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
555 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
557 func = addr & 0x0000FFFF;
558 dev = (addr >> 16) & 0x0000FFFF;
559 pci = g_malloc0(sizeof(*pci));
560 pci->domain = dev;
561 pci->slot = slot;
562 pci->function = func;
563 pci->bus = bus;
564 break;
567 free_dev_info:
568 SetupDiDestroyDeviceInfoList(dev_info);
569 out:
570 g_free(buffer);
571 g_free(name);
572 return pci;
575 static int get_disk_bus_type(HANDLE vol_h, Error **errp)
577 STORAGE_PROPERTY_QUERY query;
578 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
579 DWORD received;
581 dev_desc = &buf;
582 dev_desc->Size = sizeof(buf);
583 query.PropertyId = StorageDeviceProperty;
584 query.QueryType = PropertyStandardQuery;
586 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
587 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
588 dev_desc->Size, &received, NULL)) {
589 error_setg_win32(errp, GetLastError(), "failed to get bus type");
590 return -1;
593 return dev_desc->BusType;
596 /* VSS provider works with volumes, thus there is no difference if
597 * the volume consist of spanned disks. Info about the first disk in the
598 * volume is returned for the spanned disk group (LVM) */
599 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
601 GuestDiskAddressList *list = NULL;
602 GuestDiskAddress *disk;
603 SCSI_ADDRESS addr, *scsi_ad;
604 DWORD len;
605 int bus;
606 HANDLE vol_h;
608 scsi_ad = &addr;
609 char *name = g_strndup(guid, strlen(guid)-1);
611 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
612 0, NULL);
613 if (vol_h == INVALID_HANDLE_VALUE) {
614 error_setg_win32(errp, GetLastError(), "failed to open volume");
615 goto out_free;
618 bus = get_disk_bus_type(vol_h, errp);
619 if (bus < 0) {
620 goto out_close;
623 disk = g_malloc0(sizeof(*disk));
624 disk->bus_type = find_bus_type(bus);
625 if (bus == BusTypeScsi || bus == BusTypeAta || bus == BusTypeRAID
626 #if (_WIN32_WINNT >= 0x0600)
627 /* This bus type is not supported before Windows Server 2003 SP1 */
628 || bus == BusTypeSas
629 #endif
631 /* We are able to use the same ioctls for different bus types
632 * according to Microsoft docs
633 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
634 if (DeviceIoControl(vol_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
635 sizeof(SCSI_ADDRESS), &len, NULL)) {
636 disk->unit = addr.Lun;
637 disk->target = addr.TargetId;
638 disk->bus = addr.PathId;
639 disk->pci_controller = get_pci_info(name, errp);
641 /* We do not set error in this case, because we still have enough
642 * information about volume. */
643 } else {
644 disk->pci_controller = NULL;
647 list = g_malloc0(sizeof(*list));
648 list->value = disk;
649 list->next = NULL;
650 out_close:
651 CloseHandle(vol_h);
652 out_free:
653 g_free(name);
654 return list;
657 #else
659 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
661 return NULL;
664 #endif /* CONFIG_QGA_NTDDSCSI */
666 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
668 DWORD info_size;
669 char mnt, *mnt_point;
670 char fs_name[32];
671 char vol_info[MAX_PATH+1];
672 size_t len;
673 uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
674 GuestFilesystemInfo *fs = NULL;
676 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
677 if (GetLastError() != ERROR_MORE_DATA) {
678 error_setg_win32(errp, GetLastError(), "failed to get volume name");
679 return NULL;
682 mnt_point = g_malloc(info_size + 1);
683 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
684 &info_size)) {
685 error_setg_win32(errp, GetLastError(), "failed to get volume name");
686 goto free;
689 len = strlen(mnt_point);
690 mnt_point[len] = '\\';
691 mnt_point[len+1] = 0;
692 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
693 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
694 if (GetLastError() != ERROR_NOT_READY) {
695 error_setg_win32(errp, GetLastError(), "failed to get volume info");
697 goto free;
700 fs_name[sizeof(fs_name) - 1] = 0;
701 fs = g_malloc(sizeof(*fs));
702 fs->name = g_strdup(guid);
703 fs->has_total_bytes = false;
704 fs->has_used_bytes = false;
705 if (len == 0) {
706 fs->mountpoint = g_strdup("System Reserved");
707 } else {
708 fs->mountpoint = g_strndup(mnt_point, len);
709 if (GetDiskFreeSpaceEx(fs->mountpoint,
710 (PULARGE_INTEGER) & i64FreeBytesToCaller,
711 (PULARGE_INTEGER) & i64TotalBytes,
712 (PULARGE_INTEGER) & i64FreeBytes)) {
713 fs->used_bytes = i64TotalBytes - i64FreeBytes;
714 fs->total_bytes = i64TotalBytes;
715 fs->has_total_bytes = true;
716 fs->has_used_bytes = true;
719 fs->type = g_strdup(fs_name);
720 fs->disk = build_guest_disk_info(guid, errp);
721 free:
722 g_free(mnt_point);
723 return fs;
726 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
728 HANDLE vol_h;
729 GuestFilesystemInfoList *new, *ret = NULL;
730 char guid[256];
732 vol_h = FindFirstVolume(guid, sizeof(guid));
733 if (vol_h == INVALID_HANDLE_VALUE) {
734 error_setg_win32(errp, GetLastError(), "failed to find any volume");
735 return NULL;
738 do {
739 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
740 if (info == NULL) {
741 continue;
743 new = g_malloc(sizeof(*ret));
744 new->value = info;
745 new->next = ret;
746 ret = new;
747 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
749 if (GetLastError() != ERROR_NO_MORE_FILES) {
750 error_setg_win32(errp, GetLastError(), "failed to find next volume");
753 FindVolumeClose(vol_h);
754 return ret;
758 * Return status of freeze/thaw
760 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
762 if (!vss_initialized()) {
763 error_setg(errp, QERR_UNSUPPORTED);
764 return 0;
767 if (ga_is_frozen(ga_state)) {
768 return GUEST_FSFREEZE_STATUS_FROZEN;
771 return GUEST_FSFREEZE_STATUS_THAWED;
775 * Freeze local file systems using Volume Shadow-copy Service.
776 * The frozen state is limited for up to 10 seconds by VSS.
778 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
780 int i;
781 Error *local_err = NULL;
783 if (!vss_initialized()) {
784 error_setg(errp, QERR_UNSUPPORTED);
785 return 0;
788 slog("guest-fsfreeze called");
790 /* cannot risk guest agent blocking itself on a write in this state */
791 ga_set_frozen(ga_state);
793 qga_vss_fsfreeze(&i, true, &local_err);
794 if (local_err) {
795 error_propagate(errp, local_err);
796 goto error;
799 return i;
801 error:
802 local_err = NULL;
803 qmp_guest_fsfreeze_thaw(&local_err);
804 if (local_err) {
805 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
806 error_free(local_err);
808 return 0;
811 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
812 strList *mountpoints,
813 Error **errp)
815 error_setg(errp, QERR_UNSUPPORTED);
817 return 0;
821 * Thaw local file systems using Volume Shadow-copy Service.
823 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
825 int i;
827 if (!vss_initialized()) {
828 error_setg(errp, QERR_UNSUPPORTED);
829 return 0;
832 qga_vss_fsfreeze(&i, false, errp);
834 ga_unset_frozen(ga_state);
835 return i;
838 static void guest_fsfreeze_cleanup(void)
840 Error *err = NULL;
842 if (!vss_initialized()) {
843 return;
846 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
847 qmp_guest_fsfreeze_thaw(&err);
848 if (err) {
849 slog("failed to clean up frozen filesystems: %s",
850 error_get_pretty(err));
851 error_free(err);
855 vss_deinit(true);
859 * Walk list of mounted file systems in the guest, and discard unused
860 * areas.
862 GuestFilesystemTrimResponse *
863 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
865 GuestFilesystemTrimResponse *resp;
866 HANDLE handle;
867 WCHAR guid[MAX_PATH] = L"";
869 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
870 if (handle == INVALID_HANDLE_VALUE) {
871 error_setg_win32(errp, GetLastError(), "failed to find any volume");
872 return NULL;
875 resp = g_new0(GuestFilesystemTrimResponse, 1);
877 do {
878 GuestFilesystemTrimResult *res;
879 GuestFilesystemTrimResultList *list;
880 PWCHAR uc_path;
881 DWORD char_count = 0;
882 char *path, *out;
883 GError *gerr = NULL;
884 gchar * argv[4];
886 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
888 if (GetLastError() != ERROR_MORE_DATA) {
889 continue;
891 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
892 continue;
895 uc_path = g_malloc(sizeof(WCHAR) * char_count);
896 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
897 &char_count) || !*uc_path) {
898 /* strange, but this condition could be faced even with size == 2 */
899 g_free(uc_path);
900 continue;
903 res = g_new0(GuestFilesystemTrimResult, 1);
905 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
907 g_free(uc_path);
909 if (!path) {
910 res->has_error = true;
911 res->error = g_strdup(gerr->message);
912 g_error_free(gerr);
913 break;
916 res->path = path;
918 list = g_new0(GuestFilesystemTrimResultList, 1);
919 list->value = res;
920 list->next = resp->paths;
922 resp->paths = list;
924 memset(argv, 0, sizeof(argv));
925 argv[0] = (gchar *)"defrag.exe";
926 argv[1] = (gchar *)"/L";
927 argv[2] = path;
929 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
930 &out /* stdout */, NULL /* stdin */,
931 NULL, &gerr)) {
932 res->has_error = true;
933 res->error = g_strdup(gerr->message);
934 g_error_free(gerr);
935 } else {
936 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
937 Error is reported in the output with something like
938 (x89000020) etc code in the stdout */
940 int i;
941 gchar **lines = g_strsplit(out, "\r\n", 0);
942 g_free(out);
944 for (i = 0; lines[i] != NULL; i++) {
945 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
946 continue;
948 res->has_error = true;
949 res->error = g_strdup(lines[i]);
950 break;
952 g_strfreev(lines);
954 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
956 FindVolumeClose(handle);
957 return resp;
960 typedef enum {
961 GUEST_SUSPEND_MODE_DISK,
962 GUEST_SUSPEND_MODE_RAM
963 } GuestSuspendMode;
965 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
967 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
968 Error *local_err = NULL;
970 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
971 if (!GetPwrCapabilities(&sys_pwr_caps)) {
972 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
973 "failed to determine guest suspend capabilities");
974 goto out;
977 switch (mode) {
978 case GUEST_SUSPEND_MODE_DISK:
979 if (!sys_pwr_caps.SystemS4) {
980 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
981 "suspend-to-disk not supported by OS");
983 break;
984 case GUEST_SUSPEND_MODE_RAM:
985 if (!sys_pwr_caps.SystemS3) {
986 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
987 "suspend-to-ram not supported by OS");
989 break;
990 default:
991 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
992 "GuestSuspendMode");
995 out:
996 error_propagate(errp, local_err);
999 static DWORD WINAPI do_suspend(LPVOID opaque)
1001 GuestSuspendMode *mode = opaque;
1002 DWORD ret = 0;
1004 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1005 slog("failed to suspend guest, %lu", GetLastError());
1006 ret = -1;
1008 g_free(mode);
1009 return ret;
1012 void qmp_guest_suspend_disk(Error **errp)
1014 Error *local_err = NULL;
1015 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1017 *mode = GUEST_SUSPEND_MODE_DISK;
1018 check_suspend_mode(*mode, &local_err);
1019 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1020 execute_async(do_suspend, mode, &local_err);
1022 if (local_err) {
1023 error_propagate(errp, local_err);
1024 g_free(mode);
1028 void qmp_guest_suspend_ram(Error **errp)
1030 Error *local_err = NULL;
1031 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1033 *mode = GUEST_SUSPEND_MODE_RAM;
1034 check_suspend_mode(*mode, &local_err);
1035 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1036 execute_async(do_suspend, mode, &local_err);
1038 if (local_err) {
1039 error_propagate(errp, local_err);
1040 g_free(mode);
1044 void qmp_guest_suspend_hybrid(Error **errp)
1046 error_setg(errp, QERR_UNSUPPORTED);
1049 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1051 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1052 ULONG adptr_addrs_len = 0;
1053 DWORD ret;
1055 /* Call the first time to get the adptr_addrs_len. */
1056 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1057 NULL, adptr_addrs, &adptr_addrs_len);
1059 adptr_addrs = g_malloc(adptr_addrs_len);
1060 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1061 NULL, adptr_addrs, &adptr_addrs_len);
1062 if (ret != ERROR_SUCCESS) {
1063 error_setg_win32(errp, ret, "failed to get adapters addresses");
1064 g_free(adptr_addrs);
1065 adptr_addrs = NULL;
1067 return adptr_addrs;
1070 static char *guest_wctomb_dup(WCHAR *wstr)
1072 char *str;
1073 size_t i;
1075 i = wcslen(wstr) + 1;
1076 str = g_malloc(i);
1077 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
1078 wstr, -1, str, i, NULL, NULL);
1079 return str;
1082 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1083 Error **errp)
1085 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1086 DWORD len;
1087 int ret;
1089 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1090 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1091 len = sizeof(addr_str);
1092 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1093 ip_addr->Address.iSockaddrLength,
1094 NULL,
1095 addr_str,
1096 &len);
1097 if (ret != 0) {
1098 error_setg_win32(errp, WSAGetLastError(),
1099 "failed address presentation form conversion");
1100 return NULL;
1102 return g_strdup(addr_str);
1104 return NULL;
1107 #if (_WIN32_WINNT >= 0x0600)
1108 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1110 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1111 * field to obtain the prefix.
1113 return ip_addr->OnLinkPrefixLength;
1115 #else
1116 /* When using the Windows XP and 2003 build environment, do the best we can to
1117 * figure out the prefix.
1119 static IP_ADAPTER_INFO *guest_get_adapters_info(void)
1121 IP_ADAPTER_INFO *adptr_info = NULL;
1122 ULONG adptr_info_len = 0;
1123 DWORD ret;
1125 /* Call the first time to get the adptr_info_len. */
1126 GetAdaptersInfo(adptr_info, &adptr_info_len);
1128 adptr_info = g_malloc(adptr_info_len);
1129 ret = GetAdaptersInfo(adptr_info, &adptr_info_len);
1130 if (ret != ERROR_SUCCESS) {
1131 g_free(adptr_info);
1132 adptr_info = NULL;
1134 return adptr_info;
1137 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1139 int64_t prefix = -1; /* Use for AF_INET6 and unknown/undetermined values. */
1140 IP_ADAPTER_INFO *adptr_info, *info;
1141 IP_ADDR_STRING *ip;
1142 struct in_addr *p;
1144 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
1145 return prefix;
1147 adptr_info = guest_get_adapters_info();
1148 if (adptr_info == NULL) {
1149 return prefix;
1152 /* Match up the passed in ip_addr with one found in adaptr_info.
1153 * The matching one in adptr_info will have the netmask.
1155 p = &((struct sockaddr_in *)ip_addr->Address.lpSockaddr)->sin_addr;
1156 for (info = adptr_info; info; info = info->Next) {
1157 for (ip = &info->IpAddressList; ip; ip = ip->Next) {
1158 if (p->S_un.S_addr == inet_addr(ip->IpAddress.String)) {
1159 prefix = ctpop32(inet_addr(ip->IpMask.String));
1160 goto out;
1164 out:
1165 g_free(adptr_info);
1166 return prefix;
1168 #endif
1170 #define INTERFACE_PATH_BUF_SZ 512
1172 static DWORD get_interface_index(const char *guid)
1174 ULONG index;
1175 DWORD status;
1176 wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1177 snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1178 wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1179 status = GetAdapterIndex (wbuf, &index);
1180 if (status != NO_ERROR) {
1181 return (DWORD)~0;
1182 } else {
1183 return index;
1187 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1189 static int guest_get_network_stats(const char *name,
1190 GuestNetworkInterfaceStat *stats)
1192 OSVERSIONINFO os_ver;
1194 os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1195 GetVersionEx(&os_ver);
1196 if (os_ver.dwMajorVersion >= 6) {
1197 MIB_IF_ROW2 a_mid_ifrow;
1198 GetIfEntry2Func getifentry2_ex;
1199 DWORD if_index = 0;
1200 HMODULE module = GetModuleHandle("iphlpapi");
1201 PVOID func = GetProcAddress(module, "GetIfEntry2");
1203 if (func == NULL) {
1204 return -1;
1207 getifentry2_ex = (GetIfEntry2Func)func;
1208 if_index = get_interface_index(name);
1209 if (if_index == (DWORD)~0) {
1210 return -1;
1213 memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1214 a_mid_ifrow.InterfaceIndex = if_index;
1215 if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1216 stats->rx_bytes = a_mid_ifrow.InOctets;
1217 stats->rx_packets = a_mid_ifrow.InUcastPkts;
1218 stats->rx_errs = a_mid_ifrow.InErrors;
1219 stats->rx_dropped = a_mid_ifrow.InDiscards;
1220 stats->tx_bytes = a_mid_ifrow.OutOctets;
1221 stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1222 stats->tx_errs = a_mid_ifrow.OutErrors;
1223 stats->tx_dropped = a_mid_ifrow.OutDiscards;
1224 return 0;
1227 return -1;
1230 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1232 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1233 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1234 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1235 GuestIpAddressList *head_addr, *cur_addr;
1236 GuestNetworkInterfaceList *info;
1237 GuestNetworkInterfaceStat *interface_stat = NULL;
1238 GuestIpAddressList *address_item = NULL;
1239 unsigned char *mac_addr;
1240 char *addr_str;
1241 WORD wsa_version;
1242 WSADATA wsa_data;
1243 int ret;
1245 adptr_addrs = guest_get_adapters_addresses(errp);
1246 if (adptr_addrs == NULL) {
1247 return NULL;
1250 /* Make WSA APIs available. */
1251 wsa_version = MAKEWORD(2, 2);
1252 ret = WSAStartup(wsa_version, &wsa_data);
1253 if (ret != 0) {
1254 error_setg_win32(errp, ret, "failed socket startup");
1255 goto out;
1258 for (addr = adptr_addrs; addr; addr = addr->Next) {
1259 info = g_malloc0(sizeof(*info));
1261 if (cur_item == NULL) {
1262 head = cur_item = info;
1263 } else {
1264 cur_item->next = info;
1265 cur_item = info;
1268 info->value = g_malloc0(sizeof(*info->value));
1269 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1271 if (addr->PhysicalAddressLength != 0) {
1272 mac_addr = addr->PhysicalAddress;
1274 info->value->hardware_address =
1275 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1276 (int) mac_addr[0], (int) mac_addr[1],
1277 (int) mac_addr[2], (int) mac_addr[3],
1278 (int) mac_addr[4], (int) mac_addr[5]);
1280 info->value->has_hardware_address = true;
1283 head_addr = NULL;
1284 cur_addr = NULL;
1285 for (ip_addr = addr->FirstUnicastAddress;
1286 ip_addr;
1287 ip_addr = ip_addr->Next) {
1288 addr_str = guest_addr_to_str(ip_addr, errp);
1289 if (addr_str == NULL) {
1290 continue;
1293 address_item = g_malloc0(sizeof(*address_item));
1295 if (!cur_addr) {
1296 head_addr = cur_addr = address_item;
1297 } else {
1298 cur_addr->next = address_item;
1299 cur_addr = address_item;
1302 address_item->value = g_malloc0(sizeof(*address_item->value));
1303 address_item->value->ip_address = addr_str;
1304 address_item->value->prefix = guest_ip_prefix(ip_addr);
1305 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1306 address_item->value->ip_address_type =
1307 GUEST_IP_ADDRESS_TYPE_IPV4;
1308 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1309 address_item->value->ip_address_type =
1310 GUEST_IP_ADDRESS_TYPE_IPV6;
1313 if (head_addr) {
1314 info->value->has_ip_addresses = true;
1315 info->value->ip_addresses = head_addr;
1317 if (!info->value->has_statistics) {
1318 interface_stat = g_malloc0(sizeof(*interface_stat));
1319 if (guest_get_network_stats(addr->AdapterName,
1320 interface_stat) == -1) {
1321 info->value->has_statistics = false;
1322 g_free(interface_stat);
1323 } else {
1324 info->value->statistics = interface_stat;
1325 info->value->has_statistics = true;
1329 WSACleanup();
1330 out:
1331 g_free(adptr_addrs);
1332 return head;
1335 int64_t qmp_guest_get_time(Error **errp)
1337 SYSTEMTIME ts = {0};
1338 FILETIME tf;
1340 GetSystemTime(&ts);
1341 if (ts.wYear < 1601 || ts.wYear > 30827) {
1342 error_setg(errp, "Failed to get time");
1343 return -1;
1346 if (!SystemTimeToFileTime(&ts, &tf)) {
1347 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1348 return -1;
1351 return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1352 - W32_FT_OFFSET) * 100;
1355 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1357 Error *local_err = NULL;
1358 SYSTEMTIME ts;
1359 FILETIME tf;
1360 LONGLONG time;
1362 if (!has_time) {
1363 /* Unfortunately, Windows libraries don't provide an easy way to access
1364 * RTC yet:
1366 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1368 * Instead, a workaround is to use the Windows win32tm command to
1369 * resync the time using the Windows Time service.
1371 LPVOID msg_buffer;
1372 DWORD ret_flags;
1374 HRESULT hr = system("w32tm /resync /nowait");
1376 if (GetLastError() != 0) {
1377 strerror_s((LPTSTR) & msg_buffer, 0, errno);
1378 error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1379 } else if (hr != 0) {
1380 if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1381 error_setg(errp, "Windows Time service not running on the "
1382 "guest");
1383 } else {
1384 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1385 FORMAT_MESSAGE_FROM_SYSTEM |
1386 FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1387 (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1388 SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1389 NULL)) {
1390 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1391 "t retrieve error message", hr);
1392 } else {
1393 error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1394 (LPCTSTR)msg_buffer);
1395 LocalFree(msg_buffer);
1398 } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1399 error_setg(errp, "No internet connection on guest, sync not "
1400 "accurate");
1402 return;
1405 /* Validate time passed by user. */
1406 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1407 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1408 return;
1411 time = time_ns / 100 + W32_FT_OFFSET;
1413 tf.dwLowDateTime = (DWORD) time;
1414 tf.dwHighDateTime = (DWORD) (time >> 32);
1416 if (!FileTimeToSystemTime(&tf, &ts)) {
1417 error_setg(errp, "Failed to convert system time %d",
1418 (int)GetLastError());
1419 return;
1422 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1423 if (local_err) {
1424 error_propagate(errp, local_err);
1425 return;
1428 if (!SetSystemTime(&ts)) {
1429 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1430 return;
1434 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1436 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1437 DWORD length;
1438 GuestLogicalProcessorList *head, **link;
1439 Error *local_err = NULL;
1440 int64_t current;
1442 ptr = pslpi = NULL;
1443 length = 0;
1444 current = 0;
1445 head = NULL;
1446 link = &head;
1448 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1449 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1450 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1451 ptr = pslpi = g_malloc0(length);
1452 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1453 error_setg(&local_err, "Failed to get processor information: %d",
1454 (int)GetLastError());
1456 } else {
1457 error_setg(&local_err,
1458 "Failed to get processor information buffer length: %d",
1459 (int)GetLastError());
1462 while ((local_err == NULL) && (length > 0)) {
1463 if (pslpi->Relationship == RelationProcessorCore) {
1464 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1466 while (cpu_bits > 0) {
1467 if (!!(cpu_bits & 1)) {
1468 GuestLogicalProcessor *vcpu;
1469 GuestLogicalProcessorList *entry;
1471 vcpu = g_malloc0(sizeof *vcpu);
1472 vcpu->logical_id = current++;
1473 vcpu->online = true;
1474 vcpu->has_can_offline = true;
1476 entry = g_malloc0(sizeof *entry);
1477 entry->value = vcpu;
1479 *link = entry;
1480 link = &entry->next;
1482 cpu_bits >>= 1;
1485 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1486 pslpi++; /* next entry */
1489 g_free(ptr);
1491 if (local_err == NULL) {
1492 if (head != NULL) {
1493 return head;
1495 /* there's no guest with zero VCPUs */
1496 error_setg(&local_err, "Guest reported zero VCPUs");
1499 qapi_free_GuestLogicalProcessorList(head);
1500 error_propagate(errp, local_err);
1501 return NULL;
1504 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1506 error_setg(errp, QERR_UNSUPPORTED);
1507 return -1;
1510 static gchar *
1511 get_net_error_message(gint error)
1513 HMODULE module = NULL;
1514 gchar *retval = NULL;
1515 wchar_t *msg = NULL;
1516 int flags;
1517 size_t nchars;
1519 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1520 FORMAT_MESSAGE_IGNORE_INSERTS |
1521 FORMAT_MESSAGE_FROM_SYSTEM;
1523 if (error >= NERR_BASE && error <= MAX_NERR) {
1524 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1526 if (module != NULL) {
1527 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1531 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1533 if (msg != NULL) {
1534 nchars = wcslen(msg);
1536 if (nchars >= 2 &&
1537 msg[nchars - 1] == L'\n' &&
1538 msg[nchars - 2] == L'\r') {
1539 msg[nchars - 2] = L'\0';
1542 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1544 LocalFree(msg);
1547 if (module != NULL) {
1548 FreeLibrary(module);
1551 return retval;
1554 void qmp_guest_set_user_password(const char *username,
1555 const char *password,
1556 bool crypted,
1557 Error **errp)
1559 NET_API_STATUS nas;
1560 char *rawpasswddata = NULL;
1561 size_t rawpasswdlen;
1562 wchar_t *user = NULL, *wpass = NULL;
1563 USER_INFO_1003 pi1003 = { 0, };
1564 GError *gerr = NULL;
1566 if (crypted) {
1567 error_setg(errp, QERR_UNSUPPORTED);
1568 return;
1571 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1572 if (!rawpasswddata) {
1573 return;
1575 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1576 rawpasswddata[rawpasswdlen] = '\0';
1578 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1579 if (!user) {
1580 goto done;
1583 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1584 if (!wpass) {
1585 goto done;
1588 pi1003.usri1003_password = wpass;
1589 nas = NetUserSetInfo(NULL, user,
1590 1003, (LPBYTE)&pi1003,
1591 NULL);
1593 if (nas != NERR_Success) {
1594 gchar *msg = get_net_error_message(nas);
1595 error_setg(errp, "failed to set password: %s", msg);
1596 g_free(msg);
1599 done:
1600 if (gerr) {
1601 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1602 g_error_free(gerr);
1604 g_free(user);
1605 g_free(wpass);
1606 g_free(rawpasswddata);
1609 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1611 error_setg(errp, QERR_UNSUPPORTED);
1612 return NULL;
1615 GuestMemoryBlockResponseList *
1616 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1618 error_setg(errp, QERR_UNSUPPORTED);
1619 return NULL;
1622 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1624 error_setg(errp, QERR_UNSUPPORTED);
1625 return NULL;
1628 /* add unsupported commands to the blacklist */
1629 GList *ga_command_blacklist_init(GList *blacklist)
1631 const char *list_unsupported[] = {
1632 "guest-suspend-hybrid",
1633 "guest-set-vcpus",
1634 "guest-get-memory-blocks", "guest-set-memory-blocks",
1635 "guest-get-memory-block-size",
1636 "guest-fsfreeze-freeze-list",
1637 NULL};
1638 char **p = (char **)list_unsupported;
1640 while (*p) {
1641 blacklist = g_list_append(blacklist, g_strdup(*p++));
1644 if (!vss_init(true)) {
1645 g_debug("vss_init failed, vss commands are going to be disabled");
1646 const char *list[] = {
1647 "guest-get-fsinfo", "guest-fsfreeze-status",
1648 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1649 p = (char **)list;
1651 while (*p) {
1652 blacklist = g_list_append(blacklist, g_strdup(*p++));
1656 return blacklist;
1659 /* register init/cleanup routines for stateful command groups */
1660 void ga_command_state_init(GAState *s, GACommandState *cs)
1662 if (!vss_initialized()) {
1663 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1667 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1668 typedef struct _GA_WTSINFOA {
1669 WTS_CONNECTSTATE_CLASS State;
1670 DWORD SessionId;
1671 DWORD IncomingBytes;
1672 DWORD OutgoingBytes;
1673 DWORD IncomingFrames;
1674 DWORD OutgoingFrames;
1675 DWORD IncomingCompressedBytes;
1676 DWORD OutgoingCompressedBy;
1677 CHAR WinStationName[WINSTATIONNAME_LENGTH];
1678 CHAR Domain[DOMAIN_LENGTH];
1679 CHAR UserName[USERNAME_LENGTH + 1];
1680 LARGE_INTEGER ConnectTime;
1681 LARGE_INTEGER DisconnectTime;
1682 LARGE_INTEGER LastInputTime;
1683 LARGE_INTEGER LogonTime;
1684 LARGE_INTEGER CurrentTime;
1686 } GA_WTSINFOA;
1688 GuestUserList *qmp_guest_get_users(Error **err)
1690 #if (_WIN32_WINNT >= 0x0600)
1691 #define QGA_NANOSECONDS 10000000
1693 GHashTable *cache = NULL;
1694 GuestUserList *head = NULL, *cur_item = NULL;
1696 DWORD buffer_size = 0, count = 0, i = 0;
1697 GA_WTSINFOA *info = NULL;
1698 WTS_SESSION_INFOA *entries = NULL;
1699 GuestUserList *item = NULL;
1700 GuestUser *user = NULL;
1701 gpointer value = NULL;
1702 INT64 login = 0;
1703 double login_time = 0;
1705 cache = g_hash_table_new(g_str_hash, g_str_equal);
1707 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
1708 for (i = 0; i < count; ++i) {
1709 buffer_size = 0;
1710 info = NULL;
1711 if (WTSQuerySessionInformationA(
1712 NULL,
1713 entries[i].SessionId,
1714 WTSSessionInfo,
1715 (LPSTR *)&info,
1716 &buffer_size
1717 )) {
1719 if (strlen(info->UserName) == 0) {
1720 WTSFreeMemory(info);
1721 continue;
1724 login = info->LogonTime.QuadPart;
1725 login -= W32_FT_OFFSET;
1726 login_time = ((double)login) / QGA_NANOSECONDS;
1728 if (g_hash_table_contains(cache, info->UserName)) {
1729 value = g_hash_table_lookup(cache, info->UserName);
1730 user = (GuestUser *)value;
1731 if (user->login_time > login_time) {
1732 user->login_time = login_time;
1734 } else {
1735 item = g_new0(GuestUserList, 1);
1736 item->value = g_new0(GuestUser, 1);
1738 item->value->user = g_strdup(info->UserName);
1739 item->value->domain = g_strdup(info->Domain);
1740 item->value->has_domain = true;
1742 item->value->login_time = login_time;
1744 g_hash_table_add(cache, item->value->user);
1746 if (!cur_item) {
1747 head = cur_item = item;
1748 } else {
1749 cur_item->next = item;
1750 cur_item = item;
1754 WTSFreeMemory(info);
1756 WTSFreeMemory(entries);
1758 g_hash_table_destroy(cache);
1759 return head;
1760 #else
1761 error_setg(err, QERR_UNSUPPORTED);
1762 return NULL;
1763 #endif
1766 typedef struct _ga_matrix_lookup_t {
1767 int major;
1768 int minor;
1769 char const *version;
1770 char const *version_id;
1771 } ga_matrix_lookup_t;
1773 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
1775 /* Desktop editions */
1776 { 5, 0, "Microsoft Windows 2000", "2000"},
1777 { 5, 1, "Microsoft Windows XP", "xp"},
1778 { 6, 0, "Microsoft Windows Vista", "vista"},
1779 { 6, 1, "Microsoft Windows 7" "7"},
1780 { 6, 2, "Microsoft Windows 8", "8"},
1781 { 6, 3, "Microsoft Windows 8.1", "8.1"},
1782 {10, 0, "Microsoft Windows 10", "10"},
1783 { 0, 0, 0}
1785 /* Server editions */
1786 { 5, 2, "Microsoft Windows Server 2003", "2003"},
1787 { 6, 0, "Microsoft Windows Server 2008", "2008"},
1788 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
1789 { 6, 2, "Microsoft Windows Server 2012", "2012"},
1790 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
1791 {10, 0, "Microsoft Windows Server 2016", "2016"},
1792 { 0, 0, 0},
1793 { 0, 0, 0}
1797 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
1799 typedef NTSTATUS(WINAPI * rtl_get_version_t)(
1800 RTL_OSVERSIONINFOEXW *os_version_info_ex);
1802 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
1804 HMODULE module = GetModuleHandle("ntdll");
1805 PVOID fun = GetProcAddress(module, "RtlGetVersion");
1806 if (fun == NULL) {
1807 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1808 "Failed to get address of RtlGetVersion");
1809 return;
1812 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
1813 rtl_get_version(info);
1814 return;
1817 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
1819 DWORD major = os_version->dwMajorVersion;
1820 DWORD minor = os_version->dwMinorVersion;
1821 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
1822 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
1823 while (table->version != NULL) {
1824 if (major == table->major && minor == table->minor) {
1825 if (id) {
1826 return g_strdup(table->version_id);
1827 } else {
1828 return g_strdup(table->version);
1831 ++table;
1833 slog("failed to lookup Windows version: major=%lu, minor=%lu",
1834 major, minor);
1835 return g_strdup("N/A");
1838 static char *ga_get_win_product_name(Error **errp)
1840 HKEY key = NULL;
1841 DWORD size = 128;
1842 char *result = g_malloc0(size);
1843 LONG err = ERROR_SUCCESS;
1845 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
1846 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
1847 &key);
1848 if (err != ERROR_SUCCESS) {
1849 error_setg_win32(errp, err, "failed to open registry key");
1850 goto fail;
1853 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
1854 (LPBYTE)result, &size);
1855 if (err == ERROR_MORE_DATA) {
1856 slog("ProductName longer than expected (%lu bytes), retrying",
1857 size);
1858 g_free(result);
1859 result = NULL;
1860 if (size > 0) {
1861 result = g_malloc0(size);
1862 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
1863 (LPBYTE)result, &size);
1866 if (err != ERROR_SUCCESS) {
1867 error_setg_win32(errp, err, "failed to retrive ProductName");
1868 goto fail;
1871 return result;
1873 fail:
1874 g_free(result);
1875 return NULL;
1878 static char *ga_get_current_arch(void)
1880 SYSTEM_INFO info;
1881 GetNativeSystemInfo(&info);
1882 char *result = NULL;
1883 switch (info.wProcessorArchitecture) {
1884 case PROCESSOR_ARCHITECTURE_AMD64:
1885 result = g_strdup("x86_64");
1886 break;
1887 case PROCESSOR_ARCHITECTURE_ARM:
1888 result = g_strdup("arm");
1889 break;
1890 case PROCESSOR_ARCHITECTURE_IA64:
1891 result = g_strdup("ia64");
1892 break;
1893 case PROCESSOR_ARCHITECTURE_INTEL:
1894 result = g_strdup("x86");
1895 break;
1896 case PROCESSOR_ARCHITECTURE_UNKNOWN:
1897 default:
1898 slog("unknown processor architecture 0x%0x",
1899 info.wProcessorArchitecture);
1900 result = g_strdup("unknown");
1901 break;
1903 return result;
1906 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
1908 Error *local_err = NULL;
1909 OSVERSIONINFOEXW os_version = {0};
1910 bool server;
1911 char *product_name;
1912 GuestOSInfo *info;
1914 ga_get_win_version(&os_version, &local_err);
1915 if (local_err) {
1916 error_propagate(errp, local_err);
1917 return NULL;
1920 server = os_version.wProductType != VER_NT_WORKSTATION;
1921 product_name = ga_get_win_product_name(&local_err);
1922 if (product_name == NULL) {
1923 error_propagate(errp, local_err);
1924 return NULL;
1927 info = g_new0(GuestOSInfo, 1);
1929 info->has_kernel_version = true;
1930 info->kernel_version = g_strdup_printf("%lu.%lu",
1931 os_version.dwMajorVersion,
1932 os_version.dwMinorVersion);
1933 info->has_kernel_release = true;
1934 info->kernel_release = g_strdup_printf("%lu",
1935 os_version.dwBuildNumber);
1936 info->has_machine = true;
1937 info->machine = ga_get_current_arch();
1939 info->has_id = true;
1940 info->id = g_strdup("mswindows");
1941 info->has_name = true;
1942 info->name = g_strdup("Microsoft Windows");
1943 info->has_pretty_name = true;
1944 info->pretty_name = product_name;
1945 info->has_version = true;
1946 info->version = ga_get_win_name(&os_version, false);
1947 info->has_version_id = true;
1948 info->version_id = ga_get_win_name(&os_version, true);
1949 info->has_variant = true;
1950 info->variant = g_strdup(server ? "server" : "client");
1951 info->has_variant_id = true;
1952 info->variant_id = g_strdup(server ? "server" : "client");
1954 return info;