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