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