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