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