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