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