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