]> git.proxmox.com Git - mirror_qemu.git/blob - qga/commands-win32.c
gqa-win: get_pci_info: Free parent_dev_info properly
[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 GuestPCIAddress *get_pci_info(int number, Error **errp)
516 {
517 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
518 HDEVINFO parent_dev_info = INVALID_HANDLE_VALUE;
519
520 SP_DEVINFO_DATA dev_info_data;
521 SP_DEVICE_INTERFACE_DATA dev_iface_data;
522 HANDLE dev_file;
523 int i;
524 GuestPCIAddress *pci = NULL;
525 bool partial_pci = false;
526
527 pci = g_malloc0(sizeof(*pci));
528 pci->domain = -1;
529 pci->slot = -1;
530 pci->function = -1;
531 pci->bus = -1;
532
533 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
534 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
535 if (dev_info == INVALID_HANDLE_VALUE) {
536 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
537 goto end;
538 }
539
540 g_debug("enumerating devices");
541 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
542 dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
543 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
544 PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
545 STORAGE_DEVICE_NUMBER sdn;
546 char *parent_dev_id = NULL;
547 SP_DEVINFO_DATA parent_dev_info_data;
548 DWORD j;
549 DWORD size = 0;
550
551 g_debug("getting device path");
552 if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
553 &GUID_DEVINTERFACE_DISK, 0,
554 &dev_iface_data)) {
555 while (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
556 pdev_iface_detail_data,
557 size, &size,
558 &dev_info_data)) {
559 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
560 pdev_iface_detail_data = g_malloc(size);
561 pdev_iface_detail_data->cbSize =
562 sizeof(*pdev_iface_detail_data);
563 } else {
564 error_setg_win32(errp, GetLastError(),
565 "failed to get device interfaces");
566 goto end;
567 }
568 }
569
570 dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
571 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
572 NULL);
573 g_free(pdev_iface_detail_data);
574
575 if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
576 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
577 CloseHandle(dev_file);
578 error_setg_win32(errp, GetLastError(),
579 "failed to get device slot number");
580 goto end;
581 }
582
583 CloseHandle(dev_file);
584 if (sdn.DeviceNumber != number) {
585 continue;
586 }
587 } else {
588 error_setg_win32(errp, GetLastError(),
589 "failed to get device interfaces");
590 goto end;
591 }
592
593 g_debug("found device slot %d. Getting storage controller", number);
594 {
595 CONFIGRET cr;
596 DEVINST dev_inst, parent_dev_inst;
597 ULONG dev_id_size = 0;
598
599 size = 0;
600 while (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
601 parent_dev_id, size, &size)) {
602 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
603 parent_dev_id = g_malloc(size);
604 } else {
605 error_setg_win32(errp, GetLastError(),
606 "failed to get device instance ID");
607 goto end;
608 }
609 }
610
611 /*
612 * CM API used here as opposed to
613 * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
614 * which exports are only available in mingw-w64 6+
615 */
616 cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
617 if (cr != CR_SUCCESS) {
618 g_error("CM_Locate_DevInst failed with code %lx", cr);
619 error_setg_win32(errp, GetLastError(),
620 "failed to get device instance");
621 goto end;
622 }
623 cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
624 if (cr != CR_SUCCESS) {
625 g_error("CM_Get_Parent failed with code %lx", cr);
626 error_setg_win32(errp, GetLastError(),
627 "failed to get parent device instance");
628 goto end;
629 }
630
631 cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
632 if (cr != CR_SUCCESS) {
633 g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
634 error_setg_win32(errp, GetLastError(),
635 "failed to get parent device ID length");
636 goto end;
637 }
638
639 ++dev_id_size;
640 if (dev_id_size > size) {
641 g_free(parent_dev_id);
642 parent_dev_id = g_malloc(dev_id_size);
643 }
644
645 cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
646 0);
647 if (cr != CR_SUCCESS) {
648 g_error("CM_Get_Device_ID failed with code %lx", cr);
649 error_setg_win32(errp, GetLastError(),
650 "failed to get parent device ID");
651 goto end;
652 }
653 }
654
655 g_debug("querying storage controller %s for PCI information",
656 parent_dev_id);
657 parent_dev_info =
658 SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
659 NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
660 g_free(parent_dev_id);
661
662 if (parent_dev_info == INVALID_HANDLE_VALUE) {
663 error_setg_win32(errp, GetLastError(),
664 "failed to get parent device");
665 goto end;
666 }
667
668 parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
669 if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
670 error_setg_win32(errp, GetLastError(),
671 "failed to get parent device data");
672 goto end;
673 }
674
675 for (j = 0;
676 SetupDiEnumDeviceInfo(parent_dev_info, j, &parent_dev_info_data);
677 j++) {
678 DWORD addr, bus, ui_slot, type;
679 int func, slot;
680
681 /*
682 * There is no need to allocate buffer in the next functions. The
683 * size is known and ULONG according to
684 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
685 */
686 if (!SetupDiGetDeviceRegistryProperty(
687 parent_dev_info, &parent_dev_info_data, SPDRP_BUSNUMBER,
688 &type, (PBYTE)&bus, size, NULL)) {
689 debug_error("failed to get PCI bus");
690 bus = -1;
691 partial_pci = true;
692 }
693
694 /*
695 * The function retrieves the device's address. This value will be
696 * transformed into device function and number
697 */
698 if (!SetupDiGetDeviceRegistryProperty(
699 parent_dev_info, &parent_dev_info_data, SPDRP_ADDRESS,
700 &type, (PBYTE)&addr, size, NULL)) {
701 debug_error("failed to get PCI address");
702 addr = -1;
703 partial_pci = true;
704 }
705
706 /*
707 * This call returns UINumber of DEVICE_CAPABILITIES structure.
708 * This number is typically a user-perceived slot number.
709 */
710 if (!SetupDiGetDeviceRegistryProperty(
711 parent_dev_info, &parent_dev_info_data, SPDRP_UI_NUMBER,
712 &type, (PBYTE)&ui_slot, size, NULL)) {
713 debug_error("failed to get PCI slot");
714 ui_slot = -1;
715 partial_pci = true;
716 }
717
718 /*
719 * SetupApi gives us the same information as driver with
720 * IoGetDeviceProperty. According to Microsoft:
721 *
722 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
723 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
724 * SPDRP_ADDRESS is propertyAddress, so we do the same.
725 *
726 * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
727 */
728 if (partial_pci) {
729 pci->domain = -1;
730 pci->slot = -1;
731 pci->function = -1;
732 pci->bus = -1;
733 continue;
734 } else {
735 func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
736 slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
737 if ((int)ui_slot != slot) {
738 g_debug("mismatch with reported slot values: %d vs %d",
739 (int)ui_slot, slot);
740 }
741 pci->domain = 0;
742 pci->slot = (int)ui_slot;
743 pci->function = func;
744 pci->bus = (int)bus;
745 break;
746 }
747 }
748 break;
749 }
750
751 end:
752 if (parent_dev_info != INVALID_HANDLE_VALUE) {
753 SetupDiDestroyDeviceInfoList(parent_dev_info);
754 }
755 if (dev_info != INVALID_HANDLE_VALUE) {
756 SetupDiDestroyDeviceInfoList(dev_info);
757 }
758 return pci;
759 }
760
761 static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
762 Error **errp)
763 {
764 STORAGE_PROPERTY_QUERY query;
765 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
766 DWORD received;
767 ULONG size = sizeof(buf);
768
769 dev_desc = &buf;
770 query.PropertyId = StorageDeviceProperty;
771 query.QueryType = PropertyStandardQuery;
772
773 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
774 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
775 size, &received, NULL)) {
776 error_setg_win32(errp, GetLastError(), "failed to get bus type");
777 return;
778 }
779 disk->bus_type = find_bus_type(dev_desc->BusType);
780 g_debug("bus type %d", disk->bus_type);
781
782 /* Query once more. Now with long enough buffer. */
783 size = dev_desc->Size;
784 dev_desc = g_malloc0(size);
785 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
786 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
787 size, &received, NULL)) {
788 error_setg_win32(errp, GetLastError(), "failed to get serial number");
789 g_debug("failed to get serial number");
790 goto out_free;
791 }
792 if (dev_desc->SerialNumberOffset > 0) {
793 const char *serial;
794 size_t len;
795
796 if (dev_desc->SerialNumberOffset >= received) {
797 error_setg(errp, "failed to get serial number: offset outside the buffer");
798 g_debug("serial number offset outside the buffer");
799 goto out_free;
800 }
801 serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
802 len = received - dev_desc->SerialNumberOffset;
803 g_debug("serial number \"%s\"", serial);
804 if (*serial != 0) {
805 disk->serial = g_strndup(serial, len);
806 disk->has_serial = true;
807 }
808 }
809 out_free:
810 g_free(dev_desc);
811
812 return;
813 }
814
815 static void get_single_disk_info(int disk_number,
816 GuestDiskAddress *disk, Error **errp)
817 {
818 SCSI_ADDRESS addr, *scsi_ad;
819 DWORD len;
820 HANDLE disk_h;
821 Error *local_err = NULL;
822
823 scsi_ad = &addr;
824
825 g_debug("getting disk info for: %s", disk->dev);
826 disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
827 0, NULL);
828 if (disk_h == INVALID_HANDLE_VALUE) {
829 error_setg_win32(errp, GetLastError(), "failed to open disk");
830 return;
831 }
832
833 get_disk_properties(disk_h, disk, &local_err);
834 if (local_err) {
835 error_propagate(errp, local_err);
836 goto err_close;
837 }
838
839 g_debug("bus type %d", disk->bus_type);
840 /* always set pci_controller as required by schema. get_pci_info() should
841 * report -1 values for non-PCI buses rather than fail. fail the command
842 * if that doesn't hold since that suggests some other unexpected
843 * breakage
844 */
845 disk->pci_controller = get_pci_info(disk_number, &local_err);
846 if (local_err) {
847 error_propagate(errp, local_err);
848 goto err_close;
849 }
850 if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
851 || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
852 || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
853 /* This bus type is not supported before Windows Server 2003 SP1 */
854 || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
855 ) {
856 /* We are able to use the same ioctls for different bus types
857 * according to Microsoft docs
858 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
859 g_debug("getting SCSI info");
860 if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
861 sizeof(SCSI_ADDRESS), &len, NULL)) {
862 disk->unit = addr.Lun;
863 disk->target = addr.TargetId;
864 disk->bus = addr.PathId;
865 }
866 /* We do not set error in this case, because we still have enough
867 * information about volume. */
868 }
869
870 err_close:
871 CloseHandle(disk_h);
872 return;
873 }
874
875 /* VSS provider works with volumes, thus there is no difference if
876 * the volume consist of spanned disks. Info about the first disk in the
877 * volume is returned for the spanned disk group (LVM) */
878 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
879 {
880 Error *local_err = NULL;
881 GuestDiskAddressList *list = NULL;
882 GuestDiskAddress *disk = NULL;
883 int i;
884 HANDLE vol_h;
885 DWORD size;
886 PVOLUME_DISK_EXTENTS extents = NULL;
887
888 /* strip final backslash */
889 char *name = g_strdup(guid);
890 if (g_str_has_suffix(name, "\\")) {
891 name[strlen(name) - 1] = 0;
892 }
893
894 g_debug("opening %s", name);
895 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
896 0, NULL);
897 if (vol_h == INVALID_HANDLE_VALUE) {
898 error_setg_win32(errp, GetLastError(), "failed to open volume");
899 goto out;
900 }
901
902 /* Get list of extents */
903 g_debug("getting disk extents");
904 size = sizeof(VOLUME_DISK_EXTENTS);
905 extents = g_malloc0(size);
906 if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
907 0, extents, size, &size, NULL)) {
908 DWORD last_err = GetLastError();
909 if (last_err == ERROR_MORE_DATA) {
910 /* Try once more with big enough buffer */
911 g_free(extents);
912 extents = g_malloc0(size);
913 if (!DeviceIoControl(
914 vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
915 0, extents, size, NULL, NULL)) {
916 error_setg_win32(errp, GetLastError(),
917 "failed to get disk extents");
918 goto out;
919 }
920 } else if (last_err == ERROR_INVALID_FUNCTION) {
921 /* Possibly CD-ROM or a shared drive. Try to pass the volume */
922 g_debug("volume not on disk");
923 disk = g_malloc0(sizeof(GuestDiskAddress));
924 disk->has_dev = true;
925 disk->dev = g_strdup(name);
926 get_single_disk_info(0xffffffff, disk, &local_err);
927 if (local_err) {
928 g_debug("failed to get disk info, ignoring error: %s",
929 error_get_pretty(local_err));
930 error_free(local_err);
931 goto out;
932 }
933 QAPI_LIST_PREPEND(list, disk);
934 disk = NULL;
935 goto out;
936 } else {
937 error_setg_win32(errp, GetLastError(),
938 "failed to get disk extents");
939 goto out;
940 }
941 }
942 g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
943
944 /* Go through each extent */
945 for (i = 0; i < extents->NumberOfDiskExtents; i++) {
946 disk = g_malloc0(sizeof(GuestDiskAddress));
947
948 /* Disk numbers directly correspond to numbers used in UNCs
949 *
950 * See documentation for DISK_EXTENT:
951 * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
952 *
953 * See also Naming Files, Paths and Namespaces:
954 * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
955 */
956 disk->has_dev = true;
957 disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
958 extents->Extents[i].DiskNumber);
959
960 get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
961 if (local_err) {
962 error_propagate(errp, local_err);
963 goto out;
964 }
965 QAPI_LIST_PREPEND(list, disk);
966 disk = NULL;
967 }
968
969
970 out:
971 if (vol_h != INVALID_HANDLE_VALUE) {
972 CloseHandle(vol_h);
973 }
974 qapi_free_GuestDiskAddress(disk);
975 g_free(extents);
976 g_free(name);
977
978 return list;
979 }
980
981 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
982 {
983 GuestDiskInfoList *ret = NULL;
984 HDEVINFO dev_info;
985 SP_DEVICE_INTERFACE_DATA dev_iface_data;
986 int i;
987
988 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
989 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
990 if (dev_info == INVALID_HANDLE_VALUE) {
991 error_setg_win32(errp, GetLastError(), "failed to get device tree");
992 return NULL;
993 }
994
995 g_debug("enumerating devices");
996 dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
997 for (i = 0;
998 SetupDiEnumDeviceInterfaces(dev_info, NULL, &GUID_DEVINTERFACE_DISK,
999 i, &dev_iface_data);
1000 i++) {
1001 GuestDiskAddress *address = NULL;
1002 GuestDiskInfo *disk = NULL;
1003 Error *local_err = NULL;
1004 g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA
1005 pdev_iface_detail_data = NULL;
1006 STORAGE_DEVICE_NUMBER sdn;
1007 HANDLE dev_file;
1008 DWORD size = 0;
1009 BOOL result;
1010 int attempt;
1011
1012 g_debug(" getting device path");
1013 for (attempt = 0, result = FALSE; attempt < 2 && !result; attempt++) {
1014 result = SetupDiGetDeviceInterfaceDetail(dev_info,
1015 &dev_iface_data, pdev_iface_detail_data, size, &size, NULL);
1016 if (result) {
1017 break;
1018 }
1019 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1020 pdev_iface_detail_data = g_realloc(pdev_iface_detail_data,
1021 size);
1022 pdev_iface_detail_data->cbSize =
1023 sizeof(*pdev_iface_detail_data);
1024 } else {
1025 g_debug("failed to get device interface details");
1026 break;
1027 }
1028 }
1029 if (!result) {
1030 g_debug("skipping device");
1031 continue;
1032 }
1033
1034 g_debug(" device: %s", pdev_iface_detail_data->DevicePath);
1035 dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
1036 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
1037 if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
1038 NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
1039 CloseHandle(dev_file);
1040 debug_error("failed to get storage device number");
1041 continue;
1042 }
1043 CloseHandle(dev_file);
1044
1045 disk = g_new0(GuestDiskInfo, 1);
1046 disk->name = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
1047 sdn.DeviceNumber);
1048
1049 g_debug(" number: %lu", sdn.DeviceNumber);
1050 address = g_malloc0(sizeof(GuestDiskAddress));
1051 address->has_dev = true;
1052 address->dev = g_strdup(disk->name);
1053 get_single_disk_info(sdn.DeviceNumber, address, &local_err);
1054 if (local_err) {
1055 g_debug("failed to get disk info: %s",
1056 error_get_pretty(local_err));
1057 error_free(local_err);
1058 qapi_free_GuestDiskAddress(address);
1059 address = NULL;
1060 } else {
1061 disk->address = address;
1062 disk->has_address = true;
1063 }
1064
1065 QAPI_LIST_PREPEND(ret, disk);
1066 }
1067
1068 SetupDiDestroyDeviceInfoList(dev_info);
1069 return ret;
1070 }
1071
1072 #else
1073
1074 static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
1075 {
1076 return NULL;
1077 }
1078
1079 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1080 {
1081 error_setg(errp, QERR_UNSUPPORTED);
1082 return NULL;
1083 }
1084
1085 #endif /* CONFIG_QGA_NTDDSCSI */
1086
1087 static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
1088 {
1089 DWORD info_size;
1090 char mnt, *mnt_point;
1091 wchar_t wfs_name[32];
1092 char fs_name[32];
1093 wchar_t vol_info[MAX_PATH + 1];
1094 size_t len;
1095 uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
1096 GuestFilesystemInfo *fs = NULL;
1097 HANDLE hLocalDiskHandle = INVALID_HANDLE_VALUE;
1098
1099 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
1100 if (GetLastError() != ERROR_MORE_DATA) {
1101 error_setg_win32(errp, GetLastError(), "failed to get volume name");
1102 return NULL;
1103 }
1104
1105 mnt_point = g_malloc(info_size + 1);
1106 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
1107 &info_size)) {
1108 error_setg_win32(errp, GetLastError(), "failed to get volume name");
1109 goto free;
1110 }
1111
1112 hLocalDiskHandle = CreateFile(guid, 0 , 0, NULL, OPEN_EXISTING,
1113 FILE_ATTRIBUTE_NORMAL |
1114 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1115 if (INVALID_HANDLE_VALUE == hLocalDiskHandle) {
1116 error_setg_win32(errp, GetLastError(), "failed to get handle for volume");
1117 goto free;
1118 }
1119
1120 len = strlen(mnt_point);
1121 mnt_point[len] = '\\';
1122 mnt_point[len + 1] = 0;
1123
1124 if (!GetVolumeInformationByHandleW(hLocalDiskHandle, vol_info,
1125 sizeof(vol_info), NULL, NULL, NULL,
1126 (LPWSTR) & wfs_name, sizeof(wfs_name))) {
1127 if (GetLastError() != ERROR_NOT_READY) {
1128 error_setg_win32(errp, GetLastError(), "failed to get volume info");
1129 }
1130 goto free;
1131 }
1132
1133 fs = g_malloc(sizeof(*fs));
1134 fs->name = g_strdup(guid);
1135 fs->has_total_bytes = false;
1136 fs->has_used_bytes = false;
1137 if (len == 0) {
1138 fs->mountpoint = g_strdup("System Reserved");
1139 } else {
1140 fs->mountpoint = g_strndup(mnt_point, len);
1141 if (GetDiskFreeSpaceEx(fs->mountpoint,
1142 (PULARGE_INTEGER) & i64FreeBytesToCaller,
1143 (PULARGE_INTEGER) & i64TotalBytes,
1144 (PULARGE_INTEGER) & i64FreeBytes)) {
1145 fs->used_bytes = i64TotalBytes - i64FreeBytes;
1146 fs->total_bytes = i64TotalBytes;
1147 fs->has_total_bytes = true;
1148 fs->has_used_bytes = true;
1149 }
1150 }
1151 wcstombs(fs_name, wfs_name, sizeof(wfs_name));
1152 fs->type = g_strdup(fs_name);
1153 fs->disk = build_guest_disk_info(guid, errp);
1154 free:
1155 if (hLocalDiskHandle != INVALID_HANDLE_VALUE) {
1156 CloseHandle(hLocalDiskHandle);
1157 }
1158 g_free(mnt_point);
1159 return fs;
1160 }
1161
1162 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1163 {
1164 HANDLE vol_h;
1165 GuestFilesystemInfoList *ret = NULL;
1166 char guid[256];
1167
1168 vol_h = FindFirstVolume(guid, sizeof(guid));
1169 if (vol_h == INVALID_HANDLE_VALUE) {
1170 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1171 return NULL;
1172 }
1173
1174 do {
1175 Error *local_err = NULL;
1176 GuestFilesystemInfo *info = build_guest_fsinfo(guid, &local_err);
1177 if (local_err) {
1178 g_debug("failed to get filesystem info, ignoring error: %s",
1179 error_get_pretty(local_err));
1180 error_free(local_err);
1181 continue;
1182 }
1183 QAPI_LIST_PREPEND(ret, info);
1184 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
1185
1186 if (GetLastError() != ERROR_NO_MORE_FILES) {
1187 error_setg_win32(errp, GetLastError(), "failed to find next volume");
1188 }
1189
1190 FindVolumeClose(vol_h);
1191 return ret;
1192 }
1193
1194 /*
1195 * Return status of freeze/thaw
1196 */
1197 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1198 {
1199 if (!vss_initialized()) {
1200 error_setg(errp, QERR_UNSUPPORTED);
1201 return 0;
1202 }
1203
1204 if (ga_is_frozen(ga_state)) {
1205 return GUEST_FSFREEZE_STATUS_FROZEN;
1206 }
1207
1208 return GUEST_FSFREEZE_STATUS_THAWED;
1209 }
1210
1211 /*
1212 * Freeze local file systems using Volume Shadow-copy Service.
1213 * The frozen state is limited for up to 10 seconds by VSS.
1214 */
1215 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1216 {
1217 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1218 }
1219
1220 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1221 strList *mountpoints,
1222 Error **errp)
1223 {
1224 int i;
1225 Error *local_err = NULL;
1226
1227 if (!vss_initialized()) {
1228 error_setg(errp, QERR_UNSUPPORTED);
1229 return 0;
1230 }
1231
1232 slog("guest-fsfreeze called");
1233
1234 /* cannot risk guest agent blocking itself on a write in this state */
1235 ga_set_frozen(ga_state);
1236
1237 qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
1238 if (local_err) {
1239 error_propagate(errp, local_err);
1240 goto error;
1241 }
1242
1243 return i;
1244
1245 error:
1246 local_err = NULL;
1247 qmp_guest_fsfreeze_thaw(&local_err);
1248 if (local_err) {
1249 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
1250 error_free(local_err);
1251 }
1252 return 0;
1253 }
1254
1255 /*
1256 * Thaw local file systems using Volume Shadow-copy Service.
1257 */
1258 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1259 {
1260 int i;
1261
1262 if (!vss_initialized()) {
1263 error_setg(errp, QERR_UNSUPPORTED);
1264 return 0;
1265 }
1266
1267 qga_vss_fsfreeze(&i, false, NULL, errp);
1268
1269 ga_unset_frozen(ga_state);
1270 return i;
1271 }
1272
1273 static void guest_fsfreeze_cleanup(void)
1274 {
1275 Error *err = NULL;
1276
1277 if (!vss_initialized()) {
1278 return;
1279 }
1280
1281 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1282 qmp_guest_fsfreeze_thaw(&err);
1283 if (err) {
1284 slog("failed to clean up frozen filesystems: %s",
1285 error_get_pretty(err));
1286 error_free(err);
1287 }
1288 }
1289
1290 vss_deinit(true);
1291 }
1292
1293 /*
1294 * Walk list of mounted file systems in the guest, and discard unused
1295 * areas.
1296 */
1297 GuestFilesystemTrimResponse *
1298 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1299 {
1300 GuestFilesystemTrimResponse *resp;
1301 HANDLE handle;
1302 WCHAR guid[MAX_PATH] = L"";
1303 OSVERSIONINFO osvi;
1304 BOOL win8_or_later;
1305
1306 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
1307 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1308 GetVersionEx(&osvi);
1309 win8_or_later = (osvi.dwMajorVersion > 6 ||
1310 ((osvi.dwMajorVersion == 6) &&
1311 (osvi.dwMinorVersion >= 2)));
1312 if (!win8_or_later) {
1313 error_setg(errp, "fstrim is only supported for Win8+");
1314 return NULL;
1315 }
1316
1317 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
1318 if (handle == INVALID_HANDLE_VALUE) {
1319 error_setg_win32(errp, GetLastError(), "failed to find any volume");
1320 return NULL;
1321 }
1322
1323 resp = g_new0(GuestFilesystemTrimResponse, 1);
1324
1325 do {
1326 GuestFilesystemTrimResult *res;
1327 PWCHAR uc_path;
1328 DWORD char_count = 0;
1329 char *path, *out;
1330 GError *gerr = NULL;
1331 gchar *argv[4];
1332
1333 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1334
1335 if (GetLastError() != ERROR_MORE_DATA) {
1336 continue;
1337 }
1338 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1339 continue;
1340 }
1341
1342 uc_path = g_malloc(sizeof(WCHAR) * char_count);
1343 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1344 &char_count) || !*uc_path) {
1345 /* strange, but this condition could be faced even with size == 2 */
1346 g_free(uc_path);
1347 continue;
1348 }
1349
1350 res = g_new0(GuestFilesystemTrimResult, 1);
1351
1352 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1353
1354 g_free(uc_path);
1355
1356 if (!path) {
1357 res->has_error = true;
1358 res->error = g_strdup(gerr->message);
1359 g_error_free(gerr);
1360 break;
1361 }
1362
1363 res->path = path;
1364
1365 QAPI_LIST_PREPEND(resp->paths, res);
1366
1367 memset(argv, 0, sizeof(argv));
1368 argv[0] = (gchar *)"defrag.exe";
1369 argv[1] = (gchar *)"/L";
1370 argv[2] = path;
1371
1372 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1373 &out /* stdout */, NULL /* stdin */,
1374 NULL, &gerr)) {
1375 res->has_error = true;
1376 res->error = g_strdup(gerr->message);
1377 g_error_free(gerr);
1378 } else {
1379 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1380 Error is reported in the output with something like
1381 (x89000020) etc code in the stdout */
1382
1383 int i;
1384 gchar **lines = g_strsplit(out, "\r\n", 0);
1385 g_free(out);
1386
1387 for (i = 0; lines[i] != NULL; i++) {
1388 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1389 continue;
1390 }
1391 res->has_error = true;
1392 res->error = g_strdup(lines[i]);
1393 break;
1394 }
1395 g_strfreev(lines);
1396 }
1397 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1398
1399 FindVolumeClose(handle);
1400 return resp;
1401 }
1402
1403 typedef enum {
1404 GUEST_SUSPEND_MODE_DISK,
1405 GUEST_SUSPEND_MODE_RAM
1406 } GuestSuspendMode;
1407
1408 static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
1409 {
1410 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1411
1412 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1413 if (!GetPwrCapabilities(&sys_pwr_caps)) {
1414 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1415 "failed to determine guest suspend capabilities");
1416 return;
1417 }
1418
1419 switch (mode) {
1420 case GUEST_SUSPEND_MODE_DISK:
1421 if (!sys_pwr_caps.SystemS4) {
1422 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1423 "suspend-to-disk not supported by OS");
1424 }
1425 break;
1426 case GUEST_SUSPEND_MODE_RAM:
1427 if (!sys_pwr_caps.SystemS3) {
1428 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1429 "suspend-to-ram not supported by OS");
1430 }
1431 break;
1432 default:
1433 abort();
1434 }
1435 }
1436
1437 static DWORD WINAPI do_suspend(LPVOID opaque)
1438 {
1439 GuestSuspendMode *mode = opaque;
1440 DWORD ret = 0;
1441
1442 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
1443 g_autofree gchar *emsg = g_win32_error_message(GetLastError());
1444 slog("failed to suspend guest: %s", emsg);
1445 ret = -1;
1446 }
1447 g_free(mode);
1448 return ret;
1449 }
1450
1451 void qmp_guest_suspend_disk(Error **errp)
1452 {
1453 Error *local_err = NULL;
1454 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1455
1456 *mode = GUEST_SUSPEND_MODE_DISK;
1457 check_suspend_mode(*mode, &local_err);
1458 if (local_err) {
1459 goto out;
1460 }
1461 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1462 if (local_err) {
1463 goto out;
1464 }
1465 execute_async(do_suspend, mode, &local_err);
1466
1467 out:
1468 if (local_err) {
1469 error_propagate(errp, local_err);
1470 g_free(mode);
1471 }
1472 }
1473
1474 void qmp_guest_suspend_ram(Error **errp)
1475 {
1476 Error *local_err = NULL;
1477 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1478
1479 *mode = GUEST_SUSPEND_MODE_RAM;
1480 check_suspend_mode(*mode, &local_err);
1481 if (local_err) {
1482 goto out;
1483 }
1484 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1485 if (local_err) {
1486 goto out;
1487 }
1488 execute_async(do_suspend, mode, &local_err);
1489
1490 out:
1491 if (local_err) {
1492 error_propagate(errp, local_err);
1493 g_free(mode);
1494 }
1495 }
1496
1497 void qmp_guest_suspend_hybrid(Error **errp)
1498 {
1499 error_setg(errp, QERR_UNSUPPORTED);
1500 }
1501
1502 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1503 {
1504 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1505 ULONG adptr_addrs_len = 0;
1506 DWORD ret;
1507
1508 /* Call the first time to get the adptr_addrs_len. */
1509 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1510 NULL, adptr_addrs, &adptr_addrs_len);
1511
1512 adptr_addrs = g_malloc(adptr_addrs_len);
1513 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1514 NULL, adptr_addrs, &adptr_addrs_len);
1515 if (ret != ERROR_SUCCESS) {
1516 error_setg_win32(errp, ret, "failed to get adapters addresses");
1517 g_free(adptr_addrs);
1518 adptr_addrs = NULL;
1519 }
1520 return adptr_addrs;
1521 }
1522
1523 static char *guest_wctomb_dup(WCHAR *wstr)
1524 {
1525 char *str;
1526 size_t str_size;
1527
1528 str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
1529 /* add 1 to str_size for NULL terminator */
1530 str = g_malloc(str_size + 1);
1531 WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
1532 return str;
1533 }
1534
1535 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1536 Error **errp)
1537 {
1538 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1539 DWORD len;
1540 int ret;
1541
1542 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1543 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1544 len = sizeof(addr_str);
1545 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1546 ip_addr->Address.iSockaddrLength,
1547 NULL,
1548 addr_str,
1549 &len);
1550 if (ret != 0) {
1551 error_setg_win32(errp, WSAGetLastError(),
1552 "failed address presentation form conversion");
1553 return NULL;
1554 }
1555 return g_strdup(addr_str);
1556 }
1557 return NULL;
1558 }
1559
1560 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1561 {
1562 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1563 * field to obtain the prefix.
1564 */
1565 return ip_addr->OnLinkPrefixLength;
1566 }
1567
1568 #define INTERFACE_PATH_BUF_SZ 512
1569
1570 static DWORD get_interface_index(const char *guid)
1571 {
1572 ULONG index;
1573 DWORD status;
1574 wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1575 snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1576 wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1577 status = GetAdapterIndex (wbuf, &index);
1578 if (status != NO_ERROR) {
1579 return (DWORD)~0;
1580 } else {
1581 return index;
1582 }
1583 }
1584
1585 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1586
1587 static int guest_get_network_stats(const char *name,
1588 GuestNetworkInterfaceStat *stats)
1589 {
1590 OSVERSIONINFO os_ver;
1591
1592 os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1593 GetVersionEx(&os_ver);
1594 if (os_ver.dwMajorVersion >= 6) {
1595 MIB_IF_ROW2 a_mid_ifrow;
1596 GetIfEntry2Func getifentry2_ex;
1597 DWORD if_index = 0;
1598 HMODULE module = GetModuleHandle("iphlpapi");
1599 PVOID func = GetProcAddress(module, "GetIfEntry2");
1600
1601 if (func == NULL) {
1602 return -1;
1603 }
1604
1605 getifentry2_ex = (GetIfEntry2Func)func;
1606 if_index = get_interface_index(name);
1607 if (if_index == (DWORD)~0) {
1608 return -1;
1609 }
1610
1611 memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1612 a_mid_ifrow.InterfaceIndex = if_index;
1613 if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1614 stats->rx_bytes = a_mid_ifrow.InOctets;
1615 stats->rx_packets = a_mid_ifrow.InUcastPkts;
1616 stats->rx_errs = a_mid_ifrow.InErrors;
1617 stats->rx_dropped = a_mid_ifrow.InDiscards;
1618 stats->tx_bytes = a_mid_ifrow.OutOctets;
1619 stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1620 stats->tx_errs = a_mid_ifrow.OutErrors;
1621 stats->tx_dropped = a_mid_ifrow.OutDiscards;
1622 return 0;
1623 }
1624 }
1625 return -1;
1626 }
1627
1628 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1629 {
1630 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1631 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1632 GuestNetworkInterfaceList *head = NULL, **tail = &head;
1633 GuestIpAddressList *head_addr, **tail_addr;
1634 GuestNetworkInterface *info;
1635 GuestNetworkInterfaceStat *interface_stat = NULL;
1636 GuestIpAddress *address_item = NULL;
1637 unsigned char *mac_addr;
1638 char *addr_str;
1639 WORD wsa_version;
1640 WSADATA wsa_data;
1641 int ret;
1642
1643 adptr_addrs = guest_get_adapters_addresses(errp);
1644 if (adptr_addrs == NULL) {
1645 return NULL;
1646 }
1647
1648 /* Make WSA APIs available. */
1649 wsa_version = MAKEWORD(2, 2);
1650 ret = WSAStartup(wsa_version, &wsa_data);
1651 if (ret != 0) {
1652 error_setg_win32(errp, ret, "failed socket startup");
1653 goto out;
1654 }
1655
1656 for (addr = adptr_addrs; addr; addr = addr->Next) {
1657 info = g_malloc0(sizeof(*info));
1658
1659 QAPI_LIST_APPEND(tail, info);
1660
1661 info->name = guest_wctomb_dup(addr->FriendlyName);
1662
1663 if (addr->PhysicalAddressLength != 0) {
1664 mac_addr = addr->PhysicalAddress;
1665
1666 info->hardware_address =
1667 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1668 (int) mac_addr[0], (int) mac_addr[1],
1669 (int) mac_addr[2], (int) mac_addr[3],
1670 (int) mac_addr[4], (int) mac_addr[5]);
1671
1672 info->has_hardware_address = true;
1673 }
1674
1675 head_addr = NULL;
1676 tail_addr = &head_addr;
1677 for (ip_addr = addr->FirstUnicastAddress;
1678 ip_addr;
1679 ip_addr = ip_addr->Next) {
1680 addr_str = guest_addr_to_str(ip_addr, errp);
1681 if (addr_str == NULL) {
1682 continue;
1683 }
1684
1685 address_item = g_malloc0(sizeof(*address_item));
1686
1687 QAPI_LIST_APPEND(tail_addr, address_item);
1688
1689 address_item->ip_address = addr_str;
1690 address_item->prefix = guest_ip_prefix(ip_addr);
1691 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1692 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1693 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1694 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1695 }
1696 }
1697 if (head_addr) {
1698 info->has_ip_addresses = true;
1699 info->ip_addresses = head_addr;
1700 }
1701 if (!info->has_statistics) {
1702 interface_stat = g_malloc0(sizeof(*interface_stat));
1703 if (guest_get_network_stats(addr->AdapterName,
1704 interface_stat) == -1) {
1705 info->has_statistics = false;
1706 g_free(interface_stat);
1707 } else {
1708 info->statistics = interface_stat;
1709 info->has_statistics = true;
1710 }
1711 }
1712 }
1713 WSACleanup();
1714 out:
1715 g_free(adptr_addrs);
1716 return head;
1717 }
1718
1719 static int64_t filetime_to_ns(const FILETIME *tf)
1720 {
1721 return ((((int64_t)tf->dwHighDateTime << 32) | tf->dwLowDateTime)
1722 - W32_FT_OFFSET) * 100;
1723 }
1724
1725 int64_t qmp_guest_get_time(Error **errp)
1726 {
1727 SYSTEMTIME ts = {0};
1728 FILETIME tf;
1729
1730 GetSystemTime(&ts);
1731 if (ts.wYear < 1601 || ts.wYear > 30827) {
1732 error_setg(errp, "Failed to get time");
1733 return -1;
1734 }
1735
1736 if (!SystemTimeToFileTime(&ts, &tf)) {
1737 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1738 return -1;
1739 }
1740
1741 return filetime_to_ns(&tf);
1742 }
1743
1744 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1745 {
1746 Error *local_err = NULL;
1747 SYSTEMTIME ts;
1748 FILETIME tf;
1749 LONGLONG time;
1750
1751 if (!has_time) {
1752 /* Unfortunately, Windows libraries don't provide an easy way to access
1753 * RTC yet:
1754 *
1755 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1756 *
1757 * Instead, a workaround is to use the Windows win32tm command to
1758 * resync the time using the Windows Time service.
1759 */
1760 LPVOID msg_buffer;
1761 DWORD ret_flags;
1762
1763 HRESULT hr = system("w32tm /resync /nowait");
1764
1765 if (GetLastError() != 0) {
1766 strerror_s((LPTSTR) & msg_buffer, 0, errno);
1767 error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1768 } else if (hr != 0) {
1769 if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1770 error_setg(errp, "Windows Time service not running on the "
1771 "guest");
1772 } else {
1773 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1774 FORMAT_MESSAGE_FROM_SYSTEM |
1775 FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1776 (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1777 SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1778 NULL)) {
1779 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1780 "t retrieve error message", hr);
1781 } else {
1782 error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1783 (LPCTSTR)msg_buffer);
1784 LocalFree(msg_buffer);
1785 }
1786 }
1787 } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1788 error_setg(errp, "No internet connection on guest, sync not "
1789 "accurate");
1790 }
1791 return;
1792 }
1793
1794 /* Validate time passed by user. */
1795 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1796 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1797 return;
1798 }
1799
1800 time = time_ns / 100 + W32_FT_OFFSET;
1801
1802 tf.dwLowDateTime = (DWORD) time;
1803 tf.dwHighDateTime = (DWORD) (time >> 32);
1804
1805 if (!FileTimeToSystemTime(&tf, &ts)) {
1806 error_setg(errp, "Failed to convert system time %d",
1807 (int)GetLastError());
1808 return;
1809 }
1810
1811 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1812 if (local_err) {
1813 error_propagate(errp, local_err);
1814 return;
1815 }
1816
1817 if (!SetSystemTime(&ts)) {
1818 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1819 return;
1820 }
1821 }
1822
1823 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1824 {
1825 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1826 DWORD length;
1827 GuestLogicalProcessorList *head, **tail;
1828 Error *local_err = NULL;
1829 int64_t current;
1830
1831 ptr = pslpi = NULL;
1832 length = 0;
1833 current = 0;
1834 head = NULL;
1835 tail = &head;
1836
1837 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1838 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1839 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1840 ptr = pslpi = g_malloc0(length);
1841 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1842 error_setg(&local_err, "Failed to get processor information: %d",
1843 (int)GetLastError());
1844 }
1845 } else {
1846 error_setg(&local_err,
1847 "Failed to get processor information buffer length: %d",
1848 (int)GetLastError());
1849 }
1850
1851 while ((local_err == NULL) && (length > 0)) {
1852 if (pslpi->Relationship == RelationProcessorCore) {
1853 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1854
1855 while (cpu_bits > 0) {
1856 if (!!(cpu_bits & 1)) {
1857 GuestLogicalProcessor *vcpu;
1858
1859 vcpu = g_malloc0(sizeof *vcpu);
1860 vcpu->logical_id = current++;
1861 vcpu->online = true;
1862 vcpu->has_can_offline = true;
1863
1864 QAPI_LIST_APPEND(tail, vcpu);
1865 }
1866 cpu_bits >>= 1;
1867 }
1868 }
1869 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1870 pslpi++; /* next entry */
1871 }
1872
1873 g_free(ptr);
1874
1875 if (local_err == NULL) {
1876 if (head != NULL) {
1877 return head;
1878 }
1879 /* there's no guest with zero VCPUs */
1880 error_setg(&local_err, "Guest reported zero VCPUs");
1881 }
1882
1883 qapi_free_GuestLogicalProcessorList(head);
1884 error_propagate(errp, local_err);
1885 return NULL;
1886 }
1887
1888 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1889 {
1890 error_setg(errp, QERR_UNSUPPORTED);
1891 return -1;
1892 }
1893
1894 static gchar *
1895 get_net_error_message(gint error)
1896 {
1897 HMODULE module = NULL;
1898 gchar *retval = NULL;
1899 wchar_t *msg = NULL;
1900 int flags;
1901 size_t nchars;
1902
1903 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1904 FORMAT_MESSAGE_IGNORE_INSERTS |
1905 FORMAT_MESSAGE_FROM_SYSTEM;
1906
1907 if (error >= NERR_BASE && error <= MAX_NERR) {
1908 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1909
1910 if (module != NULL) {
1911 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1912 }
1913 }
1914
1915 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1916
1917 if (msg != NULL) {
1918 nchars = wcslen(msg);
1919
1920 if (nchars >= 2 &&
1921 msg[nchars - 1] == L'\n' &&
1922 msg[nchars - 2] == L'\r') {
1923 msg[nchars - 2] = L'\0';
1924 }
1925
1926 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1927
1928 LocalFree(msg);
1929 }
1930
1931 if (module != NULL) {
1932 FreeLibrary(module);
1933 }
1934
1935 return retval;
1936 }
1937
1938 void qmp_guest_set_user_password(const char *username,
1939 const char *password,
1940 bool crypted,
1941 Error **errp)
1942 {
1943 NET_API_STATUS nas;
1944 char *rawpasswddata = NULL;
1945 size_t rawpasswdlen;
1946 wchar_t *user = NULL, *wpass = NULL;
1947 USER_INFO_1003 pi1003 = { 0, };
1948 GError *gerr = NULL;
1949
1950 if (crypted) {
1951 error_setg(errp, QERR_UNSUPPORTED);
1952 return;
1953 }
1954
1955 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1956 if (!rawpasswddata) {
1957 return;
1958 }
1959 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1960 rawpasswddata[rawpasswdlen] = '\0';
1961
1962 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1963 if (!user) {
1964 goto done;
1965 }
1966
1967 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1968 if (!wpass) {
1969 goto done;
1970 }
1971
1972 pi1003.usri1003_password = wpass;
1973 nas = NetUserSetInfo(NULL, user,
1974 1003, (LPBYTE)&pi1003,
1975 NULL);
1976
1977 if (nas != NERR_Success) {
1978 gchar *msg = get_net_error_message(nas);
1979 error_setg(errp, "failed to set password: %s", msg);
1980 g_free(msg);
1981 }
1982
1983 done:
1984 if (gerr) {
1985 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1986 g_error_free(gerr);
1987 }
1988 g_free(user);
1989 g_free(wpass);
1990 g_free(rawpasswddata);
1991 }
1992
1993 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1994 {
1995 error_setg(errp, QERR_UNSUPPORTED);
1996 return NULL;
1997 }
1998
1999 GuestMemoryBlockResponseList *
2000 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2001 {
2002 error_setg(errp, QERR_UNSUPPORTED);
2003 return NULL;
2004 }
2005
2006 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2007 {
2008 error_setg(errp, QERR_UNSUPPORTED);
2009 return NULL;
2010 }
2011
2012 /* add unsupported commands to the blacklist */
2013 GList *ga_command_blacklist_init(GList *blacklist)
2014 {
2015 const char *list_unsupported[] = {
2016 "guest-suspend-hybrid",
2017 "guest-set-vcpus",
2018 "guest-get-memory-blocks", "guest-set-memory-blocks",
2019 "guest-get-memory-block-size", "guest-get-memory-block-info",
2020 NULL};
2021 char **p = (char **)list_unsupported;
2022
2023 while (*p) {
2024 blacklist = g_list_append(blacklist, g_strdup(*p++));
2025 }
2026
2027 if (!vss_init(true)) {
2028 g_debug("vss_init failed, vss commands are going to be disabled");
2029 const char *list[] = {
2030 "guest-get-fsinfo", "guest-fsfreeze-status",
2031 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
2032 p = (char **)list;
2033
2034 while (*p) {
2035 blacklist = g_list_append(blacklist, g_strdup(*p++));
2036 }
2037 }
2038
2039 return blacklist;
2040 }
2041
2042 /* register init/cleanup routines for stateful command groups */
2043 void ga_command_state_init(GAState *s, GACommandState *cs)
2044 {
2045 if (!vss_initialized()) {
2046 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2047 }
2048 }
2049
2050 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
2051 typedef struct _GA_WTSINFOA {
2052 WTS_CONNECTSTATE_CLASS State;
2053 DWORD SessionId;
2054 DWORD IncomingBytes;
2055 DWORD OutgoingBytes;
2056 DWORD IncomingFrames;
2057 DWORD OutgoingFrames;
2058 DWORD IncomingCompressedBytes;
2059 DWORD OutgoingCompressedBy;
2060 CHAR WinStationName[WINSTATIONNAME_LENGTH];
2061 CHAR Domain[DOMAIN_LENGTH];
2062 CHAR UserName[USERNAME_LENGTH + 1];
2063 LARGE_INTEGER ConnectTime;
2064 LARGE_INTEGER DisconnectTime;
2065 LARGE_INTEGER LastInputTime;
2066 LARGE_INTEGER LogonTime;
2067 LARGE_INTEGER CurrentTime;
2068
2069 } GA_WTSINFOA;
2070
2071 GuestUserList *qmp_guest_get_users(Error **errp)
2072 {
2073 #define QGA_NANOSECONDS 10000000
2074
2075 GHashTable *cache = NULL;
2076 GuestUserList *head = NULL, **tail = &head;
2077
2078 DWORD buffer_size = 0, count = 0, i = 0;
2079 GA_WTSINFOA *info = NULL;
2080 WTS_SESSION_INFOA *entries = NULL;
2081 GuestUser *user = NULL;
2082 gpointer value = NULL;
2083 INT64 login = 0;
2084 double login_time = 0;
2085
2086 cache = g_hash_table_new(g_str_hash, g_str_equal);
2087
2088 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
2089 for (i = 0; i < count; ++i) {
2090 buffer_size = 0;
2091 info = NULL;
2092 if (WTSQuerySessionInformationA(
2093 NULL,
2094 entries[i].SessionId,
2095 WTSSessionInfo,
2096 (LPSTR *)&info,
2097 &buffer_size
2098 )) {
2099
2100 if (strlen(info->UserName) == 0) {
2101 WTSFreeMemory(info);
2102 continue;
2103 }
2104
2105 login = info->LogonTime.QuadPart;
2106 login -= W32_FT_OFFSET;
2107 login_time = ((double)login) / QGA_NANOSECONDS;
2108
2109 if (g_hash_table_contains(cache, info->UserName)) {
2110 value = g_hash_table_lookup(cache, info->UserName);
2111 user = (GuestUser *)value;
2112 if (user->login_time > login_time) {
2113 user->login_time = login_time;
2114 }
2115 } else {
2116 user = g_new0(GuestUser, 1);
2117
2118 user->user = g_strdup(info->UserName);
2119 user->domain = g_strdup(info->Domain);
2120 user->has_domain = true;
2121
2122 user->login_time = login_time;
2123
2124 g_hash_table_add(cache, user->user);
2125
2126 QAPI_LIST_APPEND(tail, user);
2127 }
2128 }
2129 WTSFreeMemory(info);
2130 }
2131 WTSFreeMemory(entries);
2132 }
2133 g_hash_table_destroy(cache);
2134 return head;
2135 }
2136
2137 typedef struct _ga_matrix_lookup_t {
2138 int major;
2139 int minor;
2140 char const *version;
2141 char const *version_id;
2142 } ga_matrix_lookup_t;
2143
2144 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
2145 {
2146 /* Desktop editions */
2147 { 5, 0, "Microsoft Windows 2000", "2000"},
2148 { 5, 1, "Microsoft Windows XP", "xp"},
2149 { 6, 0, "Microsoft Windows Vista", "vista"},
2150 { 6, 1, "Microsoft Windows 7" "7"},
2151 { 6, 2, "Microsoft Windows 8", "8"},
2152 { 6, 3, "Microsoft Windows 8.1", "8.1"},
2153 {10, 0, "Microsoft Windows 10", "10"},
2154 { 0, 0, 0}
2155 },{
2156 /* Server editions */
2157 { 5, 2, "Microsoft Windows Server 2003", "2003"},
2158 { 6, 0, "Microsoft Windows Server 2008", "2008"},
2159 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
2160 { 6, 2, "Microsoft Windows Server 2012", "2012"},
2161 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
2162 { 0, 0, 0},
2163 { 0, 0, 0},
2164 { 0, 0, 0}
2165 }
2166 };
2167
2168 typedef struct _ga_win_10_0_server_t {
2169 int final_build;
2170 char const *version;
2171 char const *version_id;
2172 } ga_win_10_0_server_t;
2173
2174 static ga_win_10_0_server_t const WIN_10_0_SERVER_VERSION_MATRIX[4] = {
2175 {14393, "Microsoft Windows Server 2016", "2016"},
2176 {17763, "Microsoft Windows Server 2019", "2019"},
2177 {20344, "Microsoft Windows Server 2022", "2022"},
2178 {0, 0}
2179 };
2180
2181 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2182 {
2183 typedef NTSTATUS(WINAPI *rtl_get_version_t)(
2184 RTL_OSVERSIONINFOEXW *os_version_info_ex);
2185
2186 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2187
2188 HMODULE module = GetModuleHandle("ntdll");
2189 PVOID fun = GetProcAddress(module, "RtlGetVersion");
2190 if (fun == NULL) {
2191 error_setg(errp, QERR_QGA_COMMAND_FAILED,
2192 "Failed to get address of RtlGetVersion");
2193 return;
2194 }
2195
2196 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2197 rtl_get_version(info);
2198 return;
2199 }
2200
2201 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
2202 {
2203 DWORD major = os_version->dwMajorVersion;
2204 DWORD minor = os_version->dwMinorVersion;
2205 DWORD build = os_version->dwBuildNumber;
2206 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2207 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
2208 ga_win_10_0_server_t const *win_10_0_table = WIN_10_0_SERVER_VERSION_MATRIX;
2209 while (table->version != NULL) {
2210 if (major == 10 && minor == 0 && tbl_idx) {
2211 while (win_10_0_table->version != NULL) {
2212 if (build <= win_10_0_table->final_build) {
2213 if (id) {
2214 return g_strdup(win_10_0_table->version_id);
2215 } else {
2216 return g_strdup(win_10_0_table->version);
2217 }
2218 }
2219 win_10_0_table++;
2220 }
2221 } else if (major == table->major && minor == table->minor) {
2222 if (id) {
2223 return g_strdup(table->version_id);
2224 } else {
2225 return g_strdup(table->version);
2226 }
2227 }
2228 ++table;
2229 }
2230 slog("failed to lookup Windows version: major=%lu, minor=%lu",
2231 major, minor);
2232 return g_strdup("N/A");
2233 }
2234
2235 static char *ga_get_win_product_name(Error **errp)
2236 {
2237 HKEY key = INVALID_HANDLE_VALUE;
2238 DWORD size = 128;
2239 char *result = g_malloc0(size);
2240 LONG err = ERROR_SUCCESS;
2241
2242 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2243 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2244 &key);
2245 if (err != ERROR_SUCCESS) {
2246 error_setg_win32(errp, err, "failed to open registry key");
2247 g_free(result);
2248 return NULL;
2249 }
2250
2251 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2252 (LPBYTE)result, &size);
2253 if (err == ERROR_MORE_DATA) {
2254 slog("ProductName longer than expected (%lu bytes), retrying",
2255 size);
2256 g_free(result);
2257 result = NULL;
2258 if (size > 0) {
2259 result = g_malloc0(size);
2260 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2261 (LPBYTE)result, &size);
2262 }
2263 }
2264 if (err != ERROR_SUCCESS) {
2265 error_setg_win32(errp, err, "failed to retrive ProductName");
2266 goto fail;
2267 }
2268
2269 RegCloseKey(key);
2270 return result;
2271
2272 fail:
2273 if (key != INVALID_HANDLE_VALUE) {
2274 RegCloseKey(key);
2275 }
2276 g_free(result);
2277 return NULL;
2278 }
2279
2280 static char *ga_get_current_arch(void)
2281 {
2282 SYSTEM_INFO info;
2283 GetNativeSystemInfo(&info);
2284 char *result = NULL;
2285 switch (info.wProcessorArchitecture) {
2286 case PROCESSOR_ARCHITECTURE_AMD64:
2287 result = g_strdup("x86_64");
2288 break;
2289 case PROCESSOR_ARCHITECTURE_ARM:
2290 result = g_strdup("arm");
2291 break;
2292 case PROCESSOR_ARCHITECTURE_IA64:
2293 result = g_strdup("ia64");
2294 break;
2295 case PROCESSOR_ARCHITECTURE_INTEL:
2296 result = g_strdup("x86");
2297 break;
2298 case PROCESSOR_ARCHITECTURE_UNKNOWN:
2299 default:
2300 slog("unknown processor architecture 0x%0x",
2301 info.wProcessorArchitecture);
2302 result = g_strdup("unknown");
2303 break;
2304 }
2305 return result;
2306 }
2307
2308 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2309 {
2310 Error *local_err = NULL;
2311 OSVERSIONINFOEXW os_version = {0};
2312 bool server;
2313 char *product_name;
2314 GuestOSInfo *info;
2315
2316 ga_get_win_version(&os_version, &local_err);
2317 if (local_err) {
2318 error_propagate(errp, local_err);
2319 return NULL;
2320 }
2321
2322 server = os_version.wProductType != VER_NT_WORKSTATION;
2323 product_name = ga_get_win_product_name(errp);
2324 if (product_name == NULL) {
2325 return NULL;
2326 }
2327
2328 info = g_new0(GuestOSInfo, 1);
2329
2330 info->has_kernel_version = true;
2331 info->kernel_version = g_strdup_printf("%lu.%lu",
2332 os_version.dwMajorVersion,
2333 os_version.dwMinorVersion);
2334 info->has_kernel_release = true;
2335 info->kernel_release = g_strdup_printf("%lu",
2336 os_version.dwBuildNumber);
2337 info->has_machine = true;
2338 info->machine = ga_get_current_arch();
2339
2340 info->has_id = true;
2341 info->id = g_strdup("mswindows");
2342 info->has_name = true;
2343 info->name = g_strdup("Microsoft Windows");
2344 info->has_pretty_name = true;
2345 info->pretty_name = product_name;
2346 info->has_version = true;
2347 info->version = ga_get_win_name(&os_version, false);
2348 info->has_version_id = true;
2349 info->version_id = ga_get_win_name(&os_version, true);
2350 info->has_variant = true;
2351 info->variant = g_strdup(server ? "server" : "client");
2352 info->has_variant_id = true;
2353 info->variant_id = g_strdup(server ? "server" : "client");
2354
2355 return info;
2356 }
2357
2358 /*
2359 * Safely get device property. Returned strings are using wide characters.
2360 * Caller is responsible for freeing the buffer.
2361 */
2362 static LPBYTE cm_get_property(DEVINST devInst, const DEVPROPKEY *propName,
2363 PDEVPROPTYPE propType)
2364 {
2365 CONFIGRET cr;
2366 g_autofree LPBYTE buffer = NULL;
2367 ULONG buffer_len = 0;
2368
2369 /* First query for needed space */
2370 cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2371 buffer, &buffer_len, 0);
2372 if (cr != CR_SUCCESS && cr != CR_BUFFER_SMALL) {
2373
2374 slog("failed to get property size, error=0x%lx", cr);
2375 return NULL;
2376 }
2377 buffer = g_new0(BYTE, buffer_len + 1);
2378 cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
2379 buffer, &buffer_len, 0);
2380 if (cr != CR_SUCCESS) {
2381 slog("failed to get device property, error=0x%lx", cr);
2382 return NULL;
2383 }
2384 return g_steal_pointer(&buffer);
2385 }
2386
2387 static GStrv ga_get_hardware_ids(DEVINST devInstance)
2388 {
2389 GArray *values = NULL;
2390 DEVPROPTYPE cm_type;
2391 LPWSTR id;
2392 g_autofree LPWSTR property = (LPWSTR)cm_get_property(devInstance,
2393 &qga_DEVPKEY_Device_HardwareIds, &cm_type);
2394 if (property == NULL) {
2395 slog("failed to get hardware IDs");
2396 return NULL;
2397 }
2398 if (*property == '\0') {
2399 /* empty list */
2400 return NULL;
2401 }
2402 values = g_array_new(TRUE, TRUE, sizeof(gchar *));
2403 for (id = property; '\0' != *id; id += lstrlenW(id) + 1) {
2404 gchar *id8 = g_utf16_to_utf8(id, -1, NULL, NULL, NULL);
2405 g_array_append_val(values, id8);
2406 }
2407 return (GStrv)g_array_free(values, FALSE);
2408 }
2409
2410 /*
2411 * https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
2412 */
2413 #define DEVICE_PCI_RE "PCI\\\\VEN_(1AF4|1B36)&DEV_([0-9A-B]{4})(&|$)"
2414
2415 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
2416 {
2417 GuestDeviceInfoList *head = NULL, **tail = &head;
2418 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2419 SP_DEVINFO_DATA dev_info_data;
2420 int i, j;
2421 GError *gerr = NULL;
2422 g_autoptr(GRegex) device_pci_re = NULL;
2423 DEVPROPTYPE cm_type;
2424
2425 device_pci_re = g_regex_new(DEVICE_PCI_RE,
2426 G_REGEX_ANCHORED | G_REGEX_OPTIMIZE, 0,
2427 &gerr);
2428 g_assert(device_pci_re != NULL);
2429
2430 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
2431 dev_info = SetupDiGetClassDevs(0, 0, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES);
2432 if (dev_info == INVALID_HANDLE_VALUE) {
2433 error_setg(errp, "failed to get device tree");
2434 return NULL;
2435 }
2436
2437 slog("enumerating devices");
2438 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
2439 bool skip = true;
2440 g_autofree LPWSTR name = NULL;
2441 g_autofree LPFILETIME date = NULL;
2442 g_autofree LPWSTR version = NULL;
2443 g_auto(GStrv) hw_ids = NULL;
2444 g_autoptr(GuestDeviceInfo) device = g_new0(GuestDeviceInfo, 1);
2445 g_autofree char *vendor_id = NULL;
2446 g_autofree char *device_id = NULL;
2447
2448 name = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2449 &qga_DEVPKEY_NAME, &cm_type);
2450 if (name == NULL) {
2451 slog("failed to get device description");
2452 continue;
2453 }
2454 device->driver_name = g_utf16_to_utf8(name, -1, NULL, NULL, NULL);
2455 if (device->driver_name == NULL) {
2456 error_setg(errp, "conversion to utf8 failed (driver name)");
2457 return NULL;
2458 }
2459 slog("querying device: %s", device->driver_name);
2460 hw_ids = ga_get_hardware_ids(dev_info_data.DevInst);
2461 if (hw_ids == NULL) {
2462 continue;
2463 }
2464 for (j = 0; hw_ids[j] != NULL; j++) {
2465 g_autoptr(GMatchInfo) match_info;
2466 GuestDeviceIdPCI *id;
2467 if (!g_regex_match(device_pci_re, hw_ids[j], 0, &match_info)) {
2468 continue;
2469 }
2470 skip = false;
2471
2472 vendor_id = g_match_info_fetch(match_info, 1);
2473 device_id = g_match_info_fetch(match_info, 2);
2474
2475 device->id = g_new0(GuestDeviceId, 1);
2476 device->has_id = true;
2477 device->id->type = GUEST_DEVICE_TYPE_PCI;
2478 id = &device->id->u.pci;
2479 id->vendor_id = g_ascii_strtoull(vendor_id, NULL, 16);
2480 id->device_id = g_ascii_strtoull(device_id, NULL, 16);
2481
2482 break;
2483 }
2484 if (skip) {
2485 continue;
2486 }
2487
2488 version = (LPWSTR)cm_get_property(dev_info_data.DevInst,
2489 &qga_DEVPKEY_Device_DriverVersion, &cm_type);
2490 if (version == NULL) {
2491 slog("failed to get driver version");
2492 continue;
2493 }
2494 device->driver_version = g_utf16_to_utf8(version, -1, NULL,
2495 NULL, NULL);
2496 if (device->driver_version == NULL) {
2497 error_setg(errp, "conversion to utf8 failed (driver version)");
2498 return NULL;
2499 }
2500 device->has_driver_version = true;
2501
2502 date = (LPFILETIME)cm_get_property(dev_info_data.DevInst,
2503 &qga_DEVPKEY_Device_DriverDate, &cm_type);
2504 if (date == NULL) {
2505 slog("failed to get driver date");
2506 continue;
2507 }
2508 device->driver_date = filetime_to_ns(date);
2509 device->has_driver_date = true;
2510
2511 slog("driver: %s\ndriver version: %" PRId64 ",%s\n",
2512 device->driver_name, device->driver_date,
2513 device->driver_version);
2514 QAPI_LIST_APPEND(tail, g_steal_pointer(&device));
2515 }
2516
2517 if (dev_info != INVALID_HANDLE_VALUE) {
2518 SetupDiDestroyDeviceInfoList(dev_info);
2519 }
2520 return head;
2521 }