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