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