xref: /openbmc/qemu/qga/commands-win32.c (revision e3a99063)
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     if (local_err) {
1326         goto out;
1327     }
1328     acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1329     if (local_err) {
1330         goto out;
1331     }
1332     execute_async(do_suspend, mode, &local_err);
1333 
1334 out:
1335     if (local_err) {
1336         error_propagate(errp, local_err);
1337         g_free(mode);
1338     }
1339 }
1340 
1341 void qmp_guest_suspend_ram(Error **errp)
1342 {
1343     Error *local_err = NULL;
1344     GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
1345 
1346     *mode = GUEST_SUSPEND_MODE_RAM;
1347     check_suspend_mode(*mode, &local_err);
1348     if (local_err) {
1349         goto out;
1350     }
1351     acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
1352     if (local_err) {
1353         goto out;
1354     }
1355     execute_async(do_suspend, mode, &local_err);
1356 
1357 out:
1358     if (local_err) {
1359         error_propagate(errp, local_err);
1360         g_free(mode);
1361     }
1362 }
1363 
1364 void qmp_guest_suspend_hybrid(Error **errp)
1365 {
1366     error_setg(errp, QERR_UNSUPPORTED);
1367 }
1368 
1369 static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
1370 {
1371     IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
1372     ULONG adptr_addrs_len = 0;
1373     DWORD ret;
1374 
1375     /* Call the first time to get the adptr_addrs_len. */
1376     GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1377                          NULL, adptr_addrs, &adptr_addrs_len);
1378 
1379     adptr_addrs = g_malloc(adptr_addrs_len);
1380     ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
1381                                NULL, adptr_addrs, &adptr_addrs_len);
1382     if (ret != ERROR_SUCCESS) {
1383         error_setg_win32(errp, ret, "failed to get adapters addresses");
1384         g_free(adptr_addrs);
1385         adptr_addrs = NULL;
1386     }
1387     return adptr_addrs;
1388 }
1389 
1390 static char *guest_wctomb_dup(WCHAR *wstr)
1391 {
1392     char *str;
1393     size_t str_size;
1394 
1395     str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
1396     /* add 1 to str_size for NULL terminator */
1397     str = g_malloc(str_size + 1);
1398     WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
1399     return str;
1400 }
1401 
1402 static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
1403                                Error **errp)
1404 {
1405     char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
1406     DWORD len;
1407     int ret;
1408 
1409     if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
1410             ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1411         len = sizeof(addr_str);
1412         ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
1413                                  ip_addr->Address.iSockaddrLength,
1414                                  NULL,
1415                                  addr_str,
1416                                  &len);
1417         if (ret != 0) {
1418             error_setg_win32(errp, WSAGetLastError(),
1419                 "failed address presentation form conversion");
1420             return NULL;
1421         }
1422         return g_strdup(addr_str);
1423     }
1424     return NULL;
1425 }
1426 
1427 static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
1428 {
1429     /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
1430      * field to obtain the prefix.
1431      */
1432     return ip_addr->OnLinkPrefixLength;
1433 }
1434 
1435 #define INTERFACE_PATH_BUF_SZ 512
1436 
1437 static DWORD get_interface_index(const char *guid)
1438 {
1439     ULONG index;
1440     DWORD status;
1441     wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
1442     snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
1443     wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
1444     status = GetAdapterIndex (wbuf, &index);
1445     if (status != NO_ERROR) {
1446         return (DWORD)~0;
1447     } else {
1448         return index;
1449     }
1450 }
1451 
1452 typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
1453 
1454 static int guest_get_network_stats(const char *name,
1455                                    GuestNetworkInterfaceStat *stats)
1456 {
1457     OSVERSIONINFO os_ver;
1458 
1459     os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1460     GetVersionEx(&os_ver);
1461     if (os_ver.dwMajorVersion >= 6) {
1462         MIB_IF_ROW2 a_mid_ifrow;
1463         GetIfEntry2Func getifentry2_ex;
1464         DWORD if_index = 0;
1465         HMODULE module = GetModuleHandle("iphlpapi");
1466         PVOID func = GetProcAddress(module, "GetIfEntry2");
1467 
1468         if (func == NULL) {
1469             return -1;
1470         }
1471 
1472         getifentry2_ex = (GetIfEntry2Func)func;
1473         if_index = get_interface_index(name);
1474         if (if_index == (DWORD)~0) {
1475             return -1;
1476         }
1477 
1478         memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
1479         a_mid_ifrow.InterfaceIndex = if_index;
1480         if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
1481             stats->rx_bytes = a_mid_ifrow.InOctets;
1482             stats->rx_packets = a_mid_ifrow.InUcastPkts;
1483             stats->rx_errs = a_mid_ifrow.InErrors;
1484             stats->rx_dropped = a_mid_ifrow.InDiscards;
1485             stats->tx_bytes = a_mid_ifrow.OutOctets;
1486             stats->tx_packets = a_mid_ifrow.OutUcastPkts;
1487             stats->tx_errs = a_mid_ifrow.OutErrors;
1488             stats->tx_dropped = a_mid_ifrow.OutDiscards;
1489             return 0;
1490         }
1491     }
1492     return -1;
1493 }
1494 
1495 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1496 {
1497     IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
1498     IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
1499     GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1500     GuestIpAddressList *head_addr, *cur_addr;
1501     GuestNetworkInterfaceList *info;
1502     GuestNetworkInterfaceStat *interface_stat = NULL;
1503     GuestIpAddressList *address_item = NULL;
1504     unsigned char *mac_addr;
1505     char *addr_str;
1506     WORD wsa_version;
1507     WSADATA wsa_data;
1508     int ret;
1509 
1510     adptr_addrs = guest_get_adapters_addresses(errp);
1511     if (adptr_addrs == NULL) {
1512         return NULL;
1513     }
1514 
1515     /* Make WSA APIs available. */
1516     wsa_version = MAKEWORD(2, 2);
1517     ret = WSAStartup(wsa_version, &wsa_data);
1518     if (ret != 0) {
1519         error_setg_win32(errp, ret, "failed socket startup");
1520         goto out;
1521     }
1522 
1523     for (addr = adptr_addrs; addr; addr = addr->Next) {
1524         info = g_malloc0(sizeof(*info));
1525 
1526         if (cur_item == NULL) {
1527             head = cur_item = info;
1528         } else {
1529             cur_item->next = info;
1530             cur_item = info;
1531         }
1532 
1533         info->value = g_malloc0(sizeof(*info->value));
1534         info->value->name = guest_wctomb_dup(addr->FriendlyName);
1535 
1536         if (addr->PhysicalAddressLength != 0) {
1537             mac_addr = addr->PhysicalAddress;
1538 
1539             info->value->hardware_address =
1540                 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1541                                 (int) mac_addr[0], (int) mac_addr[1],
1542                                 (int) mac_addr[2], (int) mac_addr[3],
1543                                 (int) mac_addr[4], (int) mac_addr[5]);
1544 
1545             info->value->has_hardware_address = true;
1546         }
1547 
1548         head_addr = NULL;
1549         cur_addr = NULL;
1550         for (ip_addr = addr->FirstUnicastAddress;
1551                 ip_addr;
1552                 ip_addr = ip_addr->Next) {
1553             addr_str = guest_addr_to_str(ip_addr, errp);
1554             if (addr_str == NULL) {
1555                 continue;
1556             }
1557 
1558             address_item = g_malloc0(sizeof(*address_item));
1559 
1560             if (!cur_addr) {
1561                 head_addr = cur_addr = address_item;
1562             } else {
1563                 cur_addr->next = address_item;
1564                 cur_addr = address_item;
1565             }
1566 
1567             address_item->value = g_malloc0(sizeof(*address_item->value));
1568             address_item->value->ip_address = addr_str;
1569             address_item->value->prefix = guest_ip_prefix(ip_addr);
1570             if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
1571                 address_item->value->ip_address_type =
1572                     GUEST_IP_ADDRESS_TYPE_IPV4;
1573             } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
1574                 address_item->value->ip_address_type =
1575                     GUEST_IP_ADDRESS_TYPE_IPV6;
1576             }
1577         }
1578         if (head_addr) {
1579             info->value->has_ip_addresses = true;
1580             info->value->ip_addresses = head_addr;
1581         }
1582         if (!info->value->has_statistics) {
1583             interface_stat = g_malloc0(sizeof(*interface_stat));
1584             if (guest_get_network_stats(addr->AdapterName,
1585                 interface_stat) == -1) {
1586                 info->value->has_statistics = false;
1587                 g_free(interface_stat);
1588             } else {
1589                 info->value->statistics = interface_stat;
1590                 info->value->has_statistics = true;
1591             }
1592         }
1593     }
1594     WSACleanup();
1595 out:
1596     g_free(adptr_addrs);
1597     return head;
1598 }
1599 
1600 int64_t qmp_guest_get_time(Error **errp)
1601 {
1602     SYSTEMTIME ts = {0};
1603     FILETIME tf;
1604 
1605     GetSystemTime(&ts);
1606     if (ts.wYear < 1601 || ts.wYear > 30827) {
1607         error_setg(errp, "Failed to get time");
1608         return -1;
1609     }
1610 
1611     if (!SystemTimeToFileTime(&ts, &tf)) {
1612         error_setg(errp, "Failed to convert system time: %d", (int)GetLastError());
1613         return -1;
1614     }
1615 
1616     return ((((int64_t)tf.dwHighDateTime << 32) | tf.dwLowDateTime)
1617                 - W32_FT_OFFSET) * 100;
1618 }
1619 
1620 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
1621 {
1622     Error *local_err = NULL;
1623     SYSTEMTIME ts;
1624     FILETIME tf;
1625     LONGLONG time;
1626 
1627     if (!has_time) {
1628         /* Unfortunately, Windows libraries don't provide an easy way to access
1629          * RTC yet:
1630          *
1631          * https://msdn.microsoft.com/en-us/library/aa908981.aspx
1632          *
1633          * Instead, a workaround is to use the Windows win32tm command to
1634          * resync the time using the Windows Time service.
1635          */
1636         LPVOID msg_buffer;
1637         DWORD ret_flags;
1638 
1639         HRESULT hr = system("w32tm /resync /nowait");
1640 
1641         if (GetLastError() != 0) {
1642             strerror_s((LPTSTR) & msg_buffer, 0, errno);
1643             error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
1644         } else if (hr != 0) {
1645             if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
1646                 error_setg(errp, "Windows Time service not running on the "
1647                                  "guest");
1648             } else {
1649                 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1650                                    FORMAT_MESSAGE_FROM_SYSTEM |
1651                                    FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
1652                                    (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
1653                                    SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
1654                                    NULL)) {
1655                     error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
1656                                      "t retrieve error message", hr);
1657                 } else {
1658                     error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
1659                                (LPCTSTR)msg_buffer);
1660                     LocalFree(msg_buffer);
1661                 }
1662             }
1663         } else if (!InternetGetConnectedState(&ret_flags, 0)) {
1664             error_setg(errp, "No internet connection on guest, sync not "
1665                              "accurate");
1666         }
1667         return;
1668     }
1669 
1670     /* Validate time passed by user. */
1671     if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
1672         error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
1673         return;
1674     }
1675 
1676     time = time_ns / 100 + W32_FT_OFFSET;
1677 
1678     tf.dwLowDateTime = (DWORD) time;
1679     tf.dwHighDateTime = (DWORD) (time >> 32);
1680 
1681     if (!FileTimeToSystemTime(&tf, &ts)) {
1682         error_setg(errp, "Failed to convert system time %d",
1683                    (int)GetLastError());
1684         return;
1685     }
1686 
1687     acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
1688     if (local_err) {
1689         error_propagate(errp, local_err);
1690         return;
1691     }
1692 
1693     if (!SetSystemTime(&ts)) {
1694         error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
1695         return;
1696     }
1697 }
1698 
1699 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1700 {
1701     PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
1702     DWORD length;
1703     GuestLogicalProcessorList *head, **link;
1704     Error *local_err = NULL;
1705     int64_t current;
1706 
1707     ptr = pslpi = NULL;
1708     length = 0;
1709     current = 0;
1710     head = NULL;
1711     link = &head;
1712 
1713     if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
1714         (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1715         (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
1716         ptr = pslpi = g_malloc0(length);
1717         if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
1718             error_setg(&local_err, "Failed to get processor information: %d",
1719                        (int)GetLastError());
1720         }
1721     } else {
1722         error_setg(&local_err,
1723                    "Failed to get processor information buffer length: %d",
1724                    (int)GetLastError());
1725     }
1726 
1727     while ((local_err == NULL) && (length > 0)) {
1728         if (pslpi->Relationship == RelationProcessorCore) {
1729             ULONG_PTR cpu_bits = pslpi->ProcessorMask;
1730 
1731             while (cpu_bits > 0) {
1732                 if (!!(cpu_bits & 1)) {
1733                     GuestLogicalProcessor *vcpu;
1734                     GuestLogicalProcessorList *entry;
1735 
1736                     vcpu = g_malloc0(sizeof *vcpu);
1737                     vcpu->logical_id = current++;
1738                     vcpu->online = true;
1739                     vcpu->has_can_offline = true;
1740 
1741                     entry = g_malloc0(sizeof *entry);
1742                     entry->value = vcpu;
1743 
1744                     *link = entry;
1745                     link = &entry->next;
1746                 }
1747                 cpu_bits >>= 1;
1748             }
1749         }
1750         length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1751         pslpi++; /* next entry */
1752     }
1753 
1754     g_free(ptr);
1755 
1756     if (local_err == NULL) {
1757         if (head != NULL) {
1758             return head;
1759         }
1760         /* there's no guest with zero VCPUs */
1761         error_setg(&local_err, "Guest reported zero VCPUs");
1762     }
1763 
1764     qapi_free_GuestLogicalProcessorList(head);
1765     error_propagate(errp, local_err);
1766     return NULL;
1767 }
1768 
1769 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1770 {
1771     error_setg(errp, QERR_UNSUPPORTED);
1772     return -1;
1773 }
1774 
1775 static gchar *
1776 get_net_error_message(gint error)
1777 {
1778     HMODULE module = NULL;
1779     gchar *retval = NULL;
1780     wchar_t *msg = NULL;
1781     int flags;
1782     size_t nchars;
1783 
1784     flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
1785         FORMAT_MESSAGE_IGNORE_INSERTS |
1786         FORMAT_MESSAGE_FROM_SYSTEM;
1787 
1788     if (error >= NERR_BASE && error <= MAX_NERR) {
1789         module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
1790 
1791         if (module != NULL) {
1792             flags |= FORMAT_MESSAGE_FROM_HMODULE;
1793         }
1794     }
1795 
1796     FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
1797 
1798     if (msg != NULL) {
1799         nchars = wcslen(msg);
1800 
1801         if (nchars >= 2 &&
1802             msg[nchars - 1] == L'\n' &&
1803             msg[nchars - 2] == L'\r') {
1804             msg[nchars - 2] = L'\0';
1805         }
1806 
1807         retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
1808 
1809         LocalFree(msg);
1810     }
1811 
1812     if (module != NULL) {
1813         FreeLibrary(module);
1814     }
1815 
1816     return retval;
1817 }
1818 
1819 void qmp_guest_set_user_password(const char *username,
1820                                  const char *password,
1821                                  bool crypted,
1822                                  Error **errp)
1823 {
1824     NET_API_STATUS nas;
1825     char *rawpasswddata = NULL;
1826     size_t rawpasswdlen;
1827     wchar_t *user = NULL, *wpass = NULL;
1828     USER_INFO_1003 pi1003 = { 0, };
1829     GError *gerr = NULL;
1830 
1831     if (crypted) {
1832         error_setg(errp, QERR_UNSUPPORTED);
1833         return;
1834     }
1835 
1836     rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
1837     if (!rawpasswddata) {
1838         return;
1839     }
1840     rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1841     rawpasswddata[rawpasswdlen] = '\0';
1842 
1843     user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
1844     if (!user) {
1845         goto done;
1846     }
1847 
1848     wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
1849     if (!wpass) {
1850         goto done;
1851     }
1852 
1853     pi1003.usri1003_password = wpass;
1854     nas = NetUserSetInfo(NULL, user,
1855                          1003, (LPBYTE)&pi1003,
1856                          NULL);
1857 
1858     if (nas != NERR_Success) {
1859         gchar *msg = get_net_error_message(nas);
1860         error_setg(errp, "failed to set password: %s", msg);
1861         g_free(msg);
1862     }
1863 
1864 done:
1865     if (gerr) {
1866         error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
1867         g_error_free(gerr);
1868     }
1869     g_free(user);
1870     g_free(wpass);
1871     g_free(rawpasswddata);
1872 }
1873 
1874 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1875 {
1876     error_setg(errp, QERR_UNSUPPORTED);
1877     return NULL;
1878 }
1879 
1880 GuestMemoryBlockResponseList *
1881 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1882 {
1883     error_setg(errp, QERR_UNSUPPORTED);
1884     return NULL;
1885 }
1886 
1887 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1888 {
1889     error_setg(errp, QERR_UNSUPPORTED);
1890     return NULL;
1891 }
1892 
1893 /* add unsupported commands to the blacklist */
1894 GList *ga_command_blacklist_init(GList *blacklist)
1895 {
1896     const char *list_unsupported[] = {
1897         "guest-suspend-hybrid",
1898         "guest-set-vcpus",
1899         "guest-get-memory-blocks", "guest-set-memory-blocks",
1900         "guest-get-memory-block-size", "guest-get-memory-block-info",
1901         NULL};
1902     char **p = (char **)list_unsupported;
1903 
1904     while (*p) {
1905         blacklist = g_list_append(blacklist, g_strdup(*p++));
1906     }
1907 
1908     if (!vss_init(true)) {
1909         g_debug("vss_init failed, vss commands are going to be disabled");
1910         const char *list[] = {
1911             "guest-get-fsinfo", "guest-fsfreeze-status",
1912             "guest-fsfreeze-freeze", "guest-fsfreeze-thaw", NULL};
1913         p = (char **)list;
1914 
1915         while (*p) {
1916             blacklist = g_list_append(blacklist, g_strdup(*p++));
1917         }
1918     }
1919 
1920     return blacklist;
1921 }
1922 
1923 /* register init/cleanup routines for stateful command groups */
1924 void ga_command_state_init(GAState *s, GACommandState *cs)
1925 {
1926     if (!vss_initialized()) {
1927         ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1928     }
1929 }
1930 
1931 /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
1932 typedef struct _GA_WTSINFOA {
1933     WTS_CONNECTSTATE_CLASS State;
1934     DWORD SessionId;
1935     DWORD IncomingBytes;
1936     DWORD OutgoingBytes;
1937     DWORD IncomingFrames;
1938     DWORD OutgoingFrames;
1939     DWORD IncomingCompressedBytes;
1940     DWORD OutgoingCompressedBy;
1941     CHAR WinStationName[WINSTATIONNAME_LENGTH];
1942     CHAR Domain[DOMAIN_LENGTH];
1943     CHAR UserName[USERNAME_LENGTH + 1];
1944     LARGE_INTEGER ConnectTime;
1945     LARGE_INTEGER DisconnectTime;
1946     LARGE_INTEGER LastInputTime;
1947     LARGE_INTEGER LogonTime;
1948     LARGE_INTEGER CurrentTime;
1949 
1950 } GA_WTSINFOA;
1951 
1952 GuestUserList *qmp_guest_get_users(Error **errp)
1953 {
1954 #define QGA_NANOSECONDS 10000000
1955 
1956     GHashTable *cache = NULL;
1957     GuestUserList *head = NULL, *cur_item = NULL;
1958 
1959     DWORD buffer_size = 0, count = 0, i = 0;
1960     GA_WTSINFOA *info = NULL;
1961     WTS_SESSION_INFOA *entries = NULL;
1962     GuestUserList *item = NULL;
1963     GuestUser *user = NULL;
1964     gpointer value = NULL;
1965     INT64 login = 0;
1966     double login_time = 0;
1967 
1968     cache = g_hash_table_new(g_str_hash, g_str_equal);
1969 
1970     if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
1971         for (i = 0; i < count; ++i) {
1972             buffer_size = 0;
1973             info = NULL;
1974             if (WTSQuerySessionInformationA(
1975                 NULL,
1976                 entries[i].SessionId,
1977                 WTSSessionInfo,
1978                 (LPSTR *)&info,
1979                 &buffer_size
1980             )) {
1981 
1982                 if (strlen(info->UserName) == 0) {
1983                     WTSFreeMemory(info);
1984                     continue;
1985                 }
1986 
1987                 login = info->LogonTime.QuadPart;
1988                 login -= W32_FT_OFFSET;
1989                 login_time = ((double)login) / QGA_NANOSECONDS;
1990 
1991                 if (g_hash_table_contains(cache, info->UserName)) {
1992                     value = g_hash_table_lookup(cache, info->UserName);
1993                     user = (GuestUser *)value;
1994                     if (user->login_time > login_time) {
1995                         user->login_time = login_time;
1996                     }
1997                 } else {
1998                     item = g_new0(GuestUserList, 1);
1999                     item->value = g_new0(GuestUser, 1);
2000 
2001                     item->value->user = g_strdup(info->UserName);
2002                     item->value->domain = g_strdup(info->Domain);
2003                     item->value->has_domain = true;
2004 
2005                     item->value->login_time = login_time;
2006 
2007                     g_hash_table_add(cache, item->value->user);
2008 
2009                     if (!cur_item) {
2010                         head = cur_item = item;
2011                     } else {
2012                         cur_item->next = item;
2013                         cur_item = item;
2014                     }
2015                 }
2016             }
2017             WTSFreeMemory(info);
2018         }
2019         WTSFreeMemory(entries);
2020     }
2021     g_hash_table_destroy(cache);
2022     return head;
2023 }
2024 
2025 typedef struct _ga_matrix_lookup_t {
2026     int major;
2027     int minor;
2028     char const *version;
2029     char const *version_id;
2030 } ga_matrix_lookup_t;
2031 
2032 static ga_matrix_lookup_t const WIN_VERSION_MATRIX[2][8] = {
2033     {
2034         /* Desktop editions */
2035         { 5, 0, "Microsoft Windows 2000",   "2000"},
2036         { 5, 1, "Microsoft Windows XP",     "xp"},
2037         { 6, 0, "Microsoft Windows Vista",  "vista"},
2038         { 6, 1, "Microsoft Windows 7"       "7"},
2039         { 6, 2, "Microsoft Windows 8",      "8"},
2040         { 6, 3, "Microsoft Windows 8.1",    "8.1"},
2041         {10, 0, "Microsoft Windows 10",     "10"},
2042         { 0, 0, 0}
2043     },{
2044         /* Server editions */
2045         { 5, 2, "Microsoft Windows Server 2003",        "2003"},
2046         { 6, 0, "Microsoft Windows Server 2008",        "2008"},
2047         { 6, 1, "Microsoft Windows Server 2008 R2",     "2008r2"},
2048         { 6, 2, "Microsoft Windows Server 2012",        "2012"},
2049         { 6, 3, "Microsoft Windows Server 2012 R2",     "2012r2"},
2050         { 0, 0, 0},
2051         { 0, 0, 0},
2052         { 0, 0, 0}
2053     }
2054 };
2055 
2056 typedef struct _ga_win_10_0_server_t {
2057     int final_build;
2058     char const *version;
2059     char const *version_id;
2060 } ga_win_10_0_server_t;
2061 
2062 static ga_win_10_0_server_t const WIN_10_0_SERVER_VERSION_MATRIX[3] = {
2063     {14393, "Microsoft Windows Server 2016",    "2016"},
2064     {17763, "Microsoft Windows Server 2019",    "2019"},
2065     {0, 0}
2066 };
2067 
2068 static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
2069 {
2070     typedef NTSTATUS(WINAPI * rtl_get_version_t)(
2071         RTL_OSVERSIONINFOEXW *os_version_info_ex);
2072 
2073     info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2074 
2075     HMODULE module = GetModuleHandle("ntdll");
2076     PVOID fun = GetProcAddress(module, "RtlGetVersion");
2077     if (fun == NULL) {
2078         error_setg(errp, QERR_QGA_COMMAND_FAILED,
2079             "Failed to get address of RtlGetVersion");
2080         return;
2081     }
2082 
2083     rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
2084     rtl_get_version(info);
2085     return;
2086 }
2087 
2088 static char *ga_get_win_name(OSVERSIONINFOEXW const *os_version, bool id)
2089 {
2090     DWORD major = os_version->dwMajorVersion;
2091     DWORD minor = os_version->dwMinorVersion;
2092     DWORD build = os_version->dwBuildNumber;
2093     int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
2094     ga_matrix_lookup_t const *table = WIN_VERSION_MATRIX[tbl_idx];
2095     ga_win_10_0_server_t const *win_10_0_table = WIN_10_0_SERVER_VERSION_MATRIX;
2096     while (table->version != NULL) {
2097         if (major == 10 && minor == 0 && tbl_idx) {
2098             while (win_10_0_table->version != NULL) {
2099                 if (build <= win_10_0_table->final_build) {
2100                     if (id) {
2101                         return g_strdup(win_10_0_table->version_id);
2102                     } else {
2103                         return g_strdup(win_10_0_table->version);
2104                     }
2105                 }
2106                 win_10_0_table++;
2107             }
2108         } else if (major == table->major && minor == table->minor) {
2109             if (id) {
2110                 return g_strdup(table->version_id);
2111             } else {
2112                 return g_strdup(table->version);
2113             }
2114         }
2115         ++table;
2116     }
2117     slog("failed to lookup Windows version: major=%lu, minor=%lu",
2118         major, minor);
2119     return g_strdup("N/A");
2120 }
2121 
2122 static char *ga_get_win_product_name(Error **errp)
2123 {
2124     HKEY key = NULL;
2125     DWORD size = 128;
2126     char *result = g_malloc0(size);
2127     LONG err = ERROR_SUCCESS;
2128 
2129     err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
2130                       "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
2131                       &key);
2132     if (err != ERROR_SUCCESS) {
2133         error_setg_win32(errp, err, "failed to open registry key");
2134         goto fail;
2135     }
2136 
2137     err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2138                             (LPBYTE)result, &size);
2139     if (err == ERROR_MORE_DATA) {
2140         slog("ProductName longer than expected (%lu bytes), retrying",
2141                 size);
2142         g_free(result);
2143         result = NULL;
2144         if (size > 0) {
2145             result = g_malloc0(size);
2146             err = RegQueryValueExA(key, "ProductName", NULL, NULL,
2147                                     (LPBYTE)result, &size);
2148         }
2149     }
2150     if (err != ERROR_SUCCESS) {
2151         error_setg_win32(errp, err, "failed to retrive ProductName");
2152         goto fail;
2153     }
2154 
2155     return result;
2156 
2157 fail:
2158     g_free(result);
2159     return NULL;
2160 }
2161 
2162 static char *ga_get_current_arch(void)
2163 {
2164     SYSTEM_INFO info;
2165     GetNativeSystemInfo(&info);
2166     char *result = NULL;
2167     switch (info.wProcessorArchitecture) {
2168     case PROCESSOR_ARCHITECTURE_AMD64:
2169         result = g_strdup("x86_64");
2170         break;
2171     case PROCESSOR_ARCHITECTURE_ARM:
2172         result = g_strdup("arm");
2173         break;
2174     case PROCESSOR_ARCHITECTURE_IA64:
2175         result = g_strdup("ia64");
2176         break;
2177     case PROCESSOR_ARCHITECTURE_INTEL:
2178         result = g_strdup("x86");
2179         break;
2180     case PROCESSOR_ARCHITECTURE_UNKNOWN:
2181     default:
2182         slog("unknown processor architecture 0x%0x",
2183             info.wProcessorArchitecture);
2184         result = g_strdup("unknown");
2185         break;
2186     }
2187     return result;
2188 }
2189 
2190 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2191 {
2192     Error *local_err = NULL;
2193     OSVERSIONINFOEXW os_version = {0};
2194     bool server;
2195     char *product_name;
2196     GuestOSInfo *info;
2197 
2198     ga_get_win_version(&os_version, &local_err);
2199     if (local_err) {
2200         error_propagate(errp, local_err);
2201         return NULL;
2202     }
2203 
2204     server = os_version.wProductType != VER_NT_WORKSTATION;
2205     product_name = ga_get_win_product_name(&local_err);
2206     if (product_name == NULL) {
2207         error_propagate(errp, local_err);
2208         return NULL;
2209     }
2210 
2211     info = g_new0(GuestOSInfo, 1);
2212 
2213     info->has_kernel_version = true;
2214     info->kernel_version = g_strdup_printf("%lu.%lu",
2215         os_version.dwMajorVersion,
2216         os_version.dwMinorVersion);
2217     info->has_kernel_release = true;
2218     info->kernel_release = g_strdup_printf("%lu",
2219         os_version.dwBuildNumber);
2220     info->has_machine = true;
2221     info->machine = ga_get_current_arch();
2222 
2223     info->has_id = true;
2224     info->id = g_strdup("mswindows");
2225     info->has_name = true;
2226     info->name = g_strdup("Microsoft Windows");
2227     info->has_pretty_name = true;
2228     info->pretty_name = product_name;
2229     info->has_version = true;
2230     info->version = ga_get_win_name(&os_version, false);
2231     info->has_version_id = true;
2232     info->version_id = ga_get_win_name(&os_version, true);
2233     info->has_variant = true;
2234     info->variant = g_strdup(server ? "server" : "client");
2235     info->has_variant_id = true;
2236     info->variant_id = g_strdup(server ? "server" : "client");
2237 
2238     return info;
2239 }
2240