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