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