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