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