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