dump-guest-memory: add "detach" flag for QMP/HMP interfaces.
[qemu/kevin.git] / qga / commands-win32.c
blobcf0757cd0fb490702e4b60db3c2fd2a3d2cbe556
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 "qemu/osdep.h"
15 #include <glib.h>
16 #include <wtypes.h>
17 #include <powrprof.h>
18 #include <winsock2.h>
19 #include <ws2tcpip.h>
20 #include <iptypes.h>
21 #include <iphlpapi.h>
22 #ifdef CONFIG_QGA_NTDDSCSI
23 #include <winioctl.h>
24 #include <ntddscsi.h>
25 #include <setupapi.h>
26 #include <initguid.h>
27 #endif
28 #include <lm.h>
30 #include "qga/guest-agent-core.h"
31 #include "qga/vss-win32.h"
32 #include "qga-qmp-commands.h"
33 #include "qapi/qmp/qerror.h"
34 #include "qemu/queue.h"
35 #include "qemu/host-utils.h"
36 #include "qemu/base64.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),
62 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
64 typedef struct OpenFlags {
65 const char *forms;
66 DWORD desired_access;
67 DWORD creation_disposition;
68 } OpenFlags;
69 static OpenFlags guest_file_open_modes[] = {
70 {"r", GENERIC_READ, OPEN_EXISTING},
71 {"rb", GENERIC_READ, OPEN_EXISTING},
72 {"w", GENERIC_WRITE, CREATE_ALWAYS},
73 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
74 {"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
75 {"r+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
76 {"rb+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
77 {"r+b", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
78 {"w+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
79 {"wb+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
80 {"w+b", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
81 {"a+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
82 {"ab+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
83 {"a+b", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS }
86 static OpenFlags *find_open_flag(const char *mode_str)
88 int mode;
89 Error **errp = NULL;
91 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
92 OpenFlags *flags = guest_file_open_modes + mode;
94 if (strcmp(flags->forms, mode_str) == 0) {
95 return flags;
99 error_setg(errp, "invalid file open mode '%s'", mode_str);
100 return NULL;
103 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
105 GuestFileHandle *gfh;
106 int64_t handle;
108 handle = ga_get_fd_handle(ga_state, errp);
109 if (handle < 0) {
110 return -1;
112 gfh = g_new0(GuestFileHandle, 1);
113 gfh->id = handle;
114 gfh->fh = fh;
115 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
117 return handle;
120 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
122 GuestFileHandle *gfh;
123 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
124 if (gfh->id == id) {
125 return gfh;
128 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
129 return NULL;
132 static void handle_set_nonblocking(HANDLE fh)
134 DWORD file_type, pipe_state;
135 file_type = GetFileType(fh);
136 if (file_type != FILE_TYPE_PIPE) {
137 return;
139 /* If file_type == FILE_TYPE_PIPE, according to MSDN
140 * the specified file is socket or named pipe */
141 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
142 NULL, NULL, NULL, 0)) {
143 return;
145 /* The fd is named pipe fd */
146 if (pipe_state & PIPE_NOWAIT) {
147 return;
150 pipe_state |= PIPE_NOWAIT;
151 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
154 int64_t qmp_guest_file_open(const char *path, bool has_mode,
155 const char *mode, Error **errp)
157 int64_t fd;
158 HANDLE fh;
159 HANDLE templ_file = NULL;
160 DWORD share_mode = FILE_SHARE_READ;
161 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
162 LPSECURITY_ATTRIBUTES sa_attr = NULL;
163 OpenFlags *guest_flags;
165 if (!has_mode) {
166 mode = "r";
168 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
169 guest_flags = find_open_flag(mode);
170 if (guest_flags == NULL) {
171 error_setg(errp, "invalid file open mode");
172 return -1;
175 fh = CreateFile(path, guest_flags->desired_access, share_mode, sa_attr,
176 guest_flags->creation_disposition, flags_and_attr,
177 templ_file);
178 if (fh == INVALID_HANDLE_VALUE) {
179 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
180 path);
181 return -1;
184 /* set fd non-blocking to avoid common use cases (like reading from a
185 * named pipe) from hanging the agent
187 handle_set_nonblocking(fh);
189 fd = guest_file_handle_add(fh, errp);
190 if (fd < 0) {
191 CloseHandle(fh);
192 error_setg(errp, "failed to add handle to qmp handle table");
193 return -1;
196 slog("guest-file-open, handle: % " PRId64, fd);
197 return fd;
200 void qmp_guest_file_close(int64_t handle, Error **errp)
202 bool ret;
203 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
204 slog("guest-file-close called, handle: %" PRId64, handle);
205 if (gfh == NULL) {
206 return;
208 ret = CloseHandle(gfh->fh);
209 if (!ret) {
210 error_setg_win32(errp, GetLastError(), "failed close handle");
211 return;
214 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
215 g_free(gfh);
218 static void acquire_privilege(const char *name, Error **errp)
220 HANDLE token = NULL;
221 TOKEN_PRIVILEGES priv;
222 Error *local_err = NULL;
224 if (OpenProcessToken(GetCurrentProcess(),
225 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
227 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
228 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
229 "no luid for requested privilege");
230 goto out;
233 priv.PrivilegeCount = 1;
234 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
236 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
237 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
238 "unable to acquire requested privilege");
239 goto out;
242 } else {
243 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
244 "failed to open privilege token");
247 out:
248 if (token) {
249 CloseHandle(token);
251 if (local_err) {
252 error_propagate(errp, local_err);
256 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
257 Error **errp)
259 Error *local_err = NULL;
261 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
262 if (!thread) {
263 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
264 "failed to dispatch asynchronous command");
265 error_propagate(errp, local_err);
269 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
271 Error *local_err = NULL;
272 UINT shutdown_flag = EWX_FORCE;
274 slog("guest-shutdown called, mode: %s", mode);
276 if (!has_mode || strcmp(mode, "powerdown") == 0) {
277 shutdown_flag |= EWX_POWEROFF;
278 } else if (strcmp(mode, "halt") == 0) {
279 shutdown_flag |= EWX_SHUTDOWN;
280 } else if (strcmp(mode, "reboot") == 0) {
281 shutdown_flag |= EWX_REBOOT;
282 } else {
283 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
284 "halt|powerdown|reboot");
285 return;
288 /* Request a shutdown privilege, but try to shut down the system
289 anyway. */
290 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
291 if (local_err) {
292 error_propagate(errp, local_err);
293 return;
296 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
297 slog("guest-shutdown failed: %lu", GetLastError());
298 error_setg(errp, QERR_UNDEFINED_ERROR);
302 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
303 int64_t count, Error **errp)
305 GuestFileRead *read_data = NULL;
306 guchar *buf;
307 HANDLE fh;
308 bool is_ok;
309 DWORD read_count;
310 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
312 if (!gfh) {
313 return NULL;
315 if (!has_count) {
316 count = QGA_READ_COUNT_DEFAULT;
317 } else if (count < 0) {
318 error_setg(errp, "value '%" PRId64
319 "' is invalid for argument count", count);
320 return NULL;
323 fh = gfh->fh;
324 buf = g_malloc0(count+1);
325 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
326 if (!is_ok) {
327 error_setg_win32(errp, GetLastError(), "failed to read file");
328 slog("guest-file-read failed, handle %" PRId64, handle);
329 } else {
330 buf[read_count] = 0;
331 read_data = g_new0(GuestFileRead, 1);
332 read_data->count = (size_t)read_count;
333 read_data->eof = read_count == 0;
335 if (read_count != 0) {
336 read_data->buf_b64 = g_base64_encode(buf, read_count);
339 g_free(buf);
341 return read_data;
344 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
345 bool has_count, int64_t count,
346 Error **errp)
348 GuestFileWrite *write_data = NULL;
349 guchar *buf;
350 gsize buf_len;
351 bool is_ok;
352 DWORD write_count;
353 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
354 HANDLE fh;
356 if (!gfh) {
357 return NULL;
359 fh = gfh->fh;
360 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
361 if (!buf) {
362 return NULL;
365 if (!has_count) {
366 count = buf_len;
367 } else if (count < 0 || count > buf_len) {
368 error_setg(errp, "value '%" PRId64
369 "' is invalid for argument count", count);
370 goto done;
373 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
374 if (!is_ok) {
375 error_setg_win32(errp, GetLastError(), "failed to write to file");
376 slog("guest-file-write-failed, handle: %" PRId64, handle);
377 } else {
378 write_data = g_new0(GuestFileWrite, 1);
379 write_data->count = (size_t) write_count;
382 done:
383 g_free(buf);
384 return write_data;
387 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
388 int64_t whence_code, Error **errp)
390 GuestFileHandle *gfh;
391 GuestFileSeek *seek_data;
392 HANDLE fh;
393 LARGE_INTEGER new_pos, off_pos;
394 off_pos.QuadPart = offset;
395 BOOL res;
396 int whence;
398 gfh = guest_file_handle_find(handle, errp);
399 if (!gfh) {
400 return NULL;
403 /* We stupidly exposed 'whence':'int' in our qapi */
404 switch (whence_code) {
405 case QGA_SEEK_SET:
406 whence = SEEK_SET;
407 break;
408 case QGA_SEEK_CUR:
409 whence = SEEK_CUR;
410 break;
411 case QGA_SEEK_END:
412 whence = SEEK_END;
413 break;
414 default:
415 error_setg(errp, "invalid whence code %"PRId64, whence_code);
416 return NULL;
419 fh = gfh->fh;
420 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
421 if (!res) {
422 error_setg_win32(errp, GetLastError(), "failed to seek file");
423 return NULL;
425 seek_data = g_new0(GuestFileSeek, 1);
426 seek_data->position = new_pos.QuadPart;
427 return seek_data;
430 void qmp_guest_file_flush(int64_t handle, Error **errp)
432 HANDLE fh;
433 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
434 if (!gfh) {
435 return;
438 fh = gfh->fh;
439 if (!FlushFileBuffers(fh)) {
440 error_setg_win32(errp, GetLastError(), "failed to flush file");
444 #ifdef CONFIG_QGA_NTDDSCSI
446 static STORAGE_BUS_TYPE win2qemu[] = {
447 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
448 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
449 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
450 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
451 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
452 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
453 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
454 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
455 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
456 #if (_WIN32_WINNT >= 0x0600)
457 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
458 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
459 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
460 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
461 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
462 #endif
463 #if (_WIN32_WINNT >= 0x0601)
464 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
465 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
466 #endif
469 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
471 if (bus > ARRAY_SIZE(win2qemu) || (int)bus < 0) {
472 return GUEST_DISK_BUS_TYPE_UNKNOWN;
474 return win2qemu[(int)bus];
477 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME,
478 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2,
479 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
481 static GuestPCIAddress *get_pci_info(char *guid, Error **errp)
483 HDEVINFO dev_info;
484 SP_DEVINFO_DATA dev_info_data;
485 DWORD size = 0;
486 int i;
487 char dev_name[MAX_PATH];
488 char *buffer = NULL;
489 GuestPCIAddress *pci = NULL;
490 char *name = g_strdup(&guid[4]);
492 if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {
493 error_setg_win32(errp, GetLastError(), "failed to get dos device name");
494 goto out;
497 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, 0, 0,
498 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
499 if (dev_info == INVALID_HANDLE_VALUE) {
500 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
501 goto out;
504 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
505 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
506 DWORD addr, bus, slot, func, dev, data, size2;
507 while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
508 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
509 &data, (PBYTE)buffer, size,
510 &size2)) {
511 size = MAX(size, size2);
512 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
513 g_free(buffer);
514 /* Double the size to avoid problems on
515 * W2k MBCS systems per KB 888609.
516 * https://support.microsoft.com/en-us/kb/259695 */
517 buffer = g_malloc(size * 2);
518 } else {
519 error_setg_win32(errp, GetLastError(),
520 "failed to get device name");
521 goto out;
525 if (g_strcmp0(buffer, dev_name)) {
526 continue;
529 /* There is no need to allocate buffer in the next functions. The size
530 * is known and ULONG according to
531 * https://support.microsoft.com/en-us/kb/253232
532 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
534 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
535 SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {
536 break;
539 /* The function retrieves the device's address. This value will be
540 * transformed into device function and number */
541 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
542 SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {
543 break;
546 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
547 * This number is typically a user-perceived slot number. */
548 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
549 SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {
550 break;
553 /* SetupApi gives us the same information as driver with
554 * IoGetDeviceProperty. According to Microsoft
555 * https://support.microsoft.com/en-us/kb/253232
556 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
557 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
558 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
560 func = addr & 0x0000FFFF;
561 dev = (addr >> 16) & 0x0000FFFF;
562 pci = g_malloc0(sizeof(*pci));
563 pci->domain = dev;
564 pci->slot = slot;
565 pci->function = func;
566 pci->bus = bus;
567 break;
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 GuestFilesystemInfo *fs = NULL;
675 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
676 if (GetLastError() != ERROR_MORE_DATA) {
677 error_setg_win32(errp, GetLastError(), "failed to get volume name");
678 return NULL;
681 mnt_point = g_malloc(info_size + 1);
682 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
683 &info_size)) {
684 error_setg_win32(errp, GetLastError(), "failed to get volume name");
685 goto free;
688 len = strlen(mnt_point);
689 mnt_point[len] = '\\';
690 mnt_point[len+1] = 0;
691 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
692 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
693 if (GetLastError() != ERROR_NOT_READY) {
694 error_setg_win32(errp, GetLastError(), "failed to get volume info");
696 goto free;
699 fs_name[sizeof(fs_name) - 1] = 0;
700 fs = g_malloc(sizeof(*fs));
701 fs->name = g_strdup(guid);
702 if (len == 0) {
703 fs->mountpoint = g_strdup("System Reserved");
704 } else {
705 fs->mountpoint = g_strndup(mnt_point, len);
707 fs->type = g_strdup(fs_name);
708 fs->disk = build_guest_disk_info(guid, errp);
709 free:
710 g_free(mnt_point);
711 return fs;
714 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
716 HANDLE vol_h;
717 GuestFilesystemInfoList *new, *ret = NULL;
718 char guid[256];
720 vol_h = FindFirstVolume(guid, sizeof(guid));
721 if (vol_h == INVALID_HANDLE_VALUE) {
722 error_setg_win32(errp, GetLastError(), "failed to find any volume");
723 return NULL;
726 do {
727 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
728 if (info == NULL) {
729 continue;
731 new = g_malloc(sizeof(*ret));
732 new->value = info;
733 new->next = ret;
734 ret = new;
735 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
737 if (GetLastError() != ERROR_NO_MORE_FILES) {
738 error_setg_win32(errp, GetLastError(), "failed to find next volume");
741 FindVolumeClose(vol_h);
742 return ret;
746 * Return status of freeze/thaw
748 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
750 if (!vss_initialized()) {
751 error_setg(errp, QERR_UNSUPPORTED);
752 return 0;
755 if (ga_is_frozen(ga_state)) {
756 return GUEST_FSFREEZE_STATUS_FROZEN;
759 return GUEST_FSFREEZE_STATUS_THAWED;
763 * Freeze local file systems using Volume Shadow-copy Service.
764 * The frozen state is limited for up to 10 seconds by VSS.
766 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
768 int i;
769 Error *local_err = NULL;
771 if (!vss_initialized()) {
772 error_setg(errp, QERR_UNSUPPORTED);
773 return 0;
776 slog("guest-fsfreeze called");
778 /* cannot risk guest agent blocking itself on a write in this state */
779 ga_set_frozen(ga_state);
781 qga_vss_fsfreeze(&i, &local_err, true);
782 if (local_err) {
783 error_propagate(errp, local_err);
784 goto error;
787 return i;
789 error:
790 local_err = NULL;
791 qmp_guest_fsfreeze_thaw(&local_err);
792 if (local_err) {
793 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
794 error_free(local_err);
796 return 0;
799 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
800 strList *mountpoints,
801 Error **errp)
803 error_setg(errp, QERR_UNSUPPORTED);
805 return 0;
809 * Thaw local file systems using Volume Shadow-copy Service.
811 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
813 int i;
815 if (!vss_initialized()) {
816 error_setg(errp, QERR_UNSUPPORTED);
817 return 0;
820 qga_vss_fsfreeze(&i, errp, false);
822 ga_unset_frozen(ga_state);
823 return i;
826 static void guest_fsfreeze_cleanup(void)
828 Error *err = NULL;
830 if (!vss_initialized()) {
831 return;
834 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
835 qmp_guest_fsfreeze_thaw(&err);
836 if (err) {
837 slog("failed to clean up frozen filesystems: %s",
838 error_get_pretty(err));
839 error_free(err);
843 vss_deinit(true);
847 * Walk list of mounted file systems in the guest, and discard unused
848 * areas.
850 GuestFilesystemTrimResponse *
851 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
853 error_setg(errp, QERR_UNSUPPORTED);
854 return NULL;
857 typedef enum {
858 GUEST_SUSPEND_MODE_DISK,
859 GUEST_SUSPEND_MODE_RAM
860 } GuestSuspendMode;
862 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
864 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
865 Error *local_err = NULL;
867 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
868 if (!GetPwrCapabilities(&sys_pwr_caps)) {
869 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
870 "failed to determine guest suspend capabilities");
871 goto out;
874 switch (mode) {
875 case GUEST_SUSPEND_MODE_DISK:
876 if (!sys_pwr_caps.SystemS4) {
877 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
878 "suspend-to-disk not supported by OS");
880 break;
881 case GUEST_SUSPEND_MODE_RAM:
882 if (!sys_pwr_caps.SystemS3) {
883 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
884 "suspend-to-ram not supported by OS");
886 break;
887 default:
888 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
889 "GuestSuspendMode");
892 out:
893 if (local_err) {
894 error_propagate(errp, local_err);
898 static DWORD WINAPI do_suspend(LPVOID opaque)
900 GuestSuspendMode *mode = opaque;
901 DWORD ret = 0;
903 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
904 slog("failed to suspend guest, %lu", GetLastError());
905 ret = -1;
907 g_free(mode);
908 return ret;
911 void qmp_guest_suspend_disk(Error **errp)
913 Error *local_err = NULL;
914 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
916 *mode = GUEST_SUSPEND_MODE_DISK;
917 check_suspend_mode(*mode, &local_err);
918 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
919 execute_async(do_suspend, mode, &local_err);
921 if (local_err) {
922 error_propagate(errp, local_err);
923 g_free(mode);
927 void qmp_guest_suspend_ram(Error **errp)
929 Error *local_err = NULL;
930 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
932 *mode = GUEST_SUSPEND_MODE_RAM;
933 check_suspend_mode(*mode, &local_err);
934 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
935 execute_async(do_suspend, mode, &local_err);
937 if (local_err) {
938 error_propagate(errp, local_err);
939 g_free(mode);
943 void qmp_guest_suspend_hybrid(Error **errp)
945 error_setg(errp, QERR_UNSUPPORTED);
948 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
950 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
951 ULONG adptr_addrs_len = 0;
952 DWORD ret;
954 /* Call the first time to get the adptr_addrs_len. */
955 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
956 NULL, adptr_addrs, &adptr_addrs_len);
958 adptr_addrs = g_malloc(adptr_addrs_len);
959 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
960 NULL, adptr_addrs, &adptr_addrs_len);
961 if (ret != ERROR_SUCCESS) {
962 error_setg_win32(errp, ret, "failed to get adapters addresses");
963 g_free(adptr_addrs);
964 adptr_addrs = NULL;
966 return adptr_addrs;
969 static char *guest_wctomb_dup(WCHAR *wstr)
971 char *str;
972 size_t i;
974 i = wcslen(wstr) + 1;
975 str = g_malloc(i);
976 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
977 wstr, -1, str, i, NULL, NULL);
978 return str;
981 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
982 Error **errp)
984 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
985 DWORD len;
986 int ret;
988 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
989 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
990 len = sizeof(addr_str);
991 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
992 ip_addr->Address.iSockaddrLength,
993 NULL,
994 addr_str,
995 &len);
996 if (ret != 0) {
997 error_setg_win32(errp, WSAGetLastError(),
998 "failed address presentation form conversion");
999 return NULL;
1001 return g_strdup(addr_str);
1003 return NULL;
1006 #if (_WIN32_WINNT >= 0x0600)
1007 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1009 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1010 * field to obtain the prefix.
1012 return ip_addr->OnLinkPrefixLength;
1014 #else
1015 /* When using the Windows XP and 2003 build environment, do the best we can to
1016 * figure out the prefix.
1018 static IP_ADAPTER_INFO *guest_get_adapters_info(void)
1020 IP_ADAPTER_INFO *adptr_info = NULL;
1021 ULONG adptr_info_len = 0;
1022 DWORD ret;
1024 /* Call the first time to get the adptr_info_len. */
1025 GetAdaptersInfo(adptr_info, &adptr_info_len);
1027 adptr_info = g_malloc(adptr_info_len);
1028 ret = GetAdaptersInfo(adptr_info, &adptr_info_len);
1029 if (ret != ERROR_SUCCESS) {
1030 g_free(adptr_info);
1031 adptr_info = NULL;
1033 return adptr_info;
1036 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1038 int64_t prefix = -1; /* Use for AF_INET6 and unknown/undetermined values. */
1039 IP_ADAPTER_INFO *adptr_info, *info;
1040 IP_ADDR_STRING *ip;
1041 struct in_addr *p;
1043 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
1044 return prefix;
1046 adptr_info = guest_get_adapters_info();
1047 if (adptr_info == NULL) {
1048 return prefix;
1051 /* Match up the passed in ip_addr with one found in adaptr_info.
1052 * The matching one in adptr_info will have the netmask.
1054 p = &((struct sockaddr_in *)ip_addr->Address.lpSockaddr)->sin_addr;
1055 for (info = adptr_info; info; info = info->Next) {
1056 for (ip = &info->IpAddressList; ip; ip = ip->Next) {
1057 if (p->S_un.S_addr == inet_addr(ip->IpAddress.String)) {
1058 prefix = ctpop32(inet_addr(ip->IpMask.String));
1059 goto out;
1063 out:
1064 g_free(adptr_info);
1065 return prefix;
1067 #endif
1069 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1071 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1072 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1073 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1074 GuestIpAddressList *head_addr, *cur_addr;
1075 GuestNetworkInterfaceList *info;
1076 GuestIpAddressList *address_item = NULL;
1077 unsigned char *mac_addr;
1078 char *addr_str;
1079 WORD wsa_version;
1080 WSADATA wsa_data;
1081 int ret;
1083 adptr_addrs = guest_get_adapters_addresses(errp);
1084 if (adptr_addrs == NULL) {
1085 return NULL;
1088 /* Make WSA APIs available. */
1089 wsa_version = MAKEWORD(2, 2);
1090 ret = WSAStartup(wsa_version, &wsa_data);
1091 if (ret != 0) {
1092 error_setg_win32(errp, ret, "failed socket startup");
1093 goto out;
1096 for (addr = adptr_addrs; addr; addr = addr->Next) {
1097 info = g_malloc0(sizeof(*info));
1099 if (cur_item == NULL) {
1100 head = cur_item = info;
1101 } else {
1102 cur_item->next = info;
1103 cur_item = info;
1106 info->value = g_malloc0(sizeof(*info->value));
1107 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1109 if (addr->PhysicalAddressLength != 0) {
1110 mac_addr = addr->PhysicalAddress;
1112 info->value->hardware_address =
1113 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1114 (int) mac_addr[0], (int) mac_addr[1],
1115 (int) mac_addr[2], (int) mac_addr[3],
1116 (int) mac_addr[4], (int) mac_addr[5]);
1118 info->value->has_hardware_address = true;
1121 head_addr = NULL;
1122 cur_addr = NULL;
1123 for (ip_addr = addr->FirstUnicastAddress;
1124 ip_addr;
1125 ip_addr = ip_addr->Next) {
1126 addr_str = guest_addr_to_str(ip_addr, errp);
1127 if (addr_str == NULL) {
1128 continue;
1131 address_item = g_malloc0(sizeof(*address_item));
1133 if (!cur_addr) {
1134 head_addr = cur_addr = address_item;
1135 } else {
1136 cur_addr->next = address_item;
1137 cur_addr = address_item;
1140 address_item->value = g_malloc0(sizeof(*address_item->value));
1141 address_item->value->ip_address = addr_str;
1142 address_item->value->prefix = guest_ip_prefix(ip_addr);
1143 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1144 address_item->value->ip_address_type =
1145 GUEST_IP_ADDRESS_TYPE_IPV4;
1146 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1147 address_item->value->ip_address_type =
1148 GUEST_IP_ADDRESS_TYPE_IPV6;
1151 if (head_addr) {
1152 info->value->has_ip_addresses = true;
1153 info->value->ip_addresses = head_addr;
1156 WSACleanup();
1157 out:
1158 g_free(adptr_addrs);
1159 return head;
1162 int64_t qmp_guest_get_time(Error **errp)
1164 SYSTEMTIME ts = {0};
1165 int64_t time_ns;
1166 FILETIME tf;
1168 GetSystemTime(&ts);
1169 if (ts.wYear < 1601 || ts.wYear > 30827) {
1170 error_setg(errp, "Failed to get time");
1171 return -1;
1174 if (!SystemTimeToFileTime(&ts, &tf)) {
1175 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1176 return -1;
1179 time_ns = ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1180 - W32_FT_OFFSET) * 100;
1182 return time_ns;
1185 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1187 Error *local_err = NULL;
1188 SYSTEMTIME ts;
1189 FILETIME tf;
1190 LONGLONG time;
1192 if (!has_time) {
1193 /* Unfortunately, Windows libraries don't provide an easy way to access
1194 * RTC yet:
1196 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1198 error_setg(errp, "Time argument is required on this platform");
1199 return;
1202 /* Validate time passed by user. */
1203 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1204 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1205 return;
1208 time = time_ns / 100 + W32_FT_OFFSET;
1210 tf.dwLowDateTime = (DWORD) time;
1211 tf.dwHighDateTime = (DWORD) (time >> 32);
1213 if (!FileTimeToSystemTime(&tf, &ts)) {
1214 error_setg(errp, "Failed to convert system time %d",
1215 (int)GetLastError());
1216 return;
1219 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1220 if (local_err) {
1221 error_propagate(errp, local_err);
1222 return;
1225 if (!SetSystemTime(&ts)) {
1226 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1227 return;
1231 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1233 error_setg(errp, QERR_UNSUPPORTED);
1234 return NULL;
1237 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1239 error_setg(errp, QERR_UNSUPPORTED);
1240 return -1;
1243 static gchar *
1244 get_net_error_message(gint error)
1246 HMODULE module = NULL;
1247 gchar *retval = NULL;
1248 wchar_t *msg = NULL;
1249 int flags, nchars;
1251 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER
1252 |FORMAT_MESSAGE_IGNORE_INSERTS
1253 |FORMAT_MESSAGE_FROM_SYSTEM;
1255 if (error >= NERR_BASE && error <= MAX_NERR) {
1256 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1258 if (module != NULL) {
1259 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1263 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1265 if (msg != NULL) {
1266 nchars = wcslen(msg);
1268 if (nchars > 2 && msg[nchars-1] == '\n' && msg[nchars-2] == '\r') {
1269 msg[nchars-2] = '\0';
1272 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1274 LocalFree(msg);
1277 if (module != NULL) {
1278 FreeLibrary(module);
1281 return retval;
1284 void qmp_guest_set_user_password(const char *username,
1285 const char *password,
1286 bool crypted,
1287 Error **errp)
1289 NET_API_STATUS nas;
1290 char *rawpasswddata = NULL;
1291 size_t rawpasswdlen;
1292 wchar_t *user, *wpass;
1293 USER_INFO_1003 pi1003 = { 0, };
1295 if (crypted) {
1296 error_setg(errp, QERR_UNSUPPORTED);
1297 return;
1300 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1301 if (!rawpasswddata) {
1302 return;
1304 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1305 rawpasswddata[rawpasswdlen] = '\0';
1307 user = g_utf8_to_utf16(username, -1, NULL, NULL, NULL);
1308 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, NULL);
1310 pi1003.usri1003_password = wpass;
1311 nas = NetUserSetInfo(NULL, user,
1312 1003, (LPBYTE)&pi1003,
1313 NULL);
1315 if (nas != NERR_Success) {
1316 gchar *msg = get_net_error_message(nas);
1317 error_setg(errp, "failed to set password: %s", msg);
1318 g_free(msg);
1321 g_free(user);
1322 g_free(wpass);
1323 g_free(rawpasswddata);
1326 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1328 error_setg(errp, QERR_UNSUPPORTED);
1329 return NULL;
1332 GuestMemoryBlockResponseList *
1333 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1335 error_setg(errp, QERR_UNSUPPORTED);
1336 return NULL;
1339 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1341 error_setg(errp, QERR_UNSUPPORTED);
1342 return NULL;
1345 /* add unsupported commands to the blacklist */
1346 GList *ga_command_blacklist_init(GList *blacklist)
1348 const char *list_unsupported[] = {
1349 "guest-suspend-hybrid",
1350 "guest-get-vcpus", "guest-set-vcpus",
1351 "guest-get-memory-blocks", "guest-set-memory-blocks",
1352 "guest-get-memory-block-size",
1353 "guest-fsfreeze-freeze-list",
1354 "guest-fstrim", NULL};
1355 char **p = (char **)list_unsupported;
1357 while (*p) {
1358 blacklist = g_list_append(blacklist, g_strdup(*p++));
1361 if (!vss_init(true)) {
1362 g_debug("vss_init failed, vss commands are going to be disabled");
1363 const char *list[] = {
1364 "guest-get-fsinfo", "guest-fsfreeze-status",
1365 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1366 p = (char **)list;
1368 while (*p) {
1369 blacklist = g_list_append(blacklist, g_strdup(*p++));
1373 return blacklist;
1376 /* register init/cleanup routines for stateful command groups */
1377 void ga_command_state_init(GAState *s, GACommandState *cs)
1379 if (!vss_initialized()) {
1380 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);