s390x/kvm: don't enable CMMA when hugetlbfs will be used
[qemu.git] / qga / commands-win32.c
bloba5306e76b0022f1b61979f5b433f57048caf49b5
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 = {
59 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
63 typedef struct OpenFlags {
64 const char *forms;
65 DWORD desired_access;
66 DWORD creation_disposition;
67 } OpenFlags;
68 static OpenFlags guest_file_open_modes[] = {
69 {"r", GENERIC_READ, OPEN_EXISTING},
70 {"rb", GENERIC_READ, OPEN_EXISTING},
71 {"w", GENERIC_WRITE, CREATE_ALWAYS},
72 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
73 {"a", GENERIC_WRITE, OPEN_ALWAYS },
74 {"r+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
75 {"rb+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
76 {"r+b", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
77 {"w+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
78 {"wb+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
79 {"w+b", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
80 {"a+", GENERIC_WRITE|GENERIC_READ, OPEN_ALWAYS },
81 {"ab+", GENERIC_WRITE|GENERIC_READ, OPEN_ALWAYS },
82 {"a+b", GENERIC_WRITE|GENERIC_READ, OPEN_ALWAYS }
85 static OpenFlags *find_open_flag(const char *mode_str)
87 int mode;
88 Error **errp = NULL;
90 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
91 OpenFlags *flags = guest_file_open_modes + mode;
93 if (strcmp(flags->forms, mode_str) == 0) {
94 return flags;
98 error_setg(errp, "invalid file open mode '%s'", mode_str);
99 return NULL;
102 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
104 GuestFileHandle *gfh;
105 int64_t handle;
107 handle = ga_get_fd_handle(ga_state, errp);
108 if (handle < 0) {
109 return -1;
111 gfh = g_new0(GuestFileHandle, 1);
112 gfh->id = handle;
113 gfh->fh = fh;
114 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
116 return handle;
119 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
121 GuestFileHandle *gfh;
122 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
123 if (gfh->id == id) {
124 return gfh;
127 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
128 return NULL;
131 static void handle_set_nonblocking(HANDLE fh)
133 DWORD file_type, pipe_state;
134 file_type = GetFileType(fh);
135 if (file_type != FILE_TYPE_PIPE) {
136 return;
138 /* If file_type == FILE_TYPE_PIPE, according to MSDN
139 * the specified file is socket or named pipe */
140 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
141 NULL, NULL, NULL, 0)) {
142 return;
144 /* The fd is named pipe fd */
145 if (pipe_state & PIPE_NOWAIT) {
146 return;
149 pipe_state |= PIPE_NOWAIT;
150 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
153 int64_t qmp_guest_file_open(const char *path, bool has_mode,
154 const char *mode, Error **errp)
156 int64_t fd;
157 HANDLE fh;
158 HANDLE templ_file = NULL;
159 DWORD share_mode = FILE_SHARE_READ;
160 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
161 LPSECURITY_ATTRIBUTES sa_attr = NULL;
162 OpenFlags *guest_flags;
164 if (!has_mode) {
165 mode = "r";
167 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
168 guest_flags = find_open_flag(mode);
169 if (guest_flags == NULL) {
170 error_setg(errp, "invalid file open mode");
171 return -1;
174 fh = CreateFile(path, guest_flags->desired_access, share_mode, sa_attr,
175 guest_flags->creation_disposition, flags_and_attr,
176 templ_file);
177 if (fh == INVALID_HANDLE_VALUE) {
178 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
179 path);
180 return -1;
183 /* set fd non-blocking to avoid common use cases (like reading from a
184 * named pipe) from hanging the agent
186 handle_set_nonblocking(fh);
188 fd = guest_file_handle_add(fh, errp);
189 if (fd < 0) {
190 CloseHandle(fh);
191 error_setg(errp, "failed to add handle to qmp handle table");
192 return -1;
195 slog("guest-file-open, handle: % " PRId64, fd);
196 return fd;
199 void qmp_guest_file_close(int64_t handle, Error **errp)
201 bool ret;
202 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
203 slog("guest-file-close called, handle: %" PRId64, handle);
204 if (gfh == NULL) {
205 return;
207 ret = CloseHandle(gfh->fh);
208 if (!ret) {
209 error_setg_win32(errp, GetLastError(), "failed close handle");
210 return;
213 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
214 g_free(gfh);
217 static void acquire_privilege(const char *name, Error **errp)
219 HANDLE token = NULL;
220 TOKEN_PRIVILEGES priv;
221 Error *local_err = NULL;
223 if (OpenProcessToken(GetCurrentProcess(),
224 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
226 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
227 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
228 "no luid for requested privilege");
229 goto out;
232 priv.PrivilegeCount = 1;
233 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
235 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
236 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
237 "unable to acquire requested privilege");
238 goto out;
241 } else {
242 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
243 "failed to open privilege token");
246 out:
247 if (token) {
248 CloseHandle(token);
250 if (local_err) {
251 error_propagate(errp, local_err);
255 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
256 Error **errp)
258 Error *local_err = NULL;
260 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
261 if (!thread) {
262 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
263 "failed to dispatch asynchronous command");
264 error_propagate(errp, local_err);
268 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
270 Error *local_err = NULL;
271 UINT shutdown_flag = EWX_FORCE;
273 slog("guest-shutdown called, mode: %s", mode);
275 if (!has_mode || strcmp(mode, "powerdown") == 0) {
276 shutdown_flag |= EWX_POWEROFF;
277 } else if (strcmp(mode, "halt") == 0) {
278 shutdown_flag |= EWX_SHUTDOWN;
279 } else if (strcmp(mode, "reboot") == 0) {
280 shutdown_flag |= EWX_REBOOT;
281 } else {
282 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
283 "halt|powerdown|reboot");
284 return;
287 /* Request a shutdown privilege, but try to shut down the system
288 anyway. */
289 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
290 if (local_err) {
291 error_propagate(errp, local_err);
292 return;
295 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
296 slog("guest-shutdown failed: %lu", GetLastError());
297 error_setg(errp, QERR_UNDEFINED_ERROR);
301 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
302 int64_t count, Error **errp)
304 GuestFileRead *read_data = NULL;
305 guchar *buf;
306 HANDLE fh;
307 bool is_ok;
308 DWORD read_count;
309 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
311 if (!gfh) {
312 return NULL;
314 if (!has_count) {
315 count = QGA_READ_COUNT_DEFAULT;
316 } else if (count < 0) {
317 error_setg(errp, "value '%" PRId64
318 "' is invalid for argument count", count);
319 return NULL;
322 fh = gfh->fh;
323 buf = g_malloc0(count+1);
324 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
325 if (!is_ok) {
326 error_setg_win32(errp, GetLastError(), "failed to read file");
327 slog("guest-file-read failed, handle %" PRId64, handle);
328 } else {
329 buf[read_count] = 0;
330 read_data = g_new0(GuestFileRead, 1);
331 read_data->count = (size_t)read_count;
332 read_data->eof = read_count == 0;
334 if (read_count != 0) {
335 read_data->buf_b64 = g_base64_encode(buf, read_count);
338 g_free(buf);
340 return read_data;
343 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
344 bool has_count, int64_t count,
345 Error **errp)
347 GuestFileWrite *write_data = NULL;
348 guchar *buf;
349 gsize buf_len;
350 bool is_ok;
351 DWORD write_count;
352 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
353 HANDLE fh;
355 if (!gfh) {
356 return NULL;
358 fh = gfh->fh;
359 buf = g_base64_decode(buf_b64, &buf_len);
361 if (!has_count) {
362 count = buf_len;
363 } else if (count < 0 || count > buf_len) {
364 error_setg(errp, "value '%" PRId64
365 "' is invalid for argument count", count);
366 goto done;
369 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
370 if (!is_ok) {
371 error_setg_win32(errp, GetLastError(), "failed to write to file");
372 slog("guest-file-write-failed, handle: %" PRId64, handle);
373 } else {
374 write_data = g_new0(GuestFileWrite, 1);
375 write_data->count = (size_t) write_count;
378 done:
379 g_free(buf);
380 return write_data;
383 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
384 int64_t whence, Error **errp)
386 GuestFileHandle *gfh;
387 GuestFileSeek *seek_data;
388 HANDLE fh;
389 LARGE_INTEGER new_pos, off_pos;
390 off_pos.QuadPart = offset;
391 BOOL res;
392 gfh = guest_file_handle_find(handle, errp);
393 if (!gfh) {
394 return NULL;
397 fh = gfh->fh;
398 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
399 if (!res) {
400 error_setg_win32(errp, GetLastError(), "failed to seek file");
401 return NULL;
403 seek_data = g_new0(GuestFileSeek, 1);
404 seek_data->position = new_pos.QuadPart;
405 return seek_data;
408 void qmp_guest_file_flush(int64_t handle, Error **errp)
410 HANDLE fh;
411 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
412 if (!gfh) {
413 return;
416 fh = gfh->fh;
417 if (!FlushFileBuffers(fh)) {
418 error_setg_win32(errp, GetLastError(), "failed to flush file");
422 #ifdef CONFIG_QGA_NTDDSCSI
424 static STORAGE_BUS_TYPE win2qemu[] = {
425 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
426 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
427 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
428 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
429 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
430 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
431 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
432 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
433 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
434 #if (_WIN32_WINNT >= 0x0600)
435 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
436 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
437 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
438 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
439 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
440 #endif
441 #if (_WIN32_WINNT >= 0x0601)
442 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
443 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
444 #endif
447 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
449 if (bus > ARRAY_SIZE(win2qemu) || (int)bus < 0) {
450 return GUEST_DISK_BUS_TYPE_UNKNOWN;
452 return win2qemu[(int)bus];
455 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME,
456 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2,
457 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
459 static GuestPCIAddress *get_pci_info(char *guid, Error **errp)
461 HDEVINFO dev_info;
462 SP_DEVINFO_DATA dev_info_data;
463 DWORD size = 0;
464 int i;
465 char dev_name[MAX_PATH];
466 char *buffer = NULL;
467 GuestPCIAddress *pci = NULL;
468 char *name = g_strdup(&guid[4]);
470 if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {
471 error_setg_win32(errp, GetLastError(), "failed to get dos device name");
472 goto out;
475 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, 0, 0,
476 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
477 if (dev_info == INVALID_HANDLE_VALUE) {
478 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
479 goto out;
482 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
483 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
484 DWORD addr, bus, slot, func, dev, data, size2;
485 while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
486 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
487 &data, (PBYTE)buffer, size,
488 &size2)) {
489 size = MAX(size, size2);
490 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
491 g_free(buffer);
492 /* Double the size to avoid problems on
493 * W2k MBCS systems per KB 888609.
494 * https://support.microsoft.com/en-us/kb/259695 */
495 buffer = g_malloc(size * 2);
496 } else {
497 error_setg_win32(errp, GetLastError(),
498 "failed to get device name");
499 goto out;
503 if (g_strcmp0(buffer, dev_name)) {
504 continue;
507 /* There is no need to allocate buffer in the next functions. The size
508 * is known and ULONG according to
509 * https://support.microsoft.com/en-us/kb/253232
510 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
512 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
513 SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {
514 break;
517 /* The function retrieves the device's address. This value will be
518 * transformed into device function and number */
519 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
520 SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {
521 break;
524 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
525 * This number is typically a user-perceived slot number. */
526 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
527 SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {
528 break;
531 /* SetupApi gives us the same information as driver with
532 * IoGetDeviceProperty. According to Microsoft
533 * https://support.microsoft.com/en-us/kb/253232
534 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
535 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
536 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
538 func = addr & 0x0000FFFF;
539 dev = (addr >> 16) & 0x0000FFFF;
540 pci = g_malloc0(sizeof(*pci));
541 pci->domain = dev;
542 pci->slot = slot;
543 pci->function = func;
544 pci->bus = bus;
545 break;
547 out:
548 g_free(buffer);
549 g_free(name);
550 return pci;
553 static int get_disk_bus_type(HANDLE vol_h, Error **errp)
555 STORAGE_PROPERTY_QUERY query;
556 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
557 DWORD received;
559 dev_desc = &buf;
560 dev_desc->Size = sizeof(buf);
561 query.PropertyId = StorageDeviceProperty;
562 query.QueryType = PropertyStandardQuery;
564 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
565 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
566 dev_desc->Size, &received, NULL)) {
567 error_setg_win32(errp, GetLastError(), "failed to get bus type");
568 return -1;
571 return dev_desc->BusType;
574 /* VSS provider works with volumes, thus there is no difference if
575 * the volume consist of spanned disks. Info about the first disk in the
576 * volume is returned for the spanned disk group (LVM) */
577 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
579 GuestDiskAddressList *list = NULL;
580 GuestDiskAddress *disk;
581 SCSI_ADDRESS addr, *scsi_ad;
582 DWORD len;
583 int bus;
584 HANDLE vol_h;
586 scsi_ad = &addr;
587 char *name = g_strndup(guid, strlen(guid)-1);
589 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
590 0, NULL);
591 if (vol_h == INVALID_HANDLE_VALUE) {
592 error_setg_win32(errp, GetLastError(), "failed to open volume");
593 goto out_free;
596 bus = get_disk_bus_type(vol_h, errp);
597 if (bus < 0) {
598 goto out_close;
601 disk = g_malloc0(sizeof(*disk));
602 disk->bus_type = find_bus_type(bus);
603 if (bus == BusTypeScsi || bus == BusTypeAta || bus == BusTypeRAID
604 #if (_WIN32_WINNT >= 0x0600)
605 /* This bus type is not supported before Windows Server 2003 SP1 */
606 || bus == BusTypeSas
607 #endif
609 /* We are able to use the same ioctls for different bus types
610 * according to Microsoft docs
611 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
612 if (DeviceIoControl(vol_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
613 sizeof(SCSI_ADDRESS), &len, NULL)) {
614 disk->unit = addr.Lun;
615 disk->target = addr.TargetId;
616 disk->bus = addr.PathId;
617 disk->pci_controller = get_pci_info(name, errp);
619 /* We do not set error in this case, because we still have enough
620 * information about volume. */
621 } else {
622 disk->pci_controller = NULL;
625 list = g_malloc0(sizeof(*list));
626 list->value = disk;
627 list->next = NULL;
628 out_close:
629 CloseHandle(vol_h);
630 out_free:
631 g_free(name);
632 return list;
635 #else
637 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
639 return NULL;
642 #endif /* CONFIG_QGA_NTDDSCSI */
644 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
646 DWORD info_size;
647 char mnt, *mnt_point;
648 char fs_name[32];
649 char vol_info[MAX_PATH+1];
650 size_t len;
651 GuestFilesystemInfo *fs = NULL;
653 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
654 if (GetLastError() != ERROR_MORE_DATA) {
655 error_setg_win32(errp, GetLastError(), "failed to get volume name");
656 return NULL;
659 mnt_point = g_malloc(info_size + 1);
660 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
661 &info_size)) {
662 error_setg_win32(errp, GetLastError(), "failed to get volume name");
663 goto free;
666 len = strlen(mnt_point);
667 mnt_point[len] = '\\';
668 mnt_point[len+1] = 0;
669 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
670 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
671 if (GetLastError() != ERROR_NOT_READY) {
672 error_setg_win32(errp, GetLastError(), "failed to get volume info");
674 goto free;
677 fs_name[sizeof(fs_name) - 1] = 0;
678 fs = g_malloc(sizeof(*fs));
679 fs->name = g_strdup(guid);
680 if (len == 0) {
681 fs->mountpoint = g_strdup("System Reserved");
682 } else {
683 fs->mountpoint = g_strndup(mnt_point, len);
685 fs->type = g_strdup(fs_name);
686 fs->disk = build_guest_disk_info(guid, errp);
687 free:
688 g_free(mnt_point);
689 return fs;
692 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
694 HANDLE vol_h;
695 GuestFilesystemInfoList *new, *ret = NULL;
696 char guid[256];
698 vol_h = FindFirstVolume(guid, sizeof(guid));
699 if (vol_h == INVALID_HANDLE_VALUE) {
700 error_setg_win32(errp, GetLastError(), "failed to find any volume");
701 return NULL;
704 do {
705 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
706 if (info == NULL) {
707 continue;
709 new = g_malloc(sizeof(*ret));
710 new->value = info;
711 new->next = ret;
712 ret = new;
713 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
715 if (GetLastError() != ERROR_NO_MORE_FILES) {
716 error_setg_win32(errp, GetLastError(), "failed to find next volume");
719 FindVolumeClose(vol_h);
720 return ret;
724 * Return status of freeze/thaw
726 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
728 if (!vss_initialized()) {
729 error_setg(errp, QERR_UNSUPPORTED);
730 return 0;
733 if (ga_is_frozen(ga_state)) {
734 return GUEST_FSFREEZE_STATUS_FROZEN;
737 return GUEST_FSFREEZE_STATUS_THAWED;
741 * Freeze local file systems using Volume Shadow-copy Service.
742 * The frozen state is limited for up to 10 seconds by VSS.
744 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
746 int i;
747 Error *local_err = NULL;
749 if (!vss_initialized()) {
750 error_setg(errp, QERR_UNSUPPORTED);
751 return 0;
754 slog("guest-fsfreeze called");
756 /* cannot risk guest agent blocking itself on a write in this state */
757 ga_set_frozen(ga_state);
759 qga_vss_fsfreeze(&i, &local_err, true);
760 if (local_err) {
761 error_propagate(errp, local_err);
762 goto error;
765 return i;
767 error:
768 local_err = NULL;
769 qmp_guest_fsfreeze_thaw(&local_err);
770 if (local_err) {
771 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
772 error_free(local_err);
774 return 0;
777 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
778 strList *mountpoints,
779 Error **errp)
781 error_setg(errp, QERR_UNSUPPORTED);
783 return 0;
787 * Thaw local file systems using Volume Shadow-copy Service.
789 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
791 int i;
793 if (!vss_initialized()) {
794 error_setg(errp, QERR_UNSUPPORTED);
795 return 0;
798 qga_vss_fsfreeze(&i, errp, false);
800 ga_unset_frozen(ga_state);
801 return i;
804 static void guest_fsfreeze_cleanup(void)
806 Error *err = NULL;
808 if (!vss_initialized()) {
809 return;
812 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
813 qmp_guest_fsfreeze_thaw(&err);
814 if (err) {
815 slog("failed to clean up frozen filesystems: %s",
816 error_get_pretty(err));
817 error_free(err);
821 vss_deinit(true);
825 * Walk list of mounted file systems in the guest, and discard unused
826 * areas.
828 GuestFilesystemTrimResponse *
829 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
831 error_setg(errp, QERR_UNSUPPORTED);
832 return NULL;
835 typedef enum {
836 GUEST_SUSPEND_MODE_DISK,
837 GUEST_SUSPEND_MODE_RAM
838 } GuestSuspendMode;
840 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
842 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
843 Error *local_err = NULL;
845 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
846 if (!GetPwrCapabilities(&sys_pwr_caps)) {
847 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
848 "failed to determine guest suspend capabilities");
849 goto out;
852 switch (mode) {
853 case GUEST_SUSPEND_MODE_DISK:
854 if (!sys_pwr_caps.SystemS4) {
855 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
856 "suspend-to-disk not supported by OS");
858 break;
859 case GUEST_SUSPEND_MODE_RAM:
860 if (!sys_pwr_caps.SystemS3) {
861 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
862 "suspend-to-ram not supported by OS");
864 break;
865 default:
866 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
867 "GuestSuspendMode");
870 out:
871 if (local_err) {
872 error_propagate(errp, local_err);
876 static DWORD WINAPI do_suspend(LPVOID opaque)
878 GuestSuspendMode *mode = opaque;
879 DWORD ret = 0;
881 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
882 slog("failed to suspend guest, %lu", GetLastError());
883 ret = -1;
885 g_free(mode);
886 return ret;
889 void qmp_guest_suspend_disk(Error **errp)
891 Error *local_err = NULL;
892 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
894 *mode = GUEST_SUSPEND_MODE_DISK;
895 check_suspend_mode(*mode, &local_err);
896 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
897 execute_async(do_suspend, mode, &local_err);
899 if (local_err) {
900 error_propagate(errp, local_err);
901 g_free(mode);
905 void qmp_guest_suspend_ram(Error **errp)
907 Error *local_err = NULL;
908 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
910 *mode = GUEST_SUSPEND_MODE_RAM;
911 check_suspend_mode(*mode, &local_err);
912 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
913 execute_async(do_suspend, mode, &local_err);
915 if (local_err) {
916 error_propagate(errp, local_err);
917 g_free(mode);
921 void qmp_guest_suspend_hybrid(Error **errp)
923 error_setg(errp, QERR_UNSUPPORTED);
926 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
928 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
929 ULONG adptr_addrs_len = 0;
930 DWORD ret;
932 /* Call the first time to get the adptr_addrs_len. */
933 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
934 NULL, adptr_addrs, &adptr_addrs_len);
936 adptr_addrs = g_malloc(adptr_addrs_len);
937 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
938 NULL, adptr_addrs, &adptr_addrs_len);
939 if (ret != ERROR_SUCCESS) {
940 error_setg_win32(errp, ret, "failed to get adapters addresses");
941 g_free(adptr_addrs);
942 adptr_addrs = NULL;
944 return adptr_addrs;
947 static char *guest_wctomb_dup(WCHAR *wstr)
949 char *str;
950 size_t i;
952 i = wcslen(wstr) + 1;
953 str = g_malloc(i);
954 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
955 wstr, -1, str, i, NULL, NULL);
956 return str;
959 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
960 Error **errp)
962 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
963 DWORD len;
964 int ret;
966 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
967 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
968 len = sizeof(addr_str);
969 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
970 ip_addr->Address.iSockaddrLength,
971 NULL,
972 addr_str,
973 &len);
974 if (ret != 0) {
975 error_setg_win32(errp, WSAGetLastError(),
976 "failed address presentation form conversion");
977 return NULL;
979 return g_strdup(addr_str);
981 return NULL;
984 #if (_WIN32_WINNT >= 0x0600)
985 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
987 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
988 * field to obtain the prefix.
990 return ip_addr->OnLinkPrefixLength;
992 #else
993 /* When using the Windows XP and 2003 build environment, do the best we can to
994 * figure out the prefix.
996 static IP_ADAPTER_INFO *guest_get_adapters_info(void)
998 IP_ADAPTER_INFO *adptr_info = NULL;
999 ULONG adptr_info_len = 0;
1000 DWORD ret;
1002 /* Call the first time to get the adptr_info_len. */
1003 GetAdaptersInfo(adptr_info, &adptr_info_len);
1005 adptr_info = g_malloc(adptr_info_len);
1006 ret = GetAdaptersInfo(adptr_info, &adptr_info_len);
1007 if (ret != ERROR_SUCCESS) {
1008 g_free(adptr_info);
1009 adptr_info = NULL;
1011 return adptr_info;
1014 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1016 int64_t prefix = -1; /* Use for AF_INET6 and unknown/undetermined values. */
1017 IP_ADAPTER_INFO *adptr_info, *info;
1018 IP_ADDR_STRING *ip;
1019 struct in_addr *p;
1021 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
1022 return prefix;
1024 adptr_info = guest_get_adapters_info();
1025 if (adptr_info == NULL) {
1026 return prefix;
1029 /* Match up the passed in ip_addr with one found in adaptr_info.
1030 * The matching one in adptr_info will have the netmask.
1032 p = &((struct sockaddr_in *)ip_addr->Address.lpSockaddr)->sin_addr;
1033 for (info = adptr_info; info; info = info->Next) {
1034 for (ip = &info->IpAddressList; ip; ip = ip->Next) {
1035 if (p->S_un.S_addr == inet_addr(ip->IpAddress.String)) {
1036 prefix = ctpop32(inet_addr(ip->IpMask.String));
1037 goto out;
1041 out:
1042 g_free(adptr_info);
1043 return prefix;
1045 #endif
1047 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1049 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1050 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1051 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1052 GuestIpAddressList *head_addr, *cur_addr;
1053 GuestNetworkInterfaceList *info;
1054 GuestIpAddressList *address_item = NULL;
1055 unsigned char *mac_addr;
1056 char *addr_str;
1057 WORD wsa_version;
1058 WSADATA wsa_data;
1059 int ret;
1061 adptr_addrs = guest_get_adapters_addresses(errp);
1062 if (adptr_addrs == NULL) {
1063 return NULL;
1066 /* Make WSA APIs available. */
1067 wsa_version = MAKEWORD(2, 2);
1068 ret = WSAStartup(wsa_version, &wsa_data);
1069 if (ret != 0) {
1070 error_setg_win32(errp, ret, "failed socket startup");
1071 goto out;
1074 for (addr = adptr_addrs; addr; addr = addr->Next) {
1075 info = g_malloc0(sizeof(*info));
1077 if (cur_item == NULL) {
1078 head = cur_item = info;
1079 } else {
1080 cur_item->next = info;
1081 cur_item = info;
1084 info->value = g_malloc0(sizeof(*info->value));
1085 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1087 if (addr->PhysicalAddressLength != 0) {
1088 mac_addr = addr->PhysicalAddress;
1090 info->value->hardware_address =
1091 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1092 (int) mac_addr[0], (int) mac_addr[1],
1093 (int) mac_addr[2], (int) mac_addr[3],
1094 (int) mac_addr[4], (int) mac_addr[5]);
1096 info->value->has_hardware_address = true;
1099 head_addr = NULL;
1100 cur_addr = NULL;
1101 for (ip_addr = addr->FirstUnicastAddress;
1102 ip_addr;
1103 ip_addr = ip_addr->Next) {
1104 addr_str = guest_addr_to_str(ip_addr, errp);
1105 if (addr_str == NULL) {
1106 continue;
1109 address_item = g_malloc0(sizeof(*address_item));
1111 if (!cur_addr) {
1112 head_addr = cur_addr = address_item;
1113 } else {
1114 cur_addr->next = address_item;
1115 cur_addr = address_item;
1118 address_item->value = g_malloc0(sizeof(*address_item->value));
1119 address_item->value->ip_address = addr_str;
1120 address_item->value->prefix = guest_ip_prefix(ip_addr);
1121 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1122 address_item->value->ip_address_type =
1123 GUEST_IP_ADDRESS_TYPE_IPV4;
1124 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1125 address_item->value->ip_address_type =
1126 GUEST_IP_ADDRESS_TYPE_IPV6;
1129 if (head_addr) {
1130 info->value->has_ip_addresses = true;
1131 info->value->ip_addresses = head_addr;
1134 WSACleanup();
1135 out:
1136 g_free(adptr_addrs);
1137 return head;
1140 int64_t qmp_guest_get_time(Error **errp)
1142 SYSTEMTIME ts = {0};
1143 int64_t time_ns;
1144 FILETIME tf;
1146 GetSystemTime(&ts);
1147 if (ts.wYear < 1601 || ts.wYear > 30827) {
1148 error_setg(errp, "Failed to get time");
1149 return -1;
1152 if (!SystemTimeToFileTime(&ts, &tf)) {
1153 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1154 return -1;
1157 time_ns = ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1158 - W32_FT_OFFSET) * 100;
1160 return time_ns;
1163 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1165 Error *local_err = NULL;
1166 SYSTEMTIME ts;
1167 FILETIME tf;
1168 LONGLONG time;
1170 if (!has_time) {
1171 /* Unfortunately, Windows libraries don't provide an easy way to access
1172 * RTC yet:
1174 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1176 error_setg(errp, "Time argument is required on this platform");
1177 return;
1180 /* Validate time passed by user. */
1181 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1182 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1183 return;
1186 time = time_ns / 100 + W32_FT_OFFSET;
1188 tf.dwLowDateTime = (DWORD) time;
1189 tf.dwHighDateTime = (DWORD) (time >> 32);
1191 if (!FileTimeToSystemTime(&tf, &ts)) {
1192 error_setg(errp, "Failed to convert system time %d",
1193 (int)GetLastError());
1194 return;
1197 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1198 if (local_err) {
1199 error_propagate(errp, local_err);
1200 return;
1203 if (!SetSystemTime(&ts)) {
1204 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1205 return;
1209 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1211 error_setg(errp, QERR_UNSUPPORTED);
1212 return NULL;
1215 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1217 error_setg(errp, QERR_UNSUPPORTED);
1218 return -1;
1221 static gchar *
1222 get_net_error_message(gint error)
1224 HMODULE module = NULL;
1225 gchar *retval = NULL;
1226 wchar_t *msg = NULL;
1227 int flags, nchars;
1229 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER
1230 |FORMAT_MESSAGE_IGNORE_INSERTS
1231 |FORMAT_MESSAGE_FROM_SYSTEM;
1233 if (error >= NERR_BASE && error <= MAX_NERR) {
1234 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1236 if (module != NULL) {
1237 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1241 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1243 if (msg != NULL) {
1244 nchars = wcslen(msg);
1246 if (nchars > 2 && msg[nchars-1] == '\n' && msg[nchars-2] == '\r') {
1247 msg[nchars-2] = '\0';
1250 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1252 LocalFree(msg);
1255 if (module != NULL) {
1256 FreeLibrary(module);
1259 return retval;
1262 void qmp_guest_set_user_password(const char *username,
1263 const char *password,
1264 bool crypted,
1265 Error **errp)
1267 NET_API_STATUS nas;
1268 char *rawpasswddata = NULL;
1269 size_t rawpasswdlen;
1270 wchar_t *user, *wpass;
1271 USER_INFO_1003 pi1003 = { 0, };
1273 if (crypted) {
1274 error_setg(errp, QERR_UNSUPPORTED);
1275 return;
1278 rawpasswddata = (char *)g_base64_decode(password, &rawpasswdlen);
1279 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1280 rawpasswddata[rawpasswdlen] = '\0';
1282 user = g_utf8_to_utf16(username, -1, NULL, NULL, NULL);
1283 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, NULL);
1285 pi1003.usri1003_password = wpass;
1286 nas = NetUserSetInfo(NULL, user,
1287 1003, (LPBYTE)&pi1003,
1288 NULL);
1290 if (nas != NERR_Success) {
1291 gchar *msg = get_net_error_message(nas);
1292 error_setg(errp, "failed to set password: %s", msg);
1293 g_free(msg);
1296 g_free(user);
1297 g_free(wpass);
1298 g_free(rawpasswddata);
1301 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1303 error_setg(errp, QERR_UNSUPPORTED);
1304 return NULL;
1307 GuestMemoryBlockResponseList *
1308 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1310 error_setg(errp, QERR_UNSUPPORTED);
1311 return NULL;
1314 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1316 error_setg(errp, QERR_UNSUPPORTED);
1317 return NULL;
1320 /* add unsupported commands to the blacklist */
1321 GList *ga_command_blacklist_init(GList *blacklist)
1323 const char *list_unsupported[] = {
1324 "guest-suspend-hybrid",
1325 "guest-get-vcpus", "guest-set-vcpus",
1326 "guest-get-memory-blocks", "guest-set-memory-blocks",
1327 "guest-get-memory-block-size",
1328 "guest-fsfreeze-freeze-list",
1329 "guest-fstrim", NULL};
1330 char **p = (char **)list_unsupported;
1332 while (*p) {
1333 blacklist = g_list_append(blacklist, g_strdup(*p++));
1336 if (!vss_init(true)) {
1337 g_debug("vss_init failed, vss commands are going to be disabled");
1338 const char *list[] = {
1339 "guest-get-fsinfo", "guest-fsfreeze-status",
1340 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1341 p = (char **)list;
1343 while (*p) {
1344 blacklist = g_list_append(blacklist, g_strdup(*p++));
1348 return blacklist;
1351 /* register init/cleanup routines for stateful command groups */
1352 void ga_command_state_init(GAState *s, GACommandState *cs)
1354 if (!vss_initialized()) {
1355 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);