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