Merge remote-tracking branch 'remotes/juanquintela/tags/migration/20170922-1' into...
[qemu/kevin.git] / qga / commands-win32.c
blob619dbd2bc24f33a12ab948185d347c173b4daaa9
1 /*
2 * QEMU Guest Agent win32-specific command implementations
4 * Copyright IBM Corp. 2012
6 * Authors:
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Gal Hammer <ghammer@redhat.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
14 #ifndef _WIN32_WINNT
15 # define _WIN32_WINNT 0x0600
16 #endif
17 #include "qemu/osdep.h"
18 #include <wtypes.h>
19 #include <powrprof.h>
20 #include <winsock2.h>
21 #include <ws2tcpip.h>
22 #include <iptypes.h>
23 #include <iphlpapi.h>
24 #ifdef CONFIG_QGA_NTDDSCSI
25 #include <winioctl.h>
26 #include <ntddscsi.h>
27 #include <setupapi.h>
28 #include <initguid.h>
29 #endif
30 #include <lm.h>
31 #include <wtsapi32.h>
33 #include "qga/guest-agent-core.h"
34 #include "qga/vss-win32.h"
35 #include "qga-qmp-commands.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qemu/queue.h"
38 #include "qemu/host-utils.h"
39 #include "qemu/base64.h"
41 #ifndef SHTDN_REASON_FLAG_PLANNED
42 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
43 #endif
45 /* multiple of 100 nanoseconds elapsed between windows baseline
46 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
47 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
48 (365 * (1970 - 1601) + \
49 (1970 - 1601) / 4 - 3))
51 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
53 typedef struct GuestFileHandle {
54 int64_t id;
55 HANDLE fh;
56 QTAILQ_ENTRY(GuestFileHandle) next;
57 } GuestFileHandle;
59 static struct {
60 QTAILQ_HEAD(, GuestFileHandle) filehandles;
61 } guest_file_state = {
62 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
65 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
67 typedef struct OpenFlags {
68 const char *forms;
69 DWORD desired_access;
70 DWORD creation_disposition;
71 } OpenFlags;
72 static OpenFlags guest_file_open_modes[] = {
73 {"r", GENERIC_READ, OPEN_EXISTING},
74 {"rb", GENERIC_READ, OPEN_EXISTING},
75 {"w", GENERIC_WRITE, CREATE_ALWAYS},
76 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
77 {"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
78 {"r+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
79 {"rb+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
80 {"r+b", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
81 {"w+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
82 {"wb+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
83 {"w+b", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
84 {"a+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
85 {"ab+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
86 {"a+b", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS }
89 static OpenFlags *find_open_flag(const char *mode_str)
91 int mode;
92 Error **errp = NULL;
94 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
95 OpenFlags *flags = guest_file_open_modes + mode;
97 if (strcmp(flags->forms, mode_str) == 0) {
98 return flags;
102 error_setg(errp, "invalid file open mode '%s'", mode_str);
103 return NULL;
106 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
108 GuestFileHandle *gfh;
109 int64_t handle;
111 handle = ga_get_fd_handle(ga_state, errp);
112 if (handle < 0) {
113 return -1;
115 gfh = g_new0(GuestFileHandle, 1);
116 gfh->id = handle;
117 gfh->fh = fh;
118 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
120 return handle;
123 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
125 GuestFileHandle *gfh;
126 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
127 if (gfh->id == id) {
128 return gfh;
131 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
132 return NULL;
135 static void handle_set_nonblocking(HANDLE fh)
137 DWORD file_type, pipe_state;
138 file_type = GetFileType(fh);
139 if (file_type != FILE_TYPE_PIPE) {
140 return;
142 /* If file_type == FILE_TYPE_PIPE, according to MSDN
143 * the specified file is socket or named pipe */
144 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
145 NULL, NULL, NULL, 0)) {
146 return;
148 /* The fd is named pipe fd */
149 if (pipe_state & PIPE_NOWAIT) {
150 return;
153 pipe_state |= PIPE_NOWAIT;
154 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
157 int64_t qmp_guest_file_open(const char *path, bool has_mode,
158 const char *mode, Error **errp)
160 int64_t fd;
161 HANDLE fh;
162 HANDLE templ_file = NULL;
163 DWORD share_mode = FILE_SHARE_READ;
164 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
165 LPSECURITY_ATTRIBUTES sa_attr = NULL;
166 OpenFlags *guest_flags;
168 if (!has_mode) {
169 mode = "r";
171 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
172 guest_flags = find_open_flag(mode);
173 if (guest_flags == NULL) {
174 error_setg(errp, "invalid file open mode");
175 return -1;
178 fh = CreateFile(path, guest_flags->desired_access, share_mode, sa_attr,
179 guest_flags->creation_disposition, flags_and_attr,
180 templ_file);
181 if (fh == INVALID_HANDLE_VALUE) {
182 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
183 path);
184 return -1;
187 /* set fd non-blocking to avoid common use cases (like reading from a
188 * named pipe) from hanging the agent
190 handle_set_nonblocking(fh);
192 fd = guest_file_handle_add(fh, errp);
193 if (fd < 0) {
194 CloseHandle(fh);
195 error_setg(errp, "failed to add handle to qmp handle table");
196 return -1;
199 slog("guest-file-open, handle: % " PRId64, fd);
200 return fd;
203 void qmp_guest_file_close(int64_t handle, Error **errp)
205 bool ret;
206 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
207 slog("guest-file-close called, handle: %" PRId64, handle);
208 if (gfh == NULL) {
209 return;
211 ret = CloseHandle(gfh->fh);
212 if (!ret) {
213 error_setg_win32(errp, GetLastError(), "failed close handle");
214 return;
217 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
218 g_free(gfh);
221 static void acquire_privilege(const char *name, Error **errp)
223 HANDLE token = NULL;
224 TOKEN_PRIVILEGES priv;
225 Error *local_err = NULL;
227 if (OpenProcessToken(GetCurrentProcess(),
228 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
230 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
231 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
232 "no luid for requested privilege");
233 goto out;
236 priv.PrivilegeCount = 1;
237 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
239 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
240 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
241 "unable to acquire requested privilege");
242 goto out;
245 } else {
246 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
247 "failed to open privilege token");
250 out:
251 if (token) {
252 CloseHandle(token);
254 error_propagate(errp, local_err);
257 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
258 Error **errp)
260 Error *local_err = NULL;
262 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
263 if (!thread) {
264 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
265 "failed to dispatch asynchronous command");
266 error_propagate(errp, local_err);
270 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
272 Error *local_err = NULL;
273 UINT shutdown_flag = EWX_FORCE;
275 slog("guest-shutdown called, mode: %s", mode);
277 if (!has_mode || strcmp(mode, "powerdown") == 0) {
278 shutdown_flag |= EWX_POWEROFF;
279 } else if (strcmp(mode, "halt") == 0) {
280 shutdown_flag |= EWX_SHUTDOWN;
281 } else if (strcmp(mode, "reboot") == 0) {
282 shutdown_flag |= EWX_REBOOT;
283 } else {
284 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
285 "halt|powerdown|reboot");
286 return;
289 /* Request a shutdown privilege, but try to shut down the system
290 anyway. */
291 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
292 if (local_err) {
293 error_propagate(errp, local_err);
294 return;
297 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
298 slog("guest-shutdown failed: %lu", GetLastError());
299 error_setg(errp, QERR_UNDEFINED_ERROR);
303 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
304 int64_t count, Error **errp)
306 GuestFileRead *read_data = NULL;
307 guchar *buf;
308 HANDLE fh;
309 bool is_ok;
310 DWORD read_count;
311 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
313 if (!gfh) {
314 return NULL;
316 if (!has_count) {
317 count = QGA_READ_COUNT_DEFAULT;
318 } else if (count < 0) {
319 error_setg(errp, "value '%" PRId64
320 "' is invalid for argument count", count);
321 return NULL;
324 fh = gfh->fh;
325 buf = g_malloc0(count+1);
326 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
327 if (!is_ok) {
328 error_setg_win32(errp, GetLastError(), "failed to read file");
329 slog("guest-file-read failed, handle %" PRId64, handle);
330 } else {
331 buf[read_count] = 0;
332 read_data = g_new0(GuestFileRead, 1);
333 read_data->count = (size_t)read_count;
334 read_data->eof = read_count == 0;
336 if (read_count != 0) {
337 read_data->buf_b64 = g_base64_encode(buf, read_count);
340 g_free(buf);
342 return read_data;
345 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
346 bool has_count, int64_t count,
347 Error **errp)
349 GuestFileWrite *write_data = NULL;
350 guchar *buf;
351 gsize buf_len;
352 bool is_ok;
353 DWORD write_count;
354 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
355 HANDLE fh;
357 if (!gfh) {
358 return NULL;
360 fh = gfh->fh;
361 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
362 if (!buf) {
363 return NULL;
366 if (!has_count) {
367 count = buf_len;
368 } else if (count < 0 || count > buf_len) {
369 error_setg(errp, "value '%" PRId64
370 "' is invalid for argument count", count);
371 goto done;
374 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
375 if (!is_ok) {
376 error_setg_win32(errp, GetLastError(), "failed to write to file");
377 slog("guest-file-write-failed, handle: %" PRId64, handle);
378 } else {
379 write_data = g_new0(GuestFileWrite, 1);
380 write_data->count = (size_t) write_count;
383 done:
384 g_free(buf);
385 return write_data;
388 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
389 GuestFileWhence *whence_code,
390 Error **errp)
392 GuestFileHandle *gfh;
393 GuestFileSeek *seek_data;
394 HANDLE fh;
395 LARGE_INTEGER new_pos, off_pos;
396 off_pos.QuadPart = offset;
397 BOOL res;
398 int whence;
399 Error *err = NULL;
401 gfh = guest_file_handle_find(handle, errp);
402 if (!gfh) {
403 return NULL;
406 /* We stupidly exposed 'whence':'int' in our qapi */
407 whence = ga_parse_whence(whence_code, &err);
408 if (err) {
409 error_propagate(errp, err);
410 return NULL;
413 fh = gfh->fh;
414 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
415 if (!res) {
416 error_setg_win32(errp, GetLastError(), "failed to seek file");
417 return NULL;
419 seek_data = g_new0(GuestFileSeek, 1);
420 seek_data->position = new_pos.QuadPart;
421 return seek_data;
424 void qmp_guest_file_flush(int64_t handle, Error **errp)
426 HANDLE fh;
427 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
428 if (!gfh) {
429 return;
432 fh = gfh->fh;
433 if (!FlushFileBuffers(fh)) {
434 error_setg_win32(errp, GetLastError(), "failed to flush file");
438 #ifdef CONFIG_QGA_NTDDSCSI
440 static STORAGE_BUS_TYPE win2qemu[] = {
441 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
442 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
443 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
444 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
445 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
446 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
447 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
448 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
449 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
450 #if (_WIN32_WINNT >= 0x0600)
451 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
452 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
453 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
454 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
455 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
456 #endif
457 #if (_WIN32_WINNT >= 0x0601)
458 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
459 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
460 #endif
463 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
465 if (bus > ARRAY_SIZE(win2qemu) || (int)bus < 0) {
466 return GUEST_DISK_BUS_TYPE_UNKNOWN;
468 return win2qemu[(int)bus];
471 DEFINE_GUID(GUID_DEVINTERFACE_VOLUME,
472 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2,
473 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
475 static GuestPCIAddress *get_pci_info(char *guid, Error **errp)
477 HDEVINFO dev_info;
478 SP_DEVINFO_DATA dev_info_data;
479 DWORD size = 0;
480 int i;
481 char dev_name[MAX_PATH];
482 char *buffer = NULL;
483 GuestPCIAddress *pci = NULL;
484 char *name = g_strdup(&guid[4]);
486 if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {
487 error_setg_win32(errp, GetLastError(), "failed to get dos device name");
488 goto out;
491 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, 0, 0,
492 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
493 if (dev_info == INVALID_HANDLE_VALUE) {
494 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
495 goto out;
498 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
499 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
500 DWORD addr, bus, slot, func, dev, data, size2;
501 while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
502 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
503 &data, (PBYTE)buffer, size,
504 &size2)) {
505 size = MAX(size, size2);
506 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
507 g_free(buffer);
508 /* Double the size to avoid problems on
509 * W2k MBCS systems per KB 888609.
510 * https://support.microsoft.com/en-us/kb/259695 */
511 buffer = g_malloc(size * 2);
512 } else {
513 error_setg_win32(errp, GetLastError(),
514 "failed to get device name");
515 goto free_dev_info;
519 if (g_strcmp0(buffer, dev_name)) {
520 continue;
523 /* There is no need to allocate buffer in the next functions. The size
524 * is known and ULONG according to
525 * https://support.microsoft.com/en-us/kb/253232
526 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
528 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
529 SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {
530 break;
533 /* The function retrieves the device's address. This value will be
534 * transformed into device function and number */
535 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
536 SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {
537 break;
540 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
541 * This number is typically a user-perceived slot number. */
542 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
543 SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {
544 break;
547 /* SetupApi gives us the same information as driver with
548 * IoGetDeviceProperty. According to Microsoft
549 * https://support.microsoft.com/en-us/kb/253232
550 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
551 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
552 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
554 func = addr & 0x0000FFFF;
555 dev = (addr >> 16) & 0x0000FFFF;
556 pci = g_malloc0(sizeof(*pci));
557 pci->domain = dev;
558 pci->slot = slot;
559 pci->function = func;
560 pci->bus = bus;
561 break;
564 free_dev_info:
565 SetupDiDestroyDeviceInfoList(dev_info);
566 out:
567 g_free(buffer);
568 g_free(name);
569 return pci;
572 static int get_disk_bus_type(HANDLE vol_h, Error **errp)
574 STORAGE_PROPERTY_QUERY query;
575 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
576 DWORD received;
578 dev_desc = &buf;
579 dev_desc->Size = sizeof(buf);
580 query.PropertyId = StorageDeviceProperty;
581 query.QueryType = PropertyStandardQuery;
583 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
584 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
585 dev_desc->Size, &received, NULL)) {
586 error_setg_win32(errp, GetLastError(), "failed to get bus type");
587 return -1;
590 return dev_desc->BusType;
593 /* VSS provider works with volumes, thus there is no difference if
594 * the volume consist of spanned disks. Info about the first disk in the
595 * volume is returned for the spanned disk group (LVM) */
596 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
598 GuestDiskAddressList *list = NULL;
599 GuestDiskAddress *disk;
600 SCSI_ADDRESS addr, *scsi_ad;
601 DWORD len;
602 int bus;
603 HANDLE vol_h;
605 scsi_ad = &addr;
606 char *name = g_strndup(guid, strlen(guid)-1);
608 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
609 0, NULL);
610 if (vol_h == INVALID_HANDLE_VALUE) {
611 error_setg_win32(errp, GetLastError(), "failed to open volume");
612 goto out_free;
615 bus = get_disk_bus_type(vol_h, errp);
616 if (bus < 0) {
617 goto out_close;
620 disk = g_malloc0(sizeof(*disk));
621 disk->bus_type = find_bus_type(bus);
622 if (bus == BusTypeScsi || bus == BusTypeAta || bus == BusTypeRAID
623 #if (_WIN32_WINNT >= 0x0600)
624 /* This bus type is not supported before Windows Server 2003 SP1 */
625 || bus == BusTypeSas
626 #endif
628 /* We are able to use the same ioctls for different bus types
629 * according to Microsoft docs
630 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
631 if (DeviceIoControl(vol_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
632 sizeof(SCSI_ADDRESS), &len, NULL)) {
633 disk->unit = addr.Lun;
634 disk->target = addr.TargetId;
635 disk->bus = addr.PathId;
636 disk->pci_controller = get_pci_info(name, errp);
638 /* We do not set error in this case, because we still have enough
639 * information about volume. */
640 } else {
641 disk->pci_controller = NULL;
644 list = g_malloc0(sizeof(*list));
645 list->value = disk;
646 list->next = NULL;
647 out_close:
648 CloseHandle(vol_h);
649 out_free:
650 g_free(name);
651 return list;
654 #else
656 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
658 return NULL;
661 #endif /* CONFIG_QGA_NTDDSCSI */
663 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
665 DWORD info_size;
666 char mnt, *mnt_point;
667 char fs_name[32];
668 char vol_info[MAX_PATH+1];
669 size_t len;
670 GuestFilesystemInfo *fs = NULL;
672 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
673 if (GetLastError() != ERROR_MORE_DATA) {
674 error_setg_win32(errp, GetLastError(), "failed to get volume name");
675 return NULL;
678 mnt_point = g_malloc(info_size + 1);
679 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
680 &info_size)) {
681 error_setg_win32(errp, GetLastError(), "failed to get volume name");
682 goto free;
685 len = strlen(mnt_point);
686 mnt_point[len] = '\\';
687 mnt_point[len+1] = 0;
688 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
689 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
690 if (GetLastError() != ERROR_NOT_READY) {
691 error_setg_win32(errp, GetLastError(), "failed to get volume info");
693 goto free;
696 fs_name[sizeof(fs_name) - 1] = 0;
697 fs = g_malloc(sizeof(*fs));
698 fs->name = g_strdup(guid);
699 if (len == 0) {
700 fs->mountpoint = g_strdup("System Reserved");
701 } else {
702 fs->mountpoint = g_strndup(mnt_point, len);
704 fs->type = g_strdup(fs_name);
705 fs->disk = build_guest_disk_info(guid, errp);
706 free:
707 g_free(mnt_point);
708 return fs;
711 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
713 HANDLE vol_h;
714 GuestFilesystemInfoList *new, *ret = NULL;
715 char guid[256];
717 vol_h = FindFirstVolume(guid, sizeof(guid));
718 if (vol_h == INVALID_HANDLE_VALUE) {
719 error_setg_win32(errp, GetLastError(), "failed to find any volume");
720 return NULL;
723 do {
724 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
725 if (info == NULL) {
726 continue;
728 new = g_malloc(sizeof(*ret));
729 new->value = info;
730 new->next = ret;
731 ret = new;
732 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
734 if (GetLastError() != ERROR_NO_MORE_FILES) {
735 error_setg_win32(errp, GetLastError(), "failed to find next volume");
738 FindVolumeClose(vol_h);
739 return ret;
743 * Return status of freeze/thaw
745 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
747 if (!vss_initialized()) {
748 error_setg(errp, QERR_UNSUPPORTED);
749 return 0;
752 if (ga_is_frozen(ga_state)) {
753 return GUEST_FSFREEZE_STATUS_FROZEN;
756 return GUEST_FSFREEZE_STATUS_THAWED;
760 * Freeze local file systems using Volume Shadow-copy Service.
761 * The frozen state is limited for up to 10 seconds by VSS.
763 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
765 int i;
766 Error *local_err = NULL;
768 if (!vss_initialized()) {
769 error_setg(errp, QERR_UNSUPPORTED);
770 return 0;
773 slog("guest-fsfreeze called");
775 /* cannot risk guest agent blocking itself on a write in this state */
776 ga_set_frozen(ga_state);
778 qga_vss_fsfreeze(&i, true, &local_err);
779 if (local_err) {
780 error_propagate(errp, local_err);
781 goto error;
784 return i;
786 error:
787 local_err = NULL;
788 qmp_guest_fsfreeze_thaw(&local_err);
789 if (local_err) {
790 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
791 error_free(local_err);
793 return 0;
796 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
797 strList *mountpoints,
798 Error **errp)
800 error_setg(errp, QERR_UNSUPPORTED);
802 return 0;
806 * Thaw local file systems using Volume Shadow-copy Service.
808 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
810 int i;
812 if (!vss_initialized()) {
813 error_setg(errp, QERR_UNSUPPORTED);
814 return 0;
817 qga_vss_fsfreeze(&i, false, errp);
819 ga_unset_frozen(ga_state);
820 return i;
823 static void guest_fsfreeze_cleanup(void)
825 Error *err = NULL;
827 if (!vss_initialized()) {
828 return;
831 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
832 qmp_guest_fsfreeze_thaw(&err);
833 if (err) {
834 slog("failed to clean up frozen filesystems: %s",
835 error_get_pretty(err));
836 error_free(err);
840 vss_deinit(true);
844 * Walk list of mounted file systems in the guest, and discard unused
845 * areas.
847 GuestFilesystemTrimResponse *
848 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
850 GuestFilesystemTrimResponse *resp;
851 HANDLE handle;
852 WCHAR guid[MAX_PATH] = L"";
854 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
855 if (handle == INVALID_HANDLE_VALUE) {
856 error_setg_win32(errp, GetLastError(), "failed to find any volume");
857 return NULL;
860 resp = g_new0(GuestFilesystemTrimResponse, 1);
862 do {
863 GuestFilesystemTrimResult *res;
864 GuestFilesystemTrimResultList *list;
865 PWCHAR uc_path;
866 DWORD char_count = 0;
867 char *path, *out;
868 GError *gerr = NULL;
869 gchar * argv[4];
871 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
873 if (GetLastError() != ERROR_MORE_DATA) {
874 continue;
876 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
877 continue;
880 uc_path = g_malloc(sizeof(WCHAR) * char_count);
881 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
882 &char_count) || !*uc_path) {
883 /* strange, but this condition could be faced even with size == 2 */
884 g_free(uc_path);
885 continue;
888 res = g_new0(GuestFilesystemTrimResult, 1);
890 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
892 g_free(uc_path);
894 if (!path) {
895 res->has_error = true;
896 res->error = g_strdup(gerr->message);
897 g_error_free(gerr);
898 break;
901 res->path = path;
903 list = g_new0(GuestFilesystemTrimResultList, 1);
904 list->value = res;
905 list->next = resp->paths;
907 resp->paths = list;
909 memset(argv, 0, sizeof(argv));
910 argv[0] = (gchar *)"defrag.exe";
911 argv[1] = (gchar *)"/L";
912 argv[2] = path;
914 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
915 &out /* stdout */, NULL /* stdin */,
916 NULL, &gerr)) {
917 res->has_error = true;
918 res->error = g_strdup(gerr->message);
919 g_error_free(gerr);
920 } else {
921 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
922 Error is reported in the output with something like
923 (x89000020) etc code in the stdout */
925 int i;
926 gchar **lines = g_strsplit(out, "\r\n", 0);
927 g_free(out);
929 for (i = 0; lines[i] != NULL; i++) {
930 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
931 continue;
933 res->has_error = true;
934 res->error = g_strdup(lines[i]);
935 break;
937 g_strfreev(lines);
939 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
941 FindVolumeClose(handle);
942 return resp;
945 typedef enum {
946 GUEST_SUSPEND_MODE_DISK,
947 GUEST_SUSPEND_MODE_RAM
948 } GuestSuspendMode;
950 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
952 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
953 Error *local_err = NULL;
955 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
956 if (!GetPwrCapabilities(&sys_pwr_caps)) {
957 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
958 "failed to determine guest suspend capabilities");
959 goto out;
962 switch (mode) {
963 case GUEST_SUSPEND_MODE_DISK:
964 if (!sys_pwr_caps.SystemS4) {
965 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
966 "suspend-to-disk not supported by OS");
968 break;
969 case GUEST_SUSPEND_MODE_RAM:
970 if (!sys_pwr_caps.SystemS3) {
971 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
972 "suspend-to-ram not supported by OS");
974 break;
975 default:
976 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
977 "GuestSuspendMode");
980 out:
981 error_propagate(errp, local_err);
984 static DWORD WINAPI do_suspend(LPVOID opaque)
986 GuestSuspendMode *mode = opaque;
987 DWORD ret = 0;
989 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
990 slog("failed to suspend guest, %lu", GetLastError());
991 ret = -1;
993 g_free(mode);
994 return ret;
997 void qmp_guest_suspend_disk(Error **errp)
999 Error *local_err = NULL;
1000 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1002 *mode = GUEST_SUSPEND_MODE_DISK;
1003 check_suspend_mode(*mode, &local_err);
1004 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1005 execute_async(do_suspend, mode, &local_err);
1007 if (local_err) {
1008 error_propagate(errp, local_err);
1009 g_free(mode);
1013 void qmp_guest_suspend_ram(Error **errp)
1015 Error *local_err = NULL;
1016 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1018 *mode = GUEST_SUSPEND_MODE_RAM;
1019 check_suspend_mode(*mode, &local_err);
1020 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1021 execute_async(do_suspend, mode, &local_err);
1023 if (local_err) {
1024 error_propagate(errp, local_err);
1025 g_free(mode);
1029 void qmp_guest_suspend_hybrid(Error **errp)
1031 error_setg(errp, QERR_UNSUPPORTED);
1034 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1036 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1037 ULONG adptr_addrs_len = 0;
1038 DWORD ret;
1040 /* Call the first time to get the adptr_addrs_len. */
1041 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1042 NULL, adptr_addrs, &adptr_addrs_len);
1044 adptr_addrs = g_malloc(adptr_addrs_len);
1045 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1046 NULL, adptr_addrs, &adptr_addrs_len);
1047 if (ret != ERROR_SUCCESS) {
1048 error_setg_win32(errp, ret, "failed to get adapters addresses");
1049 g_free(adptr_addrs);
1050 adptr_addrs = NULL;
1052 return adptr_addrs;
1055 static char *guest_wctomb_dup(WCHAR *wstr)
1057 char *str;
1058 size_t i;
1060 i = wcslen(wstr) + 1;
1061 str = g_malloc(i);
1062 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
1063 wstr, -1, str, i, NULL, NULL);
1064 return str;
1067 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1068 Error **errp)
1070 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1071 DWORD len;
1072 int ret;
1074 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1075 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1076 len = sizeof(addr_str);
1077 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1078 ip_addr->Address.iSockaddrLength,
1079 NULL,
1080 addr_str,
1081 &len);
1082 if (ret != 0) {
1083 error_setg_win32(errp, WSAGetLastError(),
1084 "failed address presentation form conversion");
1085 return NULL;
1087 return g_strdup(addr_str);
1089 return NULL;
1092 #if (_WIN32_WINNT >= 0x0600)
1093 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1095 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1096 * field to obtain the prefix.
1098 return ip_addr->OnLinkPrefixLength;
1100 #else
1101 /* When using the Windows XP and 2003 build environment, do the best we can to
1102 * figure out the prefix.
1104 static IP_ADAPTER_INFO *guest_get_adapters_info(void)
1106 IP_ADAPTER_INFO *adptr_info = NULL;
1107 ULONG adptr_info_len = 0;
1108 DWORD ret;
1110 /* Call the first time to get the adptr_info_len. */
1111 GetAdaptersInfo(adptr_info, &adptr_info_len);
1113 adptr_info = g_malloc(adptr_info_len);
1114 ret = GetAdaptersInfo(adptr_info, &adptr_info_len);
1115 if (ret != ERROR_SUCCESS) {
1116 g_free(adptr_info);
1117 adptr_info = NULL;
1119 return adptr_info;
1122 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1124 int64_t prefix = -1; /* Use for AF_INET6 and unknown/undetermined values. */
1125 IP_ADAPTER_INFO *adptr_info, *info;
1126 IP_ADDR_STRING *ip;
1127 struct in_addr *p;
1129 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
1130 return prefix;
1132 adptr_info = guest_get_adapters_info();
1133 if (adptr_info == NULL) {
1134 return prefix;
1137 /* Match up the passed in ip_addr with one found in adaptr_info.
1138 * The matching one in adptr_info will have the netmask.
1140 p = &((struct sockaddr_in *)ip_addr->Address.lpSockaddr)->sin_addr;
1141 for (info = adptr_info; info; info = info->Next) {
1142 for (ip = &info->IpAddressList; ip; ip = ip->Next) {
1143 if (p->S_un.S_addr == inet_addr(ip->IpAddress.String)) {
1144 prefix = ctpop32(inet_addr(ip->IpMask.String));
1145 goto out;
1149 out:
1150 g_free(adptr_info);
1151 return prefix;
1153 #endif
1155 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1157 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1158 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1159 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1160 GuestIpAddressList *head_addr, *cur_addr;
1161 GuestNetworkInterfaceList *info;
1162 GuestIpAddressList *address_item = NULL;
1163 unsigned char *mac_addr;
1164 char *addr_str;
1165 WORD wsa_version;
1166 WSADATA wsa_data;
1167 int ret;
1169 adptr_addrs = guest_get_adapters_addresses(errp);
1170 if (adptr_addrs == NULL) {
1171 return NULL;
1174 /* Make WSA APIs available. */
1175 wsa_version = MAKEWORD(2, 2);
1176 ret = WSAStartup(wsa_version, &wsa_data);
1177 if (ret != 0) {
1178 error_setg_win32(errp, ret, "failed socket startup");
1179 goto out;
1182 for (addr = adptr_addrs; addr; addr = addr->Next) {
1183 info = g_malloc0(sizeof(*info));
1185 if (cur_item == NULL) {
1186 head = cur_item = info;
1187 } else {
1188 cur_item->next = info;
1189 cur_item = info;
1192 info->value = g_malloc0(sizeof(*info->value));
1193 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1195 if (addr->PhysicalAddressLength != 0) {
1196 mac_addr = addr->PhysicalAddress;
1198 info->value->hardware_address =
1199 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1200 (int) mac_addr[0], (int) mac_addr[1],
1201 (int) mac_addr[2], (int) mac_addr[3],
1202 (int) mac_addr[4], (int) mac_addr[5]);
1204 info->value->has_hardware_address = true;
1207 head_addr = NULL;
1208 cur_addr = NULL;
1209 for (ip_addr = addr->FirstUnicastAddress;
1210 ip_addr;
1211 ip_addr = ip_addr->Next) {
1212 addr_str = guest_addr_to_str(ip_addr, errp);
1213 if (addr_str == NULL) {
1214 continue;
1217 address_item = g_malloc0(sizeof(*address_item));
1219 if (!cur_addr) {
1220 head_addr = cur_addr = address_item;
1221 } else {
1222 cur_addr->next = address_item;
1223 cur_addr = address_item;
1226 address_item->value = g_malloc0(sizeof(*address_item->value));
1227 address_item->value->ip_address = addr_str;
1228 address_item->value->prefix = guest_ip_prefix(ip_addr);
1229 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1230 address_item->value->ip_address_type =
1231 GUEST_IP_ADDRESS_TYPE_IPV4;
1232 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1233 address_item->value->ip_address_type =
1234 GUEST_IP_ADDRESS_TYPE_IPV6;
1237 if (head_addr) {
1238 info->value->has_ip_addresses = true;
1239 info->value->ip_addresses = head_addr;
1242 WSACleanup();
1243 out:
1244 g_free(adptr_addrs);
1245 return head;
1248 int64_t qmp_guest_get_time(Error **errp)
1250 SYSTEMTIME ts = {0};
1251 FILETIME tf;
1253 GetSystemTime(&ts);
1254 if (ts.wYear < 1601 || ts.wYear > 30827) {
1255 error_setg(errp, "Failed to get time");
1256 return -1;
1259 if (!SystemTimeToFileTime(&ts, &tf)) {
1260 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1261 return -1;
1264 return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1265 - W32_FT_OFFSET) * 100;
1268 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1270 Error *local_err = NULL;
1271 SYSTEMTIME ts;
1272 FILETIME tf;
1273 LONGLONG time;
1275 if (!has_time) {
1276 /* Unfortunately, Windows libraries don't provide an easy way to access
1277 * RTC yet:
1279 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1281 error_setg(errp, "Time argument is required on this platform");
1282 return;
1285 /* Validate time passed by user. */
1286 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1287 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1288 return;
1291 time = time_ns / 100 + W32_FT_OFFSET;
1293 tf.dwLowDateTime = (DWORD) time;
1294 tf.dwHighDateTime = (DWORD) (time >> 32);
1296 if (!FileTimeToSystemTime(&tf, &ts)) {
1297 error_setg(errp, "Failed to convert system time %d",
1298 (int)GetLastError());
1299 return;
1302 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1303 if (local_err) {
1304 error_propagate(errp, local_err);
1305 return;
1308 if (!SetSystemTime(&ts)) {
1309 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1310 return;
1314 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1316 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1317 DWORD length;
1318 GuestLogicalProcessorList *head, **link;
1319 Error *local_err = NULL;
1320 int64_t current;
1322 ptr = pslpi = NULL;
1323 length = 0;
1324 current = 0;
1325 head = NULL;
1326 link = &head;
1328 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1329 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1330 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1331 ptr = pslpi = g_malloc0(length);
1332 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1333 error_setg(&local_err, "Failed to get processor information: %d",
1334 (int)GetLastError());
1336 } else {
1337 error_setg(&local_err,
1338 "Failed to get processor information buffer length: %d",
1339 (int)GetLastError());
1342 while ((local_err == NULL) && (length > 0)) {
1343 if (pslpi->Relationship == RelationProcessorCore) {
1344 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1346 while (cpu_bits > 0) {
1347 if (!!(cpu_bits & 1)) {
1348 GuestLogicalProcessor *vcpu;
1349 GuestLogicalProcessorList *entry;
1351 vcpu = g_malloc0(sizeof *vcpu);
1352 vcpu->logical_id = current++;
1353 vcpu->online = true;
1354 vcpu->has_can_offline = true;
1356 entry = g_malloc0(sizeof *entry);
1357 entry->value = vcpu;
1359 *link = entry;
1360 link = &entry->next;
1362 cpu_bits >>= 1;
1365 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1366 pslpi++; /* next entry */
1369 g_free(ptr);
1371 if (local_err == NULL) {
1372 if (head != NULL) {
1373 return head;
1375 /* there's no guest with zero VCPUs */
1376 error_setg(&local_err, "Guest reported zero VCPUs");
1379 qapi_free_GuestLogicalProcessorList(head);
1380 error_propagate(errp, local_err);
1381 return NULL;
1384 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1386 error_setg(errp, QERR_UNSUPPORTED);
1387 return -1;
1390 static gchar *
1391 get_net_error_message(gint error)
1393 HMODULE module = NULL;
1394 gchar *retval = NULL;
1395 wchar_t *msg = NULL;
1396 int flags;
1397 size_t nchars;
1399 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1400 FORMAT_MESSAGE_IGNORE_INSERTS |
1401 FORMAT_MESSAGE_FROM_SYSTEM;
1403 if (error >= NERR_BASE && error <= MAX_NERR) {
1404 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1406 if (module != NULL) {
1407 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1411 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1413 if (msg != NULL) {
1414 nchars = wcslen(msg);
1416 if (nchars >= 2 &&
1417 msg[nchars - 1] == L'\n' &&
1418 msg[nchars - 2] == L'\r') {
1419 msg[nchars - 2] = L'\0';
1422 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1424 LocalFree(msg);
1427 if (module != NULL) {
1428 FreeLibrary(module);
1431 return retval;
1434 void qmp_guest_set_user_password(const char *username,
1435 const char *password,
1436 bool crypted,
1437 Error **errp)
1439 NET_API_STATUS nas;
1440 char *rawpasswddata = NULL;
1441 size_t rawpasswdlen;
1442 wchar_t *user = NULL, *wpass = NULL;
1443 USER_INFO_1003 pi1003 = { 0, };
1444 GError *gerr = NULL;
1446 if (crypted) {
1447 error_setg(errp, QERR_UNSUPPORTED);
1448 return;
1451 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1452 if (!rawpasswddata) {
1453 return;
1455 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1456 rawpasswddata[rawpasswdlen] = '\0';
1458 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1459 if (!user) {
1460 goto done;
1463 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1464 if (!wpass) {
1465 goto done;
1468 pi1003.usri1003_password = wpass;
1469 nas = NetUserSetInfo(NULL, user,
1470 1003, (LPBYTE)&pi1003,
1471 NULL);
1473 if (nas != NERR_Success) {
1474 gchar *msg = get_net_error_message(nas);
1475 error_setg(errp, "failed to set password: %s", msg);
1476 g_free(msg);
1479 done:
1480 if (gerr) {
1481 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1482 g_error_free(gerr);
1484 g_free(user);
1485 g_free(wpass);
1486 g_free(rawpasswddata);
1489 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1491 error_setg(errp, QERR_UNSUPPORTED);
1492 return NULL;
1495 GuestMemoryBlockResponseList *
1496 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1498 error_setg(errp, QERR_UNSUPPORTED);
1499 return NULL;
1502 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1504 error_setg(errp, QERR_UNSUPPORTED);
1505 return NULL;
1508 /* add unsupported commands to the blacklist */
1509 GList *ga_command_blacklist_init(GList *blacklist)
1511 const char *list_unsupported[] = {
1512 "guest-suspend-hybrid",
1513 "guest-set-vcpus",
1514 "guest-get-memory-blocks", "guest-set-memory-blocks",
1515 "guest-get-memory-block-size",
1516 "guest-fsfreeze-freeze-list",
1517 NULL};
1518 char **p = (char **)list_unsupported;
1520 while (*p) {
1521 blacklist = g_list_append(blacklist, g_strdup(*p++));
1524 if (!vss_init(true)) {
1525 g_debug("vss_init failed, vss commands are going to be disabled");
1526 const char *list[] = {
1527 "guest-get-fsinfo", "guest-fsfreeze-status",
1528 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1529 p = (char **)list;
1531 while (*p) {
1532 blacklist = g_list_append(blacklist, g_strdup(*p++));
1536 return blacklist;
1539 /* register init/cleanup routines for stateful command groups */
1540 void ga_command_state_init(GAState *s, GACommandState *cs)
1542 if (!vss_initialized()) {
1543 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1547 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1548 typedef struct _GA_WTSINFOA {
1549 WTS_CONNECTSTATE_CLASS State;
1550 DWORD SessionId;
1551 DWORD IncomingBytes;
1552 DWORD OutgoingBytes;
1553 DWORD IncomingFrames;
1554 DWORD OutgoingFrames;
1555 DWORD IncomingCompressedBytes;
1556 DWORD OutgoingCompressedBy;
1557 CHAR WinStationName[WINSTATIONNAME_LENGTH];
1558 CHAR Domain[DOMAIN_LENGTH];
1559 CHAR UserName[USERNAME_LENGTH + 1];
1560 LARGE_INTEGER ConnectTime;
1561 LARGE_INTEGER DisconnectTime;
1562 LARGE_INTEGER LastInputTime;
1563 LARGE_INTEGER LogonTime;
1564 LARGE_INTEGER CurrentTime;
1566 } GA_WTSINFOA;
1568 GuestUserList *qmp_guest_get_users(Error **err)
1570 #if (_WIN32_WINNT >= 0x0600)
1571 #define QGA_NANOSECONDS 10000000
1573 GHashTable *cache = NULL;
1574 GuestUserList *head = NULL, *cur_item = NULL;
1576 DWORD buffer_size = 0, count = 0, i = 0;
1577 GA_WTSINFOA *info = NULL;
1578 WTS_SESSION_INFOA *entries = NULL;
1579 GuestUserList *item = NULL;
1580 GuestUser *user = NULL;
1581 gpointer value = NULL;
1582 INT64 login = 0;
1583 double login_time = 0;
1585 cache = g_hash_table_new(g_str_hash, g_str_equal);
1587 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
1588 for (i = 0; i < count; ++i) {
1589 buffer_size = 0;
1590 info = NULL;
1591 if (WTSQuerySessionInformationA(
1592 NULL,
1593 entries[i].SessionId,
1594 WTSSessionInfo,
1595 (LPSTR *)&info,
1596 &buffer_size
1597 )) {
1599 if (strlen(info->UserName) == 0) {
1600 WTSFreeMemory(info);
1601 continue;
1604 login = info->LogonTime.QuadPart;
1605 login -= W32_FT_OFFSET;
1606 login_time = ((double)login) / QGA_NANOSECONDS;
1608 if (g_hash_table_contains(cache, info->UserName)) {
1609 value = g_hash_table_lookup(cache, info->UserName);
1610 user = (GuestUser *)value;
1611 if (user->login_time > login_time) {
1612 user->login_time = login_time;
1614 } else {
1615 item = g_new0(GuestUserList, 1);
1616 item->value = g_new0(GuestUser, 1);
1618 item->value->user = g_strdup(info->UserName);
1619 item->value->domain = g_strdup(info->Domain);
1620 item->value->has_domain = true;
1622 item->value->login_time = login_time;
1624 g_hash_table_add(cache, item->value->user);
1626 if (!cur_item) {
1627 head = cur_item = item;
1628 } else {
1629 cur_item->next = item;
1630 cur_item = item;
1634 WTSFreeMemory(info);
1636 WTSFreeMemory(entries);
1638 g_hash_table_destroy(cache);
1639 return head;
1640 #else
1641 error_setg(err, QERR_UNSUPPORTED);
1642 return NULL;
1643 #endif
1646 typedef struct _ga_matrix_lookup_t {
1647 int major;
1648 int minor;
1649 char const *version;
1650 char const *version_id;
1651 } ga_matrix_lookup_t;
1653 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
1655 /* Desktop editions */
1656 { 5, 0, "Microsoft Windows 2000", "2000"},
1657 { 5, 1, "Microsoft Windows XP", "xp"},
1658 { 6, 0, "Microsoft Windows Vista", "vista"},
1659 { 6, 1, "Microsoft Windows 7" "7"},
1660 { 6, 2, "Microsoft Windows 8", "8"},
1661 { 6, 3, "Microsoft Windows 8.1", "8.1"},
1662 {10, 0, "Microsoft Windows 10", "10"},
1663 { 0, 0, 0}
1665 /* Server editions */
1666 { 5, 2, "Microsoft Windows Server 2003", "2003"},
1667 { 6, 0, "Microsoft Windows Server 2008", "2008"},
1668 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
1669 { 6, 2, "Microsoft Windows Server 2012", "2012"},
1670 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
1671 {10, 0, "Microsoft Windows Server 2016", "2016"},
1672 { 0, 0, 0},
1673 { 0, 0, 0}
1677 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
1679 typedef NTSTATUS(WINAPI * rtl_get_version_t)(
1680 RTL_OSVERSIONINFOEXW *os_version_info_ex);
1682 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
1684 HMODULE module = GetModuleHandle("ntdll");
1685 PVOID fun = GetProcAddress(module, "RtlGetVersion");
1686 if (fun == NULL) {
1687 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1688 "Failed to get address of RtlGetVersion");
1689 return;
1692 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
1693 rtl_get_version(info);
1694 return;
1697 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
1699 DWORD major = os_version->dwMajorVersion;
1700 DWORD minor = os_version->dwMinorVersion;
1701 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
1702 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
1703 while (table->version != NULL) {
1704 if (major == table->major && minor == table->minor) {
1705 if (id) {
1706 return g_strdup(table->version_id);
1707 } else {
1708 return g_strdup(table->version);
1711 ++table;
1713 slog("failed to lookup Windows version: major=%lu, minor=%lu",
1714 major, minor);
1715 return g_strdup("N/A");
1718 static char *ga_get_win_product_name(Error **errp)
1720 HKEY key = NULL;
1721 DWORD size = 128;
1722 char *result = g_malloc0(size);
1723 LONG err = ERROR_SUCCESS;
1725 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
1726 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
1727 &key);
1728 if (err != ERROR_SUCCESS) {
1729 error_setg_win32(errp, err, "failed to open registry key");
1730 goto fail;
1733 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
1734 (LPBYTE)result, &size);
1735 if (err == ERROR_MORE_DATA) {
1736 slog("ProductName longer than expected (%lu bytes), retrying",
1737 size);
1738 g_free(result);
1739 result = NULL;
1740 if (size > 0) {
1741 result = g_malloc0(size);
1742 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
1743 (LPBYTE)result, &size);
1746 if (err != ERROR_SUCCESS) {
1747 error_setg_win32(errp, err, "failed to retrive ProductName");
1748 goto fail;
1751 return result;
1753 fail:
1754 g_free(result);
1755 return NULL;
1758 static char *ga_get_current_arch(void)
1760 SYSTEM_INFO info;
1761 GetNativeSystemInfo(&info);
1762 char *result = NULL;
1763 switch (info.wProcessorArchitecture) {
1764 case PROCESSOR_ARCHITECTURE_AMD64:
1765 result = g_strdup("x86_64");
1766 break;
1767 case PROCESSOR_ARCHITECTURE_ARM:
1768 result = g_strdup("arm");
1769 break;
1770 case PROCESSOR_ARCHITECTURE_IA64:
1771 result = g_strdup("ia64");
1772 break;
1773 case PROCESSOR_ARCHITECTURE_INTEL:
1774 result = g_strdup("x86");
1775 break;
1776 case PROCESSOR_ARCHITECTURE_UNKNOWN:
1777 default:
1778 slog("unknown processor architecture 0x%0x",
1779 info.wProcessorArchitecture);
1780 result = g_strdup("unknown");
1781 break;
1783 return result;
1786 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
1788 Error *local_err = NULL;
1789 OSVERSIONINFOEXW os_version = {0};
1790 bool server;
1791 char *product_name;
1792 GuestOSInfo *info;
1794 ga_get_win_version(&os_version, &local_err);
1795 if (local_err) {
1796 error_propagate(errp, local_err);
1797 return NULL;
1800 server = os_version.wProductType != VER_NT_WORKSTATION;
1801 product_name = ga_get_win_product_name(&local_err);
1802 if (product_name == NULL) {
1803 error_propagate(errp, local_err);
1804 return NULL;
1807 info = g_new0(GuestOSInfo, 1);
1809 info->has_kernel_version = true;
1810 info->kernel_version = g_strdup_printf("%lu.%lu",
1811 os_version.dwMajorVersion,
1812 os_version.dwMinorVersion);
1813 info->has_kernel_release = true;
1814 info->kernel_release = g_strdup_printf("%lu",
1815 os_version.dwBuildNumber);
1816 info->has_machine = true;
1817 info->machine = ga_get_current_arch();
1819 info->has_id = true;
1820 info->id = g_strdup("mswindows");
1821 info->has_name = true;
1822 info->name = g_strdup("Microsoft Windows");
1823 info->has_pretty_name = true;
1824 info->pretty_name = product_name;
1825 info->has_version = true;
1826 info->version = ga_get_win_name(&os_version, false);
1827 info->has_version_id = true;
1828 info->version_id = ga_get_win_name(&os_version, true);
1829 info->has_variant = true;
1830 info->variant = g_strdup(server ? "server" : "client");
1831 info->has_variant_id = true;
1832 info->variant_id = g_strdup(server ? "server" : "client");
1834 return info;