]> git.proxmox.com Git - mirror_qemu.git/blob - qga/commands-win32.c
gqa-win: get_pci_info: Add g_autofree for few variables
[mirror_qemu.git] / qga / commands-win32.c
1 /*
2 * QEMU Guest Agent win32-specific command implementations
3 *
4 * Copyright IBM Corp. 2012
5 *
6 * Authors:
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Gal Hammer <ghammer@redhat.com>
9 *
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.
12 */
13 #include "qemu/osdep.h"
14
15 #include <wtypes.h>
16 #include <powrprof.h>
17 #include <winsock2.h>
18 #include <ws2tcpip.h>
19 #include <iptypes.h>
20 #include <iphlpapi.h>
21 #ifdef CONFIG_QGA_NTDDSCSI
22 #include <winioctl.h>
23 #include <ntddscsi.h>
24 #endif
25 #include <setupapi.h>
26 #include <cfgmgr32.h>
27 #include <initguid.h>
28 #include <devpropdef.h>
29 #include <lm.h>
30 #include <wtsapi32.h>
31 #include <wininet.h>
32
33 #include "guest-agent-core.h"
34 #include "vss-win32.h"
35 #include "qga-qapi-commands.h"
36 #include "qapi/error.h"
37 #include "qapi/qmp/qerror.h"
38 #include "qemu/queue.h"
39 #include "qemu/host-utils.h"
40 #include "qemu/base64.h"
41 #include "commands-common.h"
42
43 /*
44 * The following should be in devpkey.h, but it isn't. The key names were
45 * prefixed to avoid (future) name clashes. Once the definitions get into
46 * mingw the following lines can be removed.
47 */
48 DEFINE_DEVPROPKEY(qga_DEVPKEY_NAME, 0xb725f130, 0x47ef, 0x101a, 0xa5,
49 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac, 10);
50 /* DEVPROP_TYPE_STRING */
51 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_HardwareIds, 0xa45c254e, 0xdf1c,
52 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 3);
53 /* DEVPROP_TYPE_STRING_LIST */
54 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverDate, 0xa8b865dd, 0x2e3d,
55 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 2);
56 /* DEVPROP_TYPE_FILETIME */
57 DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverVersion, 0xa8b865dd, 0x2e3d,
58 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 3);
59 /* DEVPROP_TYPE_STRING */
60 /* The CM_Get_DevNode_PropertyW prototype is only sometimes in cfgmgr32.h */
61 #ifndef CM_Get_DevNode_Property
62 #pragma GCC diagnostic push
63 #pragma GCC diagnostic ignored "-Wredundant-decls"
64 CMAPI CONFIGRET WINAPI CM_Get_DevNode_PropertyW(
65 DEVINST dnDevInst,
66 CONST DEVPROPKEY * PropertyKey,
67 DEVPROPTYPE * PropertyType,
68 PBYTE PropertyBuffer,
69 PULONG PropertyBufferSize,
70 ULONG ulFlags
71 );
72 #define CM_Get_DevNode_Property CM_Get_DevNode_PropertyW
73 #pragma GCC diagnostic pop
74 #endif
75
76 #ifndef SHTDN_REASON_FLAG_PLANNED
77 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
78 #endif
79
80 /* multiple of 100 nanoseconds elapsed between windows baseline
81 * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
82 #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
83 (365 * (1970 - 1601) + \
84 (1970 - 1601) / 4 - 3))
85
86 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
87
88 struct GuestFileHandle {
89 int64_t id;
90 HANDLE fh;
91 QTAILQ_ENTRY(GuestFileHandle) next;
92 };
93
94 static struct {
95 QTAILQ_HEAD(, GuestFileHandle) filehandles;
96 } guest_file_state = {
97 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
98 };
99
100 #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
101
102 typedef struct OpenFlags {
103 const char *forms;
104 DWORD desired_access;
105 DWORD creation_disposition;
106 } OpenFlags;
107 static OpenFlags guest_file_open_modes[] = {
108 {"r", GENERIC_READ, OPEN_EXISTING},
109 {"rb", GENERIC_READ, OPEN_EXISTING},
110 {"w", GENERIC_WRITE, CREATE_ALWAYS},
111 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
112 {"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
113 {"r+", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
114 {"rb+", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
115 {"r+b", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
116 {"w+", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
117 {"wb+", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
118 {"w+b", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
119 {"a+", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS },
120 {"ab+", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS },
121 {"a+b", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS }
122 };
123
124 #define debug_error(msg) do { \
125 char *suffix = g_win32_error_message(GetLastError()); \
126 g_debug("%s: %s", (msg), suffix); \
127 g_free(suffix); \
128 } while (0)
129
130 static OpenFlags *find_open_flag(const char *mode_str)
131 {
132 int mode;
133 Error **errp = NULL;
134
135 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
136 OpenFlags *flags = guest_file_open_modes + mode;
137
138 if (strcmp(flags->forms, mode_str) == 0) {
139 return flags;
140 }
141 }
142
143 error_setg(errp, "invalid file open mode '%s'", mode_str);
144 return NULL;
145 }
146
147 static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
148 {
149 GuestFileHandle *gfh;
150 int64_t handle;
151
152 handle = ga_get_fd_handle(ga_state, errp);
153 if (handle < 0) {
154 return -1;
155 }
156 gfh = g_new0(GuestFileHandle, 1);
157 gfh->id = handle;
158 gfh->fh = fh;
159 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
160
161 return handle;
162 }
163
164 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
165 {
166 GuestFileHandle *gfh;
167 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
168 if (gfh->id == id) {
169 return gfh;
170 }
171 }
172 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
173 return NULL;
174 }
175
176 static void handle_set_nonblocking(HANDLE fh)
177 {
178 DWORD file_type, pipe_state;
179 file_type = GetFileType(fh);
180 if (file_type != FILE_TYPE_PIPE) {
181 return;
182 }
183 /* If file_type == FILE_TYPE_PIPE, according to MSDN
184 * the specified file is socket or named pipe */
185 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
186 NULL, NULL, NULL, 0)) {
187 return;
188 }
189 /* The fd is named pipe fd */
190 if (pipe_state & PIPE_NOWAIT) {
191 return;
192 }
193
194 pipe_state |= PIPE_NOWAIT;
195 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
196 }
197
198 int64_t qmp_guest_file_open(const char *path, bool has_mode,
199 const char *mode, Error **errp)
200 {
201 int64_t fd = -1;
202 HANDLE fh;
203 HANDLE templ_file = NULL;
204 DWORD share_mode = FILE_SHARE_READ;
205 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
206 LPSECURITY_ATTRIBUTES sa_attr = NULL;
207 OpenFlags *guest_flags;
208 GError *gerr = NULL;
209 wchar_t *w_path = NULL;
210
211 if (!has_mode) {
212 mode = "r";
213 }
214 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
215 guest_flags = find_open_flag(mode);
216 if (guest_flags == NULL) {
217 error_setg(errp, "invalid file open mode");
218 goto done;
219 }
220
221 w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
222 if (!w_path) {
223 goto done;
224 }
225
226 fh = CreateFileW(w_path, guest_flags->desired_access, share_mode, sa_attr,
227 guest_flags->creation_disposition, flags_and_attr,
228 templ_file);
229 if (fh == INVALID_HANDLE_VALUE) {
230 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
231 path);
232 goto done;
233 }
234
235 /* set fd non-blocking to avoid common use cases (like reading from a
236 * named pipe) from hanging the agent
237 */
238 handle_set_nonblocking(fh);
239
240 fd = guest_file_handle_add(fh, errp);
241 if (fd < 0) {
242 CloseHandle(fh);
243 error_setg(errp, "failed to add handle to qmp handle table");
244 goto done;
245 }
246
247 slog("guest-file-open, handle: % " PRId64, fd);
248
249 done:
250 if (gerr) {
251 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
252 g_error_free(gerr);
253 }
254 g_free(w_path);
255 return fd;
256 }
257
258 void qmp_guest_file_close(int64_t handle, Error **errp)
259 {
260 bool ret;
261 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
262 slog("guest-file-close called, handle: %" PRId64, handle);
263 if (gfh == NULL) {
264 return;
265 }
266 ret = CloseHandle(gfh->fh);
267 if (!ret) {
268 error_setg_win32(errp, GetLastError(), "failed close handle");
269 return;
270 }
271
272 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
273 g_free(gfh);
274 }
275
276 static void acquire_privilege(const char *name, Error **errp)
277 {
278 HANDLE token = NULL;
279 TOKEN_PRIVILEGES priv;
280 Error *local_err = NULL;
281
282 if (OpenProcessToken(GetCurrentProcess(),
283 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token))
284 {
285 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
286 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
287 "no luid for requested privilege");
288 goto out;
289 }
290
291 priv.PrivilegeCount = 1;
292 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
293
294 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
295 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
296 "unable to acquire requested privilege");
297 goto out;
298 }
299
300 } else {
301 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
302 "failed to open privilege token");
303 }
304
305 out:
306 if (token) {
307 CloseHandle(token);
308 }
309 error_propagate(errp, local_err);
310 }
311
312 static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
313 Error **errp)
314 {
315 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
316 if (!thread) {
317 error_setg(errp, QERR_QGA_COMMAND_FAILED,
318 "failed to dispatch asynchronous command");
319 }
320 }
321
322 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
323 {
324 Error *local_err = NULL;
325 UINT shutdown_flag = EWX_FORCE;
326
327 slog("guest-shutdown called, mode: %s", mode);
328
329 if (!has_mode || strcmp(mode, "powerdown") == 0) {
330 shutdown_flag |= EWX_POWEROFF;
331 } else if (strcmp(mode, "halt") == 0) {
332 shutdown_flag |= EWX_SHUTDOWN;
333 } else if (strcmp(mode, "reboot") == 0) {
334 shutdown_flag |= EWX_REBOOT;
335 } else {
336 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
337 "'halt', 'powerdown', or 'reboot'");
338 return;
339 }
340
341 /* Request a shutdown privilege, but try to shut down the system
342 anyway. */
343 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
344 if (local_err) {
345 error_propagate(errp, local_err);
346 return;
347 }
348
349 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
350 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
351 slog("guest-shutdown failed: %s", emsg);
352 error_setg_win32(errp, GetLastError(), "guest-shutdown failed");
353 }
354 }
355
356 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
357 int64_t count, Error **errp)
358 {
359 GuestFileRead *read_data = NULL;
360 guchar *buf;
361 HANDLE fh = gfh->fh;
362 bool is_ok;
363 DWORD read_count;
364
365 buf = g_malloc0(count + 1);
366 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
367 if (!is_ok) {
368 error_setg_win32(errp, GetLastError(), "failed to read file");
369 } else {
370 buf[read_count] = 0;
371 read_data = g_new0(GuestFileRead, 1);
372 read_data->count = (size_t)read_count;
373 read_data->eof = read_count == 0;
374
375 if (read_count != 0) {
376 read_data->buf_b64 = g_base64_encode(buf, read_count);
377 }
378 }
379 g_free(buf);
380
381 return read_data;
382 }
383
384 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
385 bool has_count, int64_t count,
386 Error **errp)
387 {
388 GuestFileWrite *write_data = NULL;
389 guchar *buf;
390 gsize buf_len;
391 bool is_ok;
392 DWORD write_count;
393 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
394 HANDLE fh;
395
396 if (!gfh) {
397 return NULL;
398 }
399 fh = gfh->fh;
400 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
401 if (!buf) {
402 return NULL;
403 }
404
405 if (!has_count) {
406 count = buf_len;
407 } else if (count < 0 || count > buf_len) {
408 error_setg(errp, "value '%" PRId64
409 "' is invalid for argument count", count);
410 goto done;
411 }
412
413 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
414 if (!is_ok) {
415 error_setg_win32(errp, GetLastError(), "failed to write to file");
416 slog("guest-file-write-failed, handle: %" PRId64, handle);
417 } else {
418 write_data = g_new0(GuestFileWrite, 1);
419 write_data->count = (size_t) write_count;
420 }
421
422 done:
423 g_free(buf);
424 return write_data;
425 }
426
427 GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
428 GuestFileWhence *whence_code,
429 Error **errp)
430 {
431 GuestFileHandle *gfh;
432 GuestFileSeek *seek_data;
433 HANDLE fh;
434 LARGE_INTEGER new_pos, off_pos;
435 off_pos.QuadPart = offset;
436 BOOL res;
437 int whence;
438 Error *err = NULL;
439
440 gfh = guest_file_handle_find(handle, errp);
441 if (!gfh) {
442 return NULL;
443 }
444
445 /* We stupidly exposed 'whence':'int' in our qapi */
446 whence = ga_parse_whence(whence_code, &err);
447 if (err) {
448 error_propagate(errp, err);
449 return NULL;
450 }
451
452 fh = gfh->fh;
453 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
454 if (!res) {
455 error_setg_win32(errp, GetLastError(), "failed to seek file");
456 return NULL;
457 }
458 seek_data = g_new0(GuestFileSeek, 1);
459 seek_data->position = new_pos.QuadPart;
460 return seek_data;
461 }
462
463 void qmp_guest_file_flush(int64_t handle, Error **errp)
464 {
465 HANDLE fh;
466 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
467 if (!gfh) {
468 return;
469 }
470
471 fh = gfh->fh;
472 if (!FlushFileBuffers(fh)) {
473 error_setg_win32(errp, GetLastError(), "failed to flush file");
474 }
475 }
476
477 #ifdef CONFIG_QGA_NTDDSCSI
478
479 static GuestDiskBusType win2qemu[] = {
480 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
481 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
482 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
483 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
484 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
485 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
486 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
487 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
488 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
489 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
490 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
491 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
492 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
493 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
494 #if (_WIN32_WINNT >= 0x0601)
495 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
496 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
497 #endif
498 };
499
500 static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
501 {
502 if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
503 return GUEST_DISK_BUS_TYPE_UNKNOWN;
504 }
505 return win2qemu[(int)bus];
506 }
507
508 DEFINE_GUID(GUID_DEVINTERFACE_DISK,
509 0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2,
510 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
511 DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT,
512 0x2accfe60L, 0xc130, 0x11d2, 0xb0, 0x82,
513 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
514
515 static void get_pci_address_for_device(GuestPCIAddress *pci,
516 HDEVINFO dev_info)
517 {
518 SP_DEVINFO_DATA dev_info_data;
519 DWORD j;
520 DWORD size;
521 bool partial_pci = false;
522
523 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
524
525 for (j = 0;
526 SetupDiEnumDeviceInfo(dev_info, j, &dev_info_data);
527 j++) {
528 DWORD addr, bus, ui_slot, type;
529 int func, slot;
530 size = sizeof(DWORD);
531
532 /*
533 * There is no need to allocate buffer in the next functions. The
534 * size is known and ULONG according to
535 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
536 */
537 if (!SetupDiGetDeviceRegistryProperty(
538 dev_info, &dev_info_data, SPDRP_BUSNUMBER,
539 &type, (PBYTE)&bus, size, NULL)) {
540 debug_error("failed to get PCI bus");
541 bus = -1;
542 partial_pci = true;
543 }
544
545 /*
546 * The function retrieves the device's address. This value will be
547 * transformed into device function and number
548 */
549 if (!SetupDiGetDeviceRegistryProperty(
550 dev_info, &dev_info_data, SPDRP_ADDRESS,
551 &type, (PBYTE)&addr, size, NULL)) {
552 debug_error("failed to get PCI address");
553 addr = -1;
554 partial_pci = true;
555 }
556
557 /*
558 * This call returns UINumber of DEVICE_CAPABILITIES structure.
559 * This number is typically a user-perceived slot number.
560 */
561 if (!SetupDiGetDeviceRegistryProperty(
562 dev_info, &dev_info_data, SPDRP_UI_NUMBER,
563 &type, (PBYTE)&ui_slot, size, NULL)) {
564 debug_error("failed to get PCI slot");
565 ui_slot = -1;
566 partial_pci = true;
567 }
568
569 /*
570 * SetupApi gives us the same information as driver with
571 * IoGetDeviceProperty. According to Microsoft:
572 *
573 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
574 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
575 * SPDRP_ADDRESS is propertyAddress, so we do the same.
576 *
577 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
578 */
579 if (partial_pci) {
580 pci->domain = -1;
581 pci->slot = -1;
582 pci->function = -1;
583 pci->bus = -1;
584 continue;
585 } else {
586 func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
587 slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
588 if ((int)ui_slot != slot) {
589 g_debug("mismatch with reported slot values: %d vs %d",
590 (int)ui_slot, slot);
591 }
592 pci->domain = 0;
593 pci->slot = (int)ui_slot;
594 pci->function = func;
595 pci->bus = (int)bus;
596 return;
597 }
598 }
599 }
600
601 static GuestPCIAddress *get_pci_info(int number, Error **errp)
602 {
603 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
604 HDEVINFO parent_dev_info = INVALID_HANDLE_VALUE;
605
606 SP_DEVINFO_DATA dev_info_data;
607 SP_DEVICE_INTERFACE_DATA dev_iface_data;
608 HANDLE dev_file;
609 int i;
610 GuestPCIAddress *pci = NULL;
611
612 pci = g_malloc0(sizeof(*pci));
613 pci->domain = -1;
614 pci->slot = -1;
615 pci->function = -1;
616 pci->bus = -1;
617
618 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
619 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
620 if (dev_info == INVALID_HANDLE_VALUE) {
621 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
622 goto end;
623 }
624
625 g_debug("enumerating devices");
626 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
627 dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
628 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
629 g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
630 STORAGE_DEVICE_NUMBER sdn;
631 g_autofree char *parent_dev_id = NULL;
632 SP_DEVINFO_DATA parent_dev_info_data;
633 DWORD size = 0;
634
635 g_debug("getting device path");
636 if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
637 &GUID_DEVINTERFACE_DISK, 0,
638 &dev_iface_data)) {
639 while (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
640 pdev_iface_detail_data,
641 size, &size,
642 &dev_info_data)) {
643 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
644 pdev_iface_detail_data = g_malloc(size);
645 pdev_iface_detail_data->cbSize =
646 sizeof(*pdev_iface_detail_data);
647 } else {
648 error_setg_win32(errp, GetLastError(),
649 "failed to get device interfaces");
650 goto end;
651 }
652 }
653
654 dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
655 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
656 NULL);
657
658 if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
659 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
660 CloseHandle(dev_file);
661 error_setg_win32(errp, GetLastError(),
662 "failed to get device slot number");
663 goto end;
664 }
665
666 CloseHandle(dev_file);
667 if (sdn.DeviceNumber != number) {
668 continue;
669 }
670 } else {
671 error_setg_win32(errp, GetLastError(),
672 "failed to get device interfaces");
673 goto end;
674 }
675
676 g_debug("found device slot %d. Getting storage controller", number);
677 {
678 CONFIGRET cr;
679 DEVINST dev_inst, parent_dev_inst;
680 ULONG dev_id_size = 0;
681
682 size = 0;
683 while (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
684 parent_dev_id, size, &size)) {
685 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
686 parent_dev_id = g_malloc(size);
687 } else {
688 error_setg_win32(errp, GetLastError(),
689 "failed to get device instance ID");
690 goto end;
691 }
692 }
693
694 /*
695 * CM API used here as opposed to
696 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
697 * which exports are only available in mingw-w64 6+
698 */
699 cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
700 if (cr != CR_SUCCESS) {
701 g_error("CM_Locate_DevInst failed with code %lx", cr);
702 error_setg_win32(errp, GetLastError(),
703 "failed to get device instance");
704 goto end;
705 }
706 cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
707 if (cr != CR_SUCCESS) {
708 g_error("CM_Get_Parent failed with code %lx", cr);
709 error_setg_win32(errp, GetLastError(),
710 "failed to get parent device instance");
711 goto end;
712 }
713
714 cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
715 if (cr != CR_SUCCESS) {
716 g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
717 error_setg_win32(errp, GetLastError(),
718 "failed to get parent device ID length");
719 goto end;
720 }
721
722 ++dev_id_size;
723 if (dev_id_size > size) {
724 g_free(parent_dev_id);
725 parent_dev_id = g_malloc(dev_id_size);
726 }
727
728 cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
729 0);
730 if (cr != CR_SUCCESS) {
731 g_error("CM_Get_Device_ID failed with code %lx", cr);
732 error_setg_win32(errp, GetLastError(),
733 "failed to get parent device ID");
734 goto end;
735 }
736 }
737
738 g_debug("querying storage controller %s for PCI information",
739 parent_dev_id);
740 parent_dev_info =
741 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
742 NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
743
744 if (parent_dev_info == INVALID_HANDLE_VALUE) {
745 error_setg_win32(errp, GetLastError(),
746 "failed to get parent device");
747 goto end;
748 }
749
750 parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
751 if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
752 error_setg_win32(errp, GetLastError(),
753 "failed to get parent device data");
754 goto end;
755 }
756
757 get_pci_address_for_device(pci, parent_dev_info);
758
759 break;
760 }
761
762 end:
763 if (parent_dev_info != INVALID_HANDLE_VALUE) {
764 SetupDiDestroyDeviceInfoList(parent_dev_info);
765 }
766 if (dev_info != INVALID_HANDLE_VALUE) {
767 SetupDiDestroyDeviceInfoList(dev_info);
768 }
769 return pci;
770 }
771
772 static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
773 Error **errp)
774 {
775 STORAGE_PROPERTY_QUERY query;
776 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
777 DWORD received;
778 ULONG size = sizeof(buf);
779
780 dev_desc = &buf;
781 query.PropertyId = StorageDeviceProperty;
782 query.QueryType = PropertyStandardQuery;
783
784 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
785 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
786 size, &received, NULL)) {
787 error_setg_win32(errp, GetLastError(), "failed to get bus type");
788 return;
789 }
790 disk->bus_type = find_bus_type(dev_desc->BusType);
791 g_debug("bus type %d", disk->bus_type);
792
793 /* Query once more. Now with long enough buffer. */
794 size = dev_desc->Size;
795 dev_desc = g_malloc0(size);
796 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
797 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
798 size, &received, NULL)) {
799 error_setg_win32(errp, GetLastError(), "failed to get serial number");
800 g_debug("failed to get serial number");
801 goto out_free;
802 }
803 if (dev_desc->SerialNumberOffset > 0) {
804 const char *serial;
805 size_t len;
806
807 if (dev_desc->SerialNumberOffset >= received) {
808 error_setg(errp, "failed to get serial number: offset outside the buffer");
809 g_debug("serial number offset outside the buffer");
810 goto out_free;
811 }
812 serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
813 len = received - dev_desc->SerialNumberOffset;
814 g_debug("serial number \"%s\"", serial);
815 if (*serial != 0) {
816 disk->serial = g_strndup(serial, len);
817 disk->has_serial = true;
818 }
819 }
820 out_free:
821 g_free(dev_desc);
822
823 return;
824 }
825
826 static void get_single_disk_info(int disk_number,
827 GuestDiskAddress *disk, Error **errp)
828 {
829 SCSI_ADDRESS addr, *scsi_ad;
830 DWORD len;
831 HANDLE disk_h;
832 Error *local_err = NULL;
833
834 scsi_ad = &addr;
835
836 g_debug("getting disk info for: %s", disk->dev);
837 disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
838 0, NULL);
839 if (disk_h == INVALID_HANDLE_VALUE) {
840 error_setg_win32(errp, GetLastError(), "failed to open disk");
841 return;
842 }
843
844 get_disk_properties(disk_h, disk, &local_err);
845 if (local_err) {
846 error_propagate(errp, local_err);
847 goto err_close;
848 }
849
850 g_debug("bus type %d", disk->bus_type);
851 /* always set pci_controller as required by schema. get_pci_info() should
852 * report -1 values for non-PCI buses rather than fail. fail the command
853 * if that doesn't hold since that suggests some other unexpected
854 * breakage
855 */
856 disk->pci_controller = get_pci_info(disk_number, &local_err);
857 if (local_err) {
858 error_propagate(errp, local_err);
859 goto err_close;
860 }
861 if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
862 || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
863 || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
864 /* This bus type is not supported before Windows Server 2003 SP1 */
865 || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
866 ) {
867 /* We are able to use the same ioctls for different bus types
868 * according to Microsoft docs
869 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
870 g_debug("getting SCSI info");
871 if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
872 sizeof(SCSI_ADDRESS), &len, NULL)) {
873 disk->unit = addr.Lun;
874 disk->target = addr.TargetId;
875 disk->bus = addr.PathId;
876 }
877 /* We do not set error in this case, because we still have enough
878 * information about volume. */
879 }
880
881 err_close:
882 CloseHandle(disk_h);
883 return;
884 }
885
886 /* VSS provider works with volumes, thus there is no difference if
887 * the volume consist of spanned disks. Info about the first disk in the
888 * volume is returned for the spanned disk group (LVM) */
889 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
890 {
891 Error *local_err = NULL;
892 GuestDiskAddressList *list = NULL;
893 GuestDiskAddress *disk = NULL;
894 int i;
895 HANDLE vol_h;
896 DWORD size;
897 PVOLUME_DISK_EXTENTS extents = NULL;
898
899 /* strip final backslash */
900 char *name = g_strdup(guid);
901 if (g_str_has_suffix(name, "\\")) {
902 name[strlen(name) - 1] = 0;
903 }
904
905 g_debug("opening %s", name);
906 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
907 0, NULL);
908 if (vol_h == INVALID_HANDLE_VALUE) {
909 error_setg_win32(errp, GetLastError(), "failed to open volume");
910 goto out;
911 }
912
913 /* Get list of extents */
914 g_debug("getting disk extents");
915 size = sizeof(VOLUME_DISK_EXTENTS);
916 extents = g_malloc0(size);
917 if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
918 0, extents, size, &size, NULL)) {
919 DWORD last_err = GetLastError();
920 if (last_err == ERROR_MORE_DATA) {
921 /* Try once more with big enough buffer */
922 g_free(extents);
923 extents = g_malloc0(size);
924 if (!DeviceIoControl(
925 vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
926 0, extents, size, NULL, NULL)) {
927 error_setg_win32(errp, GetLastError(),
928 "failed to get disk extents");
929 goto out;
930 }
931 } else if (last_err == ERROR_INVALID_FUNCTION) {
932 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
933 g_debug("volume not on disk");
934 disk = g_malloc0(sizeof(GuestDiskAddress));
935 disk->has_dev = true;
936 disk->dev = g_strdup(name);
937 get_single_disk_info(0xffffffff, disk, &local_err);
938 if (local_err) {
939 g_debug("failed to get disk info, ignoring error: %s",
940 error_get_pretty(local_err));
941 error_free(local_err);
942 goto out;
943 }
944 QAPI_LIST_PREPEND(list, disk);
945 disk = NULL;
946 goto out;
947 } else {
948 error_setg_win32(errp, GetLastError(),
949 "failed to get disk extents");
950 goto out;
951 }
952 }
953 g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
954
955 /* Go through each extent */
956 for (i = 0; i < extents->NumberOfDiskExtents; i++) {
957 disk = g_malloc0(sizeof(GuestDiskAddress));
958
959 /* Disk numbers directly correspond to numbers used in UNCs
960 *
961 * See documentation for DISK_EXTENT:
962 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
963 *
964 * See also Naming Files, Paths and Namespaces:
965 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
966 */
967 disk->has_dev = true;
968 disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
969 extents->Extents[i].DiskNumber);
970
971 get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
972 if (local_err) {
973 error_propagate(errp, local_err);
974 goto out;
975 }
976 QAPI_LIST_PREPEND(list, disk);
977 disk = NULL;
978 }
979
980
981 out:
982 if (vol_h != INVALID_HANDLE_VALUE) {
983 CloseHandle(vol_h);
984 }
985 qapi_free_GuestDiskAddress(disk);
986 g_free(extents);
987 g_free(name);
988
989 return list;
990 }
991
992 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
993 {
994 GuestDiskInfoList *ret = NULL;
995 HDEVINFO dev_info;
996 SP_DEVICE_INTERFACE_DATA dev_iface_data;
997 int i;
998
999 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
1000 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
1001 if (dev_info == INVALID_HANDLE_VALUE) {
1002 error_setg_win32(errp, GetLastError(), "failed to get device tree");
1003 return NULL;
1004 }
1005
1006 g_debug("enumerating devices");
1007 dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
1008 for (i = 0;
1009 SetupDiEnumDeviceInterfaces(dev_info, NULL, &GUID_DEVINTERFACE_DISK,
1010 i, &dev_iface_data);
1011 i++) {
1012 GuestDiskAddress *address = NULL;
1013 GuestDiskInfo *disk = NULL;
1014 Error *local_err = NULL;
1015 g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA
1016 pdev_iface_detail_data = NULL;
1017 STORAGE_DEVICE_NUMBER sdn;
1018 HANDLE dev_file;
1019 DWORD size = 0;
1020 BOOL result;
1021 int attempt;
1022
1023 g_debug(" getting device path");
1024 for (attempt = 0, result = FALSE; attempt < 2 && !result; attempt++) {
1025 result = SetupDiGetDeviceInterfaceDetail(dev_info,
1026 &dev_iface_data, pdev_iface_detail_data, size, &size, NULL);
1027 if (result) {
1028 break;
1029 }
1030 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1031 pdev_iface_detail_data = g_realloc(pdev_iface_detail_data,
1032 size);
1033 pdev_iface_detail_data->cbSize =
1034 sizeof(*pdev_iface_detail_data);
1035 } else {
1036 g_debug("failed to get device interface details");
1037 break;
1038 }
1039 }
1040 if (!result) {
1041 g_debug("skipping device");
1042 continue;
1043 }
1044
1045 g_debug(" device: %s", pdev_iface_detail_data->DevicePath);
1046 dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
1047 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
1048 if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
1049 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
1050 CloseHandle(dev_file);
1051 debug_error("failed to get storage device number");
1052 continue;
1053 }
1054 CloseHandle(dev_file);
1055
1056 disk = g_new0(GuestDiskInfo, 1);
1057 disk->name = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
1058 sdn.DeviceNumber);
1059
1060 g_debug(" number: %lu", sdn.DeviceNumber);
1061 address = g_malloc0(sizeof(GuestDiskAddress));
1062 address->has_dev = true;
1063 address->dev = g_strdup(disk->name);
1064 get_single_disk_info(sdn.DeviceNumber, address, &local_err);
1065 if (local_err) {
1066 g_debug("failed to get disk info: %s",
1067 error_get_pretty(local_err));
1068 error_free(local_err);
1069 qapi_free_GuestDiskAddress(address);
1070 address = NULL;
1071 } else {
1072 disk->address = address;
1073 disk->has_address = true;
1074 }
1075
1076 QAPI_LIST_PREPEND(ret, disk);
1077 }
1078
1079 SetupDiDestroyDeviceInfoList(dev_info);
1080 return ret;
1081 }
1082
1083 #else
1084
1085 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
1086 {
1087 return NULL;
1088 }
1089
1090 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1091 {
1092 error_setg(errp, QERR_UNSUPPORTED);
1093 return NULL;
1094 }
1095
1096 #endif /* CONFIG_QGA_NTDDSCSI */
1097
1098 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
1099 {
1100 DWORD info_size;
1101 char mnt, *mnt_point;
1102 wchar_t wfs_name[32];
1103 char fs_name[32];
1104 wchar_t vol_info[MAX_PATH + 1];
1105 size_t len;
1106 uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
1107 GuestFilesystemInfo *fs = NULL;
1108 HANDLE hLocalDiskHandle = INVALID_HANDLE_VALUE;
1109
1110 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
1111 if (GetLastError() != ERROR_MORE_DATA) {
1112 error_setg_win32(errp, GetLastError(), "failed to get volume name");
1113 return NULL;
1114 }
1115
1116 mnt_point = g_malloc(info_size + 1);
1117 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
1118 &info_size)) {
1119 error_setg_win32(errp, GetLastError(), "failed to get volume name");
1120 goto free;
1121 }
1122
1123 hLocalDiskHandle = CreateFile(guid, 0 , 0, NULL, OPEN_EXISTING,
1124 FILE_ATTRIBUTE_NORMAL |
1125 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1126 if (INVALID_HANDLE_VALUE == hLocalDiskHandle) {
1127 error_setg_win32(errp, GetLastError(), "failed to get handle for volume");
1128 goto free;
1129 }
1130
1131 len = strlen(mnt_point);
1132 mnt_point[len] = '\\';
1133 mnt_point[len + 1] = 0;
1134
1135 if (!GetVolumeInformationByHandleW(hLocalDiskHandle, vol_info,
1136 sizeof(vol_info), NULL, NULL, NULL,
1137 (LPWSTR) & wfs_name, sizeof(wfs_name))) {
1138 if (GetLastError() != ERROR_NOT_READY) {
1139 error_setg_win32(errp, GetLastError(), "failed to get volume info");
1140 }
1141 goto free;
1142 }
1143
1144 fs = g_malloc(sizeof(*fs));
1145 fs->name = g_strdup(guid);
1146 fs->has_total_bytes = false;
1147 fs->has_used_bytes = false;
1148 if (len == 0) {
1149 fs->mountpoint = g_strdup("System Reserved");
1150 } else {
1151 fs->mountpoint = g_strndup(mnt_point, len);
1152 if (GetDiskFreeSpaceEx(fs->mountpoint,
1153 (PULARGE_INTEGER) & i64FreeBytesToCaller,
1154 (PULARGE_INTEGER) & i64TotalBytes,
1155 (PULARGE_INTEGER) & i64FreeBytes)) {
1156 fs->used_bytes = i64TotalBytes - i64FreeBytes;
1157 fs->total_bytes = i64TotalBytes;
1158 fs->has_total_bytes = true;
1159 fs->has_used_bytes = true;
1160 }
1161 }
1162 wcstombs(fs_name, wfs_name, sizeof(wfs_name));
1163 fs->type = g_strdup(fs_name);
1164 fs->disk = build_guest_disk_info(guid, errp);
1165 free:
1166 if (hLocalDiskHandle != INVALID_HANDLE_VALUE) {
1167 CloseHandle(hLocalDiskHandle);
1168 }
1169 g_free(mnt_point);
1170 return fs;
1171 }
1172
1173 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1174 {
1175 HANDLE vol_h;
1176 GuestFilesystemInfoList *ret = NULL;
1177 char guid[256];
1178
1179 vol_h = FindFirstVolume(guid, sizeof(guid));
1180 if (vol_h == INVALID_HANDLE_VALUE) {
1181 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1182 return NULL;
1183 }
1184
1185 do {
1186 Error *local_err = NULL;
1187 GuestFilesystemInfo *info = build_guest_fsinfo(guid, &local_err);
1188 if (local_err) {
1189 g_debug("failed to get filesystem info, ignoring error: %s",
1190 error_get_pretty(local_err));
1191 error_free(local_err);
1192 continue;
1193 }
1194 QAPI_LIST_PREPEND(ret, info);
1195 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
1196
1197 if (GetLastError() != ERROR_NO_MORE_FILES) {
1198 error_setg_win32(errp, GetLastError(), "failed to find next volume");
1199 }
1200
1201 FindVolumeClose(vol_h);
1202 return ret;
1203 }
1204
1205 /*
1206 * Return status of freeze/thaw
1207 */
1208 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1209 {
1210 if (!vss_initialized()) {
1211 error_setg(errp, QERR_UNSUPPORTED);
1212 return 0;
1213 }
1214
1215 if (ga_is_frozen(ga_state)) {
1216 return GUEST_FSFREEZE_STATUS_FROZEN;
1217 }
1218
1219 return GUEST_FSFREEZE_STATUS_THAWED;
1220 }
1221
1222 /*
1223 * Freeze local file systems using Volume Shadow-copy Service.
1224 * The frozen state is limited for up to 10 seconds by VSS.
1225 */
1226 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1227 {
1228 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1229 }
1230
1231 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1232 strList *mountpoints,
1233 Error **errp)
1234 {
1235 int i;
1236 Error *local_err = NULL;
1237
1238 if (!vss_initialized()) {
1239 error_setg(errp, QERR_UNSUPPORTED);
1240 return 0;
1241 }
1242
1243 slog("guest-fsfreeze called");
1244
1245 /* cannot risk guest agent blocking itself on a write in this state */
1246 ga_set_frozen(ga_state);
1247
1248 qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
1249 if (local_err) {
1250 error_propagate(errp, local_err);
1251 goto error;
1252 }
1253
1254 return i;
1255
1256 error:
1257 local_err = NULL;
1258 qmp_guest_fsfreeze_thaw(&local_err);
1259 if (local_err) {
1260 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
1261 error_free(local_err);
1262 }
1263 return 0;
1264 }
1265
1266 /*
1267 * Thaw local file systems using Volume Shadow-copy Service.
1268 */
1269 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1270 {
1271 int i;
1272
1273 if (!vss_initialized()) {
1274 error_setg(errp, QERR_UNSUPPORTED);
1275 return 0;
1276 }
1277
1278 qga_vss_fsfreeze(&i, false, NULL, errp);
1279
1280 ga_unset_frozen(ga_state);
1281 return i;
1282 }
1283
1284 static void guest_fsfreeze_cleanup(void)
1285 {
1286 Error *err = NULL;
1287
1288 if (!vss_initialized()) {
1289 return;
1290 }
1291
1292 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1293 qmp_guest_fsfreeze_thaw(&err);
1294 if (err) {
1295 slog("failed to clean up frozen filesystems: %s",
1296 error_get_pretty(err));
1297 error_free(err);
1298 }
1299 }
1300
1301 vss_deinit(true);
1302 }
1303
1304 /*
1305 * Walk list of mounted file systems in the guest, and discard unused
1306 * areas.
1307 */
1308 GuestFilesystemTrimResponse *
1309 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1310 {
1311 GuestFilesystemTrimResponse *resp;
1312 HANDLE handle;
1313 WCHAR guid[MAX_PATH] = L"";
1314 OSVERSIONINFO osvi;
1315 BOOL win8_or_later;
1316
1317 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
1318 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1319 GetVersionEx(&osvi);
1320 win8_or_later = (osvi.dwMajorVersion > 6 ||
1321 ((osvi.dwMajorVersion == 6) &&
1322 (osvi.dwMinorVersion >= 2)));
1323 if (!win8_or_later) {
1324 error_setg(errp, "fstrim is only supported for Win8+");
1325 return NULL;
1326 }
1327
1328 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
1329 if (handle == INVALID_HANDLE_VALUE) {
1330 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1331 return NULL;
1332 }
1333
1334 resp = g_new0(GuestFilesystemTrimResponse, 1);
1335
1336 do {
1337 GuestFilesystemTrimResult *res;
1338 PWCHAR uc_path;
1339 DWORD char_count = 0;
1340 char *path, *out;
1341 GError *gerr = NULL;
1342 gchar *argv[4];
1343
1344 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1345
1346 if (GetLastError() != ERROR_MORE_DATA) {
1347 continue;
1348 }
1349 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1350 continue;
1351 }
1352
1353 uc_path = g_malloc(sizeof(WCHAR) * char_count);
1354 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1355 &char_count) || !*uc_path) {
1356 /* strange, but this condition could be faced even with size == 2 */
1357 g_free(uc_path);
1358 continue;
1359 }
1360
1361 res = g_new0(GuestFilesystemTrimResult, 1);
1362
1363 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1364
1365 g_free(uc_path);
1366
1367 if (!path) {
1368 res->has_error = true;
1369 res->error = g_strdup(gerr->message);
1370 g_error_free(gerr);
1371 break;
1372 }
1373
1374 res->path = path;
1375
1376 QAPI_LIST_PREPEND(resp->paths, res);
1377
1378 memset(argv, 0, sizeof(argv));
1379 argv[0] = (gchar *)"defrag.exe";
1380 argv[1] = (gchar *)"/L";
1381 argv[2] = path;
1382
1383 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1384 &out /* stdout */, NULL /* stdin */,
1385 NULL, &gerr)) {
1386 res->has_error = true;
1387 res->error = g_strdup(gerr->message);
1388 g_error_free(gerr);
1389 } else {
1390 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1391 Error is reported in the output with something like
1392 (x89000020) etc code in the stdout */
1393
1394 int i;
1395 gchar **lines = g_strsplit(out, "\r\n", 0);
1396 g_free(out);
1397
1398 for (i = 0; lines[i] != NULL; i++) {
1399 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1400 continue;
1401 }
1402 res->has_error = true;
1403 res->error = g_strdup(lines[i]);
1404 break;
1405 }
1406 g_strfreev(lines);
1407 }
1408 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1409
1410 FindVolumeClose(handle);
1411 return resp;
1412 }
1413
1414 typedef enum {
1415 GUEST_SUSPEND_MODE_DISK,
1416 GUEST_SUSPEND_MODE_RAM
1417 } GuestSuspendMode;
1418
1419 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
1420 {
1421 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1422
1423 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1424 if (!GetPwrCapabilities(&sys_pwr_caps)) {
1425 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1426 "failed to determine guest suspend capabilities");
1427 return;
1428 }
1429
1430 switch (mode) {
1431 case GUEST_SUSPEND_MODE_DISK:
1432 if (!sys_pwr_caps.SystemS4) {
1433 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1434 "suspend-to-disk not supported by OS");
1435 }
1436 break;
1437 case GUEST_SUSPEND_MODE_RAM:
1438 if (!sys_pwr_caps.SystemS3) {
1439 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1440 "suspend-to-ram not supported by OS");
1441 }
1442 break;
1443 default:
1444 abort();
1445 }
1446 }
1447
1448 static DWORD WINAPI do_suspend(LPVOID opaque)
1449 {
1450 GuestSuspendMode *mode = opaque;
1451 DWORD ret = 0;
1452
1453 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1454 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
1455 slog("failed to suspend guest: %s", emsg);
1456 ret = -1;
1457 }
1458 g_free(mode);
1459 return ret;
1460 }
1461
1462 void qmp_guest_suspend_disk(Error **errp)
1463 {
1464 Error *local_err = NULL;
1465 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1466
1467 *mode = GUEST_SUSPEND_MODE_DISK;
1468 check_suspend_mode(*mode, &local_err);
1469 if (local_err) {
1470 goto out;
1471 }
1472 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1473 if (local_err) {
1474 goto out;
1475 }
1476 execute_async(do_suspend, mode, &local_err);
1477
1478 out:
1479 if (local_err) {
1480 error_propagate(errp, local_err);
1481 g_free(mode);
1482 }
1483 }
1484
1485 void qmp_guest_suspend_ram(Error **errp)
1486 {
1487 Error *local_err = NULL;
1488 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1489
1490 *mode = GUEST_SUSPEND_MODE_RAM;
1491 check_suspend_mode(*mode, &local_err);
1492 if (local_err) {
1493 goto out;
1494 }
1495 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1496 if (local_err) {
1497 goto out;
1498 }
1499 execute_async(do_suspend, mode, &local_err);
1500
1501 out:
1502 if (local_err) {
1503 error_propagate(errp, local_err);
1504 g_free(mode);
1505 }
1506 }
1507
1508 void qmp_guest_suspend_hybrid(Error **errp)
1509 {
1510 error_setg(errp, QERR_UNSUPPORTED);
1511 }
1512
1513 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1514 {
1515 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1516 ULONG adptr_addrs_len = 0;
1517 DWORD ret;
1518
1519 /* Call the first time to get the adptr_addrs_len. */
1520 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1521 NULL, adptr_addrs, &adptr_addrs_len);
1522
1523 adptr_addrs = g_malloc(adptr_addrs_len);
1524 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1525 NULL, adptr_addrs, &adptr_addrs_len);
1526 if (ret != ERROR_SUCCESS) {
1527 error_setg_win32(errp, ret, "failed to get adapters addresses");
1528 g_free(adptr_addrs);
1529 adptr_addrs = NULL;
1530 }
1531 return adptr_addrs;
1532 }
1533
1534 static char *guest_wctomb_dup(WCHAR *wstr)
1535 {
1536 char *str;
1537 size_t str_size;
1538
1539 str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
1540 /* add 1 to str_size for NULL terminator */
1541 str = g_malloc(str_size + 1);
1542 WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
1543 return str;
1544 }
1545
1546 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1547 Error **errp)
1548 {
1549 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1550 DWORD len;
1551 int ret;
1552
1553 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1554 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1555 len = sizeof(addr_str);
1556 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1557 ip_addr->Address.iSockaddrLength,
1558 NULL,
1559 addr_str,
1560 &len);
1561 if (ret != 0) {
1562 error_setg_win32(errp, WSAGetLastError(),
1563 "failed address presentation form conversion");
1564 return NULL;
1565 }
1566 return g_strdup(addr_str);
1567 }
1568 return NULL;
1569 }
1570
1571 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1572 {
1573 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1574 * field to obtain the prefix.
1575 */
1576 return ip_addr->OnLinkPrefixLength;
1577 }
1578
1579 #define INTERFACE_PATH_BUF_SZ 512
1580
1581 static DWORD get_interface_index(const char *guid)
1582 {
1583 ULONG index;
1584 DWORD status;
1585 wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1586 snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1587 wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1588 status = GetAdapterIndex (wbuf, &index);
1589 if (status != NO_ERROR) {
1590 return (DWORD)~0;
1591 } else {
1592 return index;
1593 }
1594 }
1595
1596 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1597
1598 static int guest_get_network_stats(const char *name,
1599 GuestNetworkInterfaceStat *stats)
1600 {
1601 OSVERSIONINFO os_ver;
1602
1603 os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1604 GetVersionEx(&os_ver);
1605 if (os_ver.dwMajorVersion >= 6) {
1606 MIB_IF_ROW2 a_mid_ifrow;
1607 GetIfEntry2Func getifentry2_ex;
1608 DWORD if_index = 0;
1609 HMODULE module = GetModuleHandle("iphlpapi");
1610 PVOID func = GetProcAddress(module, "GetIfEntry2");
1611
1612 if (func == NULL) {
1613 return -1;
1614 }
1615
1616 getifentry2_ex = (GetIfEntry2Func)func;
1617 if_index = get_interface_index(name);
1618 if (if_index == (DWORD)~0) {
1619 return -1;
1620 }
1621
1622 memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1623 a_mid_ifrow.InterfaceIndex = if_index;
1624 if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1625 stats->rx_bytes = a_mid_ifrow.InOctets;
1626 stats->rx_packets = a_mid_ifrow.InUcastPkts;
1627 stats->rx_errs = a_mid_ifrow.InErrors;
1628 stats->rx_dropped = a_mid_ifrow.InDiscards;
1629 stats->tx_bytes = a_mid_ifrow.OutOctets;
1630 stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1631 stats->tx_errs = a_mid_ifrow.OutErrors;
1632 stats->tx_dropped = a_mid_ifrow.OutDiscards;
1633 return 0;
1634 }
1635 }
1636 return -1;
1637 }
1638
1639 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1640 {
1641 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1642 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1643 GuestNetworkInterfaceList *head = NULL, **tail = &head;
1644 GuestIpAddressList *head_addr, **tail_addr;
1645 GuestNetworkInterface *info;
1646 GuestNetworkInterfaceStat *interface_stat = NULL;
1647 GuestIpAddress *address_item = NULL;
1648 unsigned char *mac_addr;
1649 char *addr_str;
1650 WORD wsa_version;
1651 WSADATA wsa_data;
1652 int ret;
1653
1654 adptr_addrs = guest_get_adapters_addresses(errp);
1655 if (adptr_addrs == NULL) {
1656 return NULL;
1657 }
1658
1659 /* Make WSA APIs available. */
1660 wsa_version = MAKEWORD(2, 2);
1661 ret = WSAStartup(wsa_version, &wsa_data);
1662 if (ret != 0) {
1663 error_setg_win32(errp, ret, "failed socket startup");
1664 goto out;
1665 }
1666
1667 for (addr = adptr_addrs; addr; addr = addr->Next) {
1668 info = g_malloc0(sizeof(*info));
1669
1670 QAPI_LIST_APPEND(tail, info);
1671
1672 info->name = guest_wctomb_dup(addr->FriendlyName);
1673
1674 if (addr->PhysicalAddressLength != 0) {
1675 mac_addr = addr->PhysicalAddress;
1676
1677 info->hardware_address =
1678 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1679 (int) mac_addr[0], (int) mac_addr[1],
1680 (int) mac_addr[2], (int) mac_addr[3],
1681 (int) mac_addr[4], (int) mac_addr[5]);
1682
1683 info->has_hardware_address = true;
1684 }
1685
1686 head_addr = NULL;
1687 tail_addr = &head_addr;
1688 for (ip_addr = addr->FirstUnicastAddress;
1689 ip_addr;
1690 ip_addr = ip_addr->Next) {
1691 addr_str = guest_addr_to_str(ip_addr, errp);
1692 if (addr_str == NULL) {
1693 continue;
1694 }
1695
1696 address_item = g_malloc0(sizeof(*address_item));
1697
1698 QAPI_LIST_APPEND(tail_addr, address_item);
1699
1700 address_item->ip_address = addr_str;
1701 address_item->prefix = guest_ip_prefix(ip_addr);
1702 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1703 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1704 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1705 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1706 }
1707 }
1708 if (head_addr) {
1709 info->has_ip_addresses = true;
1710 info->ip_addresses = head_addr;
1711 }
1712 if (!info->has_statistics) {
1713 interface_stat = g_malloc0(sizeof(*interface_stat));
1714 if (guest_get_network_stats(addr->AdapterName,
1715 interface_stat) == -1) {
1716 info->has_statistics = false;
1717 g_free(interface_stat);
1718 } else {
1719 info->statistics = interface_stat;
1720 info->has_statistics = true;
1721 }
1722 }
1723 }
1724 WSACleanup();
1725 out:
1726 g_free(adptr_addrs);
1727 return head;
1728 }
1729
1730 static int64_t filetime_to_ns(const FILETIME *tf)
1731 {
1732 return ((((int64_t)tf->dwHighDateTime << 32) | tf->dwLowDateTime)
1733 - W32_FT_OFFSET) * 100;
1734 }
1735
1736 int64_t qmp_guest_get_time(Error **errp)
1737 {
1738 SYSTEMTIME ts = {0};
1739 FILETIME tf;
1740
1741 GetSystemTime(&ts);
1742 if (ts.wYear < 1601 || ts.wYear > 30827) {
1743 error_setg(errp, "Failed to get time");
1744 return -1;
1745 }
1746
1747 if (!SystemTimeToFileTime(&ts, &tf)) {
1748 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1749 return -1;
1750 }
1751
1752 return filetime_to_ns(&tf);
1753 }
1754
1755 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1756 {
1757 Error *local_err = NULL;
1758 SYSTEMTIME ts;
1759 FILETIME tf;
1760 LONGLONG time;
1761
1762 if (!has_time) {
1763 /* Unfortunately, Windows libraries don't provide an easy way to access
1764 * RTC yet:
1765 *
1766 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1767 *
1768 * Instead, a workaround is to use the Windows win32tm command to
1769 * resync the time using the Windows Time service.
1770 */
1771 LPVOID msg_buffer;
1772 DWORD ret_flags;
1773
1774 HRESULT hr = system("w32tm /resync /nowait");
1775
1776 if (GetLastError() != 0) {
1777 strerror_s((LPTSTR) & msg_buffer, 0, errno);
1778 error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1779 } else if (hr != 0) {
1780 if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1781 error_setg(errp, "Windows Time service not running on the "
1782 "guest");
1783 } else {
1784 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1785 FORMAT_MESSAGE_FROM_SYSTEM |
1786 FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1787 (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1788 SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1789 NULL)) {
1790 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1791 "t retrieve error message", hr);
1792 } else {
1793 error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1794 (LPCTSTR)msg_buffer);
1795 LocalFree(msg_buffer);
1796 }
1797 }
1798 } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1799 error_setg(errp, "No internet connection on guest, sync not "
1800 "accurate");
1801 }
1802 return;
1803 }
1804
1805 /* Validate time passed by user. */
1806 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1807 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1808 return;
1809 }
1810
1811 time = time_ns / 100 + W32_FT_OFFSET;
1812
1813 tf.dwLowDateTime = (DWORD) time;
1814 tf.dwHighDateTime = (DWORD) (time >> 32);
1815
1816 if (!FileTimeToSystemTime(&tf, &ts)) {
1817 error_setg(errp, "Failed to convert system time %d",
1818 (int)GetLastError());
1819 return;
1820 }
1821
1822 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1823 if (local_err) {
1824 error_propagate(errp, local_err);
1825 return;
1826 }
1827
1828 if (!SetSystemTime(&ts)) {
1829 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1830 return;
1831 }
1832 }
1833
1834 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1835 {
1836 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1837 DWORD length;
1838 GuestLogicalProcessorList *head, **tail;
1839 Error *local_err = NULL;
1840 int64_t current;
1841
1842 ptr = pslpi = NULL;
1843 length = 0;
1844 current = 0;
1845 head = NULL;
1846 tail = &head;
1847
1848 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1849 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1850 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1851 ptr = pslpi = g_malloc0(length);
1852 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1853 error_setg(&local_err, "Failed to get processor information: %d",
1854 (int)GetLastError());
1855 }
1856 } else {
1857 error_setg(&local_err,
1858 "Failed to get processor information buffer length: %d",
1859 (int)GetLastError());
1860 }
1861
1862 while ((local_err == NULL) && (length > 0)) {
1863 if (pslpi->Relationship == RelationProcessorCore) {
1864 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1865
1866 while (cpu_bits > 0) {
1867 if (!!(cpu_bits & 1)) {
1868 GuestLogicalProcessor *vcpu;
1869
1870 vcpu = g_malloc0(sizeof *vcpu);
1871 vcpu->logical_id = current++;
1872 vcpu->online = true;
1873 vcpu->has_can_offline = true;
1874
1875 QAPI_LIST_APPEND(tail, vcpu);
1876 }
1877 cpu_bits >>= 1;
1878 }
1879 }
1880 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1881 pslpi++; /* next entry */
1882 }
1883
1884 g_free(ptr);
1885
1886 if (local_err == NULL) {
1887 if (head != NULL) {
1888 return head;
1889 }
1890 /* there's no guest with zero VCPUs */
1891 error_setg(&local_err, "Guest reported zero VCPUs");
1892 }
1893
1894 qapi_free_GuestLogicalProcessorList(head);
1895 error_propagate(errp, local_err);
1896 return NULL;
1897 }
1898
1899 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1900 {
1901 error_setg(errp, QERR_UNSUPPORTED);
1902 return -1;
1903 }
1904
1905 static gchar *
1906 get_net_error_message(gint error)
1907 {
1908 HMODULE module = NULL;
1909 gchar *retval = NULL;
1910 wchar_t *msg = NULL;
1911 int flags;
1912 size_t nchars;
1913
1914 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1915 FORMAT_MESSAGE_IGNORE_INSERTS |
1916 FORMAT_MESSAGE_FROM_SYSTEM;
1917
1918 if (error >= NERR_BASE && error <= MAX_NERR) {
1919 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1920
1921 if (module != NULL) {
1922 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1923 }
1924 }
1925
1926 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1927
1928 if (msg != NULL) {
1929 nchars = wcslen(msg);
1930
1931 if (nchars >= 2 &&
1932 msg[nchars - 1] == L'\n' &&
1933 msg[nchars - 2] == L'\r') {
1934 msg[nchars - 2] = L'\0';
1935 }
1936
1937 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1938
1939 LocalFree(msg);
1940 }
1941
1942 if (module != NULL) {
1943 FreeLibrary(module);
1944 }
1945
1946 return retval;
1947 }
1948
1949 void qmp_guest_set_user_password(const char *username,
1950 const char *password,
1951 bool crypted,
1952 Error **errp)
1953 {
1954 NET_API_STATUS nas;
1955 char *rawpasswddata = NULL;
1956 size_t rawpasswdlen;
1957 wchar_t *user = NULL, *wpass = NULL;
1958 USER_INFO_1003 pi1003 = { 0, };
1959 GError *gerr = NULL;
1960
1961 if (crypted) {
1962 error_setg(errp, QERR_UNSUPPORTED);
1963 return;
1964 }
1965
1966 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1967 if (!rawpasswddata) {
1968 return;
1969 }
1970 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1971 rawpasswddata[rawpasswdlen] = '\0';
1972
1973 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1974 if (!user) {
1975 goto done;
1976 }
1977
1978 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1979 if (!wpass) {
1980 goto done;
1981 }
1982
1983 pi1003.usri1003_password = wpass;
1984 nas = NetUserSetInfo(NULL, user,
1985 1003, (LPBYTE)&pi1003,
1986 NULL);
1987
1988 if (nas != NERR_Success) {
1989 gchar *msg = get_net_error_message(nas);
1990 error_setg(errp, "failed to set password: %s", msg);
1991 g_free(msg);
1992 }
1993
1994 done:
1995 if (gerr) {
1996 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1997 g_error_free(gerr);
1998 }
1999 g_free(user);
2000 g_free(wpass);
2001 g_free(rawpasswddata);
2002 }
2003
2004 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2005 {
2006 error_setg(errp, QERR_UNSUPPORTED);
2007 return NULL;
2008 }
2009
2010 GuestMemoryBlockResponseList *
2011 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2012 {
2013 error_setg(errp, QERR_UNSUPPORTED);
2014 return NULL;
2015 }
2016
2017 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2018 {
2019 error_setg(errp, QERR_UNSUPPORTED);
2020 return NULL;
2021 }
2022
2023 /* add unsupported commands to the blacklist */
2024 GList *ga_command_blacklist_init(GList *blacklist)
2025 {
2026 const char *list_unsupported[] = {
2027 "guest-suspend-hybrid",
2028 "guest-set-vcpus",
2029 "guest-get-memory-blocks", "guest-set-memory-blocks",
2030 "guest-get-memory-block-size", "guest-get-memory-block-info",
2031 NULL};
2032 char **p = (char **)list_unsupported;
2033
2034 while (*p) {
2035 blacklist = g_list_append(blacklist, g_strdup(*p++));
2036 }
2037
2038 if (!vss_init(true)) {
2039 g_debug("vss_init failed, vss commands are going to be disabled");
2040 const char *list[] = {
2041 "guest-get-fsinfo", "guest-fsfreeze-status",
2042 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
2043 p = (char **)list;
2044
2045 while (*p) {
2046 blacklist = g_list_append(blacklist, g_strdup(*p++));
2047 }
2048 }
2049
2050 return blacklist;
2051 }
2052
2053 /* register init/cleanup routines for stateful command groups */
2054 void ga_command_state_init(GAState *s, GACommandState *cs)
2055 {
2056 if (!vss_initialized()) {
2057 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2058 }
2059 }
2060
2061 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
2062 typedef struct _GA_WTSINFOA {
2063 WTS_CONNECTSTATE_CLASS State;
2064 DWORD SessionId;
2065 DWORD IncomingBytes;
2066 DWORD OutgoingBytes;
2067 DWORD IncomingFrames;
2068 DWORD OutgoingFrames;
2069 DWORD IncomingCompressedBytes;
2070 DWORD OutgoingCompressedBy;
2071 CHAR WinStationName[WINSTATIONNAME_LENGTH];
2072 CHAR Domain[DOMAIN_LENGTH];
2073 CHAR UserName[USERNAME_LENGTH + 1];
2074 LARGE_INTEGER ConnectTime;
2075 LARGE_INTEGER DisconnectTime;
2076 LARGE_INTEGER LastInputTime;
2077 LARGE_INTEGER LogonTime;
2078 LARGE_INTEGER CurrentTime;
2079
2080 } GA_WTSINFOA;
2081
2082 GuestUserList *qmp_guest_get_users(Error **errp)
2083 {
2084 #define QGA_NANOSECONDS 10000000
2085
2086 GHashTable *cache = NULL;
2087 GuestUserList *head = NULL, **tail = &head;
2088
2089 DWORD buffer_size = 0, count = 0, i = 0;
2090 GA_WTSINFOA *info = NULL;
2091 WTS_SESSION_INFOA *entries = NULL;
2092 GuestUser *user = NULL;
2093 gpointer value = NULL;
2094 INT64 login = 0;
2095 double login_time = 0;
2096
2097 cache = g_hash_table_new(g_str_hash, g_str_equal);
2098
2099 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
2100 for (i = 0; i < count; ++i) {
2101 buffer_size = 0;
2102 info = NULL;
2103 if (WTSQuerySessionInformationA(
2104 NULL,
2105 entries[i].SessionId,
2106 WTSSessionInfo,
2107 (LPSTR *)&info,
2108 &buffer_size
2109 )) {
2110
2111 if (strlen(info->UserName) == 0) {
2112 WTSFreeMemory(info);
2113 continue;
2114 }
2115
2116 login = info->LogonTime.QuadPart;
2117 login -= W32_FT_OFFSET;
2118 login_time = ((double)login) / QGA_NANOSECONDS;
2119
2120 if (g_hash_table_contains(cache, info->UserName)) {
2121 value = g_hash_table_lookup(cache, info->UserName);
2122 user = (GuestUser *)value;
2123 if (user->login_time > login_time) {
2124 user->login_time = login_time;
2125 }
2126 } else {
2127 user = g_new0(GuestUser, 1);
2128
2129 user->user = g_strdup(info->UserName);
2130 user->domain = g_strdup(info->Domain);
2131 user->has_domain = true;
2132
2133 user->login_time = login_time;
2134
2135 g_hash_table_add(cache, user->user);
2136
2137 QAPI_LIST_APPEND(tail, user);
2138 }
2139 }
2140 WTSFreeMemory(info);
2141 }
2142 WTSFreeMemory(entries);
2143 }
2144 g_hash_table_destroy(cache);
2145 return head;
2146 }
2147
2148 typedef struct _ga_matrix_lookup_t {
2149 int major;
2150 int minor;
2151 char const *version;
2152 char const *version_id;
2153 } ga_matrix_lookup_t;
2154
2155 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
2156 {
2157 /* Desktop editions */
2158 { 5, 0, "Microsoft Windows 2000", "2000"},
2159 { 5, 1, "Microsoft Windows XP", "xp"},
2160 { 6, 0, "Microsoft Windows Vista", "vista"},
2161 { 6, 1, "Microsoft Windows 7" "7"},
2162 { 6, 2, "Microsoft Windows 8", "8"},
2163 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2164 {10, 0, "Microsoft Windows 10", "10"},
2165 { 0, 0, 0}
2166 },{
2167 /* Server editions */
2168 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2169 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2170 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2171 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2172 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2173 { 0, 0, 0},
2174 { 0, 0, 0},
2175 { 0, 0, 0}
2176 }
2177 };
2178
2179 typedef struct _ga_win_10_0_server_t {
2180 int final_build;
2181 char const *version;
2182 char const *version_id;
2183 } ga_win_10_0_server_t;
2184
2185 static ga_win_10_0_server_t const WIN_10_0_SERVER_VERSION_MATRIX[4] = {
2186 {14393, "Microsoft Windows Server 2016", "2016"},
2187 {17763, "Microsoft Windows Server 2019", "2019"},
2188 {20344, "Microsoft Windows Server 2022", "2022"},
2189 {0, 0}
2190 };
2191
2192 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2193 {
2194 typedef NTSTATUS(WINAPI *rtl_get_version_t)(
2195 RTL_OSVERSIONINFOEXW *os_version_info_ex);
2196
2197 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2198
2199 HMODULE module = GetModuleHandle("ntdll");
2200 PVOID fun = GetProcAddress(module, "RtlGetVersion");
2201 if (fun == NULL) {
2202 error_setg(errp, QERR_QGA_COMMAND_FAILED,
2203 "Failed to get address of RtlGetVersion");
2204 return;
2205 }
2206
2207 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2208 rtl_get_version(info);
2209 return;
2210 }
2211
2212 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
2213 {
2214 DWORD major = os_version->dwMajorVersion;
2215 DWORD minor = os_version->dwMinorVersion;
2216 DWORD build = os_version->dwBuildNumber;
2217 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2218 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
2219 ga_win_10_0_server_t const *win_10_0_table = WIN_10_0_SERVER_VERSION_MATRIX;
2220 while (table->version != NULL) {
2221 if (major == 10 && minor == 0 && tbl_idx) {
2222 while (win_10_0_table->version != NULL) {
2223 if (build <= win_10_0_table->final_build) {
2224 if (id) {
2225 return g_strdup(win_10_0_table->version_id);
2226 } else {
2227 return g_strdup(win_10_0_table->version);
2228 }
2229 }
2230 win_10_0_table++;
2231 }
2232 } else if (major == table->major && minor == table->minor) {
2233 if (id) {
2234 return g_strdup(table->version_id);
2235 } else {
2236 return g_strdup(table->version);
2237 }
2238 }
2239 ++table;
2240 }
2241 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2242 major, minor);
2243 return g_strdup("N/A");
2244 }
2245
2246 static char *ga_get_win_product_name(Error **errp)
2247 {
2248 HKEY key = INVALID_HANDLE_VALUE;
2249 DWORD size = 128;
2250 char *result = g_malloc0(size);
2251 LONG err = ERROR_SUCCESS;
2252
2253 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2254 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2255 &key);
2256 if (err != ERROR_SUCCESS) {
2257 error_setg_win32(errp, err, "failed to open registry key");
2258 g_free(result);
2259 return NULL;
2260 }
2261
2262 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2263 (LPBYTE)result, &size);
2264 if (err == ERROR_MORE_DATA) {
2265 slog("ProductName longer than expected (%lu bytes), retrying",
2266 size);
2267 g_free(result);
2268 result = NULL;
2269 if (size > 0) {
2270 result = g_malloc0(size);
2271 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2272 (LPBYTE)result, &size);
2273 }
2274 }
2275 if (err != ERROR_SUCCESS) {
2276 error_setg_win32(errp, err, "failed to retrive ProductName");
2277 goto fail;
2278 }
2279
2280 RegCloseKey(key);
2281 return result;
2282
2283 fail:
2284 if (key != INVALID_HANDLE_VALUE) {
2285 RegCloseKey(key);
2286 }
2287 g_free(result);
2288 return NULL;
2289 }
2290
2291 static char *ga_get_current_arch(void)
2292 {
2293 SYSTEM_INFO info;
2294 GetNativeSystemInfo(&info);
2295 char *result = NULL;
2296 switch (info.wProcessorArchitecture) {
2297 case PROCESSOR_ARCHITECTURE_AMD64:
2298 result = g_strdup("x86_64");
2299 break;
2300 case PROCESSOR_ARCHITECTURE_ARM:
2301 result = g_strdup("arm");
2302 break;
2303 case PROCESSOR_ARCHITECTURE_IA64:
2304 result = g_strdup("ia64");
2305 break;
2306 case PROCESSOR_ARCHITECTURE_INTEL:
2307 result = g_strdup("x86");
2308 break;
2309 case PROCESSOR_ARCHITECTURE_UNKNOWN:
2310 default:
2311 slog("unknown processor architecture 0x%0x",
2312 info.wProcessorArchitecture);
2313 result = g_strdup("unknown");
2314 break;
2315 }
2316 return result;
2317 }
2318
2319 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2320 {
2321 Error *local_err = NULL;
2322 OSVERSIONINFOEXW os_version = {0};
2323 bool server;
2324 char *product_name;
2325 GuestOSInfo *info;
2326
2327 ga_get_win_version(&os_version, &local_err);
2328 if (local_err) {
2329 error_propagate(errp, local_err);
2330 return NULL;
2331 }
2332
2333 server = os_version.wProductType != VER_NT_WORKSTATION;
2334 product_name = ga_get_win_product_name(errp);
2335 if (product_name == NULL) {
2336 return NULL;
2337 }
2338
2339 info = g_new0(GuestOSInfo, 1);
2340
2341 info->has_kernel_version = true;
2342 info->kernel_version = g_strdup_printf("%lu.%lu",
2343 os_version.dwMajorVersion,
2344 os_version.dwMinorVersion);
2345 info->has_kernel_release = true;
2346 info->kernel_release = g_strdup_printf("%lu",
2347 os_version.dwBuildNumber);
2348 info->has_machine = true;
2349 info->machine = ga_get_current_arch();
2350
2351 info->has_id = true;
2352 info->id = g_strdup("mswindows");
2353 info->has_name = true;
2354 info->name = g_strdup("Microsoft Windows");
2355 info->has_pretty_name = true;
2356 info->pretty_name = product_name;
2357 info->has_version = true;
2358 info->version = ga_get_win_name(&os_version, false);
2359 info->has_version_id = true;
2360 info->version_id = ga_get_win_name(&os_version, true);
2361 info->has_variant = true;
2362 info->variant = g_strdup(server ? "server" : "client");
2363 info->has_variant_id = true;
2364 info->variant_id = g_strdup(server ? "server" : "client");
2365
2366 return info;
2367 }
2368
2369 /*
2370 * Safely get device property. Returned strings are using wide characters.
2371 * Caller is responsible for freeing the buffer.
2372 */
2373 static LPBYTE cm_get_property(DEVINST devInst, const DEVPROPKEY *propName,
2374 PDEVPROPTYPE propType)
2375 {
2376 CONFIGRET cr;
2377 g_autofree LPBYTE buffer = NULL;
2378 ULONG buffer_len = 0;
2379
2380 /* First query for needed space */
2381 cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2382 buffer, &buffer_len, 0);
2383 if (cr != CR_SUCCESS && cr != CR_BUFFER_SMALL) {
2384
2385 slog("failed to get property size, error=0x%lx", cr);
2386 return NULL;
2387 }
2388 buffer = g_new0(BYTE, buffer_len + 1);
2389 cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2390 buffer, &buffer_len, 0);
2391 if (cr != CR_SUCCESS) {
2392 slog("failed to get device property, error=0x%lx", cr);
2393 return NULL;
2394 }
2395 return g_steal_pointer(&buffer);
2396 }
2397
2398 static GStrv ga_get_hardware_ids(DEVINST devInstance)
2399 {
2400 GArray *values = NULL;
2401 DEVPROPTYPE cm_type;
2402 LPWSTR id;
2403 g_autofree LPWSTR property = (LPWSTR)cm_get_property(devInstance,
2404 &qga_DEVPKEY_Device_HardwareIds, &cm_type);
2405 if (property == NULL) {
2406 slog("failed to get hardware IDs");
2407 return NULL;
2408 }
2409 if (*property == '\0') {
2410 /* empty list */
2411 return NULL;
2412 }
2413 values = g_array_new(TRUE, TRUE, sizeof(gchar *));
2414 for (id = property; '\0' != *id; id += lstrlenW(id) + 1) {
2415 gchar *id8 = g_utf16_to_utf8(id, -1, NULL, NULL, NULL);
2416 g_array_append_val(values, id8);
2417 }
2418 return (GStrv)g_array_free(values, FALSE);
2419 }
2420
2421 /*
2422 * https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
2423 */
2424 #define DEVICE_PCI_RE "PCI\\\\VEN_(1AF4|1B36)&DEV_([0-9A-B]{4})(&|$)"
2425
2426 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
2427 {
2428 GuestDeviceInfoList *head = NULL, **tail = &head;
2429 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2430 SP_DEVINFO_DATA dev_info_data;
2431 int i, j;
2432 GError *gerr = NULL;
2433 g_autoptr(GRegex) device_pci_re = NULL;
2434 DEVPROPTYPE cm_type;
2435
2436 device_pci_re = g_regex_new(DEVICE_PCI_RE,
2437 G_REGEX_ANCHORED | G_REGEX_OPTIMIZE, 0,
2438 &gerr);
2439 g_assert(device_pci_re != NULL);
2440
2441 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
2442 dev_info = SetupDiGetClassDevs(0, 0, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES);
2443 if (dev_info == INVALID_HANDLE_VALUE) {
2444 error_setg(errp, "failed to get device tree");
2445 return NULL;
2446 }
2447
2448 slog("enumerating devices");
2449 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
2450 bool skip = true;
2451 g_autofree LPWSTR name = NULL;
2452 g_autofree LPFILETIME date = NULL;
2453 g_autofree LPWSTR version = NULL;
2454 g_auto(GStrv) hw_ids = NULL;
2455 g_autoptr(GuestDeviceInfo) device = g_new0(GuestDeviceInfo, 1);
2456 g_autofree char *vendor_id = NULL;
2457 g_autofree char *device_id = NULL;
2458
2459 name = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2460 &qga_DEVPKEY_NAME, &cm_type);
2461 if (name == NULL) {
2462 slog("failed to get device description");
2463 continue;
2464 }
2465 device->driver_name = g_utf16_to_utf8(name, -1, NULL, NULL, NULL);
2466 if (device->driver_name == NULL) {
2467 error_setg(errp, "conversion to utf8 failed (driver name)");
2468 return NULL;
2469 }
2470 slog("querying device: %s", device->driver_name);
2471 hw_ids = ga_get_hardware_ids(dev_info_data.DevInst);
2472 if (hw_ids == NULL) {
2473 continue;
2474 }
2475 for (j = 0; hw_ids[j] != NULL; j++) {
2476 g_autoptr(GMatchInfo) match_info;
2477 GuestDeviceIdPCI *id;
2478 if (!g_regex_match(device_pci_re, hw_ids[j], 0, &match_info)) {
2479 continue;
2480 }
2481 skip = false;
2482
2483 vendor_id = g_match_info_fetch(match_info, 1);
2484 device_id = g_match_info_fetch(match_info, 2);
2485
2486 device->id = g_new0(GuestDeviceId, 1);
2487 device->has_id = true;
2488 device->id->type = GUEST_DEVICE_TYPE_PCI;
2489 id = &device->id->u.pci;
2490 id->vendor_id = g_ascii_strtoull(vendor_id, NULL, 16);
2491 id->device_id = g_ascii_strtoull(device_id, NULL, 16);
2492
2493 break;
2494 }
2495 if (skip) {
2496 continue;
2497 }
2498
2499 version = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2500 &qga_DEVPKEY_Device_DriverVersion, &cm_type);
2501 if (version == NULL) {
2502 slog("failed to get driver version");
2503 continue;
2504 }
2505 device->driver_version = g_utf16_to_utf8(version, -1, NULL,
2506 NULL, NULL);
2507 if (device->driver_version == NULL) {
2508 error_setg(errp, "conversion to utf8 failed (driver version)");
2509 return NULL;
2510 }
2511 device->has_driver_version = true;
2512
2513 date = (LPFILETIME)cm_get_property(dev_info_data.DevInst,
2514 &qga_DEVPKEY_Device_DriverDate, &cm_type);
2515 if (date == NULL) {
2516 slog("failed to get driver date");
2517 continue;
2518 }
2519 device->driver_date = filetime_to_ns(date);
2520 device->has_driver_date = true;
2521
2522 slog("driver: %s\ndriver version: %" PRId64 ",%s\n",
2523 device->driver_name, device->driver_date,
2524 device->driver_version);
2525 QAPI_LIST_APPEND(tail, g_steal_pointer(&device));
2526 }
2527
2528 if (dev_info != INVALID_HANDLE_VALUE) {
2529 SetupDiDestroyDeviceInfoList(dev_info);
2530 }
2531 return head;
2532 }