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