]> Git Repo - qemu.git/blame - qga/commands-win32.c
qga-win: refactor disk info
[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 <[email protected]>
aa59637e 8 * Gal Hammer <[email protected]>
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
c54e1eb4
MR
494DEFINE_GUID(GUID_DEVINTERFACE_VOLUME,
495 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2,
496 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
497
a3ef3b22
OK
498static GuestPCIAddress *get_pci_info(char *guid, Error **errp)
499{
c54e1eb4
MR
500 HDEVINFO dev_info;
501 SP_DEVINFO_DATA dev_info_data;
502 DWORD size = 0;
503 int i;
504 char dev_name[MAX_PATH];
505 char *buffer = NULL;
506 GuestPCIAddress *pci = NULL;
507 char *name = g_strdup(&guid[4]);
6880b94f 508 bool partial_pci = false;
0d7f937e
SJ
509 pci = g_malloc0(sizeof(*pci));
510 pci->domain = -1;
511 pci->slot = -1;
512 pci->function = -1;
513 pci->bus = -1;
c54e1eb4
MR
514
515 if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {
516 error_setg_win32(errp, GetLastError(), "failed to get dos device name");
517 goto out;
518 }
519
520 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, 0, 0,
521 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
522 if (dev_info == INVALID_HANDLE_VALUE) {
523 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
524 goto out;
525 }
526
222682ab 527 g_debug("enumerating devices");
c54e1eb4
MR
528 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
529 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
6880b94f
SJ
530 DWORD addr, bus, slot, data, size2;
531 int func, dev;
c54e1eb4
MR
532 while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
533 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
534 &data, (PBYTE)buffer, size,
535 &size2)) {
536 size = MAX(size, size2);
537 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
538 g_free(buffer);
539 /* Double the size to avoid problems on
540 * W2k MBCS systems per KB 888609.
541 * https://support.microsoft.com/en-us/kb/259695 */
542 buffer = g_malloc(size * 2);
543 } else {
544 error_setg_win32(errp, GetLastError(),
545 "failed to get device name");
9bd8e933 546 goto free_dev_info;
c54e1eb4
MR
547 }
548 }
549
550 if (g_strcmp0(buffer, dev_name)) {
551 continue;
552 }
222682ab 553 g_debug("found device %s", dev_name);
c54e1eb4
MR
554
555 /* There is no need to allocate buffer in the next functions. The size
556 * is known and ULONG according to
557 * https://support.microsoft.com/en-us/kb/253232
558 * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
559 */
560 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
561 SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {
222682ab 562 debug_error("failed to get bus");
6880b94f
SJ
563 bus = -1;
564 partial_pci = true;
c54e1eb4
MR
565 }
566
567 /* The function retrieves the device's address. This value will be
568 * transformed into device function and number */
569 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
570 SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {
222682ab 571 debug_error("failed to get address");
6880b94f
SJ
572 addr = -1;
573 partial_pci = true;
c54e1eb4
MR
574 }
575
576 /* This call returns UINumber of DEVICE_CAPABILITIES structure.
577 * This number is typically a user-perceived slot number. */
578 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
579 SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {
222682ab 580 debug_error("failed to get slot");
6880b94f
SJ
581 slot = -1;
582 partial_pci = true;
c54e1eb4
MR
583 }
584
585 /* SetupApi gives us the same information as driver with
586 * IoGetDeviceProperty. According to Microsoft
587 * https://support.microsoft.com/en-us/kb/253232
588 * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF);
589 * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF);
590 * SPDRP_ADDRESS is propertyAddress, so we do the same.*/
591
6880b94f
SJ
592 if (partial_pci) {
593 pci->domain = -1;
594 pci->slot = -1;
595 pci->function = -1;
596 pci->bus = -1;
597 } else {
598 func = ((int) addr == -1) ? -1 : addr & 0x0000FFFF;
599 dev = ((int) addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
600 pci->domain = dev;
601 pci->slot = (int) slot;
602 pci->function = func;
603 pci->bus = (int) bus;
604 }
c54e1eb4
MR
605 break;
606 }
9bd8e933
LP
607
608free_dev_info:
609 SetupDiDestroyDeviceInfoList(dev_info);
c54e1eb4
MR
610out:
611 g_free(buffer);
612 g_free(name);
613 return pci;
a3ef3b22
OK
614}
615
c76d70f4
TG
616static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
617 Error **errp)
a3ef3b22
OK
618{
619 STORAGE_PROPERTY_QUERY query;
620 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
621 DWORD received;
c76d70f4 622 ULONG size = sizeof(buf);
a3ef3b22
OK
623
624 dev_desc = &buf;
a3ef3b22
OK
625 query.PropertyId = StorageDeviceProperty;
626 query.QueryType = PropertyStandardQuery;
627
628 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
629 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
c76d70f4 630 size, &received, NULL)) {
a3ef3b22 631 error_setg_win32(errp, GetLastError(), "failed to get bus type");
c76d70f4 632 return;
a3ef3b22 633 }
c76d70f4
TG
634 disk->bus_type = find_bus_type(dev_desc->BusType);
635 g_debug("bus type %d", disk->bus_type);
a3ef3b22 636
fb08aa70
TG
637 /* Query once more. Now with long enough buffer. */
638 size = dev_desc->Size;
639 dev_desc = g_malloc0(size);
640 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
641 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
642 size, &received, NULL)) {
643 error_setg_win32(errp, GetLastError(), "failed to get serial number");
644 g_debug("failed to get serial number");
645 goto out_free;
646 }
647 if (dev_desc->SerialNumberOffset > 0) {
648 const char *serial;
649 size_t len;
650
651 if (dev_desc->SerialNumberOffset >= received) {
652 error_setg(errp, "failed to get serial number: offset outside the buffer");
653 g_debug("serial number offset outside the buffer");
654 goto out_free;
655 }
656 serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
657 len = received - dev_desc->SerialNumberOffset;
658 g_debug("serial number \"%s\"", serial);
659 if (*serial != 0) {
660 disk->serial = g_strndup(serial, len);
661 disk->has_serial = true;
662 }
663 }
664out_free:
665 g_free(dev_desc);
666
c76d70f4 667 return;
a3ef3b22
OK
668}
669
9e65fd65
TG
670static void get_single_disk_info(char *name, GuestDiskAddress *disk,
671 Error **errp)
a3ef3b22 672{
a3ef3b22
OK
673 SCSI_ADDRESS addr, *scsi_ad;
674 DWORD len;
a3ef3b22 675 HANDLE vol_h;
6880b94f 676 Error *local_err = NULL;
a3ef3b22
OK
677
678 scsi_ad = &addr;
a3ef3b22 679
222682ab 680 g_debug("getting disk info for: %s", name);
a3ef3b22
OK
681 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
682 0, NULL);
683 if (vol_h == INVALID_HANDLE_VALUE) {
684 error_setg_win32(errp, GetLastError(), "failed to open volume");
c76d70f4 685 goto err;
a3ef3b22
OK
686 }
687
c76d70f4
TG
688 get_disk_properties(vol_h, disk, &local_err);
689 if (local_err) {
690 error_propagate(errp, local_err);
691 goto err_close;
a3ef3b22
OK
692 }
693
222682ab 694 g_debug("bus type %d", disk->bus_type);
6880b94f
SJ
695 /* always set pci_controller as required by schema. get_pci_info() should
696 * report -1 values for non-PCI buses rather than fail. fail the command
697 * if that doesn't hold since that suggests some other unexpected
698 * breakage
699 */
700 disk->pci_controller = get_pci_info(name, &local_err);
701 if (local_err) {
702 error_propagate(errp, local_err);
c76d70f4 703 goto err_close;
6880b94f 704 }
c76d70f4
TG
705 if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
706 || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
707 || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
a3ef3b22
OK
708#if (_WIN32_WINNT >= 0x0600)
709 /* This bus type is not supported before Windows Server 2003 SP1 */
c76d70f4 710 || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
a3ef3b22
OK
711#endif
712 ) {
713 /* We are able to use the same ioctls for different bus types
714 * according to Microsoft docs
715 * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
222682ab 716 g_debug("getting pci-controller info");
a3ef3b22
OK
717 if (DeviceIoControl(vol_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
718 sizeof(SCSI_ADDRESS), &len, NULL)) {
719 disk->unit = addr.Lun;
720 disk->target = addr.TargetId;
721 disk->bus = addr.PathId;
a3ef3b22
OK
722 }
723 /* We do not set error in this case, because we still have enough
724 * information about volume. */
a3ef3b22
OK
725 }
726
c76d70f4 727err_close:
c76d70f4
TG
728 CloseHandle(vol_h);
729err:
9e65fd65
TG
730 return;
731}
732
733/* VSS provider works with volumes, thus there is no difference if
734 * the volume consist of spanned disks. Info about the first disk in the
735 * volume is returned for the spanned disk group (LVM) */
736static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
737{
738 Error *local_err = NULL;
739 GuestDiskAddressList *list = NULL, *cur_item = NULL;
740 GuestDiskAddress *disk = NULL;
741
742 /* strip final backslash */
743 char *name = g_strdup(guid);
744 if (g_str_has_suffix(name, "\\")) {
745 name[strlen(name) - 1] = 0;
746 }
747
748 disk = g_malloc0(sizeof(GuestDiskAddress));
749 get_single_disk_info(name, disk, &local_err);
750 if (local_err) {
751 error_propagate(errp, local_err);
752 goto out;
753 }
754
755 cur_item = g_malloc0(sizeof(*list));
756 cur_item->value = disk;
757 disk = NULL;
758 list = cur_item;
759
760out:
761 qapi_free_GuestDiskAddress(disk);
c76d70f4
TG
762 g_free(name);
763
9e65fd65 764 return list;
a3ef3b22
OK
765}
766
767#else
768
769static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
770{
771 return NULL;
772}
773
774#endif /* CONFIG_QGA_NTDDSCSI */
775
d2b3f390
OK
776static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
777{
778 DWORD info_size;
779 char mnt, *mnt_point;
780 char fs_name[32];
781 char vol_info[MAX_PATH+1];
782 size_t len;
c07e5e6e 783 uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
d2b3f390
OK
784 GuestFilesystemInfo *fs = NULL;
785
786 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
787 if (GetLastError() != ERROR_MORE_DATA) {
788 error_setg_win32(errp, GetLastError(), "failed to get volume name");
789 return NULL;
790 }
791
792 mnt_point = g_malloc(info_size + 1);
793 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
794 &info_size)) {
795 error_setg_win32(errp, GetLastError(), "failed to get volume name");
796 goto free;
797 }
798
799 len = strlen(mnt_point);
800 mnt_point[len] = '\\';
801 mnt_point[len+1] = 0;
802 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
803 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
804 if (GetLastError() != ERROR_NOT_READY) {
805 error_setg_win32(errp, GetLastError(), "failed to get volume info");
806 }
807 goto free;
808 }
809
810 fs_name[sizeof(fs_name) - 1] = 0;
811 fs = g_malloc(sizeof(*fs));
812 fs->name = g_strdup(guid);
c07e5e6e
CH
813 fs->has_total_bytes = false;
814 fs->has_used_bytes = false;
d2b3f390
OK
815 if (len == 0) {
816 fs->mountpoint = g_strdup("System Reserved");
817 } else {
818 fs->mountpoint = g_strndup(mnt_point, len);
c07e5e6e
CH
819 if (GetDiskFreeSpaceEx(fs->mountpoint,
820 (PULARGE_INTEGER) & i64FreeBytesToCaller,
821 (PULARGE_INTEGER) & i64TotalBytes,
822 (PULARGE_INTEGER) & i64FreeBytes)) {
823 fs->used_bytes = i64TotalBytes - i64FreeBytes;
824 fs->total_bytes = i64TotalBytes;
825 fs->has_total_bytes = true;
826 fs->has_used_bytes = true;
827 }
d2b3f390
OK
828 }
829 fs->type = g_strdup(fs_name);
a8f15a27 830 fs->disk = build_guest_disk_info(guid, errp);
d2b3f390
OK
831free:
832 g_free(mnt_point);
833 return fs;
834}
835
46d4c572
TS
836GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
837{
ef0a03f2
OK
838 HANDLE vol_h;
839 GuestFilesystemInfoList *new, *ret = NULL;
840 char guid[256];
841
842 vol_h = FindFirstVolume(guid, sizeof(guid));
843 if (vol_h == INVALID_HANDLE_VALUE) {
844 error_setg_win32(errp, GetLastError(), "failed to find any volume");
845 return NULL;
846 }
847
848 do {
d2b3f390
OK
849 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
850 if (info == NULL) {
851 continue;
852 }
ef0a03f2 853 new = g_malloc(sizeof(*ret));
d2b3f390 854 new->value = info;
ef0a03f2
OK
855 new->next = ret;
856 ret = new;
857 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
858
859 if (GetLastError() != ERROR_NO_MORE_FILES) {
860 error_setg_win32(errp, GetLastError(), "failed to find next volume");
861 }
862
863 FindVolumeClose(vol_h);
864 return ret;
46d4c572
TS
865}
866
d8ca685a
MR
867/*
868 * Return status of freeze/thaw
869 */
77dbc81b 870GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
d8ca685a 871{
64c00317 872 if (!vss_initialized()) {
c6bd8c70 873 error_setg(errp, QERR_UNSUPPORTED);
64c00317
TS
874 return 0;
875 }
876
877 if (ga_is_frozen(ga_state)) {
878 return GUEST_FSFREEZE_STATUS_FROZEN;
879 }
880
881 return GUEST_FSFREEZE_STATUS_THAWED;
d8ca685a
MR
882}
883
884/*
64c00317
TS
885 * Freeze local file systems using Volume Shadow-copy Service.
886 * The frozen state is limited for up to 10 seconds by VSS.
d8ca685a 887 */
77dbc81b 888int64_t qmp_guest_fsfreeze_freeze(Error **errp)
0692b03e
CH
889{
890 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
891}
892
893int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
894 strList *mountpoints,
895 Error **errp)
d8ca685a 896{
64c00317
TS
897 int i;
898 Error *local_err = NULL;
899
900 if (!vss_initialized()) {
c6bd8c70 901 error_setg(errp, QERR_UNSUPPORTED);
64c00317
TS
902 return 0;
903 }
904
905 slog("guest-fsfreeze called");
906
907 /* cannot risk guest agent blocking itself on a write in this state */
908 ga_set_frozen(ga_state);
909
0692b03e 910 qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
0f230bf7
MA
911 if (local_err) {
912 error_propagate(errp, local_err);
64c00317
TS
913 goto error;
914 }
915
916 return i;
917
918error:
0f230bf7 919 local_err = NULL;
64c00317 920 qmp_guest_fsfreeze_thaw(&local_err);
84d18f06 921 if (local_err) {
64c00317
TS
922 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
923 error_free(local_err);
924 }
d8ca685a
MR
925 return 0;
926}
927
928/*
64c00317 929 * Thaw local file systems using Volume Shadow-copy Service.
d8ca685a 930 */
77dbc81b 931int64_t qmp_guest_fsfreeze_thaw(Error **errp)
d8ca685a 932{
64c00317
TS
933 int i;
934
935 if (!vss_initialized()) {
c6bd8c70 936 error_setg(errp, QERR_UNSUPPORTED);
64c00317
TS
937 return 0;
938 }
939
0692b03e 940 qga_vss_fsfreeze(&i, false, NULL, errp);
64c00317
TS
941
942 ga_unset_frozen(ga_state);
943 return i;
944}
945
946static void guest_fsfreeze_cleanup(void)
947{
948 Error *err = NULL;
949
950 if (!vss_initialized()) {
951 return;
952 }
953
954 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
955 qmp_guest_fsfreeze_thaw(&err);
956 if (err) {
957 slog("failed to clean up frozen filesystems: %s",
958 error_get_pretty(err));
959 error_free(err);
960 }
961 }
962
963 vss_deinit(true);
d8ca685a
MR
964}
965
eab5fd59
PB
966/*
967 * Walk list of mounted file systems in the guest, and discard unused
968 * areas.
969 */
e82855d9
JO
970GuestFilesystemTrimResponse *
971qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
eab5fd59 972{
91274487
DL
973 GuestFilesystemTrimResponse *resp;
974 HANDLE handle;
975 WCHAR guid[MAX_PATH] = L"";
c5840b90
SJ
976 OSVERSIONINFO osvi;
977 BOOL win8_or_later;
978
979 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
980 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
981 GetVersionEx(&osvi);
982 win8_or_later = (osvi.dwMajorVersion > 6 ||
983 ((osvi.dwMajorVersion == 6) &&
984 (osvi.dwMinorVersion >= 2)));
985 if (!win8_or_later) {
986 error_setg(errp, "fstrim is only supported for Win8+");
987 return NULL;
988 }
91274487
DL
989
990 handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
991 if (handle == INVALID_HANDLE_VALUE) {
992 error_setg_win32(errp, GetLastError(), "failed to find any volume");
993 return NULL;
994 }
995
996 resp = g_new0(GuestFilesystemTrimResponse, 1);
997
998 do {
999 GuestFilesystemTrimResult *res;
1000 GuestFilesystemTrimResultList *list;
1001 PWCHAR uc_path;
1002 DWORD char_count = 0;
1003 char *path, *out;
1004 GError *gerr = NULL;
1005 gchar * argv[4];
1006
1007 GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
1008
1009 if (GetLastError() != ERROR_MORE_DATA) {
1010 continue;
1011 }
1012 if (GetDriveTypeW(guid) != DRIVE_FIXED) {
1013 continue;
1014 }
1015
1016 uc_path = g_malloc(sizeof(WCHAR) * char_count);
1017 if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
1018 &char_count) || !*uc_path) {
1019 /* strange, but this condition could be faced even with size == 2 */
1020 g_free(uc_path);
1021 continue;
1022 }
1023
1024 res = g_new0(GuestFilesystemTrimResult, 1);
1025
1026 path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
1027
1028 g_free(uc_path);
1029
1030 if (!path) {
1031 res->has_error = true;
1032 res->error = g_strdup(gerr->message);
1033 g_error_free(gerr);
1034 break;
1035 }
1036
1037 res->path = path;
1038
1039 list = g_new0(GuestFilesystemTrimResultList, 1);
1040 list->value = res;
1041 list->next = resp->paths;
1042
1043 resp->paths = list;
1044
1045 memset(argv, 0, sizeof(argv));
1046 argv[0] = (gchar *)"defrag.exe";
1047 argv[1] = (gchar *)"/L";
1048 argv[2] = path;
1049
1050 if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1051 &out /* stdout */, NULL /* stdin */,
1052 NULL, &gerr)) {
1053 res->has_error = true;
1054 res->error = g_strdup(gerr->message);
1055 g_error_free(gerr);
1056 } else {
1057 /* defrag.exe is UGLY. Exit code is ALWAYS zero.
1058 Error is reported in the output with something like
1059 (x89000020) etc code in the stdout */
1060
1061 int i;
1062 gchar **lines = g_strsplit(out, "\r\n", 0);
1063 g_free(out);
1064
1065 for (i = 0; lines[i] != NULL; i++) {
1066 if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
1067 continue;
1068 }
1069 res->has_error = true;
1070 res->error = g_strdup(lines[i]);
1071 break;
1072 }
1073 g_strfreev(lines);
1074 }
1075 } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
1076
1077 FindVolumeClose(handle);
1078 return resp;
eab5fd59
PB
1079}
1080
aa59637e 1081typedef enum {
f54603b6
MR
1082 GUEST_SUSPEND_MODE_DISK,
1083 GUEST_SUSPEND_MODE_RAM
aa59637e
GH
1084} GuestSuspendMode;
1085
77dbc81b 1086static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
aa59637e
GH
1087{
1088 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
1089 Error *local_err = NULL;
1090
aa59637e
GH
1091 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
1092 if (!GetPwrCapabilities(&sys_pwr_caps)) {
c6bd8c70
MA
1093 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1094 "failed to determine guest suspend capabilities");
aa59637e
GH
1095 goto out;
1096 }
1097
f54603b6
MR
1098 switch (mode) {
1099 case GUEST_SUSPEND_MODE_DISK:
1100 if (!sys_pwr_caps.SystemS4) {
c6bd8c70
MA
1101 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1102 "suspend-to-disk not supported by OS");
aa59637e 1103 }
f54603b6
MR
1104 break;
1105 case GUEST_SUSPEND_MODE_RAM:
1106 if (!sys_pwr_caps.SystemS3) {
c6bd8c70
MA
1107 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
1108 "suspend-to-ram not supported by OS");
f54603b6
MR
1109 }
1110 break;
1111 default:
c6bd8c70
MA
1112 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
1113 "GuestSuspendMode");
aa59637e
GH
1114 }
1115
aa59637e 1116out:
621ff94d 1117 error_propagate(errp, local_err);
aa59637e
GH
1118}
1119
1120static DWORD WINAPI do_suspend(LPVOID opaque)
1121{
1122 GuestSuspendMode *mode = opaque;
1123 DWORD ret = 0;
1124
1125 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
16f4e8fa 1126 slog("failed to suspend guest, %lu", GetLastError());
aa59637e
GH
1127 ret = -1;
1128 }
1129 g_free(mode);
1130 return ret;
1131}
1132
77dbc81b 1133void qmp_guest_suspend_disk(Error **errp)
11d0f125 1134{
0f230bf7 1135 Error *local_err = NULL;
f3a06403 1136 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
aa59637e
GH
1137
1138 *mode = GUEST_SUSPEND_MODE_DISK;
0f230bf7
MA
1139 check_suspend_mode(*mode, &local_err);
1140 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1141 execute_async(do_suspend, mode, &local_err);
aa59637e 1142
0f230bf7
MA
1143 if (local_err) {
1144 error_propagate(errp, local_err);
aa59637e
GH
1145 g_free(mode);
1146 }
11d0f125
LC
1147}
1148
77dbc81b 1149void qmp_guest_suspend_ram(Error **errp)
fbf42210 1150{
0f230bf7 1151 Error *local_err = NULL;
f3a06403 1152 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
f54603b6
MR
1153
1154 *mode = GUEST_SUSPEND_MODE_RAM;
0f230bf7
MA
1155 check_suspend_mode(*mode, &local_err);
1156 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1157 execute_async(do_suspend, mode, &local_err);
f54603b6 1158
0f230bf7
MA
1159 if (local_err) {
1160 error_propagate(errp, local_err);
f54603b6
MR
1161 g_free(mode);
1162 }
fbf42210
LC
1163}
1164
77dbc81b 1165void qmp_guest_suspend_hybrid(Error **errp)
95f4f404 1166{
c6bd8c70 1167 error_setg(errp, QERR_UNSUPPORTED);
95f4f404
LC
1168}
1169
d6c5528b 1170static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
3424fc9f 1171{
d6c5528b
KA
1172 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1173 ULONG adptr_addrs_len = 0;
1174 DWORD ret;
1175
1176 /* Call the first time to get the adptr_addrs_len. */
1177 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1178 NULL, adptr_addrs, &adptr_addrs_len);
1179
1180 adptr_addrs = g_malloc(adptr_addrs_len);
1181 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1182 NULL, adptr_addrs, &adptr_addrs_len);
1183 if (ret != ERROR_SUCCESS) {
1184 error_setg_win32(errp, ret, "failed to get adapters addresses");
1185 g_free(adptr_addrs);
1186 adptr_addrs = NULL;
1187 }
1188 return adptr_addrs;
1189}
1190
1191static char *guest_wctomb_dup(WCHAR *wstr)
1192{
1193 char *str;
1194 size_t i;
1195
1196 i = wcslen(wstr) + 1;
1197 str = g_malloc(i);
1198 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
1199 wstr, -1, str, i, NULL, NULL);
1200 return str;
1201}
1202
1203static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1204 Error **errp)
1205{
1206 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1207 DWORD len;
1208 int ret;
1209
1210 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1211 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1212 len = sizeof(addr_str);
1213 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1214 ip_addr->Address.iSockaddrLength,
1215 NULL,
1216 addr_str,
1217 &len);
1218 if (ret != 0) {
1219 error_setg_win32(errp, WSAGetLastError(),
1220 "failed address presentation form conversion");
1221 return NULL;
1222 }
1223 return g_strdup(addr_str);
1224 }
3424fc9f
MP
1225 return NULL;
1226}
1227
d6c5528b
KA
1228#if (_WIN32_WINNT >= 0x0600)
1229static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1230{
1231 /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1232 * field to obtain the prefix.
1233 */
1234 return ip_addr->OnLinkPrefixLength;
1235}
1236#else
1237/* When using the Windows XP and 2003 build environment, do the best we can to
1238 * figure out the prefix.
1239 */
1240static IP_ADAPTER_INFO *guest_get_adapters_info(void)
1241{
1242 IP_ADAPTER_INFO *adptr_info = NULL;
1243 ULONG adptr_info_len = 0;
1244 DWORD ret;
1245
1246 /* Call the first time to get the adptr_info_len. */
1247 GetAdaptersInfo(adptr_info, &adptr_info_len);
1248
1249 adptr_info = g_malloc(adptr_info_len);
1250 ret = GetAdaptersInfo(adptr_info, &adptr_info_len);
1251 if (ret != ERROR_SUCCESS) {
1252 g_free(adptr_info);
1253 adptr_info = NULL;
1254 }
1255 return adptr_info;
1256}
1257
1258static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1259{
1260 int64_t prefix = -1; /* Use for AF_INET6 and unknown/undetermined values. */
1261 IP_ADAPTER_INFO *adptr_info, *info;
1262 IP_ADDR_STRING *ip;
1263 struct in_addr *p;
1264
1265 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
1266 return prefix;
1267 }
1268 adptr_info = guest_get_adapters_info();
1269 if (adptr_info == NULL) {
1270 return prefix;
1271 }
1272
1273 /* Match up the passed in ip_addr with one found in adaptr_info.
1274 * The matching one in adptr_info will have the netmask.
1275 */
1276 p = &((struct sockaddr_in *)ip_addr->Address.lpSockaddr)->sin_addr;
1277 for (info = adptr_info; info; info = info->Next) {
1278 for (ip = &info->IpAddressList; ip; ip = ip->Next) {
1279 if (p->S_un.S_addr == inet_addr(ip->IpAddress.String)) {
1280 prefix = ctpop32(inet_addr(ip->IpMask.String));
1281 goto out;
1282 }
1283 }
1284 }
1285out:
1286 g_free(adptr_info);
1287 return prefix;
1288}
1289#endif
1290
53f9fcb2
ZL
1291#define INTERFACE_PATH_BUF_SZ 512
1292
1293static DWORD get_interface_index(const char *guid)
1294{
1295 ULONG index;
1296 DWORD status;
1297 wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1298 snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1299 wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1300 status = GetAdapterIndex (wbuf, &index);
1301 if (status != NO_ERROR) {
1302 return (DWORD)~0;
1303 } else {
1304 return index;
1305 }
1306}
df83eabd
ZL
1307
1308typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1309
53f9fcb2 1310static int guest_get_network_stats(const char *name,
df83eabd 1311 GuestNetworkInterfaceStat *stats)
53f9fcb2 1312{
df83eabd
ZL
1313 OSVERSIONINFO os_ver;
1314
1315 os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1316 GetVersionEx(&os_ver);
1317 if (os_ver.dwMajorVersion >= 6) {
1318 MIB_IF_ROW2 a_mid_ifrow;
1319 GetIfEntry2Func getifentry2_ex;
1320 DWORD if_index = 0;
1321 HMODULE module = GetModuleHandle("iphlpapi");
1322 PVOID func = GetProcAddress(module, "GetIfEntry2");
1323
1324 if (func == NULL) {
1325 return -1;
1326 }
1327
1328 getifentry2_ex = (GetIfEntry2Func)func;
1329 if_index = get_interface_index(name);
1330 if (if_index == (DWORD)~0) {
1331 return -1;
1332 }
1333
1334 memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1335 a_mid_ifrow.InterfaceIndex = if_index;
1336 if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1337 stats->rx_bytes = a_mid_ifrow.InOctets;
1338 stats->rx_packets = a_mid_ifrow.InUcastPkts;
1339 stats->rx_errs = a_mid_ifrow.InErrors;
1340 stats->rx_dropped = a_mid_ifrow.InDiscards;
1341 stats->tx_bytes = a_mid_ifrow.OutOctets;
1342 stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1343 stats->tx_errs = a_mid_ifrow.OutErrors;
1344 stats->tx_dropped = a_mid_ifrow.OutDiscards;
1345 return 0;
1346 }
53f9fcb2
ZL
1347 }
1348 return -1;
1349}
1350
d6c5528b
KA
1351GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1352{
1353 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1354 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1355 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1356 GuestIpAddressList *head_addr, *cur_addr;
1357 GuestNetworkInterfaceList *info;
53f9fcb2 1358 GuestNetworkInterfaceStat *interface_stat = NULL;
d6c5528b
KA
1359 GuestIpAddressList *address_item = NULL;
1360 unsigned char *mac_addr;
1361 char *addr_str;
1362 WORD wsa_version;
1363 WSADATA wsa_data;
1364 int ret;
1365
1366 adptr_addrs = guest_get_adapters_addresses(errp);
1367 if (adptr_addrs == NULL) {
1368 return NULL;
1369 }
1370
1371 /* Make WSA APIs available. */
1372 wsa_version = MAKEWORD(2, 2);
1373 ret = WSAStartup(wsa_version, &wsa_data);
1374 if (ret != 0) {
1375 error_setg_win32(errp, ret, "failed socket startup");
1376 goto out;
1377 }
1378
1379 for (addr = adptr_addrs; addr; addr = addr->Next) {
1380 info = g_malloc0(sizeof(*info));
1381
1382 if (cur_item == NULL) {
1383 head = cur_item = info;
1384 } else {
1385 cur_item->next = info;
1386 cur_item = info;
1387 }
1388
1389 info->value = g_malloc0(sizeof(*info->value));
1390 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1391
1392 if (addr->PhysicalAddressLength != 0) {
1393 mac_addr = addr->PhysicalAddress;
1394
1395 info->value->hardware_address =
1396 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1397 (int) mac_addr[0], (int) mac_addr[1],
1398 (int) mac_addr[2], (int) mac_addr[3],
1399 (int) mac_addr[4], (int) mac_addr[5]);
1400
1401 info->value->has_hardware_address = true;
1402 }
1403
1404 head_addr = NULL;
1405 cur_addr = NULL;
1406 for (ip_addr = addr->FirstUnicastAddress;
1407 ip_addr;
1408 ip_addr = ip_addr->Next) {
1409 addr_str = guest_addr_to_str(ip_addr, errp);
1410 if (addr_str == NULL) {
1411 continue;
1412 }
1413
1414 address_item = g_malloc0(sizeof(*address_item));
1415
1416 if (!cur_addr) {
1417 head_addr = cur_addr = address_item;
1418 } else {
1419 cur_addr->next = address_item;
1420 cur_addr = address_item;
1421 }
1422
1423 address_item->value = g_malloc0(sizeof(*address_item->value));
1424 address_item->value->ip_address = addr_str;
1425 address_item->value->prefix = guest_ip_prefix(ip_addr);
1426 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1427 address_item->value->ip_address_type =
1428 GUEST_IP_ADDRESS_TYPE_IPV4;
1429 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1430 address_item->value->ip_address_type =
1431 GUEST_IP_ADDRESS_TYPE_IPV6;
1432 }
1433 }
1434 if (head_addr) {
1435 info->value->has_ip_addresses = true;
1436 info->value->ip_addresses = head_addr;
1437 }
53f9fcb2
ZL
1438 if (!info->value->has_statistics) {
1439 interface_stat = g_malloc0(sizeof(*interface_stat));
1440 if (guest_get_network_stats(addr->AdapterName,
1441 interface_stat) == -1) {
1442 info->value->has_statistics = false;
1443 g_free(interface_stat);
1444 } else {
1445 info->value->statistics = interface_stat;
1446 info->value->has_statistics = true;
1447 }
1448 }
d6c5528b
KA
1449 }
1450 WSACleanup();
1451out:
1452 g_free(adptr_addrs);
1453 return head;
1454}
1455
6912e6a9
LL
1456int64_t qmp_guest_get_time(Error **errp)
1457{
3f2a6087 1458 SYSTEMTIME ts = {0};
3f2a6087
LL
1459 FILETIME tf;
1460
1461 GetSystemTime(&ts);
1462 if (ts.wYear < 1601 || ts.wYear > 30827) {
1463 error_setg(errp, "Failed to get time");
1464 return -1;
1465 }
1466
1467 if (!SystemTimeToFileTime(&ts, &tf)) {
1468 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1469 return -1;
1470 }
1471
9be38598 1472 return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
3f2a6087 1473 - W32_FT_OFFSET) * 100;
6912e6a9
LL
1474}
1475
2c958923 1476void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
a1bca57f 1477{
0f230bf7 1478 Error *local_err = NULL;
b8f954fe
LL
1479 SYSTEMTIME ts;
1480 FILETIME tf;
1481 LONGLONG time;
1482
ee17cbdc
MP
1483 if (!has_time) {
1484 /* Unfortunately, Windows libraries don't provide an easy way to access
1485 * RTC yet:
1486 *
1487 * https://msdn.microsoft.com/en-us/library/aa908981.aspx
105fad6b
BA
1488 *
1489 * Instead, a workaround is to use the Windows win32tm command to
1490 * resync the time using the Windows Time service.
ee17cbdc 1491 */
105fad6b
BA
1492 LPVOID msg_buffer;
1493 DWORD ret_flags;
1494
1495 HRESULT hr = system("w32tm /resync /nowait");
1496
1497 if (GetLastError() != 0) {
1498 strerror_s((LPTSTR) & msg_buffer, 0, errno);
1499 error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1500 } else if (hr != 0) {
1501 if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1502 error_setg(errp, "Windows Time service not running on the "
1503 "guest");
1504 } else {
1505 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1506 FORMAT_MESSAGE_FROM_SYSTEM |
1507 FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1508 (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1509 SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1510 NULL)) {
1511 error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1512 "t retrieve error message", hr);
1513 } else {
1514 error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1515 (LPCTSTR)msg_buffer);
1516 LocalFree(msg_buffer);
1517 }
1518 }
1519 } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1520 error_setg(errp, "No internet connection on guest, sync not "
1521 "accurate");
1522 }
ee17cbdc
MP
1523 return;
1524 }
1525
1526 /* Validate time passed by user. */
1527 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1528 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1529 return;
1530 }
b8f954fe 1531
ee17cbdc 1532 time = time_ns / 100 + W32_FT_OFFSET;
b8f954fe 1533
ee17cbdc
MP
1534 tf.dwLowDateTime = (DWORD) time;
1535 tf.dwHighDateTime = (DWORD) (time >> 32);
b8f954fe 1536
ee17cbdc
MP
1537 if (!FileTimeToSystemTime(&tf, &ts)) {
1538 error_setg(errp, "Failed to convert system time %d",
1539 (int)GetLastError());
1540 return;
b8f954fe
LL
1541 }
1542
0f230bf7
MA
1543 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1544 if (local_err) {
1545 error_propagate(errp, local_err);
b8f954fe
LL
1546 return;
1547 }
1548
1549 if (!SetSystemTime(&ts)) {
1550 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1551 return;
1552 }
a1bca57f
LL
1553}
1554
70e133a7
LE
1555GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1556{
a7a17362
GH
1557 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1558 DWORD length;
1559 GuestLogicalProcessorList *head, **link;
1560 Error *local_err = NULL;
1561 int64_t current;
1562
1563 ptr = pslpi = NULL;
1564 length = 0;
1565 current = 0;
1566 head = NULL;
1567 link = &head;
1568
1569 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1570 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1571 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1572 ptr = pslpi = g_malloc0(length);
1573 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1574 error_setg(&local_err, "Failed to get processor information: %d",
1575 (int)GetLastError());
1576 }
1577 } else {
1578 error_setg(&local_err,
1579 "Failed to get processor information buffer length: %d",
1580 (int)GetLastError());
1581 }
1582
1583 while ((local_err == NULL) && (length > 0)) {
1584 if (pslpi->Relationship == RelationProcessorCore) {
1585 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1586
1587 while (cpu_bits > 0) {
1588 if (!!(cpu_bits & 1)) {
1589 GuestLogicalProcessor *vcpu;
1590 GuestLogicalProcessorList *entry;
1591
1592 vcpu = g_malloc0(sizeof *vcpu);
1593 vcpu->logical_id = current++;
1594 vcpu->online = true;
54858553 1595 vcpu->has_can_offline = true;
a7a17362
GH
1596
1597 entry = g_malloc0(sizeof *entry);
1598 entry->value = vcpu;
1599
1600 *link = entry;
1601 link = &entry->next;
1602 }
1603 cpu_bits >>= 1;
1604 }
1605 }
1606 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1607 pslpi++; /* next entry */
1608 }
1609
1610 g_free(ptr);
1611
1612 if (local_err == NULL) {
1613 if (head != NULL) {
1614 return head;
1615 }
1616 /* there's no guest with zero VCPUs */
1617 error_setg(&local_err, "Guest reported zero VCPUs");
1618 }
1619
1620 qapi_free_GuestLogicalProcessorList(head);
1621 error_propagate(errp, local_err);
70e133a7
LE
1622 return NULL;
1623}
1624
1625int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1626{
c6bd8c70 1627 error_setg(errp, QERR_UNSUPPORTED);
70e133a7
LE
1628 return -1;
1629}
1630
259434b8
MAL
1631static gchar *
1632get_net_error_message(gint error)
1633{
1634 HMODULE module = NULL;
1635 gchar *retval = NULL;
1636 wchar_t *msg = NULL;
6771197d
MAL
1637 int flags;
1638 size_t nchars;
259434b8 1639
02506e2d
MAL
1640 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1641 FORMAT_MESSAGE_IGNORE_INSERTS |
1642 FORMAT_MESSAGE_FROM_SYSTEM;
259434b8
MAL
1643
1644 if (error >= NERR_BASE && error <= MAX_NERR) {
1645 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1646
1647 if (module != NULL) {
1648 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1649 }
1650 }
1651
1652 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1653
1654 if (msg != NULL) {
1655 nchars = wcslen(msg);
1656
25d943b9 1657 if (nchars >= 2 &&
6c6916da
MAL
1658 msg[nchars - 1] == L'\n' &&
1659 msg[nchars - 2] == L'\r') {
1660 msg[nchars - 2] = L'\0';
259434b8
MAL
1661 }
1662
1663 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1664
1665 LocalFree(msg);
1666 }
1667
1668 if (module != NULL) {
1669 FreeLibrary(module);
1670 }
1671
1672 return retval;
1673}
1674
215a2771
DB
1675void qmp_guest_set_user_password(const char *username,
1676 const char *password,
1677 bool crypted,
1678 Error **errp)
1679{
259434b8
MAL
1680 NET_API_STATUS nas;
1681 char *rawpasswddata = NULL;
1682 size_t rawpasswdlen;
8021de10 1683 wchar_t *user = NULL, *wpass = NULL;
259434b8 1684 USER_INFO_1003 pi1003 = { 0, };
8021de10 1685 GError *gerr = NULL;
259434b8
MAL
1686
1687 if (crypted) {
1688 error_setg(errp, QERR_UNSUPPORTED);
1689 return;
1690 }
1691
920639ca
DB
1692 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1693 if (!rawpasswddata) {
1694 return;
1695 }
259434b8
MAL
1696 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1697 rawpasswddata[rawpasswdlen] = '\0';
1698
8021de10
MAL
1699 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1700 if (!user) {
1701 goto done;
1702 }
1703
1704 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1705 if (!wpass) {
1706 goto done;
1707 }
259434b8
MAL
1708
1709 pi1003.usri1003_password = wpass;
1710 nas = NetUserSetInfo(NULL, user,
1711 1003, (LPBYTE)&pi1003,
1712 NULL);
1713
1714 if (nas != NERR_Success) {
1715 gchar *msg = get_net_error_message(nas);
1716 error_setg(errp, "failed to set password: %s", msg);
1717 g_free(msg);
1718 }
1719
8021de10
MAL
1720done:
1721 if (gerr) {
1722 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1723 g_error_free(gerr);
1724 }
259434b8
MAL
1725 g_free(user);
1726 g_free(wpass);
1727 g_free(rawpasswddata);
215a2771
DB
1728}
1729
a065aaa9
HZ
1730GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1731{
c6bd8c70 1732 error_setg(errp, QERR_UNSUPPORTED);
a065aaa9
HZ
1733 return NULL;
1734}
1735
1736GuestMemoryBlockResponseList *
1737qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1738{
c6bd8c70 1739 error_setg(errp, QERR_UNSUPPORTED);
a065aaa9
HZ
1740 return NULL;
1741}
1742
1743GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1744{
c6bd8c70 1745 error_setg(errp, QERR_UNSUPPORTED);
a065aaa9
HZ
1746 return NULL;
1747}
1748
1281c08a
TS
1749/* add unsupported commands to the blacklist */
1750GList *ga_command_blacklist_init(GList *blacklist)
1751{
1752 const char *list_unsupported[] = {
d6c5528b 1753 "guest-suspend-hybrid",
a7a17362 1754 "guest-set-vcpus",
0dd38a03
HZ
1755 "guest-get-memory-blocks", "guest-set-memory-blocks",
1756 "guest-get-memory-block-size",
91274487 1757 NULL};
1281c08a
TS
1758 char **p = (char **)list_unsupported;
1759
1760 while (*p) {
4bca81ce 1761 blacklist = g_list_append(blacklist, g_strdup(*p++));
1281c08a
TS
1762 }
1763
1764 if (!vss_init(true)) {
c69403fc 1765 g_debug("vss_init failed, vss commands are going to be disabled");
1281c08a
TS
1766 const char *list[] = {
1767 "guest-get-fsinfo", "guest-fsfreeze-status",
1768 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1769 p = (char **)list;
1770
1771 while (*p) {
4bca81ce 1772 blacklist = g_list_append(blacklist, g_strdup(*p++));
1281c08a
TS
1773 }
1774 }
1775
1776 return blacklist;
1777}
1778
d8ca685a
MR
1779/* register init/cleanup routines for stateful command groups */
1780void ga_command_state_init(GAState *s, GACommandState *cs)
1781{
1281c08a 1782 if (!vss_initialized()) {
64c00317
TS
1783 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1784 }
d8ca685a 1785}
161a56a9
VF
1786
1787/* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1788typedef struct _GA_WTSINFOA {
1789 WTS_CONNECTSTATE_CLASS State;
1790 DWORD SessionId;
1791 DWORD IncomingBytes;
1792 DWORD OutgoingBytes;
1793 DWORD IncomingFrames;
1794 DWORD OutgoingFrames;
1795 DWORD IncomingCompressedBytes;
1796 DWORD OutgoingCompressedBy;
1797 CHAR WinStationName[WINSTATIONNAME_LENGTH];
1798 CHAR Domain[DOMAIN_LENGTH];
1799 CHAR UserName[USERNAME_LENGTH + 1];
1800 LARGE_INTEGER ConnectTime;
1801 LARGE_INTEGER DisconnectTime;
1802 LARGE_INTEGER LastInputTime;
1803 LARGE_INTEGER LogonTime;
1804 LARGE_INTEGER CurrentTime;
1805
1806} GA_WTSINFOA;
1807
1808GuestUserList *qmp_guest_get_users(Error **err)
1809{
1810#if (_WIN32_WINNT >= 0x0600)
1811#define QGA_NANOSECONDS 10000000
1812
1813 GHashTable *cache = NULL;
1814 GuestUserList *head = NULL, *cur_item = NULL;
1815
1816 DWORD buffer_size = 0, count = 0, i = 0;
1817 GA_WTSINFOA *info = NULL;
1818 WTS_SESSION_INFOA *entries = NULL;
1819 GuestUserList *item = NULL;
1820 GuestUser *user = NULL;
1821 gpointer value = NULL;
1822 INT64 login = 0;
1823 double login_time = 0;
1824
1825 cache = g_hash_table_new(g_str_hash, g_str_equal);
1826
1827 if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
1828 for (i = 0; i < count; ++i) {
1829 buffer_size = 0;
1830 info = NULL;
1831 if (WTSQuerySessionInformationA(
1832 NULL,
1833 entries[i].SessionId,
1834 WTSSessionInfo,
1835 (LPSTR *)&info,
1836 &buffer_size
1837 )) {
1838
1839 if (strlen(info->UserName) == 0) {
1840 WTSFreeMemory(info);
1841 continue;
1842 }
1843
1844 login = info->LogonTime.QuadPart;
1845 login -= W32_FT_OFFSET;
1846 login_time = ((double)login) / QGA_NANOSECONDS;
1847
1848 if (g_hash_table_contains(cache, info->UserName)) {
1849 value = g_hash_table_lookup(cache, info->UserName);
1850 user = (GuestUser *)value;
1851 if (user->login_time > login_time) {
1852 user->login_time = login_time;
1853 }
1854 } else {
1855 item = g_new0(GuestUserList, 1);
1856 item->value = g_new0(GuestUser, 1);
1857
1858 item->value->user = g_strdup(info->UserName);
1859 item->value->domain = g_strdup(info->Domain);
1860 item->value->has_domain = true;
1861
1862 item->value->login_time = login_time;
1863
1864 g_hash_table_add(cache, item->value->user);
1865
1866 if (!cur_item) {
1867 head = cur_item = item;
1868 } else {
1869 cur_item->next = item;
1870 cur_item = item;
1871 }
1872 }
1873 }
1874 WTSFreeMemory(info);
1875 }
1876 WTSFreeMemory(entries);
1877 }
1878 g_hash_table_destroy(cache);
1879 return head;
1880#else
1881 error_setg(err, QERR_UNSUPPORTED);
1882 return NULL;
1883#endif
1884}
9848f797
TG
1885
1886typedef struct _ga_matrix_lookup_t {
1887 int major;
1888 int minor;
1889 char const *version;
1890 char const *version_id;
1891} ga_matrix_lookup_t;
1892
1893static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
1894 {
1895 /* Desktop editions */
1896 { 5, 0, "Microsoft Windows 2000", "2000"},
1897 { 5, 1, "Microsoft Windows XP", "xp"},
1898 { 6, 0, "Microsoft Windows Vista", "vista"},
1899 { 6, 1, "Microsoft Windows 7" "7"},
1900 { 6, 2, "Microsoft Windows 8", "8"},
1901 { 6, 3, "Microsoft Windows 8.1", "8.1"},
1902 {10, 0, "Microsoft Windows 10", "10"},
1903 { 0, 0, 0}
1904 },{
1905 /* Server editions */
1906 { 5, 2, "Microsoft Windows Server 2003", "2003"},
1907 { 6, 0, "Microsoft Windows Server 2008", "2008"},
1908 { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
1909 { 6, 2, "Microsoft Windows Server 2012", "2012"},
1910 { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
1911 {10, 0, "Microsoft Windows Server 2016", "2016"},
1912 { 0, 0, 0},
1913 { 0, 0, 0}
1914 }
1915};
1916
1917static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
1918{
1919 typedef NTSTATUS(WINAPI * rtl_get_version_t)(
1920 RTL_OSVERSIONINFOEXW *os_version_info_ex);
1921
1922 info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
1923
1924 HMODULE module = GetModuleHandle("ntdll");
1925 PVOID fun = GetProcAddress(module, "RtlGetVersion");
1926 if (fun == NULL) {
1927 error_setg(errp, QERR_QGA_COMMAND_FAILED,
1928 "Failed to get address of RtlGetVersion");
1929 return;
1930 }
1931
1932 rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
1933 rtl_get_version(info);
1934 return;
1935}
1936
1937static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
1938{
1939 DWORD major = os_version->dwMajorVersion;
1940 DWORD minor = os_version->dwMinorVersion;
1941 int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
1942 ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
1943 while (table->version != NULL) {
1944 if (major == table->major && minor == table->minor) {
1945 if (id) {
1946 return g_strdup(table->version_id);
1947 } else {
1948 return g_strdup(table->version);
1949 }
1950 }
1951 ++table;
1952 }
1953 slog("failed to lookup Windows version: major=%lu, minor=%lu",
1954 major, minor);
1955 return g_strdup("N/A");
1956}
1957
1958static char *ga_get_win_product_name(Error **errp)
1959{
1960 HKEY key = NULL;
1961 DWORD size = 128;
1962 char *result = g_malloc0(size);
1963 LONG err = ERROR_SUCCESS;
1964
1965 err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
1966 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
1967 &key);
1968 if (err != ERROR_SUCCESS) {
1969 error_setg_win32(errp, err, "failed to open registry key");
1970 goto fail;
1971 }
1972
1973 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
1974 (LPBYTE)result, &size);
1975 if (err == ERROR_MORE_DATA) {
1976 slog("ProductName longer than expected (%lu bytes), retrying",
1977 size);
1978 g_free(result);
1979 result = NULL;
1980 if (size > 0) {
1981 result = g_malloc0(size);
1982 err = RegQueryValueExA(key, "ProductName", NULL, NULL,
1983 (LPBYTE)result, &size);
1984 }
1985 }
1986 if (err != ERROR_SUCCESS) {
1987 error_setg_win32(errp, err, "failed to retrive ProductName");
1988 goto fail;
1989 }
1990
1991 return result;
1992
1993fail:
1994 g_free(result);
1995 return NULL;
1996}
1997
1998static char *ga_get_current_arch(void)
1999{
2000 SYSTEM_INFO info;
2001 GetNativeSystemInfo(&info);
2002 char *result = NULL;
2003 switch (info.wProcessorArchitecture) {
2004 case PROCESSOR_ARCHITECTURE_AMD64:
2005 result = g_strdup("x86_64");
2006 break;
2007 case PROCESSOR_ARCHITECTURE_ARM:
2008 result = g_strdup("arm");
2009 break;
2010 case PROCESSOR_ARCHITECTURE_IA64:
2011 result = g_strdup("ia64");
2012 break;
2013 case PROCESSOR_ARCHITECTURE_INTEL:
2014 result = g_strdup("x86");
2015 break;
2016 case PROCESSOR_ARCHITECTURE_UNKNOWN:
2017 default:
2018 slog("unknown processor architecture 0x%0x",
2019 info.wProcessorArchitecture);
2020 result = g_strdup("unknown");
2021 break;
2022 }
2023 return result;
2024}
2025
2026GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2027{
2028 Error *local_err = NULL;
2029 OSVERSIONINFOEXW os_version = {0};
2030 bool server;
2031 char *product_name;
2032 GuestOSInfo *info;
2033
2034 ga_get_win_version(&os_version, &local_err);
2035 if (local_err) {
2036 error_propagate(errp, local_err);
2037 return NULL;
2038 }
2039
2040 server = os_version.wProductType != VER_NT_WORKSTATION;
2041 product_name = ga_get_win_product_name(&local_err);
2042 if (product_name == NULL) {
2043 error_propagate(errp, local_err);
2044 return NULL;
2045 }
2046
2047 info = g_new0(GuestOSInfo, 1);
2048
2049 info->has_kernel_version = true;
2050 info->kernel_version = g_strdup_printf("%lu.%lu",
2051 os_version.dwMajorVersion,
2052 os_version.dwMinorVersion);
2053 info->has_kernel_release = true;
2054 info->kernel_release = g_strdup_printf("%lu",
2055 os_version.dwBuildNumber);
2056 info->has_machine = true;
2057 info->machine = ga_get_current_arch();
2058
2059 info->has_id = true;
2060 info->id = g_strdup("mswindows");
2061 info->has_name = true;
2062 info->name = g_strdup("Microsoft Windows");
2063 info->has_pretty_name = true;
2064 info->pretty_name = product_name;
2065 info->has_version = true;
2066 info->version = ga_get_win_name(&os_version, false);
2067 info->has_version_id = true;
2068 info->version_id = ga_get_win_name(&os_version, true);
2069 info->has_variant = true;
2070 info->variant = g_strdup(server ? "server" : "client");
2071 info->has_variant_id = true;
2072 info->variant_id = g_strdup(server ? "server" : "client");
2073
2074 return info;
2075}
This page took 0.63886 seconds and 4 git commands to generate.