1
2
3
4
5
6
7
8
9
10
11
12
13
14#include "qemu/osdep.h"
15#include <wtypes.h>
16#include <powrprof.h>
17#include <winsock2.h>
18#include <ws2tcpip.h>
19#include <iptypes.h>
20#include <iphlpapi.h>
21#ifdef CONFIG_QGA_NTDDSCSI
22#include <winioctl.h>
23#include <ntddscsi.h>
24#include <setupapi.h>
25#include <initguid.h>
26#endif
27#include <lm.h>
28
29#include "qga/guest-agent-core.h"
30#include "qga/vss-win32.h"
31#include "qga-qmp-commands.h"
32#include "qapi/qmp/qerror.h"
33#include "qemu/queue.h"
34#include "qemu/host-utils.h"
35#include "qemu/base64.h"
36
37#ifndef SHTDN_REASON_FLAG_PLANNED
38#define SHTDN_REASON_FLAG_PLANNED 0x80000000
39#endif
40
41
42
43#define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
44 (365 * (1970 - 1601) + \
45 (1970 - 1601) / 4 - 3))
46
47#define INVALID_SET_FILE_POINTER ((DWORD)-1)
48
49typedef struct GuestFileHandle {
50 int64_t id;
51 HANDLE fh;
52 QTAILQ_ENTRY(GuestFileHandle) next;
53} GuestFileHandle;
54
55static struct {
56 QTAILQ_HEAD(, GuestFileHandle) filehandles;
57} guest_file_state = {
58 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
59};
60
61#define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
62
63typedef struct OpenFlags {
64 const char *forms;
65 DWORD desired_access;
66 DWORD creation_disposition;
67} OpenFlags;
68static OpenFlags guest_file_open_modes[] = {
69 {"r", GENERIC_READ, OPEN_EXISTING},
70 {"rb", GENERIC_READ, OPEN_EXISTING},
71 {"w", GENERIC_WRITE, CREATE_ALWAYS},
72 {"wb", GENERIC_WRITE, CREATE_ALWAYS},
73 {"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
74 {"r+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
75 {"rb+", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
76 {"r+b", GENERIC_WRITE|GENERIC_READ, OPEN_EXISTING},
77 {"w+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
78 {"wb+", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
79 {"w+b", GENERIC_WRITE|GENERIC_READ, CREATE_ALWAYS},
80 {"a+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
81 {"ab+", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS },
82 {"a+b", FILE_GENERIC_APPEND|GENERIC_READ, OPEN_ALWAYS }
83};
84
85static OpenFlags *find_open_flag(const char *mode_str)
86{
87 int mode;
88 Error **errp = NULL;
89
90 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
91 OpenFlags *flags = guest_file_open_modes + mode;
92
93 if (strcmp(flags->forms, mode_str) == 0) {
94 return flags;
95 }
96 }
97
98 error_setg(errp, "invalid file open mode '%s'", mode_str);
99 return NULL;
100}
101
102static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
103{
104 GuestFileHandle *gfh;
105 int64_t handle;
106
107 handle = ga_get_fd_handle(ga_state, errp);
108 if (handle < 0) {
109 return -1;
110 }
111 gfh = g_new0(GuestFileHandle, 1);
112 gfh->id = handle;
113 gfh->fh = fh;
114 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
115
116 return handle;
117}
118
119static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
120{
121 GuestFileHandle *gfh;
122 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
123 if (gfh->id == id) {
124 return gfh;
125 }
126 }
127 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
128 return NULL;
129}
130
131static void handle_set_nonblocking(HANDLE fh)
132{
133 DWORD file_type, pipe_state;
134 file_type = GetFileType(fh);
135 if (file_type != FILE_TYPE_PIPE) {
136 return;
137 }
138
139
140 if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
141 NULL, NULL, NULL, 0)) {
142 return;
143 }
144
145 if (pipe_state & PIPE_NOWAIT) {
146 return;
147 }
148
149 pipe_state |= PIPE_NOWAIT;
150 SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
151}
152
153int64_t qmp_guest_file_open(const char *path, bool has_mode,
154 const char *mode, Error **errp)
155{
156 int64_t fd;
157 HANDLE fh;
158 HANDLE templ_file = NULL;
159 DWORD share_mode = FILE_SHARE_READ;
160 DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
161 LPSECURITY_ATTRIBUTES sa_attr = NULL;
162 OpenFlags *guest_flags;
163
164 if (!has_mode) {
165 mode = "r";
166 }
167 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
168 guest_flags = find_open_flag(mode);
169 if (guest_flags == NULL) {
170 error_setg(errp, "invalid file open mode");
171 return -1;
172 }
173
174 fh = CreateFile(path, guest_flags->desired_access, share_mode, sa_attr,
175 guest_flags->creation_disposition, flags_and_attr,
176 templ_file);
177 if (fh == INVALID_HANDLE_VALUE) {
178 error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
179 path);
180 return -1;
181 }
182
183
184
185
186 handle_set_nonblocking(fh);
187
188 fd = guest_file_handle_add(fh, errp);
189 if (fd < 0) {
190 CloseHandle(fh);
191 error_setg(errp, "failed to add handle to qmp handle table");
192 return -1;
193 }
194
195 slog("guest-file-open, handle: % " PRId64, fd);
196 return fd;
197}
198
199void qmp_guest_file_close(int64_t handle, Error **errp)
200{
201 bool ret;
202 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
203 slog("guest-file-close called, handle: %" PRId64, handle);
204 if (gfh == NULL) {
205 return;
206 }
207 ret = CloseHandle(gfh->fh);
208 if (!ret) {
209 error_setg_win32(errp, GetLastError(), "failed close handle");
210 return;
211 }
212
213 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
214 g_free(gfh);
215}
216
217static void acquire_privilege(const char *name, Error **errp)
218{
219 HANDLE token = NULL;
220 TOKEN_PRIVILEGES priv;
221 Error *local_err = NULL;
222
223 if (OpenProcessToken(GetCurrentProcess(),
224 TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))
225 {
226 if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
227 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
228 "no luid for requested privilege");
229 goto out;
230 }
231
232 priv.PrivilegeCount = 1;
233 priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
234
235 if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
236 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
237 "unable to acquire requested privilege");
238 goto out;
239 }
240
241 } else {
242 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
243 "failed to open privilege token");
244 }
245
246out:
247 if (token) {
248 CloseHandle(token);
249 }
250 error_propagate(errp, local_err);
251}
252
253static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
254 Error **errp)
255{
256 Error *local_err = NULL;
257
258 HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
259 if (!thread) {
260 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
261 "failed to dispatch asynchronous command");
262 error_propagate(errp, local_err);
263 }
264}
265
266void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
267{
268 Error *local_err = NULL;
269 UINT shutdown_flag = EWX_FORCE;
270
271 slog("guest-shutdown called, mode: %s", mode);
272
273 if (!has_mode || strcmp(mode, "powerdown") == 0) {
274 shutdown_flag |= EWX_POWEROFF;
275 } else if (strcmp(mode, "halt") == 0) {
276 shutdown_flag |= EWX_SHUTDOWN;
277 } else if (strcmp(mode, "reboot") == 0) {
278 shutdown_flag |= EWX_REBOOT;
279 } else {
280 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
281 "halt|powerdown|reboot");
282 return;
283 }
284
285
286
287 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
288 if (local_err) {
289 error_propagate(errp, local_err);
290 return;
291 }
292
293 if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
294 slog("guest-shutdown failed: %lu", GetLastError());
295 error_setg(errp, QERR_UNDEFINED_ERROR);
296 }
297}
298
299GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
300 int64_t count, Error **errp)
301{
302 GuestFileRead *read_data = NULL;
303 guchar *buf;
304 HANDLE fh;
305 bool is_ok;
306 DWORD read_count;
307 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
308
309 if (!gfh) {
310 return NULL;
311 }
312 if (!has_count) {
313 count = QGA_READ_COUNT_DEFAULT;
314 } else if (count < 0) {
315 error_setg(errp, "value '%" PRId64
316 "' is invalid for argument count", count);
317 return NULL;
318 }
319
320 fh = gfh->fh;
321 buf = g_malloc0(count+1);
322 is_ok = ReadFile(fh, buf, count, &read_count, NULL);
323 if (!is_ok) {
324 error_setg_win32(errp, GetLastError(), "failed to read file");
325 slog("guest-file-read failed, handle %" PRId64, handle);
326 } else {
327 buf[read_count] = 0;
328 read_data = g_new0(GuestFileRead, 1);
329 read_data->count = (size_t)read_count;
330 read_data->eof = read_count == 0;
331
332 if (read_count != 0) {
333 read_data->buf_b64 = g_base64_encode(buf, read_count);
334 }
335 }
336 g_free(buf);
337
338 return read_data;
339}
340
341GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
342 bool has_count, int64_t count,
343 Error **errp)
344{
345 GuestFileWrite *write_data = NULL;
346 guchar *buf;
347 gsize buf_len;
348 bool is_ok;
349 DWORD write_count;
350 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
351 HANDLE fh;
352
353 if (!gfh) {
354 return NULL;
355 }
356 fh = gfh->fh;
357 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
358 if (!buf) {
359 return NULL;
360 }
361
362 if (!has_count) {
363 count = buf_len;
364 } else if (count < 0 || count > buf_len) {
365 error_setg(errp, "value '%" PRId64
366 "' is invalid for argument count", count);
367 goto done;
368 }
369
370 is_ok = WriteFile(fh, buf, count, &write_count, NULL);
371 if (!is_ok) {
372 error_setg_win32(errp, GetLastError(), "failed to write to file");
373 slog("guest-file-write-failed, handle: %" PRId64, handle);
374 } else {
375 write_data = g_new0(GuestFileWrite, 1);
376 write_data->count = (size_t) write_count;
377 }
378
379done:
380 g_free(buf);
381 return write_data;
382}
383
384GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
385 GuestFileWhence *whence_code,
386 Error **errp)
387{
388 GuestFileHandle *gfh;
389 GuestFileSeek *seek_data;
390 HANDLE fh;
391 LARGE_INTEGER new_pos, off_pos;
392 off_pos.QuadPart = offset;
393 BOOL res;
394 int whence;
395 Error *err = NULL;
396
397 gfh = guest_file_handle_find(handle, errp);
398 if (!gfh) {
399 return NULL;
400 }
401
402
403 whence = ga_parse_whence(whence_code, &err);
404 if (err) {
405 error_propagate(errp, err);
406 return NULL;
407 }
408
409 fh = gfh->fh;
410 res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
411 if (!res) {
412 error_setg_win32(errp, GetLastError(), "failed to seek file");
413 return NULL;
414 }
415 seek_data = g_new0(GuestFileSeek, 1);
416 seek_data->position = new_pos.QuadPart;
417 return seek_data;
418}
419
420void qmp_guest_file_flush(int64_t handle, Error **errp)
421{
422 HANDLE fh;
423 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
424 if (!gfh) {
425 return;
426 }
427
428 fh = gfh->fh;
429 if (!FlushFileBuffers(fh)) {
430 error_setg_win32(errp, GetLastError(), "failed to flush file");
431 }
432}
433
434#ifdef CONFIG_QGA_NTDDSCSI
435
436static STORAGE_BUS_TYPE win2qemu[] = {
437 [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
438 [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
439 [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
440 [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
441 [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
442 [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
443 [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
444 [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
445 [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
446#if (_WIN32_WINNT >= 0x0600)
447 [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
448 [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
449 [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
450 [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
451 [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
452#endif
453#if (_WIN32_WINNT >= 0x0601)
454 [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
455 [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
456#endif
457};
458
459static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
460{
461 if (bus > ARRAY_SIZE(win2qemu) || (int)bus < 0) {
462 return GUEST_DISK_BUS_TYPE_UNKNOWN;
463 }
464 return win2qemu[(int)bus];
465}
466
467DEFINE_GUID(GUID_DEVINTERFACE_VOLUME,
468 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2,
469 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
470
471static GuestPCIAddress *get_pci_info(char *guid, Error **errp)
472{
473 HDEVINFO dev_info;
474 SP_DEVINFO_DATA dev_info_data;
475 DWORD size = 0;
476 int i;
477 char dev_name[MAX_PATH];
478 char *buffer = NULL;
479 GuestPCIAddress *pci = NULL;
480 char *name = g_strdup(&guid[4]);
481
482 if (!QueryDosDevice(name, dev_name, ARRAY_SIZE(dev_name))) {
483 error_setg_win32(errp, GetLastError(), "failed to get dos device name");
484 goto out;
485 }
486
487 dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, 0, 0,
488 DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
489 if (dev_info == INVALID_HANDLE_VALUE) {
490 error_setg_win32(errp, GetLastError(), "failed to get devices tree");
491 goto out;
492 }
493
494 dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
495 for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
496 DWORD addr, bus, slot, func, dev, data, size2;
497 while (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
498 SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
499 &data, (PBYTE)buffer, size,
500 &size2)) {
501 size = MAX(size, size2);
502 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
503 g_free(buffer);
504
505
506
507 buffer = g_malloc(size * 2);
508 } else {
509 error_setg_win32(errp, GetLastError(),
510 "failed to get device name");
511 goto out;
512 }
513 }
514
515 if (g_strcmp0(buffer, dev_name)) {
516 continue;
517 }
518
519
520
521
522
523
524 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
525 SPDRP_BUSNUMBER, &data, (PBYTE)&bus, size, NULL)) {
526 break;
527 }
528
529
530
531 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
532 SPDRP_ADDRESS, &data, (PBYTE)&addr, size, NULL)) {
533 break;
534 }
535
536
537
538 if (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
539 SPDRP_UI_NUMBER, &data, (PBYTE)&slot, size, NULL)) {
540 break;
541 }
542
543
544
545
546
547
548
549
550 func = addr & 0x0000FFFF;
551 dev = (addr >> 16) & 0x0000FFFF;
552 pci = g_malloc0(sizeof(*pci));
553 pci->domain = dev;
554 pci->slot = slot;
555 pci->function = func;
556 pci->bus = bus;
557 break;
558 }
559out:
560 g_free(buffer);
561 g_free(name);
562 return pci;
563}
564
565static int get_disk_bus_type(HANDLE vol_h, Error **errp)
566{
567 STORAGE_PROPERTY_QUERY query;
568 STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
569 DWORD received;
570
571 dev_desc = &buf;
572 dev_desc->Size = sizeof(buf);
573 query.PropertyId = StorageDeviceProperty;
574 query.QueryType = PropertyStandardQuery;
575
576 if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
577 sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
578 dev_desc->Size, &received, NULL)) {
579 error_setg_win32(errp, GetLastError(), "failed to get bus type");
580 return -1;
581 }
582
583 return dev_desc->BusType;
584}
585
586
587
588
589static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
590{
591 GuestDiskAddressList *list = NULL;
592 GuestDiskAddress *disk;
593 SCSI_ADDRESS addr, *scsi_ad;
594 DWORD len;
595 int bus;
596 HANDLE vol_h;
597
598 scsi_ad = &addr;
599 char *name = g_strndup(guid, strlen(guid)-1);
600
601 vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
602 0, NULL);
603 if (vol_h == INVALID_HANDLE_VALUE) {
604 error_setg_win32(errp, GetLastError(), "failed to open volume");
605 goto out_free;
606 }
607
608 bus = get_disk_bus_type(vol_h, errp);
609 if (bus < 0) {
610 goto out_close;
611 }
612
613 disk = g_malloc0(sizeof(*disk));
614 disk->bus_type = find_bus_type(bus);
615 if (bus == BusTypeScsi || bus == BusTypeAta || bus == BusTypeRAID
616#if (_WIN32_WINNT >= 0x0600)
617
618 || bus == BusTypeSas
619#endif
620 ) {
621
622
623
624 if (DeviceIoControl(vol_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
625 sizeof(SCSI_ADDRESS), &len, NULL)) {
626 disk->unit = addr.Lun;
627 disk->target = addr.TargetId;
628 disk->bus = addr.PathId;
629 disk->pci_controller = get_pci_info(name, errp);
630 }
631
632
633 } else {
634 disk->pci_controller = NULL;
635 }
636
637 list = g_malloc0(sizeof(*list));
638 list->value = disk;
639 list->next = NULL;
640out_close:
641 CloseHandle(vol_h);
642out_free:
643 g_free(name);
644 return list;
645}
646
647#else
648
649static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
650{
651 return NULL;
652}
653
654#endif
655
656static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
657{
658 DWORD info_size;
659 char mnt, *mnt_point;
660 char fs_name[32];
661 char vol_info[MAX_PATH+1];
662 size_t len;
663 GuestFilesystemInfo *fs = NULL;
664
665 GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
666 if (GetLastError() != ERROR_MORE_DATA) {
667 error_setg_win32(errp, GetLastError(), "failed to get volume name");
668 return NULL;
669 }
670
671 mnt_point = g_malloc(info_size + 1);
672 if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
673 &info_size)) {
674 error_setg_win32(errp, GetLastError(), "failed to get volume name");
675 goto free;
676 }
677
678 len = strlen(mnt_point);
679 mnt_point[len] = '\\';
680 mnt_point[len+1] = 0;
681 if (!GetVolumeInformation(mnt_point, vol_info, sizeof(vol_info), NULL, NULL,
682 NULL, (LPSTR)&fs_name, sizeof(fs_name))) {
683 if (GetLastError() != ERROR_NOT_READY) {
684 error_setg_win32(errp, GetLastError(), "failed to get volume info");
685 }
686 goto free;
687 }
688
689 fs_name[sizeof(fs_name) - 1] = 0;
690 fs = g_malloc(sizeof(*fs));
691 fs->name = g_strdup(guid);
692 if (len == 0) {
693 fs->mountpoint = g_strdup("System Reserved");
694 } else {
695 fs->mountpoint = g_strndup(mnt_point, len);
696 }
697 fs->type = g_strdup(fs_name);
698 fs->disk = build_guest_disk_info(guid, errp);
699free:
700 g_free(mnt_point);
701 return fs;
702}
703
704GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
705{
706 HANDLE vol_h;
707 GuestFilesystemInfoList *new, *ret = NULL;
708 char guid[256];
709
710 vol_h = FindFirstVolume(guid, sizeof(guid));
711 if (vol_h == INVALID_HANDLE_VALUE) {
712 error_setg_win32(errp, GetLastError(), "failed to find any volume");
713 return NULL;
714 }
715
716 do {
717 GuestFilesystemInfo *info = build_guest_fsinfo(guid, errp);
718 if (info == NULL) {
719 continue;
720 }
721 new = g_malloc(sizeof(*ret));
722 new->value = info;
723 new->next = ret;
724 ret = new;
725 } while (FindNextVolume(vol_h, guid, sizeof(guid)));
726
727 if (GetLastError() != ERROR_NO_MORE_FILES) {
728 error_setg_win32(errp, GetLastError(), "failed to find next volume");
729 }
730
731 FindVolumeClose(vol_h);
732 return ret;
733}
734
735
736
737
738GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
739{
740 if (!vss_initialized()) {
741 error_setg(errp, QERR_UNSUPPORTED);
742 return 0;
743 }
744
745 if (ga_is_frozen(ga_state)) {
746 return GUEST_FSFREEZE_STATUS_FROZEN;
747 }
748
749 return GUEST_FSFREEZE_STATUS_THAWED;
750}
751
752
753
754
755
756int64_t qmp_guest_fsfreeze_freeze(Error **errp)
757{
758 int i;
759 Error *local_err = NULL;
760
761 if (!vss_initialized()) {
762 error_setg(errp, QERR_UNSUPPORTED);
763 return 0;
764 }
765
766 slog("guest-fsfreeze called");
767
768
769 ga_set_frozen(ga_state);
770
771 qga_vss_fsfreeze(&i, &local_err, true);
772 if (local_err) {
773 error_propagate(errp, local_err);
774 goto error;
775 }
776
777 return i;
778
779error:
780 local_err = NULL;
781 qmp_guest_fsfreeze_thaw(&local_err);
782 if (local_err) {
783 g_debug("cleanup thaw: %s", error_get_pretty(local_err));
784 error_free(local_err);
785 }
786 return 0;
787}
788
789int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
790 strList *mountpoints,
791 Error **errp)
792{
793 error_setg(errp, QERR_UNSUPPORTED);
794
795 return 0;
796}
797
798
799
800
801int64_t qmp_guest_fsfreeze_thaw(Error **errp)
802{
803 int i;
804
805 if (!vss_initialized()) {
806 error_setg(errp, QERR_UNSUPPORTED);
807 return 0;
808 }
809
810 qga_vss_fsfreeze(&i, errp, false);
811
812 ga_unset_frozen(ga_state);
813 return i;
814}
815
816static void guest_fsfreeze_cleanup(void)
817{
818 Error *err = NULL;
819
820 if (!vss_initialized()) {
821 return;
822 }
823
824 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
825 qmp_guest_fsfreeze_thaw(&err);
826 if (err) {
827 slog("failed to clean up frozen filesystems: %s",
828 error_get_pretty(err));
829 error_free(err);
830 }
831 }
832
833 vss_deinit(true);
834}
835
836
837
838
839
840GuestFilesystemTrimResponse *
841qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
842{
843 error_setg(errp, QERR_UNSUPPORTED);
844 return NULL;
845}
846
847typedef enum {
848 GUEST_SUSPEND_MODE_DISK,
849 GUEST_SUSPEND_MODE_RAM
850} GuestSuspendMode;
851
852static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
853{
854 SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
855 Error *local_err = NULL;
856
857 ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
858 if (!GetPwrCapabilities(&sys_pwr_caps)) {
859 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
860 "failed to determine guest suspend capabilities");
861 goto out;
862 }
863
864 switch (mode) {
865 case GUEST_SUSPEND_MODE_DISK:
866 if (!sys_pwr_caps.SystemS4) {
867 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
868 "suspend-to-disk not supported by OS");
869 }
870 break;
871 case GUEST_SUSPEND_MODE_RAM:
872 if (!sys_pwr_caps.SystemS3) {
873 error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
874 "suspend-to-ram not supported by OS");
875 }
876 break;
877 default:
878 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",
879 "GuestSuspendMode");
880 }
881
882out:
883 error_propagate(errp, local_err);
884}
885
886static DWORD WINAPI do_suspend(LPVOID opaque)
887{
888 GuestSuspendMode *mode = opaque;
889 DWORD ret = 0;
890
891 if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
892 slog("failed to suspend guest, %lu", GetLastError());
893 ret = -1;
894 }
895 g_free(mode);
896 return ret;
897}
898
899void qmp_guest_suspend_disk(Error **errp)
900{
901 Error *local_err = NULL;
902 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
903
904 *mode = GUEST_SUSPEND_MODE_DISK;
905 check_suspend_mode(*mode, &local_err);
906 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
907 execute_async(do_suspend, mode, &local_err);
908
909 if (local_err) {
910 error_propagate(errp, local_err);
911 g_free(mode);
912 }
913}
914
915void qmp_guest_suspend_ram(Error **errp)
916{
917 Error *local_err = NULL;
918 GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
919
920 *mode = GUEST_SUSPEND_MODE_RAM;
921 check_suspend_mode(*mode, &local_err);
922 acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
923 execute_async(do_suspend, mode, &local_err);
924
925 if (local_err) {
926 error_propagate(errp, local_err);
927 g_free(mode);
928 }
929}
930
931void qmp_guest_suspend_hybrid(Error **errp)
932{
933 error_setg(errp, QERR_UNSUPPORTED);
934}
935
936static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
937{
938 IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
939 ULONG adptr_addrs_len = 0;
940 DWORD ret;
941
942
943 GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
944 NULL, adptr_addrs, &adptr_addrs_len);
945
946 adptr_addrs = g_malloc(adptr_addrs_len);
947 ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
948 NULL, adptr_addrs, &adptr_addrs_len);
949 if (ret != ERROR_SUCCESS) {
950 error_setg_win32(errp, ret, "failed to get adapters addresses");
951 g_free(adptr_addrs);
952 adptr_addrs = NULL;
953 }
954 return adptr_addrs;
955}
956
957static char *guest_wctomb_dup(WCHAR *wstr)
958{
959 char *str;
960 size_t i;
961
962 i = wcslen(wstr) + 1;
963 str = g_malloc(i);
964 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK,
965 wstr, -1, str, i, NULL, NULL);
966 return str;
967}
968
969static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
970 Error **errp)
971{
972 char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
973 DWORD len;
974 int ret;
975
976 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
977 ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
978 len = sizeof(addr_str);
979 ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
980 ip_addr->Address.iSockaddrLength,
981 NULL,
982 addr_str,
983 &len);
984 if (ret != 0) {
985 error_setg_win32(errp, WSAGetLastError(),
986 "failed address presentation form conversion");
987 return NULL;
988 }
989 return g_strdup(addr_str);
990 }
991 return NULL;
992}
993
994#if (_WIN32_WINNT >= 0x0600)
995static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
996{
997
998
999
1000 return ip_addr->OnLinkPrefixLength;
1001}
1002#else
1003
1004
1005
1006static IP_ADAPTER_INFO *guest_get_adapters_info(void)
1007{
1008 IP_ADAPTER_INFO *adptr_info = NULL;
1009 ULONG adptr_info_len = 0;
1010 DWORD ret;
1011
1012
1013 GetAdaptersInfo(adptr_info, &adptr_info_len);
1014
1015 adptr_info = g_malloc(adptr_info_len);
1016 ret = GetAdaptersInfo(adptr_info, &adptr_info_len);
1017 if (ret != ERROR_SUCCESS) {
1018 g_free(adptr_info);
1019 adptr_info = NULL;
1020 }
1021 return adptr_info;
1022}
1023
1024static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1025{
1026 int64_t prefix = -1;
1027 IP_ADAPTER_INFO *adptr_info, *info;
1028 IP_ADDR_STRING *ip;
1029 struct in_addr *p;
1030
1031 if (ip_addr->Address.lpSockaddr->sa_family != AF_INET) {
1032 return prefix;
1033 }
1034 adptr_info = guest_get_adapters_info();
1035 if (adptr_info == NULL) {
1036 return prefix;
1037 }
1038
1039
1040
1041
1042 p = &((struct sockaddr_in *)ip_addr->Address.lpSockaddr)->sin_addr;
1043 for (info = adptr_info; info; info = info->Next) {
1044 for (ip = &info->IpAddressList; ip; ip = ip->Next) {
1045 if (p->S_un.S_addr == inet_addr(ip->IpAddress.String)) {
1046 prefix = ctpop32(inet_addr(ip->IpMask.String));
1047 goto out;
1048 }
1049 }
1050 }
1051out:
1052 g_free(adptr_info);
1053 return prefix;
1054}
1055#endif
1056
1057GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1058{
1059 IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1060 IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1061 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1062 GuestIpAddressList *head_addr, *cur_addr;
1063 GuestNetworkInterfaceList *info;
1064 GuestIpAddressList *address_item = NULL;
1065 unsigned char *mac_addr;
1066 char *addr_str;
1067 WORD wsa_version;
1068 WSADATA wsa_data;
1069 int ret;
1070
1071 adptr_addrs = guest_get_adapters_addresses(errp);
1072 if (adptr_addrs == NULL) {
1073 return NULL;
1074 }
1075
1076
1077 wsa_version = MAKEWORD(2, 2);
1078 ret = WSAStartup(wsa_version, &wsa_data);
1079 if (ret != 0) {
1080 error_setg_win32(errp, ret, "failed socket startup");
1081 goto out;
1082 }
1083
1084 for (addr = adptr_addrs; addr; addr = addr->Next) {
1085 info = g_malloc0(sizeof(*info));
1086
1087 if (cur_item == NULL) {
1088 head = cur_item = info;
1089 } else {
1090 cur_item->next = info;
1091 cur_item = info;
1092 }
1093
1094 info->value = g_malloc0(sizeof(*info->value));
1095 info->value->name = guest_wctomb_dup(addr->FriendlyName);
1096
1097 if (addr->PhysicalAddressLength != 0) {
1098 mac_addr = addr->PhysicalAddress;
1099
1100 info->value->hardware_address =
1101 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1102 (int) mac_addr[0], (int) mac_addr[1],
1103 (int) mac_addr[2], (int) mac_addr[3],
1104 (int) mac_addr[4], (int) mac_addr[5]);
1105
1106 info->value->has_hardware_address = true;
1107 }
1108
1109 head_addr = NULL;
1110 cur_addr = NULL;
1111 for (ip_addr = addr->FirstUnicastAddress;
1112 ip_addr;
1113 ip_addr = ip_addr->Next) {
1114 addr_str = guest_addr_to_str(ip_addr, errp);
1115 if (addr_str == NULL) {
1116 continue;
1117 }
1118
1119 address_item = g_malloc0(sizeof(*address_item));
1120
1121 if (!cur_addr) {
1122 head_addr = cur_addr = address_item;
1123 } else {
1124 cur_addr->next = address_item;
1125 cur_addr = address_item;
1126 }
1127
1128 address_item->value = g_malloc0(sizeof(*address_item->value));
1129 address_item->value->ip_address = addr_str;
1130 address_item->value->prefix = guest_ip_prefix(ip_addr);
1131 if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1132 address_item->value->ip_address_type =
1133 GUEST_IP_ADDRESS_TYPE_IPV4;
1134 } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1135 address_item->value->ip_address_type =
1136 GUEST_IP_ADDRESS_TYPE_IPV6;
1137 }
1138 }
1139 if (head_addr) {
1140 info->value->has_ip_addresses = true;
1141 info->value->ip_addresses = head_addr;
1142 }
1143 }
1144 WSACleanup();
1145out:
1146 g_free(adptr_addrs);
1147 return head;
1148}
1149
1150int64_t qmp_guest_get_time(Error **errp)
1151{
1152 SYSTEMTIME ts = {0};
1153 FILETIME tf;
1154
1155 GetSystemTime(&ts);
1156 if (ts.wYear < 1601 || ts.wYear > 30827) {
1157 error_setg(errp, "Failed to get time");
1158 return -1;
1159 }
1160
1161 if (!SystemTimeToFileTime(&ts, &tf)) {
1162 error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1163 return -1;
1164 }
1165
1166 return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1167 - W32_FT_OFFSET) * 100;
1168}
1169
1170void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1171{
1172 Error *local_err = NULL;
1173 SYSTEMTIME ts;
1174 FILETIME tf;
1175 LONGLONG time;
1176
1177 if (!has_time) {
1178
1179
1180
1181
1182
1183 error_setg(errp, "Time argument is required on this platform");
1184 return;
1185 }
1186
1187
1188 if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1189 error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1190 return;
1191 }
1192
1193 time = time_ns / 100 + W32_FT_OFFSET;
1194
1195 tf.dwLowDateTime = (DWORD) time;
1196 tf.dwHighDateTime = (DWORD) (time >> 32);
1197
1198 if (!FileTimeToSystemTime(&tf, &ts)) {
1199 error_setg(errp, "Failed to convert system time %d",
1200 (int)GetLastError());
1201 return;
1202 }
1203
1204 acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1205 if (local_err) {
1206 error_propagate(errp, local_err);
1207 return;
1208 }
1209
1210 if (!SetSystemTime(&ts)) {
1211 error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1212 return;
1213 }
1214}
1215
1216GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1217{
1218 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1219 DWORD length;
1220 GuestLogicalProcessorList *head, **link;
1221 Error *local_err = NULL;
1222 int64_t current;
1223
1224 ptr = pslpi = NULL;
1225 length = 0;
1226 current = 0;
1227 head = NULL;
1228 link = &head;
1229
1230 if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1231 (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1232 (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1233 ptr = pslpi = g_malloc0(length);
1234 if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1235 error_setg(&local_err, "Failed to get processor information: %d",
1236 (int)GetLastError());
1237 }
1238 } else {
1239 error_setg(&local_err,
1240 "Failed to get processor information buffer length: %d",
1241 (int)GetLastError());
1242 }
1243
1244 while ((local_err == NULL) && (length > 0)) {
1245 if (pslpi->Relationship == RelationProcessorCore) {
1246 ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1247
1248 while (cpu_bits > 0) {
1249 if (!!(cpu_bits & 1)) {
1250 GuestLogicalProcessor *vcpu;
1251 GuestLogicalProcessorList *entry;
1252
1253 vcpu = g_malloc0(sizeof *vcpu);
1254 vcpu->logical_id = current++;
1255 vcpu->online = true;
1256 vcpu->has_can_offline = false;
1257
1258 entry = g_malloc0(sizeof *entry);
1259 entry->value = vcpu;
1260
1261 *link = entry;
1262 link = &entry->next;
1263 }
1264 cpu_bits >>= 1;
1265 }
1266 }
1267 length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1268 pslpi++;
1269 }
1270
1271 g_free(ptr);
1272
1273 if (local_err == NULL) {
1274 if (head != NULL) {
1275 return head;
1276 }
1277
1278 error_setg(&local_err, "Guest reported zero VCPUs");
1279 }
1280
1281 qapi_free_GuestLogicalProcessorList(head);
1282 error_propagate(errp, local_err);
1283 return NULL;
1284}
1285
1286int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1287{
1288 error_setg(errp, QERR_UNSUPPORTED);
1289 return -1;
1290}
1291
1292static gchar *
1293get_net_error_message(gint error)
1294{
1295 HMODULE module = NULL;
1296 gchar *retval = NULL;
1297 wchar_t *msg = NULL;
1298 int flags;
1299 size_t nchars;
1300
1301 flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1302 FORMAT_MESSAGE_IGNORE_INSERTS |
1303 FORMAT_MESSAGE_FROM_SYSTEM;
1304
1305 if (error >= NERR_BASE && error <= MAX_NERR) {
1306 module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1307
1308 if (module != NULL) {
1309 flags |= FORMAT_MESSAGE_FROM_HMODULE;
1310 }
1311 }
1312
1313 FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1314
1315 if (msg != NULL) {
1316 nchars = wcslen(msg);
1317
1318 if (nchars >= 2 &&
1319 msg[nchars - 1] == L'\n' &&
1320 msg[nchars - 2] == L'\r') {
1321 msg[nchars - 2] = L'\0';
1322 }
1323
1324 retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1325
1326 LocalFree(msg);
1327 }
1328
1329 if (module != NULL) {
1330 FreeLibrary(module);
1331 }
1332
1333 return retval;
1334}
1335
1336void qmp_guest_set_user_password(const char *username,
1337 const char *password,
1338 bool crypted,
1339 Error **errp)
1340{
1341 NET_API_STATUS nas;
1342 char *rawpasswddata = NULL;
1343 size_t rawpasswdlen;
1344 wchar_t *user = NULL, *wpass = NULL;
1345 USER_INFO_1003 pi1003 = { 0, };
1346 GError *gerr = NULL;
1347
1348 if (crypted) {
1349 error_setg(errp, QERR_UNSUPPORTED);
1350 return;
1351 }
1352
1353 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1354 if (!rawpasswddata) {
1355 return;
1356 }
1357 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1358 rawpasswddata[rawpasswdlen] = '\0';
1359
1360 user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1361 if (!user) {
1362 goto done;
1363 }
1364
1365 wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1366 if (!wpass) {
1367 goto done;
1368 }
1369
1370 pi1003.usri1003_password = wpass;
1371 nas = NetUserSetInfo(NULL, user,
1372 1003, (LPBYTE)&pi1003,
1373 NULL);
1374
1375 if (nas != NERR_Success) {
1376 gchar *msg = get_net_error_message(nas);
1377 error_setg(errp, "failed to set password: %s", msg);
1378 g_free(msg);
1379 }
1380
1381done:
1382 if (gerr) {
1383 error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1384 g_error_free(gerr);
1385 }
1386 g_free(user);
1387 g_free(wpass);
1388 g_free(rawpasswddata);
1389}
1390
1391GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1392{
1393 error_setg(errp, QERR_UNSUPPORTED);
1394 return NULL;
1395}
1396
1397GuestMemoryBlockResponseList *
1398qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1399{
1400 error_setg(errp, QERR_UNSUPPORTED);
1401 return NULL;
1402}
1403
1404GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1405{
1406 error_setg(errp, QERR_UNSUPPORTED);
1407 return NULL;
1408}
1409
1410
1411GList *ga_command_blacklist_init(GList *blacklist)
1412{
1413 const char *list_unsupported[] = {
1414 "guest-suspend-hybrid",
1415 "guest-set-vcpus",
1416 "guest-get-memory-blocks", "guest-set-memory-blocks",
1417 "guest-get-memory-block-size",
1418 "guest-fsfreeze-freeze-list",
1419 "guest-fstrim", NULL};
1420 char **p = (char **)list_unsupported;
1421
1422 while (*p) {
1423 blacklist = g_list_append(blacklist, g_strdup(*p++));
1424 }
1425
1426 if (!vss_init(true)) {
1427 g_debug("vss_init failed, vss commands are going to be disabled");
1428 const char *list[] = {
1429 "guest-get-fsinfo", "guest-fsfreeze-status",
1430 "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1431 p = (char **)list;
1432
1433 while (*p) {
1434 blacklist = g_list_append(blacklist, g_strdup(*p++));
1435 }
1436 }
1437
1438 return blacklist;
1439}
1440
1441
1442void ga_command_state_init(GAState *s, GACommandState *cs)
1443{
1444 if (!vss_initialized()) {
1445 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1446 }
1447}
1448