vfio/pci: Rename INTx functions for easier tracing
[qemu/ar7.git] / qga / commands-win32.c
blob41bdd3f7cc3cb5de40d5c2c5a413ebe7a916e039
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 #include <glib.h>
15 #include <wtypes.h>
16 #include <powrprof.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <winsock2.h>
20 #include <ws2tcpip.h>
21 #include <iptypes.h>
22 #include <iphlpapi.h>
23 #ifdef CONFIG_QGA_NTDDSCSI
24 #include <winioctl.h>
25 #include <ntddscsi.h>
26 #include <setupapi.h>
27 #include <initguid.h>
28 #endif
29 #include <lm.h>
31 #include "qga/guest-agent-core.h"
32 #include "qga/vss-win32.h"
33 #include "qga-qmp-commands.h"
34 #include "qapi/qmp/qerror.h"
35 #include "qemu/queue.h"
36 #include "qemu/host-utils.h"
38 #ifndef SHTDN_REASON_FLAG_PLANNED
39 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
40 #endif
42 /* multiple of 100 nanoseconds elapsed between windows baseline
43 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
44 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
45 (365 * (1970 - 1601) + \
46 (1970 - 1601) / 4 - 3))
48 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
50 typedef struct GuestFileHandle {
51 int64_t id;
52 HANDLE fh;
53 QTAILQ_ENTRY(GuestFileHandle) next;
54 } GuestFileHandle;
56 static struct {
57 QTAILQ_HEAD(, GuestFileHandle) filehandles;
58 } guest_file_state;
61 typedef struct OpenFlags {
62 const char *forms;
63 DWORD desired_access;
64 DWORD creation_disposition;
65 } OpenFlags;
66 static OpenFlags guest_file_open_modes[] = {
67 {"r", GENERIC_READ, OPEN_EXISTING},
68 {"rb", GENERIC_READ, OPEN_EXISTING},
69 {"w", GENERIC_WRITE, CREATE_ALWAYS},
70 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
71 {"a", GENERIC_WRITE, OPEN_ALWAYS },
72 {"r+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
73 {"rb+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
74 {"r+b", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
75 {"w+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
76 {"wb+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
77 {"w+b", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
78 {"a+", GENERIC_WRITE|GENERIC_READ, OPEN_ALWAYS },
79 {"ab+", GENERIC_WRITE|GENERIC_READ, OPEN_ALWAYS },
80 {"a+b", GENERIC_WRITE|GENERIC_READ, OPEN_ALWAYS }
83 static OpenFlags *find_open_flag(const char *mode_str)
85 int mode;
86 Error **errp = NULL;
88 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
89 OpenFlags *flags = guest_file_open_modes + mode;
91 if (strcmp(flags->forms, mode_str) == 0) {
92 return flags;
96 error_setg(errp, "invalid file open mode '%s'", mode_str);
97 return NULL;
100 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
102 GuestFileHandle *gfh;
103 int64_t handle;
105 handle = ga_get_fd_handle(ga_state, errp);
106 if (handle < 0) {
107 return -1;
109 gfh = g_malloc0(sizeof(GuestFileHandle));
110 gfh->id = handle;
111 gfh->fh = fh;
112 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
114 return handle;
117 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
119 GuestFileHandle *gfh;
120 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
121 if (gfh->id == id) {
122 return gfh;
125 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
126 return NULL;
129 int64_t qmp_guest_file_open(const char *path, bool has_mode,
130 const char *mode, Error **errp)
132 int64_t fd;
133 HANDLE fh;
134 HANDLE templ_file = NULL;
135 DWORD share_mode = FILE_SHARE_READ;
136 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
137 LPSECURITY_ATTRIBUTES sa_attr = NULL;
138 OpenFlags *guest_flags;
140 if (!has_mode) {
141 mode = "r";
143 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
144 guest_flags = find_open_flag(mode);
145 if (guest_flags == NULL) {
146 error_setg(errp, "invalid file open mode");
147 return -1;
150 fh = CreateFile(path, guest_flags->desired_access, share_mode, sa_attr,
151 guest_flags->creation_disposition, flags_and_attr,
152 templ_file);
153 if (fh == INVALID_HANDLE_VALUE) {
154 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
155 path);
156 return -1;
159 fd = guest_file_handle_add(fh, errp);
160 if (fd < 0) {
161 CloseHandle(&fh);
162 error_setg(errp, "failed to add handle to qmp handle table");
163 return -1;
166 slog("guest-file-open, handle: % " PRId64, fd);
167 return fd;
170 void qmp_guest_file_close(int64_t handle, Error **errp)
172 bool ret;
173 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
174 slog("guest-file-close called, handle: %" PRId64, handle);
175 if (gfh == NULL) {
176 return;
178 ret = CloseHandle(gfh->fh);
179 if (!ret) {
180 error_setg_win32(errp, GetLastError(), "failed close handle");
181 return;
184 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
185 g_free(gfh);
188 static void acquire_privilege(const char *name, Error **errp)
190 HANDLE token = NULL;
191 TOKEN_PRIVILEGES priv;
192 Error *local_err = NULL;
194 if (OpenProcessToken(GetCurrentProcess(),
195 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
197 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
198 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
199 "no luid for requested privilege");
200 goto out;
203 priv.PrivilegeCount = 1;
204 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
206 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
207 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
208 "unable to acquire requested privilege");
209 goto out;
212 } else {
213 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
214 "failed to open privilege token");
217 out:
218 if (token) {
219 CloseHandle(token);
221 if (local_err) {
222 error_propagate(errp, local_err);
226 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
227 Error **errp)
229 Error *local_err = NULL;
231 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
232 if (!thread) {
233 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
234 "failed to dispatch asynchronous command");
235 error_propagate(errp, local_err);
239 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
241 Error *local_err = NULL;
242 UINT shutdown_flag = EWX_FORCE;
244 slog("guest-shutdown called, mode: %s", mode);
246 if (!has_mode || strcmp(mode, "powerdown") == 0) {
247 shutdown_flag |= EWX_POWEROFF;
248 } else if (strcmp(mode, "halt") == 0) {
249 shutdown_flag |= EWX_SHUTDOWN;
250 } else if (strcmp(mode, "reboot") == 0) {
251 shutdown_flag |= EWX_REBOOT;
252 } else {
253 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
254 "halt|powerdown|reboot");
255 return;
258 /* Request a shutdown privilege, but try to shut down the system
259 anyway. */
260 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
261 if (local_err) {
262 error_propagate(errp, local_err);
263 return;
266 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
267 slog("guest-shutdown failed: %lu", GetLastError());
268 error_setg(errp, QERR_UNDEFINED_ERROR);
272 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
273 int64_t count, Error **errp)
275 GuestFileRead *read_data = NULL;
276 guchar *buf;
277 HANDLE fh;
278 bool is_ok;
279 DWORD read_count;
280 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
282 if (!gfh) {
283 return NULL;
285 if (!has_count) {
286 count = QGA_READ_COUNT_DEFAULT;
287 } else if (count < 0) {
288 error_setg(errp, "value '%" PRId64
289 "' is invalid for argument count", count);
290 return NULL;
293 fh = gfh->fh;
294 buf = g_malloc0(count+1);
295 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
296 if (!is_ok) {
297 error_setg_win32(errp, GetLastError(), "failed to read file");
298 slog("guest-file-read failed, handle %" PRId64, handle);
299 } else {
300 buf[read_count] = 0;
301 read_data = g_malloc0(sizeof(GuestFileRead));
302 read_data->count = (size_t)read_count;
303 read_data->eof = read_count == 0;
305 if (read_count != 0) {
306 read_data->buf_b64 = g_base64_encode(buf, read_count);
309 g_free(buf);
311 return read_data;
314 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
315 bool has_count, int64_t count,
316 Error **errp)
318 GuestFileWrite *write_data = NULL;
319 guchar *buf;
320 gsize buf_len;
321 bool is_ok;
322 DWORD write_count;
323 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
324 HANDLE fh;
326 if (!gfh) {
327 return NULL;
329 fh = gfh->fh;
330 buf = g_base64_decode(buf_b64, &buf_len);
332 if (!has_count) {
333 count = buf_len;
334 } else if (count < 0 || count > buf_len) {
335 error_setg(errp, "value '%" PRId64
336 "' is invalid for argument count", count);
337 goto done;
340 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
341 if (!is_ok) {
342 error_setg_win32(errp, GetLastError(), "failed to write to file");
343 slog("guest-file-write-failed, handle: %" PRId64, handle);
344 } else {
345 write_data = g_malloc0(sizeof(GuestFileWrite));
346 write_data->count = (size_t) write_count;
349 done:
350 g_free(buf);
351 return write_data;
354 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
355 int64_t whence, Error **errp)
357 GuestFileHandle *gfh;
358 GuestFileSeek *seek_data;
359 HANDLE fh;
360 LARGE_INTEGER new_pos, off_pos;
361 off_pos.QuadPart = offset;
362 BOOL res;
363 gfh = guest_file_handle_find(handle, errp);
364 if (!gfh) {
365 return NULL;
368 fh = gfh->fh;
369 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
370 if (!res) {
371 error_setg_win32(errp, GetLastError(), "failed to seek file");
372 return NULL;
374 seek_data = g_new0(GuestFileSeek, 1);
375 seek_data->position = new_pos.QuadPart;
376 return seek_data;
379 void qmp_guest_file_flush(int64_t handle, Error **errp)
381 HANDLE fh;
382 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
383 if (!gfh) {
384 return;
387 fh = gfh->fh;
388 if (!FlushFileBuffers(fh)) {
389 error_setg_win32(errp, GetLastError(), "failed to flush file");
393 static void guest_file_init(void)
395 QTAILQ_INIT(&guest_file_state.filehandles);
398 #ifdef CONFIG_QGA_NTDDSCSI
400 static STORAGE_BUS_TYPE win2qemu[] = {
401 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
402 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
403 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
404 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
405 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
406 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
407 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
408 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
409 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
410 #if (_WIN32_WINNT >= 0x0600)
411 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
412 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
413 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
414 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
415 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
416 #endif
417 #if (_WIN32_WINNT >= 0x0601)
418 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
419 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
420 #endif
423 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
425 if (bus > ARRAY_SIZE(win2qemu) || (int)bus < 0) {
426 return GUEST_DISK_BUS_TYPE_UNKNOWN;
428 return win2qemu[(int)bus];
431 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME,
432 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2,
433 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
435 static GuestPCIAddress *get_pci_info(char *guid, Error **errp)
437 HDEVINFO dev_info;
438 SP_DEVINFO_DATA dev_info_data;
439 DWORD size = 0;
440 int i;
441 char dev_name[MAX_PATH];
442 char *buffer = NULL;
443 GuestPCIAddress *pci = NULL;
444 char *name = g_strdup(&guid[4]);
446 if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {
447 error_setg_win32(errp, GetLastError(), "failed to get dos device name");
448 goto out;
451 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, 0, 0,
452 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
453 if (dev_info == INVALID_HANDLE_VALUE) {
454 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
455 goto out;
458 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
459 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
460 DWORD addr, bus, slot, func, dev, data, size2;
461 while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
462 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
463 &data, (PBYTE)buffer, size,
464 &size2)) {
465 size = MAX(size, size2);
466 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
467 g_free(buffer);
468 /* Double the size to avoid problems on
469 * W2k MBCS systems per KB 888609.
470 * https://support.microsoft.com/en-us/kb/259695 */
471 buffer = g_malloc(size * 2);
472 } else {
473 error_setg_win32(errp, GetLastError(),
474 "failed to get device name");
475 goto out;
479 if (g_strcmp0(buffer, dev_name)) {
480 continue;
483 /* There is no need to allocate buffer in the next functions. The size
484 * is known and ULONG according to
485 * https://support.microsoft.com/en-us/kb/253232
486 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
488 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
489 SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {
490 break;
493 /* The function retrieves the device's address. This value will be
494 * transformed into device function and number */
495 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
496 SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {
497 break;
500 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
501 * This number is typically a user-perceived slot number. */
502 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
503 SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {
504 break;
507 /* SetupApi gives us the same information as driver with
508 * IoGetDeviceProperty. According to Microsoft
509 * https://support.microsoft.com/en-us/kb/253232
510 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
511 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
512 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
514 func = addr & 0x0000FFFF;
515 dev = (addr >> 16) & 0x0000FFFF;
516 pci = g_malloc0(sizeof(*pci));
517 pci->domain = dev;
518 pci->slot = slot;
519 pci->function = func;
520 pci->bus = bus;
521 break;
523 out:
524 g_free(buffer);
525 g_free(name);
526 return pci;
529 static int get_disk_bus_type(HANDLE vol_h, Error **errp)
531 STORAGE_PROPERTY_QUERY query;
532 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
533 DWORD received;
535 dev_desc = &buf;
536 dev_desc->Size = sizeof(buf);
537 query.PropertyId = StorageDeviceProperty;
538 query.QueryType = PropertyStandardQuery;
540 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
541 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
542 dev_desc->Size, &received, NULL)) {
543 error_setg_win32(errp, GetLastError(), "failed to get bus type");
544 return -1;
547 return dev_desc->BusType;
550 /* VSS provider works with volumes, thus there is no difference if
551 * the volume consist of spanned disks. Info about the first disk in the
552 * volume is returned for the spanned disk group (LVM) */
553 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
555 GuestDiskAddressList *list = NULL;
556 GuestDiskAddress *disk;
557 SCSI_ADDRESS addr, *scsi_ad;
558 DWORD len;
559 int bus;
560 HANDLE vol_h;
562 scsi_ad = &addr;
563 char *name = g_strndup(guid, strlen(guid)-1);
565 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
566 0, NULL);
567 if (vol_h == INVALID_HANDLE_VALUE) {
568 error_setg_win32(errp, GetLastError(), "failed to open volume");
569 goto out_free;
572 bus = get_disk_bus_type(vol_h, errp);
573 if (bus < 0) {
574 goto out_close;
577 disk = g_malloc0(sizeof(*disk));
578 disk->bus_type = find_bus_type(bus);
579 if (bus == BusTypeScsi || bus == BusTypeAta || bus == BusTypeRAID
580 #if (_WIN32_WINNT >= 0x0600)
581 /* This bus type is not supported before Windows Server 2003 SP1 */
582 || bus == BusTypeSas
583 #endif
585 /* We are able to use the same ioctls for different bus types
586 * according to Microsoft docs
587 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
588 if (DeviceIoControl(vol_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
589 sizeof(SCSI_ADDRESS), &len, NULL)) {
590 disk->unit = addr.Lun;
591 disk->target = addr.TargetId;
592 disk->bus = addr.PathId;
593 disk->pci_controller = get_pci_info(name, errp);
595 /* We do not set error in this case, because we still have enough
596 * information about volume. */
597 } else {
598 disk->pci_controller = NULL;
601 list = g_malloc0(sizeof(*list));
602 list->value = disk;
603 list->next = NULL;
604 out_close:
605 CloseHandle(vol_h);
606 out_free:
607 g_free(name);
608 return list;
611 #else
613 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
615 return NULL;
618 #endif /* CONFIG_QGA_NTDDSCSI */
620 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
622 DWORD info_size;
623 char mnt, *mnt_point;
624 char fs_name[32];
625 char vol_info[MAX_PATH+1];
626 size_t len;
627 GuestFilesystemInfo *fs = NULL;
629 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
630 if (GetLastError() != ERROR_MORE_DATA) {
631 error_setg_win32(errp, GetLastError(), "failed to get volume name");
632 return NULL;
635 mnt_point = g_malloc(info_size + 1);
636 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
637 &info_size)) {
638 error_setg_win32(errp, GetLastError(), "failed to get volume name");
639 goto free;
642 len = strlen(mnt_point);
643 mnt_point[len] = '\\';
644 mnt_point[len+1] = 0;
645 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
646 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
647 if (GetLastError() != ERROR_NOT_READY) {
648 error_setg_win32(errp, GetLastError(), "failed to get volume info");
650 goto free;
653 fs_name[sizeof(fs_name) - 1] = 0;
654 fs = g_malloc(sizeof(*fs));
655 fs->name = g_strdup(guid);
656 if (len == 0) {
657 fs->mountpoint = g_strdup("System Reserved");
658 } else {
659 fs->mountpoint = g_strndup(mnt_point, len);
661 fs->type = g_strdup(fs_name);
662 fs->disk = build_guest_disk_info(guid, errp);
663 free:
664 g_free(mnt_point);
665 return fs;
668 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
670 HANDLE vol_h;
671 GuestFilesystemInfoList *new, *ret = NULL;
672 char guid[256];
674 vol_h = FindFirstVolume(guid, sizeof(guid));
675 if (vol_h == INVALID_HANDLE_VALUE) {
676 error_setg_win32(errp, GetLastError(), "failed to find any volume");
677 return NULL;
680 do {
681 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
682 if (info == NULL) {
683 continue;
685 new = g_malloc(sizeof(*ret));
686 new->value = info;
687 new->next = ret;
688 ret = new;
689 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
691 if (GetLastError() != ERROR_NO_MORE_FILES) {
692 error_setg_win32(errp, GetLastError(), "failed to find next volume");
695 FindVolumeClose(vol_h);
696 return ret;
700 * Return status of freeze/thaw
702 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
704 if (!vss_initialized()) {
705 error_setg(errp, QERR_UNSUPPORTED);
706 return 0;
709 if (ga_is_frozen(ga_state)) {
710 return GUEST_FSFREEZE_STATUS_FROZEN;
713 return GUEST_FSFREEZE_STATUS_THAWED;
717 * Freeze local file systems using Volume Shadow-copy Service.
718 * The frozen state is limited for up to 10 seconds by VSS.
720 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
722 int i;
723 Error *local_err = NULL;
725 if (!vss_initialized()) {
726 error_setg(errp, QERR_UNSUPPORTED);
727 return 0;
730 slog("guest-fsfreeze called");
732 /* cannot risk guest agent blocking itself on a write in this state */
733 ga_set_frozen(ga_state);
735 qga_vss_fsfreeze(&i, &local_err, true);
736 if (local_err) {
737 error_propagate(errp, local_err);
738 goto error;
741 return i;
743 error:
744 local_err = NULL;
745 qmp_guest_fsfreeze_thaw(&local_err);
746 if (local_err) {
747 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
748 error_free(local_err);
750 return 0;
753 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
754 strList *mountpoints,
755 Error **errp)
757 error_setg(errp, QERR_UNSUPPORTED);
759 return 0;
763 * Thaw local file systems using Volume Shadow-copy Service.
765 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
767 int i;
769 if (!vss_initialized()) {
770 error_setg(errp, QERR_UNSUPPORTED);
771 return 0;
774 qga_vss_fsfreeze(&i, errp, false);
776 ga_unset_frozen(ga_state);
777 return i;
780 static void guest_fsfreeze_cleanup(void)
782 Error *err = NULL;
784 if (!vss_initialized()) {
785 return;
788 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
789 qmp_guest_fsfreeze_thaw(&err);
790 if (err) {
791 slog("failed to clean up frozen filesystems: %s",
792 error_get_pretty(err));
793 error_free(err);
797 vss_deinit(true);
801 * Walk list of mounted file systems in the guest, and discard unused
802 * areas.
804 GuestFilesystemTrimResponse *
805 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
807 error_setg(errp, QERR_UNSUPPORTED);
808 return NULL;
811 typedef enum {
812 GUEST_SUSPEND_MODE_DISK,
813 GUEST_SUSPEND_MODE_RAM
814 } GuestSuspendMode;
816 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
818 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
819 Error *local_err = NULL;
821 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
822 if (!GetPwrCapabilities(&sys_pwr_caps)) {
823 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
824 "failed to determine guest suspend capabilities");
825 goto out;
828 switch (mode) {
829 case GUEST_SUSPEND_MODE_DISK:
830 if (!sys_pwr_caps.SystemS4) {
831 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
832 "suspend-to-disk not supported by OS");
834 break;
835 case GUEST_SUSPEND_MODE_RAM:
836 if (!sys_pwr_caps.SystemS3) {
837 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
838 "suspend-to-ram not supported by OS");
840 break;
841 default:
842 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
843 "GuestSuspendMode");
846 out:
847 if (local_err) {
848 error_propagate(errp, local_err);
852 static DWORD WINAPI do_suspend(LPVOID opaque)
854 GuestSuspendMode *mode = opaque;
855 DWORD ret = 0;
857 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
858 slog("failed to suspend guest, %lu", GetLastError());
859 ret = -1;
861 g_free(mode);
862 return ret;
865 void qmp_guest_suspend_disk(Error **errp)
867 Error *local_err = NULL;
868 GuestSuspendMode *mode = g_malloc(sizeof(GuestSuspendMode));
870 *mode = GUEST_SUSPEND_MODE_DISK;
871 check_suspend_mode(*mode, &local_err);
872 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
873 execute_async(do_suspend, mode, &local_err);
875 if (local_err) {
876 error_propagate(errp, local_err);
877 g_free(mode);
881 void qmp_guest_suspend_ram(Error **errp)
883 Error *local_err = NULL;
884 GuestSuspendMode *mode = g_malloc(sizeof(GuestSuspendMode));
886 *mode = GUEST_SUSPEND_MODE_RAM;
887 check_suspend_mode(*mode, &local_err);
888 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
889 execute_async(do_suspend, mode, &local_err);
891 if (local_err) {
892 error_propagate(errp, local_err);
893 g_free(mode);
897 void qmp_guest_suspend_hybrid(Error **errp)
899 error_setg(errp, QERR_UNSUPPORTED);
902 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
904 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
905 ULONG adptr_addrs_len = 0;
906 DWORD ret;
908 /* Call the first time to get the adptr_addrs_len. */
909 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
910 NULL, adptr_addrs, &adptr_addrs_len);
912 adptr_addrs = g_malloc(adptr_addrs_len);
913 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
914 NULL, adptr_addrs, &adptr_addrs_len);
915 if (ret != ERROR_SUCCESS) {
916 error_setg_win32(errp, ret, "failed to get adapters addresses");
917 g_free(adptr_addrs);
918 adptr_addrs = NULL;
920 return adptr_addrs;
923 static char *guest_wctomb_dup(WCHAR *wstr)
925 char *str;
926 size_t i;
928 i = wcslen(wstr) + 1;
929 str = g_malloc(i);
930 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
931 wstr, -1, str, i, NULL, NULL);
932 return str;
935 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
936 Error **errp)
938 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
939 DWORD len;
940 int ret;
942 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
943 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
944 len = sizeof(addr_str);
945 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
946 ip_addr->Address.iSockaddrLength,
947 NULL,
948 addr_str,
949 &len);
950 if (ret != 0) {
951 error_setg_win32(errp, WSAGetLastError(),
952 "failed address presentation form conversion");
953 return NULL;
955 return g_strdup(addr_str);
957 return NULL;
960 #if (_WIN32_WINNT >= 0x0600)
961 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
963 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
964 * field to obtain the prefix.
966 return ip_addr->OnLinkPrefixLength;
968 #else
969 /* When using the Windows XP and 2003 build environment, do the best we can to
970 * figure out the prefix.
972 static IP_ADAPTER_INFO *guest_get_adapters_info(void)
974 IP_ADAPTER_INFO *adptr_info = NULL;
975 ULONG adptr_info_len = 0;
976 DWORD ret;
978 /* Call the first time to get the adptr_info_len. */
979 GetAdaptersInfo(adptr_info, &adptr_info_len);
981 adptr_info = g_malloc(adptr_info_len);
982 ret = GetAdaptersInfo(adptr_info, &adptr_info_len);
983 if (ret != ERROR_SUCCESS) {
984 g_free(adptr_info);
985 adptr_info = NULL;
987 return adptr_info;
990 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
992 int64_t prefix = -1; /* Use for AF_INET6 and unknown/undetermined values. */
993 IP_ADAPTER_INFO *adptr_info, *info;
994 IP_ADDR_STRING *ip;
995 struct in_addr *p;
997 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
998 return prefix;
1000 adptr_info = guest_get_adapters_info();
1001 if (adptr_info == NULL) {
1002 return prefix;
1005 /* Match up the passed in ip_addr with one found in adaptr_info.
1006 * The matching one in adptr_info will have the netmask.
1008 p = &((struct sockaddr_in *)ip_addr->Address.lpSockaddr)->sin_addr;
1009 for (info = adptr_info; info; info = info->Next) {
1010 for (ip = &info->IpAddressList; ip; ip = ip->Next) {
1011 if (p->S_un.S_addr == inet_addr(ip->IpAddress.String)) {
1012 prefix = ctpop32(inet_addr(ip->IpMask.String));
1013 goto out;
1017 out:
1018 g_free(adptr_info);
1019 return prefix;
1021 #endif
1023 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1025 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1026 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1027 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1028 GuestIpAddressList *head_addr, *cur_addr;
1029 GuestNetworkInterfaceList *info;
1030 GuestIpAddressList *address_item = NULL;
1031 unsigned char *mac_addr;
1032 char *addr_str;
1033 WORD wsa_version;
1034 WSADATA wsa_data;
1035 int ret;
1037 adptr_addrs = guest_get_adapters_addresses(errp);
1038 if (adptr_addrs == NULL) {
1039 return NULL;
1042 /* Make WSA APIs available. */
1043 wsa_version = MAKEWORD(2, 2);
1044 ret = WSAStartup(wsa_version, &wsa_data);
1045 if (ret != 0) {
1046 error_setg_win32(errp, ret, "failed socket startup");
1047 goto out;
1050 for (addr = adptr_addrs; addr; addr = addr->Next) {
1051 info = g_malloc0(sizeof(*info));
1053 if (cur_item == NULL) {
1054 head = cur_item = info;
1055 } else {
1056 cur_item->next = info;
1057 cur_item = info;
1060 info->value = g_malloc0(sizeof(*info->value));
1061 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1063 if (addr->PhysicalAddressLength != 0) {
1064 mac_addr = addr->PhysicalAddress;
1066 info->value->hardware_address =
1067 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1068 (int) mac_addr[0], (int) mac_addr[1],
1069 (int) mac_addr[2], (int) mac_addr[3],
1070 (int) mac_addr[4], (int) mac_addr[5]);
1072 info->value->has_hardware_address = true;
1075 head_addr = NULL;
1076 cur_addr = NULL;
1077 for (ip_addr = addr->FirstUnicastAddress;
1078 ip_addr;
1079 ip_addr = ip_addr->Next) {
1080 addr_str = guest_addr_to_str(ip_addr, errp);
1081 if (addr_str == NULL) {
1082 continue;
1085 address_item = g_malloc0(sizeof(*address_item));
1087 if (!cur_addr) {
1088 head_addr = cur_addr = address_item;
1089 } else {
1090 cur_addr->next = address_item;
1091 cur_addr = address_item;
1094 address_item->value = g_malloc0(sizeof(*address_item->value));
1095 address_item->value->ip_address = addr_str;
1096 address_item->value->prefix = guest_ip_prefix(ip_addr);
1097 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1098 address_item->value->ip_address_type =
1099 GUEST_IP_ADDRESS_TYPE_IPV4;
1100 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1101 address_item->value->ip_address_type =
1102 GUEST_IP_ADDRESS_TYPE_IPV6;
1105 if (head_addr) {
1106 info->value->has_ip_addresses = true;
1107 info->value->ip_addresses = head_addr;
1110 WSACleanup();
1111 out:
1112 g_free(adptr_addrs);
1113 return head;
1116 int64_t qmp_guest_get_time(Error **errp)
1118 SYSTEMTIME ts = {0};
1119 int64_t time_ns;
1120 FILETIME tf;
1122 GetSystemTime(&ts);
1123 if (ts.wYear < 1601 || ts.wYear > 30827) {
1124 error_setg(errp, "Failed to get time");
1125 return -1;
1128 if (!SystemTimeToFileTime(&ts, &tf)) {
1129 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1130 return -1;
1133 time_ns = ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1134 - W32_FT_OFFSET) * 100;
1136 return time_ns;
1139 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1141 Error *local_err = NULL;
1142 SYSTEMTIME ts;
1143 FILETIME tf;
1144 LONGLONG time;
1146 if (!has_time) {
1147 /* Unfortunately, Windows libraries don't provide an easy way to access
1148 * RTC yet:
1150 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1152 error_setg(errp, "Time argument is required on this platform");
1153 return;
1156 /* Validate time passed by user. */
1157 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1158 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1159 return;
1162 time = time_ns / 100 + W32_FT_OFFSET;
1164 tf.dwLowDateTime = (DWORD) time;
1165 tf.dwHighDateTime = (DWORD) (time >> 32);
1167 if (!FileTimeToSystemTime(&tf, &ts)) {
1168 error_setg(errp, "Failed to convert system time %d",
1169 (int)GetLastError());
1170 return;
1173 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1174 if (local_err) {
1175 error_propagate(errp, local_err);
1176 return;
1179 if (!SetSystemTime(&ts)) {
1180 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1181 return;
1185 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1187 error_setg(errp, QERR_UNSUPPORTED);
1188 return NULL;
1191 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1193 error_setg(errp, QERR_UNSUPPORTED);
1194 return -1;
1197 static gchar *
1198 get_net_error_message(gint error)
1200 HMODULE module = NULL;
1201 gchar *retval = NULL;
1202 wchar_t *msg = NULL;
1203 int flags, nchars;
1205 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER
1206 |FORMAT_MESSAGE_IGNORE_INSERTS
1207 |FORMAT_MESSAGE_FROM_SYSTEM;
1209 if (error >= NERR_BASE && error <= MAX_NERR) {
1210 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1212 if (module != NULL) {
1213 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1217 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1219 if (msg != NULL) {
1220 nchars = wcslen(msg);
1222 if (nchars > 2 && msg[nchars-1] == '\n' && msg[nchars-2] == '\r') {
1223 msg[nchars-2] = '\0';
1226 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1228 LocalFree(msg);
1231 if (module != NULL) {
1232 FreeLibrary(module);
1235 return retval;
1238 void qmp_guest_set_user_password(const char *username,
1239 const char *password,
1240 bool crypted,
1241 Error **errp)
1243 NET_API_STATUS nas;
1244 char *rawpasswddata = NULL;
1245 size_t rawpasswdlen;
1246 wchar_t *user, *wpass;
1247 USER_INFO_1003 pi1003 = { 0, };
1249 if (crypted) {
1250 error_setg(errp, QERR_UNSUPPORTED);
1251 return;
1254 rawpasswddata = (char *)g_base64_decode(password, &rawpasswdlen);
1255 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1256 rawpasswddata[rawpasswdlen] = '\0';
1258 user = g_utf8_to_utf16(username, -1, NULL, NULL, NULL);
1259 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, NULL);
1261 pi1003.usri1003_password = wpass;
1262 nas = NetUserSetInfo(NULL, user,
1263 1003, (LPBYTE)&pi1003,
1264 NULL);
1266 if (nas != NERR_Success) {
1267 gchar *msg = get_net_error_message(nas);
1268 error_setg(errp, "failed to set password: %s", msg);
1269 g_free(msg);
1272 g_free(user);
1273 g_free(wpass);
1274 g_free(rawpasswddata);
1277 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1279 error_setg(errp, QERR_UNSUPPORTED);
1280 return NULL;
1283 GuestMemoryBlockResponseList *
1284 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1286 error_setg(errp, QERR_UNSUPPORTED);
1287 return NULL;
1290 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1292 error_setg(errp, QERR_UNSUPPORTED);
1293 return NULL;
1296 /* add unsupported commands to the blacklist */
1297 GList *ga_command_blacklist_init(GList *blacklist)
1299 const char *list_unsupported[] = {
1300 "guest-suspend-hybrid",
1301 "guest-get-vcpus", "guest-set-vcpus",
1302 "guest-get-memory-blocks", "guest-set-memory-blocks",
1303 "guest-get-memory-block-size",
1304 "guest-fsfreeze-freeze-list",
1305 "guest-fstrim", NULL};
1306 char **p = (char **)list_unsupported;
1308 while (*p) {
1309 blacklist = g_list_append(blacklist, g_strdup(*p++));
1312 if (!vss_init(true)) {
1313 g_debug("vss_init failed, vss commands are going to be disabled");
1314 const char *list[] = {
1315 "guest-get-fsinfo", "guest-fsfreeze-status",
1316 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1317 p = (char **)list;
1319 while (*p) {
1320 blacklist = g_list_append(blacklist, g_strdup(*p++));
1324 return blacklist;
1327 /* register init/cleanup routines for stateful command groups */
1328 void ga_command_state_init(GAState *s, GACommandState *cs)
1330 if (!vss_initialized()) {
1331 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1333 ga_command_state_add(cs, guest_file_init, NULL);