1 /* 2 * QEMU Guest Agent POSIX-specific command implementations 3 * 4 * Copyright IBM Corp. 2011 5 * 6 * Authors: 7 * Michael Roth <mdroth@linux.vnet.ibm.com> 8 * Michal Privoznik <mprivozn@redhat.com> 9 * 10 * This work is licensed under the terms of the GNU GPL, version 2 or later. 11 * See the COPYING file in the top-level directory. 12 */ 13 14 #include "qemu/osdep.h" 15 #include <sys/ioctl.h> 16 #include <sys/utsname.h> 17 #include <sys/wait.h> 18 #include <dirent.h> 19 #include "qga-qapi-commands.h" 20 #include "qapi/error.h" 21 #include "qapi/qmp/qerror.h" 22 #include "qemu/host-utils.h" 23 #include "qemu/sockets.h" 24 #include "qemu/base64.h" 25 #include "qemu/cutils.h" 26 #include "commands-common.h" 27 #include "block/nvme.h" 28 #include "cutils.h" 29 30 #ifdef HAVE_UTMPX 31 #include <utmpx.h> 32 #endif 33 34 #if defined(__linux__) 35 #include <mntent.h> 36 #include <sys/statvfs.h> 37 #include <linux/nvme_ioctl.h> 38 39 #ifdef CONFIG_LIBUDEV 40 #include <libudev.h> 41 #endif 42 #endif 43 44 #ifdef HAVE_GETIFADDRS 45 #include <arpa/inet.h> 46 #include <sys/socket.h> 47 #include <net/if.h> 48 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(CONFIG_SOLARIS) 49 #include <net/if_arp.h> 50 #include <netinet/if_ether.h> 51 #if !defined(ETHER_ADDR_LEN) && defined(ETHERADDRL) 52 #define ETHER_ADDR_LEN ETHERADDRL 53 #endif 54 #else 55 #include <net/ethernet.h> 56 #endif 57 #ifdef CONFIG_SOLARIS 58 #include <sys/sockio.h> 59 #endif 60 #endif 61 62 static void ga_wait_child(pid_t pid, int *status, Error **errp) 63 { 64 pid_t rpid; 65 66 *status = 0; 67 68 rpid = RETRY_ON_EINTR(waitpid(pid, status, 0)); 69 70 if (rpid == -1) { 71 error_setg_errno(errp, errno, "failed to wait for child (pid: %d)", 72 pid); 73 return; 74 } 75 76 g_assert(rpid == pid); 77 } 78 79 static ssize_t ga_pipe_read_str(int fd[2], char **str) 80 { 81 ssize_t n, len = 0; 82 char buf[1024]; 83 84 close(fd[1]); 85 fd[1] = -1; 86 while ((n = read(fd[0], buf, sizeof(buf))) != 0) { 87 if (n < 0) { 88 if (errno == EINTR) { 89 continue; 90 } else { 91 len = -errno; 92 break; 93 } 94 } 95 *str = g_realloc(*str, len + n + 1); 96 memcpy(*str + len, buf, n); 97 len += n; 98 *str[len] = '\0'; 99 } 100 close(fd[0]); 101 fd[0] = -1; 102 103 return len; 104 } 105 106 /* 107 * Helper to run command with input/output redirection, 108 * sending string to stdin and taking error message from 109 * stdout/err. 110 */ 111 static int ga_run_command(const char *argv[], const char *in_str, 112 const char *action, Error **errp) 113 { 114 pid_t pid; 115 int status; 116 int retcode = -1; 117 int infd[2] = { -1, -1 }; 118 int outfd[2] = { -1, -1 }; 119 char *str = NULL; 120 ssize_t len = 0; 121 122 if ((in_str && !g_unix_open_pipe(infd, FD_CLOEXEC, NULL)) || 123 !g_unix_open_pipe(outfd, FD_CLOEXEC, NULL)) { 124 error_setg(errp, "cannot create pipe FDs"); 125 goto out; 126 } 127 128 pid = fork(); 129 if (pid == 0) { 130 char *cherr = NULL; 131 132 setsid(); 133 134 if (in_str) { 135 /* Redirect stdin to infd. */ 136 close(infd[1]); 137 dup2(infd[0], 0); 138 close(infd[0]); 139 } else { 140 reopen_fd_to_null(0); 141 } 142 143 /* Redirect stdout/stderr to outfd. */ 144 close(outfd[0]); 145 dup2(outfd[1], 1); 146 dup2(outfd[1], 2); 147 close(outfd[1]); 148 149 execvp(argv[0], (char *const *)argv); 150 151 /* Write the cause of failed exec to pipe for the parent to read it. */ 152 cherr = g_strdup_printf("failed to exec '%s'", argv[0]); 153 perror(cherr); 154 g_free(cherr); 155 _exit(EXIT_FAILURE); 156 } else if (pid < 0) { 157 error_setg_errno(errp, errno, "failed to create child process"); 158 goto out; 159 } 160 161 if (in_str) { 162 close(infd[0]); 163 infd[0] = -1; 164 if (qemu_write_full(infd[1], in_str, strlen(in_str)) != 165 strlen(in_str)) { 166 error_setg_errno(errp, errno, "%s: cannot write to stdin pipe", 167 action); 168 goto out; 169 } 170 close(infd[1]); 171 infd[1] = -1; 172 } 173 174 len = ga_pipe_read_str(outfd, &str); 175 if (len < 0) { 176 error_setg_errno(errp, -len, "%s: cannot read from stdout/stderr pipe", 177 action); 178 goto out; 179 } 180 181 ga_wait_child(pid, &status, errp); 182 if (*errp) { 183 goto out; 184 } 185 186 if (!WIFEXITED(status)) { 187 if (len) { 188 error_setg(errp, "child process has terminated abnormally: %s", 189 str); 190 } else { 191 error_setg(errp, "child process has terminated abnormally"); 192 } 193 goto out; 194 } 195 196 retcode = WEXITSTATUS(status); 197 198 if (WEXITSTATUS(status)) { 199 if (len) { 200 error_setg(errp, "child process has failed to %s: %s", 201 action, str); 202 } else { 203 error_setg(errp, "child process has failed to %s: exit status %d", 204 action, WEXITSTATUS(status)); 205 } 206 goto out; 207 } 208 209 out: 210 g_free(str); 211 212 if (infd[0] != -1) { 213 close(infd[0]); 214 } 215 if (infd[1] != -1) { 216 close(infd[1]); 217 } 218 if (outfd[0] != -1) { 219 close(outfd[0]); 220 } 221 if (outfd[1] != -1) { 222 close(outfd[1]); 223 } 224 225 return retcode; 226 } 227 228 void qmp_guest_shutdown(const char *mode, Error **errp) 229 { 230 const char *shutdown_flag; 231 Error *local_err = NULL; 232 233 #ifdef CONFIG_SOLARIS 234 const char *powerdown_flag = "-i5"; 235 const char *halt_flag = "-i0"; 236 const char *reboot_flag = "-i6"; 237 #elif defined(CONFIG_BSD) 238 const char *powerdown_flag = "-p"; 239 const char *halt_flag = "-h"; 240 const char *reboot_flag = "-r"; 241 #else 242 const char *powerdown_flag = "-P"; 243 const char *halt_flag = "-H"; 244 const char *reboot_flag = "-r"; 245 #endif 246 247 slog("guest-shutdown called, mode: %s", mode); 248 if (!mode || strcmp(mode, "powerdown") == 0) { 249 shutdown_flag = powerdown_flag; 250 } else if (strcmp(mode, "halt") == 0) { 251 shutdown_flag = halt_flag; 252 } else if (strcmp(mode, "reboot") == 0) { 253 shutdown_flag = reboot_flag; 254 } else { 255 error_setg(errp, 256 "mode is invalid (valid values are: halt|powerdown|reboot"); 257 return; 258 } 259 260 const char *argv[] = {"/sbin/shutdown", 261 #ifdef CONFIG_SOLARIS 262 shutdown_flag, "-g0", "-y", 263 #elif defined(CONFIG_BSD) 264 shutdown_flag, "+0", 265 #else 266 "-h", shutdown_flag, "+0", 267 #endif 268 "hypervisor initiated shutdown", (char *) NULL}; 269 270 ga_run_command(argv, NULL, "shutdown", &local_err); 271 if (local_err) { 272 error_propagate(errp, local_err); 273 return; 274 } 275 276 /* succeeded */ 277 } 278 279 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp) 280 { 281 int ret; 282 Error *local_err = NULL; 283 struct timeval tv; 284 const char *argv[] = {"/sbin/hwclock", has_time ? "-w" : "-s", NULL}; 285 286 /* If user has passed a time, validate and set it. */ 287 if (has_time) { 288 GDate date = { 0, }; 289 290 /* year-2038 will overflow in case time_t is 32bit */ 291 if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) { 292 error_setg(errp, "Time %" PRId64 " is too large", time_ns); 293 return; 294 } 295 296 tv.tv_sec = time_ns / 1000000000; 297 tv.tv_usec = (time_ns % 1000000000) / 1000; 298 g_date_set_time_t(&date, tv.tv_sec); 299 if (date.year < 1970 || date.year >= 2070) { 300 error_setg_errno(errp, errno, "Invalid time"); 301 return; 302 } 303 304 ret = settimeofday(&tv, NULL); 305 if (ret < 0) { 306 error_setg_errno(errp, errno, "Failed to set time to guest"); 307 return; 308 } 309 } 310 311 /* Now, if user has passed a time to set and the system time is set, we 312 * just need to synchronize the hardware clock. However, if no time was 313 * passed, user is requesting the opposite: set the system time from the 314 * hardware clock (RTC). */ 315 ga_run_command(argv, NULL, "set hardware clock to system time", 316 &local_err); 317 if (local_err) { 318 error_propagate(errp, local_err); 319 return; 320 } 321 } 322 323 typedef enum { 324 RW_STATE_NEW, 325 RW_STATE_READING, 326 RW_STATE_WRITING, 327 } RwState; 328 329 struct GuestFileHandle { 330 uint64_t id; 331 FILE *fh; 332 RwState state; 333 QTAILQ_ENTRY(GuestFileHandle) next; 334 }; 335 336 static struct { 337 QTAILQ_HEAD(, GuestFileHandle) filehandles; 338 } guest_file_state = { 339 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles), 340 }; 341 342 static int64_t guest_file_handle_add(FILE *fh, Error **errp) 343 { 344 GuestFileHandle *gfh; 345 int64_t handle; 346 347 handle = ga_get_fd_handle(ga_state, errp); 348 if (handle < 0) { 349 return -1; 350 } 351 352 gfh = g_new0(GuestFileHandle, 1); 353 gfh->id = handle; 354 gfh->fh = fh; 355 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next); 356 357 return handle; 358 } 359 360 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp) 361 { 362 GuestFileHandle *gfh; 363 364 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) 365 { 366 if (gfh->id == id) { 367 return gfh; 368 } 369 } 370 371 error_setg(errp, "handle '%" PRId64 "' has not been found", id); 372 return NULL; 373 } 374 375 typedef const char * const ccpc; 376 377 #ifndef O_BINARY 378 #define O_BINARY 0 379 #endif 380 381 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */ 382 static const struct { 383 ccpc *forms; 384 int oflag_base; 385 } guest_file_open_modes[] = { 386 { (ccpc[]){ "r", NULL }, O_RDONLY }, 387 { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY }, 388 { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC }, 389 { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY }, 390 { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND }, 391 { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY }, 392 { (ccpc[]){ "r+", NULL }, O_RDWR }, 393 { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY }, 394 { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC }, 395 { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY }, 396 { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND }, 397 { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY } 398 }; 399 400 static int 401 find_open_flag(const char *mode_str, Error **errp) 402 { 403 unsigned mode; 404 405 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) { 406 ccpc *form; 407 408 form = guest_file_open_modes[mode].forms; 409 while (*form != NULL && strcmp(*form, mode_str) != 0) { 410 ++form; 411 } 412 if (*form != NULL) { 413 break; 414 } 415 } 416 417 if (mode == ARRAY_SIZE(guest_file_open_modes)) { 418 error_setg(errp, "invalid file open mode '%s'", mode_str); 419 return -1; 420 } 421 return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK; 422 } 423 424 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \ 425 S_IRGRP | S_IWGRP | \ 426 S_IROTH | S_IWOTH) 427 428 static FILE * 429 safe_open_or_create(const char *path, const char *mode, Error **errp) 430 { 431 int oflag; 432 int fd = -1; 433 FILE *f = NULL; 434 435 oflag = find_open_flag(mode, errp); 436 if (oflag < 0) { 437 goto end; 438 } 439 440 /* If the caller wants / allows creation of a new file, we implement it 441 * with a two step process: open() + (open() / fchmod()). 442 * 443 * First we insist on creating the file exclusively as a new file. If 444 * that succeeds, we're free to set any file-mode bits on it. (The 445 * motivation is that we want to set those file-mode bits independently 446 * of the current umask.) 447 * 448 * If the exclusive creation fails because the file already exists 449 * (EEXIST is not possible for any other reason), we just attempt to 450 * open the file, but in this case we won't be allowed to change the 451 * file-mode bits on the preexistent file. 452 * 453 * The pathname should never disappear between the two open()s in 454 * practice. If it happens, then someone very likely tried to race us. 455 * In this case just go ahead and report the ENOENT from the second 456 * open() to the caller. 457 * 458 * If the caller wants to open a preexistent file, then the first 459 * open() is decisive and its third argument is ignored, and the second 460 * open() and the fchmod() are never called. 461 */ 462 fd = qga_open_cloexec(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0); 463 if (fd == -1 && errno == EEXIST) { 464 oflag &= ~(unsigned)O_CREAT; 465 fd = qga_open_cloexec(path, oflag, 0); 466 } 467 if (fd == -1) { 468 error_setg_errno(errp, errno, 469 "failed to open file '%s' (mode: '%s')", 470 path, mode); 471 goto end; 472 } 473 474 if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) { 475 error_setg_errno(errp, errno, "failed to set permission " 476 "0%03o on new file '%s' (mode: '%s')", 477 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode); 478 goto end; 479 } 480 481 f = fdopen(fd, mode); 482 if (f == NULL) { 483 error_setg_errno(errp, errno, "failed to associate stdio stream with " 484 "file descriptor %d, file '%s' (mode: '%s')", 485 fd, path, mode); 486 } 487 488 end: 489 if (f == NULL && fd != -1) { 490 close(fd); 491 if (oflag & O_CREAT) { 492 unlink(path); 493 } 494 } 495 return f; 496 } 497 498 int64_t qmp_guest_file_open(const char *path, const char *mode, 499 Error **errp) 500 { 501 FILE *fh; 502 Error *local_err = NULL; 503 int64_t handle; 504 505 if (!mode) { 506 mode = "r"; 507 } 508 slog("guest-file-open called, filepath: %s, mode: %s", path, mode); 509 fh = safe_open_or_create(path, mode, &local_err); 510 if (local_err != NULL) { 511 error_propagate(errp, local_err); 512 return -1; 513 } 514 515 /* set fd non-blocking to avoid common use cases (like reading from a 516 * named pipe) from hanging the agent 517 */ 518 if (!g_unix_set_fd_nonblocking(fileno(fh), true, NULL)) { 519 fclose(fh); 520 error_setg_errno(errp, errno, "Failed to set FD nonblocking"); 521 return -1; 522 } 523 524 handle = guest_file_handle_add(fh, errp); 525 if (handle < 0) { 526 fclose(fh); 527 return -1; 528 } 529 530 slog("guest-file-open, handle: %" PRId64, handle); 531 return handle; 532 } 533 534 void qmp_guest_file_close(int64_t handle, Error **errp) 535 { 536 GuestFileHandle *gfh = guest_file_handle_find(handle, errp); 537 int ret; 538 539 slog("guest-file-close called, handle: %" PRId64, handle); 540 if (!gfh) { 541 return; 542 } 543 544 ret = fclose(gfh->fh); 545 if (ret == EOF) { 546 error_setg_errno(errp, errno, "failed to close handle"); 547 return; 548 } 549 550 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next); 551 g_free(gfh); 552 } 553 554 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh, 555 int64_t count, Error **errp) 556 { 557 GuestFileRead *read_data = NULL; 558 guchar *buf; 559 FILE *fh = gfh->fh; 560 size_t read_count; 561 562 /* explicitly flush when switching from writing to reading */ 563 if (gfh->state == RW_STATE_WRITING) { 564 int ret = fflush(fh); 565 if (ret == EOF) { 566 error_setg_errno(errp, errno, "failed to flush file"); 567 return NULL; 568 } 569 gfh->state = RW_STATE_NEW; 570 } 571 572 buf = g_malloc0(count + 1); 573 read_count = fread(buf, 1, count, fh); 574 if (ferror(fh)) { 575 error_setg_errno(errp, errno, "failed to read file"); 576 } else { 577 buf[read_count] = 0; 578 read_data = g_new0(GuestFileRead, 1); 579 read_data->count = read_count; 580 read_data->eof = feof(fh); 581 if (read_count) { 582 read_data->buf_b64 = g_base64_encode(buf, read_count); 583 } 584 gfh->state = RW_STATE_READING; 585 } 586 g_free(buf); 587 clearerr(fh); 588 589 return read_data; 590 } 591 592 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64, 593 bool has_count, int64_t count, 594 Error **errp) 595 { 596 GuestFileWrite *write_data = NULL; 597 guchar *buf; 598 gsize buf_len; 599 int write_count; 600 GuestFileHandle *gfh = guest_file_handle_find(handle, errp); 601 FILE *fh; 602 603 if (!gfh) { 604 return NULL; 605 } 606 607 fh = gfh->fh; 608 609 if (gfh->state == RW_STATE_READING) { 610 int ret = fseek(fh, 0, SEEK_CUR); 611 if (ret == -1) { 612 error_setg_errno(errp, errno, "failed to seek file"); 613 return NULL; 614 } 615 gfh->state = RW_STATE_NEW; 616 } 617 618 buf = qbase64_decode(buf_b64, -1, &buf_len, errp); 619 if (!buf) { 620 return NULL; 621 } 622 623 if (!has_count) { 624 count = buf_len; 625 } else if (count < 0 || count > buf_len) { 626 error_setg(errp, "value '%" PRId64 "' is invalid for argument count", 627 count); 628 g_free(buf); 629 return NULL; 630 } 631 632 write_count = fwrite(buf, 1, count, fh); 633 if (ferror(fh)) { 634 error_setg_errno(errp, errno, "failed to write to file"); 635 slog("guest-file-write failed, handle: %" PRId64, handle); 636 } else { 637 write_data = g_new0(GuestFileWrite, 1); 638 write_data->count = write_count; 639 write_data->eof = feof(fh); 640 gfh->state = RW_STATE_WRITING; 641 } 642 g_free(buf); 643 clearerr(fh); 644 645 return write_data; 646 } 647 648 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset, 649 GuestFileWhence *whence_code, 650 Error **errp) 651 { 652 GuestFileHandle *gfh = guest_file_handle_find(handle, errp); 653 GuestFileSeek *seek_data = NULL; 654 FILE *fh; 655 int ret; 656 int whence; 657 Error *err = NULL; 658 659 if (!gfh) { 660 return NULL; 661 } 662 663 /* We stupidly exposed 'whence':'int' in our qapi */ 664 whence = ga_parse_whence(whence_code, &err); 665 if (err) { 666 error_propagate(errp, err); 667 return NULL; 668 } 669 670 fh = gfh->fh; 671 ret = fseek(fh, offset, whence); 672 if (ret == -1) { 673 error_setg_errno(errp, errno, "failed to seek file"); 674 if (errno == ESPIPE) { 675 /* file is non-seekable, stdio shouldn't be buffering anyways */ 676 gfh->state = RW_STATE_NEW; 677 } 678 } else { 679 seek_data = g_new0(GuestFileSeek, 1); 680 seek_data->position = ftell(fh); 681 seek_data->eof = feof(fh); 682 gfh->state = RW_STATE_NEW; 683 } 684 clearerr(fh); 685 686 return seek_data; 687 } 688 689 void qmp_guest_file_flush(int64_t handle, Error **errp) 690 { 691 GuestFileHandle *gfh = guest_file_handle_find(handle, errp); 692 FILE *fh; 693 int ret; 694 695 if (!gfh) { 696 return; 697 } 698 699 fh = gfh->fh; 700 ret = fflush(fh); 701 if (ret == EOF) { 702 error_setg_errno(errp, errno, "failed to flush file"); 703 } else { 704 gfh->state = RW_STATE_NEW; 705 } 706 } 707 708 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM) 709 void free_fs_mount_list(FsMountList *mounts) 710 { 711 FsMount *mount, *temp; 712 713 if (!mounts) { 714 return; 715 } 716 717 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) { 718 QTAILQ_REMOVE(mounts, mount, next); 719 g_free(mount->dirname); 720 g_free(mount->devtype); 721 g_free(mount); 722 } 723 } 724 #endif 725 726 #if defined(CONFIG_FSFREEZE) 727 typedef enum { 728 FSFREEZE_HOOK_THAW = 0, 729 FSFREEZE_HOOK_FREEZE, 730 } FsfreezeHookArg; 731 732 static const char *fsfreeze_hook_arg_string[] = { 733 "thaw", 734 "freeze", 735 }; 736 737 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp) 738 { 739 const char *hook; 740 const char *arg_str = fsfreeze_hook_arg_string[arg]; 741 Error *local_err = NULL; 742 743 hook = ga_fsfreeze_hook(ga_state); 744 if (!hook) { 745 return; 746 } 747 748 const char *argv[] = {hook, arg_str, NULL}; 749 750 slog("executing fsfreeze hook with arg '%s'", arg_str); 751 ga_run_command(argv, NULL, "execute fsfreeze hook", &local_err); 752 if (local_err) { 753 error_propagate(errp, local_err); 754 return; 755 } 756 } 757 758 /* 759 * Return status of freeze/thaw 760 */ 761 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp) 762 { 763 if (ga_is_frozen(ga_state)) { 764 return GUEST_FSFREEZE_STATUS_FROZEN; 765 } 766 767 return GUEST_FSFREEZE_STATUS_THAWED; 768 } 769 770 int64_t qmp_guest_fsfreeze_freeze(Error **errp) 771 { 772 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp); 773 } 774 775 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints, 776 strList *mountpoints, 777 Error **errp) 778 { 779 int ret; 780 FsMountList mounts; 781 Error *local_err = NULL; 782 783 slog("guest-fsfreeze called"); 784 785 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err); 786 if (local_err) { 787 error_propagate(errp, local_err); 788 return -1; 789 } 790 791 QTAILQ_INIT(&mounts); 792 if (!build_fs_mount_list(&mounts, &local_err)) { 793 error_propagate(errp, local_err); 794 return -1; 795 } 796 797 /* cannot risk guest agent blocking itself on a write in this state */ 798 ga_set_frozen(ga_state); 799 800 ret = qmp_guest_fsfreeze_do_freeze_list(has_mountpoints, mountpoints, 801 mounts, errp); 802 803 free_fs_mount_list(&mounts); 804 /* We may not issue any FIFREEZE here. 805 * Just unset ga_state here and ready for the next call. 806 */ 807 if (ret == 0) { 808 ga_unset_frozen(ga_state); 809 } else if (ret < 0) { 810 qmp_guest_fsfreeze_thaw(NULL); 811 } 812 return ret; 813 } 814 815 int64_t qmp_guest_fsfreeze_thaw(Error **errp) 816 { 817 int ret; 818 819 ret = qmp_guest_fsfreeze_do_thaw(errp); 820 if (ret >= 0) { 821 ga_unset_frozen(ga_state); 822 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp); 823 } else { 824 ret = 0; 825 } 826 827 return ret; 828 } 829 830 static void guest_fsfreeze_cleanup(void) 831 { 832 Error *err = NULL; 833 834 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) { 835 qmp_guest_fsfreeze_thaw(&err); 836 if (err) { 837 slog("failed to clean up frozen filesystems: %s", 838 error_get_pretty(err)); 839 error_free(err); 840 } 841 } 842 } 843 #endif 844 845 /* linux-specific implementations. avoid this if at all possible. */ 846 #if defined(__linux__) 847 #if defined(CONFIG_FSFREEZE) 848 849 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp) 850 { 851 char *path; 852 char *dpath; 853 char *driver = NULL; 854 char buf[PATH_MAX]; 855 ssize_t len; 856 857 path = g_strndup(syspath, pathlen); 858 dpath = g_strdup_printf("%s/driver", path); 859 len = readlink(dpath, buf, sizeof(buf) - 1); 860 if (len != -1) { 861 buf[len] = 0; 862 driver = g_path_get_basename(buf); 863 } 864 g_free(dpath); 865 g_free(path); 866 return driver; 867 } 868 869 static int compare_uint(const void *_a, const void *_b) 870 { 871 unsigned int a = *(unsigned int *)_a; 872 unsigned int b = *(unsigned int *)_b; 873 874 return a < b ? -1 : a > b ? 1 : 0; 875 } 876 877 /* Walk the specified sysfs and build a sorted list of host or ata numbers */ 878 static int build_hosts(char const *syspath, char const *host, bool ata, 879 unsigned int *hosts, int hosts_max, Error **errp) 880 { 881 char *path; 882 DIR *dir; 883 struct dirent *entry; 884 int i = 0; 885 886 path = g_strndup(syspath, host - syspath); 887 dir = opendir(path); 888 if (!dir) { 889 error_setg_errno(errp, errno, "opendir(\"%s\")", path); 890 g_free(path); 891 return -1; 892 } 893 894 while (i < hosts_max) { 895 entry = readdir(dir); 896 if (!entry) { 897 break; 898 } 899 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) { 900 ++i; 901 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) { 902 ++i; 903 } 904 } 905 906 qsort(hosts, i, sizeof(hosts[0]), compare_uint); 907 908 g_free(path); 909 closedir(dir); 910 return i; 911 } 912 913 /* 914 * Store disk device info for devices on the PCI bus. 915 * Returns true if information has been stored, or false for failure. 916 */ 917 static bool build_guest_fsinfo_for_pci_dev(char const *syspath, 918 GuestDiskAddress *disk, 919 Error **errp) 920 { 921 unsigned int pci[4], host, hosts[8], tgt[3]; 922 int i, nhosts = 0, pcilen; 923 GuestPCIAddress *pciaddr = disk->pci_controller; 924 bool has_ata = false, has_host = false, has_tgt = false; 925 char *p, *q, *driver = NULL; 926 bool ret = false; 927 928 p = strstr(syspath, "/devices/pci"); 929 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n", 930 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) { 931 g_debug("only pci device is supported: sysfs path '%s'", syspath); 932 return false; 933 } 934 935 p += 12 + pcilen; 936 while (true) { 937 driver = get_pci_driver(syspath, p - syspath, errp); 938 if (driver && (g_str_equal(driver, "ata_piix") || 939 g_str_equal(driver, "sym53c8xx") || 940 g_str_equal(driver, "virtio-pci") || 941 g_str_equal(driver, "ahci") || 942 g_str_equal(driver, "nvme") || 943 g_str_equal(driver, "xhci_hcd") || 944 g_str_equal(driver, "ehci-pci"))) { 945 break; 946 } 947 948 g_free(driver); 949 if (sscanf(p, "/%x:%x:%x.%x%n", 950 pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) { 951 p += pcilen; 952 continue; 953 } 954 955 g_debug("unsupported driver or sysfs path '%s'", syspath); 956 return false; 957 } 958 959 p = strstr(syspath, "/target"); 960 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u", 961 tgt, tgt + 1, tgt + 2) == 3) { 962 has_tgt = true; 963 } 964 965 p = strstr(syspath, "/ata"); 966 if (p) { 967 q = p + 4; 968 has_ata = true; 969 } else { 970 p = strstr(syspath, "/host"); 971 q = p + 5; 972 } 973 if (p && sscanf(q, "%u", &host) == 1) { 974 has_host = true; 975 nhosts = build_hosts(syspath, p, has_ata, hosts, 976 ARRAY_SIZE(hosts), errp); 977 if (nhosts < 0) { 978 goto cleanup; 979 } 980 } 981 982 pciaddr->domain = pci[0]; 983 pciaddr->bus = pci[1]; 984 pciaddr->slot = pci[2]; 985 pciaddr->function = pci[3]; 986 987 if (strcmp(driver, "ata_piix") == 0) { 988 /* a host per ide bus, target*:0:<unit>:0 */ 989 if (!has_host || !has_tgt) { 990 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver); 991 goto cleanup; 992 } 993 for (i = 0; i < nhosts; i++) { 994 if (host == hosts[i]) { 995 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE; 996 disk->bus = i; 997 disk->unit = tgt[1]; 998 break; 999 } 1000 } 1001 if (i >= nhosts) { 1002 g_debug("no host for '%s' (driver '%s')", syspath, driver); 1003 goto cleanup; 1004 } 1005 } else if (strcmp(driver, "sym53c8xx") == 0) { 1006 /* scsi(LSI Logic): target*:0:<unit>:0 */ 1007 if (!has_tgt) { 1008 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver); 1009 goto cleanup; 1010 } 1011 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI; 1012 disk->unit = tgt[1]; 1013 } else if (strcmp(driver, "virtio-pci") == 0) { 1014 if (has_tgt) { 1015 /* virtio-scsi: target*:0:0:<unit> */ 1016 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI; 1017 disk->unit = tgt[2]; 1018 } else { 1019 /* virtio-blk: 1 disk per 1 device */ 1020 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO; 1021 } 1022 } else if (strcmp(driver, "ahci") == 0) { 1023 /* ahci: 1 host per 1 unit */ 1024 if (!has_host || !has_tgt) { 1025 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver); 1026 goto cleanup; 1027 } 1028 for (i = 0; i < nhosts; i++) { 1029 if (host == hosts[i]) { 1030 disk->unit = i; 1031 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA; 1032 break; 1033 } 1034 } 1035 if (i >= nhosts) { 1036 g_debug("no host for '%s' (driver '%s')", syspath, driver); 1037 goto cleanup; 1038 } 1039 } else if (strcmp(driver, "nvme") == 0) { 1040 disk->bus_type = GUEST_DISK_BUS_TYPE_NVME; 1041 } else if (strcmp(driver, "ehci-pci") == 0 || strcmp(driver, "xhci_hcd") == 0) { 1042 disk->bus_type = GUEST_DISK_BUS_TYPE_USB; 1043 } else { 1044 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath); 1045 goto cleanup; 1046 } 1047 1048 ret = true; 1049 1050 cleanup: 1051 g_free(driver); 1052 return ret; 1053 } 1054 1055 /* 1056 * Store disk device info for non-PCI virtio devices (for example s390x 1057 * channel I/O devices). Returns true if information has been stored, or 1058 * false for failure. 1059 */ 1060 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath, 1061 GuestDiskAddress *disk, 1062 Error **errp) 1063 { 1064 unsigned int tgt[3]; 1065 char *p; 1066 1067 if (!strstr(syspath, "/virtio") || !strstr(syspath, "/block")) { 1068 g_debug("Unsupported virtio device '%s'", syspath); 1069 return false; 1070 } 1071 1072 p = strstr(syspath, "/target"); 1073 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u", 1074 &tgt[0], &tgt[1], &tgt[2]) == 3) { 1075 /* virtio-scsi: target*:0:<target>:<unit> */ 1076 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI; 1077 disk->bus = tgt[0]; 1078 disk->target = tgt[1]; 1079 disk->unit = tgt[2]; 1080 } else { 1081 /* virtio-blk: 1 disk per 1 device */ 1082 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO; 1083 } 1084 1085 return true; 1086 } 1087 1088 /* 1089 * Store disk device info for CCW devices (s390x channel I/O devices). 1090 * Returns true if information has been stored, or false for failure. 1091 */ 1092 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath, 1093 GuestDiskAddress *disk, 1094 Error **errp) 1095 { 1096 unsigned int cssid, ssid, subchno, devno; 1097 char *p; 1098 1099 p = strstr(syspath, "/devices/css"); 1100 if (!p || sscanf(p + 12, "%*x/%x.%x.%x/%*x.%*x.%x/", 1101 &cssid, &ssid, &subchno, &devno) < 4) { 1102 g_debug("could not parse ccw device sysfs path: %s", syspath); 1103 return false; 1104 } 1105 1106 disk->ccw_address = g_new0(GuestCCWAddress, 1); 1107 disk->ccw_address->cssid = cssid; 1108 disk->ccw_address->ssid = ssid; 1109 disk->ccw_address->subchno = subchno; 1110 disk->ccw_address->devno = devno; 1111 1112 if (strstr(p, "/virtio")) { 1113 build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp); 1114 } 1115 1116 return true; 1117 } 1118 1119 /* Store disk device info specified by @sysfs into @fs */ 1120 static void build_guest_fsinfo_for_real_device(char const *syspath, 1121 GuestFilesystemInfo *fs, 1122 Error **errp) 1123 { 1124 GuestDiskAddress *disk; 1125 GuestPCIAddress *pciaddr; 1126 bool has_hwinf; 1127 #ifdef CONFIG_LIBUDEV 1128 struct udev *udev = NULL; 1129 struct udev_device *udevice = NULL; 1130 #endif 1131 1132 pciaddr = g_new0(GuestPCIAddress, 1); 1133 pciaddr->domain = -1; /* -1 means field is invalid */ 1134 pciaddr->bus = -1; 1135 pciaddr->slot = -1; 1136 pciaddr->function = -1; 1137 1138 disk = g_new0(GuestDiskAddress, 1); 1139 disk->pci_controller = pciaddr; 1140 disk->bus_type = GUEST_DISK_BUS_TYPE_UNKNOWN; 1141 1142 #ifdef CONFIG_LIBUDEV 1143 udev = udev_new(); 1144 udevice = udev_device_new_from_syspath(udev, syspath); 1145 if (udev == NULL || udevice == NULL) { 1146 g_debug("failed to query udev"); 1147 } else { 1148 const char *devnode, *serial; 1149 devnode = udev_device_get_devnode(udevice); 1150 if (devnode != NULL) { 1151 disk->dev = g_strdup(devnode); 1152 } 1153 serial = udev_device_get_property_value(udevice, "ID_SERIAL"); 1154 if (serial != NULL && *serial != 0) { 1155 disk->serial = g_strdup(serial); 1156 } 1157 } 1158 1159 udev_unref(udev); 1160 udev_device_unref(udevice); 1161 #endif 1162 1163 if (strstr(syspath, "/devices/pci")) { 1164 has_hwinf = build_guest_fsinfo_for_pci_dev(syspath, disk, errp); 1165 } else if (strstr(syspath, "/devices/css")) { 1166 has_hwinf = build_guest_fsinfo_for_ccw_dev(syspath, disk, errp); 1167 } else if (strstr(syspath, "/virtio")) { 1168 has_hwinf = build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp); 1169 } else { 1170 g_debug("Unsupported device type for '%s'", syspath); 1171 has_hwinf = false; 1172 } 1173 1174 if (has_hwinf || disk->dev || disk->serial) { 1175 QAPI_LIST_PREPEND(fs->disk, disk); 1176 } else { 1177 qapi_free_GuestDiskAddress(disk); 1178 } 1179 } 1180 1181 static void build_guest_fsinfo_for_device(char const *devpath, 1182 GuestFilesystemInfo *fs, 1183 Error **errp); 1184 1185 /* Store a list of slave devices of virtual volume specified by @syspath into 1186 * @fs */ 1187 static void build_guest_fsinfo_for_virtual_device(char const *syspath, 1188 GuestFilesystemInfo *fs, 1189 Error **errp) 1190 { 1191 Error *err = NULL; 1192 DIR *dir; 1193 char *dirpath; 1194 struct dirent *entry; 1195 1196 dirpath = g_strdup_printf("%s/slaves", syspath); 1197 dir = opendir(dirpath); 1198 if (!dir) { 1199 if (errno != ENOENT) { 1200 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath); 1201 } 1202 g_free(dirpath); 1203 return; 1204 } 1205 1206 for (;;) { 1207 errno = 0; 1208 entry = readdir(dir); 1209 if (entry == NULL) { 1210 if (errno) { 1211 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath); 1212 } 1213 break; 1214 } 1215 1216 if (entry->d_type == DT_LNK) { 1217 char *path; 1218 1219 g_debug(" slave device '%s'", entry->d_name); 1220 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name); 1221 build_guest_fsinfo_for_device(path, fs, &err); 1222 g_free(path); 1223 1224 if (err) { 1225 error_propagate(errp, err); 1226 break; 1227 } 1228 } 1229 } 1230 1231 g_free(dirpath); 1232 closedir(dir); 1233 } 1234 1235 static bool is_disk_virtual(const char *devpath, Error **errp) 1236 { 1237 g_autofree char *syspath = realpath(devpath, NULL); 1238 1239 if (!syspath) { 1240 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath); 1241 return false; 1242 } 1243 return strstr(syspath, "/devices/virtual/block/") != NULL; 1244 } 1245 1246 /* Dispatch to functions for virtual/real device */ 1247 static void build_guest_fsinfo_for_device(char const *devpath, 1248 GuestFilesystemInfo *fs, 1249 Error **errp) 1250 { 1251 ERRP_GUARD(); 1252 g_autofree char *syspath = NULL; 1253 bool is_virtual = false; 1254 1255 syspath = realpath(devpath, NULL); 1256 if (!syspath) { 1257 if (errno != ENOENT) { 1258 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath); 1259 return; 1260 } 1261 1262 /* ENOENT: This devpath may not exist because of container config */ 1263 if (!fs->name) { 1264 fs->name = g_path_get_basename(devpath); 1265 } 1266 return; 1267 } 1268 1269 if (!fs->name) { 1270 fs->name = g_path_get_basename(syspath); 1271 } 1272 1273 g_debug(" parse sysfs path '%s'", syspath); 1274 is_virtual = is_disk_virtual(syspath, errp); 1275 if (*errp != NULL) { 1276 return; 1277 } 1278 if (is_virtual) { 1279 build_guest_fsinfo_for_virtual_device(syspath, fs, errp); 1280 } else { 1281 build_guest_fsinfo_for_real_device(syspath, fs, errp); 1282 } 1283 } 1284 1285 #ifdef CONFIG_LIBUDEV 1286 1287 /* 1288 * Wrapper around build_guest_fsinfo_for_device() for getting just 1289 * the disk address. 1290 */ 1291 static GuestDiskAddress *get_disk_address(const char *syspath, Error **errp) 1292 { 1293 g_autoptr(GuestFilesystemInfo) fs = NULL; 1294 1295 fs = g_new0(GuestFilesystemInfo, 1); 1296 build_guest_fsinfo_for_device(syspath, fs, errp); 1297 if (fs->disk != NULL) { 1298 return g_steal_pointer(&fs->disk->value); 1299 } 1300 return NULL; 1301 } 1302 1303 static char *get_alias_for_syspath(const char *syspath) 1304 { 1305 struct udev *udev = NULL; 1306 struct udev_device *udevice = NULL; 1307 char *ret = NULL; 1308 1309 udev = udev_new(); 1310 if (udev == NULL) { 1311 g_debug("failed to query udev"); 1312 goto out; 1313 } 1314 udevice = udev_device_new_from_syspath(udev, syspath); 1315 if (udevice == NULL) { 1316 g_debug("failed to query udev for path: %s", syspath); 1317 goto out; 1318 } else { 1319 const char *alias = udev_device_get_property_value( 1320 udevice, "DM_NAME"); 1321 /* 1322 * NULL means there was an error and empty string means there is no 1323 * alias. In case of no alias we return NULL instead of empty string. 1324 */ 1325 if (alias == NULL) { 1326 g_debug("failed to query udev for device alias for: %s", 1327 syspath); 1328 } else if (*alias != 0) { 1329 ret = g_strdup(alias); 1330 } 1331 } 1332 1333 out: 1334 udev_unref(udev); 1335 udev_device_unref(udevice); 1336 return ret; 1337 } 1338 1339 static char *get_device_for_syspath(const char *syspath) 1340 { 1341 struct udev *udev = NULL; 1342 struct udev_device *udevice = NULL; 1343 char *ret = NULL; 1344 1345 udev = udev_new(); 1346 if (udev == NULL) { 1347 g_debug("failed to query udev"); 1348 goto out; 1349 } 1350 udevice = udev_device_new_from_syspath(udev, syspath); 1351 if (udevice == NULL) { 1352 g_debug("failed to query udev for path: %s", syspath); 1353 goto out; 1354 } else { 1355 ret = g_strdup(udev_device_get_devnode(udevice)); 1356 } 1357 1358 out: 1359 udev_unref(udev); 1360 udev_device_unref(udevice); 1361 return ret; 1362 } 1363 1364 static void get_disk_deps(const char *disk_dir, GuestDiskInfo *disk) 1365 { 1366 g_autofree char *deps_dir = NULL; 1367 const gchar *dep; 1368 GDir *dp_deps = NULL; 1369 1370 /* List dependent disks */ 1371 deps_dir = g_strdup_printf("%s/slaves", disk_dir); 1372 g_debug(" listing entries in: %s", deps_dir); 1373 dp_deps = g_dir_open(deps_dir, 0, NULL); 1374 if (dp_deps == NULL) { 1375 g_debug("failed to list entries in %s", deps_dir); 1376 return; 1377 } 1378 disk->has_dependencies = true; 1379 while ((dep = g_dir_read_name(dp_deps)) != NULL) { 1380 g_autofree char *dep_dir = NULL; 1381 char *dev_name; 1382 1383 /* Add dependent disks */ 1384 dep_dir = g_strdup_printf("%s/%s", deps_dir, dep); 1385 dev_name = get_device_for_syspath(dep_dir); 1386 if (dev_name != NULL) { 1387 g_debug(" adding dependent device: %s", dev_name); 1388 QAPI_LIST_PREPEND(disk->dependencies, dev_name); 1389 } 1390 } 1391 g_dir_close(dp_deps); 1392 } 1393 1394 /* 1395 * Detect partitions subdirectory, name is "<disk_name><number>" or 1396 * "<disk_name>p<number>" 1397 * 1398 * @disk_name -- last component of /sys path (e.g. sda) 1399 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda) 1400 * @disk_dev -- device node of the disk (e.g. /dev/sda) 1401 */ 1402 static GuestDiskInfoList *get_disk_partitions( 1403 GuestDiskInfoList *list, 1404 const char *disk_name, const char *disk_dir, 1405 const char *disk_dev) 1406 { 1407 GuestDiskInfoList *ret = list; 1408 struct dirent *de_disk; 1409 DIR *dp_disk = NULL; 1410 size_t len = strlen(disk_name); 1411 1412 dp_disk = opendir(disk_dir); 1413 while ((de_disk = readdir(dp_disk)) != NULL) { 1414 g_autofree char *partition_dir = NULL; 1415 char *dev_name; 1416 GuestDiskInfo *partition; 1417 1418 if (!(de_disk->d_type & DT_DIR)) { 1419 continue; 1420 } 1421 1422 if (!(strncmp(disk_name, de_disk->d_name, len) == 0 && 1423 ((*(de_disk->d_name + len) == 'p' && 1424 isdigit(*(de_disk->d_name + len + 1))) || 1425 isdigit(*(de_disk->d_name + len))))) { 1426 continue; 1427 } 1428 1429 partition_dir = g_strdup_printf("%s/%s", 1430 disk_dir, de_disk->d_name); 1431 dev_name = get_device_for_syspath(partition_dir); 1432 if (dev_name == NULL) { 1433 g_debug("Failed to get device name for syspath: %s", 1434 disk_dir); 1435 continue; 1436 } 1437 partition = g_new0(GuestDiskInfo, 1); 1438 partition->name = dev_name; 1439 partition->partition = true; 1440 partition->has_dependencies = true; 1441 /* Add parent disk as dependent for easier tracking of hierarchy */ 1442 QAPI_LIST_PREPEND(partition->dependencies, g_strdup(disk_dev)); 1443 1444 QAPI_LIST_PREPEND(ret, partition); 1445 } 1446 closedir(dp_disk); 1447 1448 return ret; 1449 } 1450 1451 static void get_nvme_smart(GuestDiskInfo *disk) 1452 { 1453 int fd; 1454 GuestNVMeSmart *smart; 1455 NvmeSmartLog log = {0}; 1456 struct nvme_admin_cmd cmd = { 1457 .opcode = NVME_ADM_CMD_GET_LOG_PAGE, 1458 .nsid = NVME_NSID_BROADCAST, 1459 .addr = (uintptr_t)&log, 1460 .data_len = sizeof(log), 1461 .cdw10 = NVME_LOG_SMART_INFO | (1 << 15) /* RAE bit */ 1462 | (((sizeof(log) >> 2) - 1) << 16) 1463 }; 1464 1465 fd = qga_open_cloexec(disk->name, O_RDONLY, 0); 1466 if (fd == -1) { 1467 g_debug("Failed to open device: %s: %s", disk->name, g_strerror(errno)); 1468 return; 1469 } 1470 1471 if (ioctl(fd, NVME_IOCTL_ADMIN_CMD, &cmd)) { 1472 g_debug("Failed to get smart: %s: %s", disk->name, g_strerror(errno)); 1473 close(fd); 1474 return; 1475 } 1476 1477 disk->smart = g_new0(GuestDiskSmart, 1); 1478 disk->smart->type = GUEST_DISK_BUS_TYPE_NVME; 1479 1480 smart = &disk->smart->u.nvme; 1481 smart->critical_warning = log.critical_warning; 1482 smart->temperature = lduw_le_p(&log.temperature); /* unaligned field */ 1483 smart->available_spare = log.available_spare; 1484 smart->available_spare_threshold = log.available_spare_threshold; 1485 smart->percentage_used = log.percentage_used; 1486 smart->data_units_read_lo = le64_to_cpu(log.data_units_read[0]); 1487 smart->data_units_read_hi = le64_to_cpu(log.data_units_read[1]); 1488 smart->data_units_written_lo = le64_to_cpu(log.data_units_written[0]); 1489 smart->data_units_written_hi = le64_to_cpu(log.data_units_written[1]); 1490 smart->host_read_commands_lo = le64_to_cpu(log.host_read_commands[0]); 1491 smart->host_read_commands_hi = le64_to_cpu(log.host_read_commands[1]); 1492 smart->host_write_commands_lo = le64_to_cpu(log.host_write_commands[0]); 1493 smart->host_write_commands_hi = le64_to_cpu(log.host_write_commands[1]); 1494 smart->controller_busy_time_lo = le64_to_cpu(log.controller_busy_time[0]); 1495 smart->controller_busy_time_hi = le64_to_cpu(log.controller_busy_time[1]); 1496 smart->power_cycles_lo = le64_to_cpu(log.power_cycles[0]); 1497 smart->power_cycles_hi = le64_to_cpu(log.power_cycles[1]); 1498 smart->power_on_hours_lo = le64_to_cpu(log.power_on_hours[0]); 1499 smart->power_on_hours_hi = le64_to_cpu(log.power_on_hours[1]); 1500 smart->unsafe_shutdowns_lo = le64_to_cpu(log.unsafe_shutdowns[0]); 1501 smart->unsafe_shutdowns_hi = le64_to_cpu(log.unsafe_shutdowns[1]); 1502 smart->media_errors_lo = le64_to_cpu(log.media_errors[0]); 1503 smart->media_errors_hi = le64_to_cpu(log.media_errors[1]); 1504 smart->number_of_error_log_entries_lo = 1505 le64_to_cpu(log.number_of_error_log_entries[0]); 1506 smart->number_of_error_log_entries_hi = 1507 le64_to_cpu(log.number_of_error_log_entries[1]); 1508 1509 close(fd); 1510 } 1511 1512 static void get_disk_smart(GuestDiskInfo *disk) 1513 { 1514 if (disk->address 1515 && (disk->address->bus_type == GUEST_DISK_BUS_TYPE_NVME)) { 1516 get_nvme_smart(disk); 1517 } 1518 } 1519 1520 GuestDiskInfoList *qmp_guest_get_disks(Error **errp) 1521 { 1522 GuestDiskInfoList *ret = NULL; 1523 GuestDiskInfo *disk; 1524 DIR *dp = NULL; 1525 struct dirent *de = NULL; 1526 1527 g_debug("listing /sys/block directory"); 1528 dp = opendir("/sys/block"); 1529 if (dp == NULL) { 1530 error_setg_errno(errp, errno, "Can't open directory \"/sys/block\""); 1531 return NULL; 1532 } 1533 while ((de = readdir(dp)) != NULL) { 1534 g_autofree char *disk_dir = NULL, *line = NULL, 1535 *size_path = NULL; 1536 char *dev_name; 1537 Error *local_err = NULL; 1538 if (de->d_type != DT_LNK) { 1539 g_debug(" skipping entry: %s", de->d_name); 1540 continue; 1541 } 1542 1543 /* Check size and skip zero-sized disks */ 1544 g_debug(" checking disk size"); 1545 size_path = g_strdup_printf("/sys/block/%s/size", de->d_name); 1546 if (!g_file_get_contents(size_path, &line, NULL, NULL)) { 1547 g_debug(" failed to read disk size"); 1548 continue; 1549 } 1550 if (g_strcmp0(line, "0\n") == 0) { 1551 g_debug(" skipping zero-sized disk"); 1552 continue; 1553 } 1554 1555 g_debug(" adding %s", de->d_name); 1556 disk_dir = g_strdup_printf("/sys/block/%s", de->d_name); 1557 dev_name = get_device_for_syspath(disk_dir); 1558 if (dev_name == NULL) { 1559 g_debug("Failed to get device name for syspath: %s", 1560 disk_dir); 1561 continue; 1562 } 1563 disk = g_new0(GuestDiskInfo, 1); 1564 disk->name = dev_name; 1565 disk->partition = false; 1566 disk->alias = get_alias_for_syspath(disk_dir); 1567 QAPI_LIST_PREPEND(ret, disk); 1568 1569 /* Get address for non-virtual devices */ 1570 bool is_virtual = is_disk_virtual(disk_dir, &local_err); 1571 if (local_err != NULL) { 1572 g_debug(" failed to check disk path, ignoring error: %s", 1573 error_get_pretty(local_err)); 1574 error_free(local_err); 1575 local_err = NULL; 1576 /* Don't try to get the address */ 1577 is_virtual = true; 1578 } 1579 if (!is_virtual) { 1580 disk->address = get_disk_address(disk_dir, &local_err); 1581 if (local_err != NULL) { 1582 g_debug(" failed to get device info, ignoring error: %s", 1583 error_get_pretty(local_err)); 1584 error_free(local_err); 1585 local_err = NULL; 1586 } 1587 } 1588 1589 get_disk_deps(disk_dir, disk); 1590 get_disk_smart(disk); 1591 ret = get_disk_partitions(ret, de->d_name, disk_dir, dev_name); 1592 } 1593 1594 closedir(dp); 1595 1596 return ret; 1597 } 1598 1599 #else 1600 1601 GuestDiskInfoList *qmp_guest_get_disks(Error **errp) 1602 { 1603 error_setg(errp, QERR_UNSUPPORTED); 1604 return NULL; 1605 } 1606 1607 #endif 1608 1609 /* Return a list of the disk device(s)' info which @mount lies on */ 1610 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount, 1611 Error **errp) 1612 { 1613 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs)); 1614 struct statvfs buf; 1615 unsigned long used, nonroot_total, fr_size; 1616 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u", 1617 mount->devmajor, mount->devminor); 1618 1619 fs->mountpoint = g_strdup(mount->dirname); 1620 fs->type = g_strdup(mount->devtype); 1621 build_guest_fsinfo_for_device(devpath, fs, errp); 1622 1623 if (statvfs(fs->mountpoint, &buf) == 0) { 1624 fr_size = buf.f_frsize; 1625 used = buf.f_blocks - buf.f_bfree; 1626 nonroot_total = used + buf.f_bavail; 1627 fs->used_bytes = used * fr_size; 1628 fs->total_bytes = nonroot_total * fr_size; 1629 fs->total_bytes_privileged = buf.f_blocks * fr_size; 1630 1631 fs->has_total_bytes = true; 1632 fs->has_total_bytes_privileged = true; 1633 fs->has_used_bytes = true; 1634 } 1635 1636 g_free(devpath); 1637 1638 return fs; 1639 } 1640 1641 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp) 1642 { 1643 FsMountList mounts; 1644 struct FsMount *mount; 1645 GuestFilesystemInfoList *ret = NULL; 1646 Error *local_err = NULL; 1647 1648 QTAILQ_INIT(&mounts); 1649 if (!build_fs_mount_list(&mounts, &local_err)) { 1650 error_propagate(errp, local_err); 1651 return NULL; 1652 } 1653 1654 QTAILQ_FOREACH(mount, &mounts, next) { 1655 g_debug("Building guest fsinfo for '%s'", mount->dirname); 1656 1657 QAPI_LIST_PREPEND(ret, build_guest_fsinfo(mount, &local_err)); 1658 if (local_err) { 1659 error_propagate(errp, local_err); 1660 qapi_free_GuestFilesystemInfoList(ret); 1661 ret = NULL; 1662 break; 1663 } 1664 } 1665 1666 free_fs_mount_list(&mounts); 1667 return ret; 1668 } 1669 #endif /* CONFIG_FSFREEZE */ 1670 1671 #if defined(CONFIG_FSTRIM) 1672 /* 1673 * Walk list of mounted file systems in the guest, and trim them. 1674 */ 1675 GuestFilesystemTrimResponse * 1676 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp) 1677 { 1678 GuestFilesystemTrimResponse *response; 1679 GuestFilesystemTrimResult *result; 1680 int ret = 0; 1681 FsMountList mounts; 1682 struct FsMount *mount; 1683 int fd; 1684 struct fstrim_range r; 1685 1686 slog("guest-fstrim called"); 1687 1688 QTAILQ_INIT(&mounts); 1689 if (!build_fs_mount_list(&mounts, errp)) { 1690 return NULL; 1691 } 1692 1693 response = g_malloc0(sizeof(*response)); 1694 1695 QTAILQ_FOREACH(mount, &mounts, next) { 1696 result = g_malloc0(sizeof(*result)); 1697 result->path = g_strdup(mount->dirname); 1698 1699 QAPI_LIST_PREPEND(response->paths, result); 1700 1701 fd = qga_open_cloexec(mount->dirname, O_RDONLY, 0); 1702 if (fd == -1) { 1703 result->error = g_strdup_printf("failed to open: %s", 1704 strerror(errno)); 1705 continue; 1706 } 1707 1708 /* We try to cull filesystems we know won't work in advance, but other 1709 * filesystems may not implement fstrim for less obvious reasons. 1710 * These will report EOPNOTSUPP; while in some other cases ENOTTY 1711 * will be reported (e.g. CD-ROMs). 1712 * Any other error means an unexpected error. 1713 */ 1714 r.start = 0; 1715 r.len = -1; 1716 r.minlen = has_minimum ? minimum : 0; 1717 ret = ioctl(fd, FITRIM, &r); 1718 if (ret == -1) { 1719 if (errno == ENOTTY || errno == EOPNOTSUPP) { 1720 result->error = g_strdup("trim not supported"); 1721 } else { 1722 result->error = g_strdup_printf("failed to trim: %s", 1723 strerror(errno)); 1724 } 1725 close(fd); 1726 continue; 1727 } 1728 1729 result->has_minimum = true; 1730 result->minimum = r.minlen; 1731 result->has_trimmed = true; 1732 result->trimmed = r.len; 1733 close(fd); 1734 } 1735 1736 free_fs_mount_list(&mounts); 1737 return response; 1738 } 1739 #endif /* CONFIG_FSTRIM */ 1740 1741 #endif /* __linux__ */ 1742 1743 #if defined(__linux__) || defined(__FreeBSD__) 1744 void qmp_guest_set_user_password(const char *username, 1745 const char *password, 1746 bool crypted, 1747 Error **errp) 1748 { 1749 Error *local_err = NULL; 1750 g_autofree char *rawpasswddata = NULL; 1751 size_t rawpasswdlen; 1752 1753 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp); 1754 if (!rawpasswddata) { 1755 return; 1756 } 1757 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1); 1758 rawpasswddata[rawpasswdlen] = '\0'; 1759 1760 if (strchr(rawpasswddata, '\n')) { 1761 error_setg(errp, "forbidden characters in raw password"); 1762 return; 1763 } 1764 1765 if (strchr(username, '\n') || 1766 strchr(username, ':')) { 1767 error_setg(errp, "forbidden characters in username"); 1768 return; 1769 } 1770 1771 #ifdef __FreeBSD__ 1772 g_autofree char *chpasswddata = g_strdup(rawpasswddata); 1773 const char *crypt_flag = crypted ? "-H" : "-h"; 1774 const char *argv[] = {"pw", "usermod", "-n", username, 1775 crypt_flag, "0", NULL}; 1776 #else 1777 g_autofree char *chpasswddata = g_strdup_printf("%s:%s\n", username, 1778 rawpasswddata); 1779 const char *crypt_flag = crypted ? "-e" : NULL; 1780 const char *argv[] = {"chpasswd", crypt_flag, NULL}; 1781 #endif 1782 1783 ga_run_command(argv, chpasswddata, "set user password", &local_err); 1784 if (local_err) { 1785 error_propagate(errp, local_err); 1786 return; 1787 } 1788 } 1789 #else /* __linux__ || __FreeBSD__ */ 1790 void qmp_guest_set_user_password(const char *username, 1791 const char *password, 1792 bool crypted, 1793 Error **errp) 1794 { 1795 error_setg(errp, QERR_UNSUPPORTED); 1796 } 1797 #endif /* __linux__ || __FreeBSD__ */ 1798 1799 #ifdef __linux__ 1800 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf, 1801 int size, Error **errp) 1802 { 1803 int fd; 1804 int res; 1805 1806 errno = 0; 1807 fd = openat(dirfd, pathname, O_RDONLY); 1808 if (fd == -1) { 1809 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname); 1810 return; 1811 } 1812 1813 res = pread(fd, buf, size, 0); 1814 if (res == -1) { 1815 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname); 1816 } else if (res == 0) { 1817 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname); 1818 } 1819 close(fd); 1820 } 1821 1822 static void ga_write_sysfs_file(int dirfd, const char *pathname, 1823 const char *buf, int size, Error **errp) 1824 { 1825 int fd; 1826 1827 errno = 0; 1828 fd = openat(dirfd, pathname, O_WRONLY); 1829 if (fd == -1) { 1830 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname); 1831 return; 1832 } 1833 1834 if (pwrite(fd, buf, size, 0) == -1) { 1835 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname); 1836 } 1837 1838 close(fd); 1839 } 1840 1841 /* Transfer online/offline status between @mem_blk and the guest system. 1842 * 1843 * On input either @errp or *@errp must be NULL. 1844 * 1845 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed: 1846 * - R: mem_blk->phys_index 1847 * - W: mem_blk->online 1848 * - W: mem_blk->can_offline 1849 * 1850 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed: 1851 * - R: mem_blk->phys_index 1852 * - R: mem_blk->online 1853 *- R: mem_blk->can_offline 1854 * Written members remain unmodified on error. 1855 */ 1856 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk, 1857 GuestMemoryBlockResponse *result, 1858 Error **errp) 1859 { 1860 char *dirpath; 1861 int dirfd; 1862 char *status; 1863 Error *local_err = NULL; 1864 1865 if (!sys2memblk) { 1866 DIR *dp; 1867 1868 if (!result) { 1869 error_setg(errp, "Internal error, 'result' should not be NULL"); 1870 return; 1871 } 1872 errno = 0; 1873 dp = opendir("/sys/devices/system/memory/"); 1874 /* if there is no 'memory' directory in sysfs, 1875 * we think this VM does not support online/offline memory block, 1876 * any other solution? 1877 */ 1878 if (!dp) { 1879 if (errno == ENOENT) { 1880 result->response = 1881 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED; 1882 } 1883 goto out1; 1884 } 1885 closedir(dp); 1886 } 1887 1888 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/", 1889 mem_blk->phys_index); 1890 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY); 1891 if (dirfd == -1) { 1892 if (sys2memblk) { 1893 error_setg_errno(errp, errno, "open(\"%s\")", dirpath); 1894 } else { 1895 if (errno == ENOENT) { 1896 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND; 1897 } else { 1898 result->response = 1899 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED; 1900 } 1901 } 1902 g_free(dirpath); 1903 goto out1; 1904 } 1905 g_free(dirpath); 1906 1907 status = g_malloc0(10); 1908 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err); 1909 if (local_err) { 1910 /* treat with sysfs file that not exist in old kernel */ 1911 if (errno == ENOENT) { 1912 error_free(local_err); 1913 if (sys2memblk) { 1914 mem_blk->online = true; 1915 mem_blk->can_offline = false; 1916 } else if (!mem_blk->online) { 1917 result->response = 1918 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED; 1919 } 1920 } else { 1921 if (sys2memblk) { 1922 error_propagate(errp, local_err); 1923 } else { 1924 error_free(local_err); 1925 result->response = 1926 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED; 1927 } 1928 } 1929 goto out2; 1930 } 1931 1932 if (sys2memblk) { 1933 char removable = '0'; 1934 1935 mem_blk->online = (strncmp(status, "online", 6) == 0); 1936 1937 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err); 1938 if (local_err) { 1939 /* if no 'removable' file, it doesn't support offline mem blk */ 1940 if (errno == ENOENT) { 1941 error_free(local_err); 1942 mem_blk->can_offline = false; 1943 } else { 1944 error_propagate(errp, local_err); 1945 } 1946 } else { 1947 mem_blk->can_offline = (removable != '0'); 1948 } 1949 } else { 1950 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) { 1951 const char *new_state = mem_blk->online ? "online" : "offline"; 1952 1953 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state), 1954 &local_err); 1955 if (local_err) { 1956 error_free(local_err); 1957 result->response = 1958 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED; 1959 goto out2; 1960 } 1961 1962 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS; 1963 result->has_error_code = false; 1964 } /* otherwise pretend successful re-(on|off)-lining */ 1965 } 1966 g_free(status); 1967 close(dirfd); 1968 return; 1969 1970 out2: 1971 g_free(status); 1972 close(dirfd); 1973 out1: 1974 if (!sys2memblk) { 1975 result->has_error_code = true; 1976 result->error_code = errno; 1977 } 1978 } 1979 1980 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp) 1981 { 1982 GuestMemoryBlockList *head, **tail; 1983 Error *local_err = NULL; 1984 struct dirent *de; 1985 DIR *dp; 1986 1987 head = NULL; 1988 tail = &head; 1989 1990 dp = opendir("/sys/devices/system/memory/"); 1991 if (!dp) { 1992 /* it's ok if this happens to be a system that doesn't expose 1993 * memory blocks via sysfs, but otherwise we should report 1994 * an error 1995 */ 1996 if (errno != ENOENT) { 1997 error_setg_errno(errp, errno, "Can't open directory" 1998 "\"/sys/devices/system/memory/\""); 1999 } 2000 return NULL; 2001 } 2002 2003 /* Note: the phys_index of memory block may be discontinuous, 2004 * this is because a memblk is the unit of the Sparse Memory design, which 2005 * allows discontinuous memory ranges (ex. NUMA), so here we should 2006 * traverse the memory block directory. 2007 */ 2008 while ((de = readdir(dp)) != NULL) { 2009 GuestMemoryBlock *mem_blk; 2010 2011 if ((strncmp(de->d_name, "memory", 6) != 0) || 2012 !(de->d_type & DT_DIR)) { 2013 continue; 2014 } 2015 2016 mem_blk = g_malloc0(sizeof *mem_blk); 2017 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */ 2018 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10); 2019 mem_blk->has_can_offline = true; /* lolspeak ftw */ 2020 transfer_memory_block(mem_blk, true, NULL, &local_err); 2021 if (local_err) { 2022 break; 2023 } 2024 2025 QAPI_LIST_APPEND(tail, mem_blk); 2026 } 2027 2028 closedir(dp); 2029 if (local_err == NULL) { 2030 /* there's no guest with zero memory blocks */ 2031 if (head == NULL) { 2032 error_setg(errp, "guest reported zero memory blocks!"); 2033 } 2034 return head; 2035 } 2036 2037 qapi_free_GuestMemoryBlockList(head); 2038 error_propagate(errp, local_err); 2039 return NULL; 2040 } 2041 2042 GuestMemoryBlockResponseList * 2043 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp) 2044 { 2045 GuestMemoryBlockResponseList *head, **tail; 2046 Error *local_err = NULL; 2047 2048 head = NULL; 2049 tail = &head; 2050 2051 while (mem_blks != NULL) { 2052 GuestMemoryBlockResponse *result; 2053 GuestMemoryBlock *current_mem_blk = mem_blks->value; 2054 2055 result = g_malloc0(sizeof(*result)); 2056 result->phys_index = current_mem_blk->phys_index; 2057 transfer_memory_block(current_mem_blk, false, result, &local_err); 2058 if (local_err) { /* should never happen */ 2059 goto err; 2060 } 2061 2062 QAPI_LIST_APPEND(tail, result); 2063 mem_blks = mem_blks->next; 2064 } 2065 2066 return head; 2067 err: 2068 qapi_free_GuestMemoryBlockResponseList(head); 2069 error_propagate(errp, local_err); 2070 return NULL; 2071 } 2072 2073 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp) 2074 { 2075 Error *local_err = NULL; 2076 char *dirpath; 2077 int dirfd; 2078 char *buf; 2079 GuestMemoryBlockInfo *info; 2080 2081 dirpath = g_strdup_printf("/sys/devices/system/memory/"); 2082 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY); 2083 if (dirfd == -1) { 2084 error_setg_errno(errp, errno, "open(\"%s\")", dirpath); 2085 g_free(dirpath); 2086 return NULL; 2087 } 2088 g_free(dirpath); 2089 2090 buf = g_malloc0(20); 2091 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err); 2092 close(dirfd); 2093 if (local_err) { 2094 g_free(buf); 2095 error_propagate(errp, local_err); 2096 return NULL; 2097 } 2098 2099 info = g_new0(GuestMemoryBlockInfo, 1); 2100 info->size = strtol(buf, NULL, 16); /* the unit is bytes */ 2101 2102 g_free(buf); 2103 2104 return info; 2105 } 2106 2107 #define MAX_NAME_LEN 128 2108 static GuestDiskStatsInfoList *guest_get_diskstats(Error **errp) 2109 { 2110 #ifdef CONFIG_LINUX 2111 GuestDiskStatsInfoList *head = NULL, **tail = &head; 2112 const char *diskstats = "/proc/diskstats"; 2113 FILE *fp; 2114 size_t n; 2115 char *line = NULL; 2116 2117 fp = fopen(diskstats, "r"); 2118 if (fp == NULL) { 2119 error_setg_errno(errp, errno, "open(\"%s\")", diskstats); 2120 return NULL; 2121 } 2122 2123 while (getline(&line, &n, fp) != -1) { 2124 g_autofree GuestDiskStatsInfo *diskstatinfo = NULL; 2125 g_autofree GuestDiskStats *diskstat = NULL; 2126 char dev_name[MAX_NAME_LEN]; 2127 unsigned int ios_pgr, tot_ticks, rq_ticks, wr_ticks, dc_ticks, fl_ticks; 2128 unsigned long rd_ios, rd_merges_or_rd_sec, rd_ticks_or_wr_sec, wr_ios; 2129 unsigned long wr_merges, rd_sec_or_wr_ios, wr_sec; 2130 unsigned long dc_ios, dc_merges, dc_sec, fl_ios; 2131 unsigned int major, minor; 2132 int i; 2133 2134 i = sscanf(line, "%u %u %s %lu %lu %lu" 2135 "%lu %lu %lu %lu %u %u %u %u" 2136 "%lu %lu %lu %u %lu %u", 2137 &major, &minor, dev_name, 2138 &rd_ios, &rd_merges_or_rd_sec, &rd_sec_or_wr_ios, 2139 &rd_ticks_or_wr_sec, &wr_ios, &wr_merges, &wr_sec, 2140 &wr_ticks, &ios_pgr, &tot_ticks, &rq_ticks, 2141 &dc_ios, &dc_merges, &dc_sec, &dc_ticks, 2142 &fl_ios, &fl_ticks); 2143 2144 if (i < 7) { 2145 continue; 2146 } 2147 2148 diskstatinfo = g_new0(GuestDiskStatsInfo, 1); 2149 diskstatinfo->name = g_strdup(dev_name); 2150 diskstatinfo->major = major; 2151 diskstatinfo->minor = minor; 2152 2153 diskstat = g_new0(GuestDiskStats, 1); 2154 if (i == 7) { 2155 diskstat->has_read_ios = true; 2156 diskstat->read_ios = rd_ios; 2157 diskstat->has_read_sectors = true; 2158 diskstat->read_sectors = rd_merges_or_rd_sec; 2159 diskstat->has_write_ios = true; 2160 diskstat->write_ios = rd_sec_or_wr_ios; 2161 diskstat->has_write_sectors = true; 2162 diskstat->write_sectors = rd_ticks_or_wr_sec; 2163 } 2164 if (i >= 14) { 2165 diskstat->has_read_ios = true; 2166 diskstat->read_ios = rd_ios; 2167 diskstat->has_read_sectors = true; 2168 diskstat->read_sectors = rd_sec_or_wr_ios; 2169 diskstat->has_read_merges = true; 2170 diskstat->read_merges = rd_merges_or_rd_sec; 2171 diskstat->has_read_ticks = true; 2172 diskstat->read_ticks = rd_ticks_or_wr_sec; 2173 diskstat->has_write_ios = true; 2174 diskstat->write_ios = wr_ios; 2175 diskstat->has_write_sectors = true; 2176 diskstat->write_sectors = wr_sec; 2177 diskstat->has_write_merges = true; 2178 diskstat->write_merges = wr_merges; 2179 diskstat->has_write_ticks = true; 2180 diskstat->write_ticks = wr_ticks; 2181 diskstat->has_ios_pgr = true; 2182 diskstat->ios_pgr = ios_pgr; 2183 diskstat->has_total_ticks = true; 2184 diskstat->total_ticks = tot_ticks; 2185 diskstat->has_weight_ticks = true; 2186 diskstat->weight_ticks = rq_ticks; 2187 } 2188 if (i >= 18) { 2189 diskstat->has_discard_ios = true; 2190 diskstat->discard_ios = dc_ios; 2191 diskstat->has_discard_merges = true; 2192 diskstat->discard_merges = dc_merges; 2193 diskstat->has_discard_sectors = true; 2194 diskstat->discard_sectors = dc_sec; 2195 diskstat->has_discard_ticks = true; 2196 diskstat->discard_ticks = dc_ticks; 2197 } 2198 if (i >= 20) { 2199 diskstat->has_flush_ios = true; 2200 diskstat->flush_ios = fl_ios; 2201 diskstat->has_flush_ticks = true; 2202 diskstat->flush_ticks = fl_ticks; 2203 } 2204 2205 diskstatinfo->stats = g_steal_pointer(&diskstat); 2206 QAPI_LIST_APPEND(tail, diskstatinfo); 2207 diskstatinfo = NULL; 2208 } 2209 free(line); 2210 fclose(fp); 2211 return head; 2212 #else 2213 g_debug("disk stats reporting available only for Linux"); 2214 return NULL; 2215 #endif 2216 } 2217 2218 GuestDiskStatsInfoList *qmp_guest_get_diskstats(Error **errp) 2219 { 2220 return guest_get_diskstats(errp); 2221 } 2222 2223 GuestCpuStatsList *qmp_guest_get_cpustats(Error **errp) 2224 { 2225 GuestCpuStatsList *head = NULL, **tail = &head; 2226 const char *cpustats = "/proc/stat"; 2227 int clk_tck = sysconf(_SC_CLK_TCK); 2228 FILE *fp; 2229 size_t n; 2230 char *line = NULL; 2231 2232 fp = fopen(cpustats, "r"); 2233 if (fp == NULL) { 2234 error_setg_errno(errp, errno, "open(\"%s\")", cpustats); 2235 return NULL; 2236 } 2237 2238 while (getline(&line, &n, fp) != -1) { 2239 GuestCpuStats *cpustat = NULL; 2240 GuestLinuxCpuStats *linuxcpustat; 2241 int i; 2242 unsigned long user, system, idle, iowait, irq, softirq, steal, guest; 2243 unsigned long nice, guest_nice; 2244 char name[64]; 2245 2246 i = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu", 2247 name, &user, &nice, &system, &idle, &iowait, &irq, &softirq, 2248 &steal, &guest, &guest_nice); 2249 2250 /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */ 2251 if ((i == EOF) || strncmp(name, "cpu", 3) || (name[3] == '\0')) { 2252 continue; 2253 } 2254 2255 if (i < 5) { 2256 slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats); 2257 break; 2258 } 2259 2260 cpustat = g_new0(GuestCpuStats, 1); 2261 cpustat->type = GUEST_CPU_STATS_TYPE_LINUX; 2262 2263 linuxcpustat = &cpustat->u.q_linux; 2264 linuxcpustat->cpu = atoi(&name[3]); 2265 linuxcpustat->user = user * 1000 / clk_tck; 2266 linuxcpustat->nice = nice * 1000 / clk_tck; 2267 linuxcpustat->system = system * 1000 / clk_tck; 2268 linuxcpustat->idle = idle * 1000 / clk_tck; 2269 2270 if (i > 5) { 2271 linuxcpustat->has_iowait = true; 2272 linuxcpustat->iowait = iowait * 1000 / clk_tck; 2273 } 2274 2275 if (i > 6) { 2276 linuxcpustat->has_irq = true; 2277 linuxcpustat->irq = irq * 1000 / clk_tck; 2278 linuxcpustat->has_softirq = true; 2279 linuxcpustat->softirq = softirq * 1000 / clk_tck; 2280 } 2281 2282 if (i > 8) { 2283 linuxcpustat->has_steal = true; 2284 linuxcpustat->steal = steal * 1000 / clk_tck; 2285 } 2286 2287 if (i > 9) { 2288 linuxcpustat->has_guest = true; 2289 linuxcpustat->guest = guest * 1000 / clk_tck; 2290 } 2291 2292 if (i > 10) { 2293 linuxcpustat->has_guest = true; 2294 linuxcpustat->guest = guest * 1000 / clk_tck; 2295 linuxcpustat->has_guestnice = true; 2296 linuxcpustat->guestnice = guest_nice * 1000 / clk_tck; 2297 } 2298 2299 QAPI_LIST_APPEND(tail, cpustat); 2300 } 2301 2302 free(line); 2303 fclose(fp); 2304 return head; 2305 } 2306 2307 #else /* defined(__linux__) */ 2308 2309 void qmp_guest_suspend_disk(Error **errp) 2310 { 2311 error_setg(errp, QERR_UNSUPPORTED); 2312 } 2313 2314 void qmp_guest_suspend_ram(Error **errp) 2315 { 2316 error_setg(errp, QERR_UNSUPPORTED); 2317 } 2318 2319 void qmp_guest_suspend_hybrid(Error **errp) 2320 { 2321 error_setg(errp, QERR_UNSUPPORTED); 2322 } 2323 2324 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp) 2325 { 2326 error_setg(errp, QERR_UNSUPPORTED); 2327 return NULL; 2328 } 2329 2330 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp) 2331 { 2332 error_setg(errp, QERR_UNSUPPORTED); 2333 return -1; 2334 } 2335 2336 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp) 2337 { 2338 error_setg(errp, QERR_UNSUPPORTED); 2339 return NULL; 2340 } 2341 2342 GuestMemoryBlockResponseList * 2343 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp) 2344 { 2345 error_setg(errp, QERR_UNSUPPORTED); 2346 return NULL; 2347 } 2348 2349 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp) 2350 { 2351 error_setg(errp, QERR_UNSUPPORTED); 2352 return NULL; 2353 } 2354 2355 #endif 2356 2357 #ifdef HAVE_GETIFADDRS 2358 static GuestNetworkInterface * 2359 guest_find_interface(GuestNetworkInterfaceList *head, 2360 const char *name) 2361 { 2362 for (; head; head = head->next) { 2363 if (strcmp(head->value->name, name) == 0) { 2364 return head->value; 2365 } 2366 } 2367 2368 return NULL; 2369 } 2370 2371 static int guest_get_network_stats(const char *name, 2372 GuestNetworkInterfaceStat *stats) 2373 { 2374 #ifdef CONFIG_LINUX 2375 int name_len; 2376 char const *devinfo = "/proc/net/dev"; 2377 FILE *fp; 2378 char *line = NULL, *colon; 2379 size_t n = 0; 2380 fp = fopen(devinfo, "r"); 2381 if (!fp) { 2382 g_debug("failed to open network stats %s: %s", devinfo, 2383 g_strerror(errno)); 2384 return -1; 2385 } 2386 name_len = strlen(name); 2387 while (getline(&line, &n, fp) != -1) { 2388 long long dummy; 2389 long long rx_bytes; 2390 long long rx_packets; 2391 long long rx_errs; 2392 long long rx_dropped; 2393 long long tx_bytes; 2394 long long tx_packets; 2395 long long tx_errs; 2396 long long tx_dropped; 2397 char *trim_line; 2398 trim_line = g_strchug(line); 2399 if (trim_line[0] == '\0') { 2400 continue; 2401 } 2402 colon = strchr(trim_line, ':'); 2403 if (!colon) { 2404 continue; 2405 } 2406 if (colon - name_len == trim_line && 2407 strncmp(trim_line, name, name_len) == 0) { 2408 if (sscanf(colon + 1, 2409 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld", 2410 &rx_bytes, &rx_packets, &rx_errs, &rx_dropped, 2411 &dummy, &dummy, &dummy, &dummy, 2412 &tx_bytes, &tx_packets, &tx_errs, &tx_dropped, 2413 &dummy, &dummy, &dummy, &dummy) != 16) { 2414 continue; 2415 } 2416 stats->rx_bytes = rx_bytes; 2417 stats->rx_packets = rx_packets; 2418 stats->rx_errs = rx_errs; 2419 stats->rx_dropped = rx_dropped; 2420 stats->tx_bytes = tx_bytes; 2421 stats->tx_packets = tx_packets; 2422 stats->tx_errs = tx_errs; 2423 stats->tx_dropped = tx_dropped; 2424 fclose(fp); 2425 g_free(line); 2426 return 0; 2427 } 2428 } 2429 fclose(fp); 2430 g_free(line); 2431 g_debug("/proc/net/dev: Interface '%s' not found", name); 2432 #else /* !CONFIG_LINUX */ 2433 g_debug("Network stats reporting available only for Linux"); 2434 #endif /* !CONFIG_LINUX */ 2435 return -1; 2436 } 2437 2438 #ifndef CONFIG_BSD 2439 /* 2440 * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a 2441 * buffer with ETHER_ADDR_LEN length at least. 2442 * 2443 * Returns false in case of an error, otherwise true. "obtained" argument 2444 * is true if a MAC address was obtained successful, otherwise false. 2445 */ 2446 bool guest_get_hw_addr(struct ifaddrs *ifa, unsigned char *buf, 2447 bool *obtained, Error **errp) 2448 { 2449 struct ifreq ifr; 2450 int sock; 2451 2452 *obtained = false; 2453 2454 /* we haven't obtained HW address yet */ 2455 sock = socket(PF_INET, SOCK_STREAM, 0); 2456 if (sock == -1) { 2457 error_setg_errno(errp, errno, "failed to create socket"); 2458 return false; 2459 } 2460 2461 memset(&ifr, 0, sizeof(ifr)); 2462 pstrcpy(ifr.ifr_name, IF_NAMESIZE, ifa->ifa_name); 2463 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) { 2464 /* 2465 * We can't get the hw addr of this interface, but that's not a 2466 * fatal error. 2467 */ 2468 if (errno == EADDRNOTAVAIL) { 2469 /* The interface doesn't have a hw addr (e.g. loopback). */ 2470 g_debug("failed to get MAC address of %s: %s", 2471 ifa->ifa_name, strerror(errno)); 2472 } else{ 2473 g_warning("failed to get MAC address of %s: %s", 2474 ifa->ifa_name, strerror(errno)); 2475 } 2476 } else { 2477 #ifdef CONFIG_SOLARIS 2478 memcpy(buf, &ifr.ifr_addr.sa_data, ETHER_ADDR_LEN); 2479 #else 2480 memcpy(buf, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN); 2481 #endif 2482 *obtained = true; 2483 } 2484 close(sock); 2485 return true; 2486 } 2487 #endif /* CONFIG_BSD */ 2488 2489 /* 2490 * Build information about guest interfaces 2491 */ 2492 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp) 2493 { 2494 GuestNetworkInterfaceList *head = NULL, **tail = &head; 2495 struct ifaddrs *ifap, *ifa; 2496 2497 if (getifaddrs(&ifap) < 0) { 2498 error_setg_errno(errp, errno, "getifaddrs failed"); 2499 goto error; 2500 } 2501 2502 for (ifa = ifap; ifa; ifa = ifa->ifa_next) { 2503 GuestNetworkInterface *info; 2504 GuestIpAddressList **address_tail; 2505 GuestIpAddress *address_item = NULL; 2506 GuestNetworkInterfaceStat *interface_stat = NULL; 2507 char addr4[INET_ADDRSTRLEN]; 2508 char addr6[INET6_ADDRSTRLEN]; 2509 unsigned char mac_addr[ETHER_ADDR_LEN]; 2510 bool obtained; 2511 void *p; 2512 2513 g_debug("Processing %s interface", ifa->ifa_name); 2514 2515 info = guest_find_interface(head, ifa->ifa_name); 2516 2517 if (!info) { 2518 info = g_malloc0(sizeof(*info)); 2519 info->name = g_strdup(ifa->ifa_name); 2520 2521 QAPI_LIST_APPEND(tail, info); 2522 } 2523 2524 if (!info->hardware_address) { 2525 if (!guest_get_hw_addr(ifa, mac_addr, &obtained, errp)) { 2526 goto error; 2527 } 2528 if (obtained) { 2529 info->hardware_address = 2530 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x", 2531 (int) mac_addr[0], (int) mac_addr[1], 2532 (int) mac_addr[2], (int) mac_addr[3], 2533 (int) mac_addr[4], (int) mac_addr[5]); 2534 } 2535 } 2536 2537 if (ifa->ifa_addr && 2538 ifa->ifa_addr->sa_family == AF_INET) { 2539 /* interface with IPv4 address */ 2540 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; 2541 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) { 2542 error_setg_errno(errp, errno, "inet_ntop failed"); 2543 goto error; 2544 } 2545 2546 address_item = g_malloc0(sizeof(*address_item)); 2547 address_item->ip_address = g_strdup(addr4); 2548 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4; 2549 2550 if (ifa->ifa_netmask) { 2551 /* Count the number of set bits in netmask. 2552 * This is safe as '1' and '0' cannot be shuffled in netmask. */ 2553 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr; 2554 address_item->prefix = ctpop32(((uint32_t *) p)[0]); 2555 } 2556 } else if (ifa->ifa_addr && 2557 ifa->ifa_addr->sa_family == AF_INET6) { 2558 /* interface with IPv6 address */ 2559 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr; 2560 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) { 2561 error_setg_errno(errp, errno, "inet_ntop failed"); 2562 goto error; 2563 } 2564 2565 address_item = g_malloc0(sizeof(*address_item)); 2566 address_item->ip_address = g_strdup(addr6); 2567 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6; 2568 2569 if (ifa->ifa_netmask) { 2570 /* Count the number of set bits in netmask. 2571 * This is safe as '1' and '0' cannot be shuffled in netmask. */ 2572 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr; 2573 address_item->prefix = 2574 ctpop32(((uint32_t *) p)[0]) + 2575 ctpop32(((uint32_t *) p)[1]) + 2576 ctpop32(((uint32_t *) p)[2]) + 2577 ctpop32(((uint32_t *) p)[3]); 2578 } 2579 } 2580 2581 if (!address_item) { 2582 continue; 2583 } 2584 2585 address_tail = &info->ip_addresses; 2586 while (*address_tail) { 2587 address_tail = &(*address_tail)->next; 2588 } 2589 QAPI_LIST_APPEND(address_tail, address_item); 2590 2591 info->has_ip_addresses = true; 2592 2593 if (!info->statistics) { 2594 interface_stat = g_malloc0(sizeof(*interface_stat)); 2595 if (guest_get_network_stats(info->name, interface_stat) == -1) { 2596 g_free(interface_stat); 2597 } else { 2598 info->statistics = interface_stat; 2599 } 2600 } 2601 } 2602 2603 freeifaddrs(ifap); 2604 return head; 2605 2606 error: 2607 freeifaddrs(ifap); 2608 qapi_free_GuestNetworkInterfaceList(head); 2609 return NULL; 2610 } 2611 2612 #else 2613 2614 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp) 2615 { 2616 error_setg(errp, QERR_UNSUPPORTED); 2617 return NULL; 2618 } 2619 2620 #endif /* HAVE_GETIFADDRS */ 2621 2622 #if !defined(CONFIG_FSFREEZE) 2623 2624 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp) 2625 { 2626 error_setg(errp, QERR_UNSUPPORTED); 2627 return NULL; 2628 } 2629 2630 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp) 2631 { 2632 error_setg(errp, QERR_UNSUPPORTED); 2633 2634 return 0; 2635 } 2636 2637 int64_t qmp_guest_fsfreeze_freeze(Error **errp) 2638 { 2639 error_setg(errp, QERR_UNSUPPORTED); 2640 2641 return 0; 2642 } 2643 2644 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints, 2645 strList *mountpoints, 2646 Error **errp) 2647 { 2648 error_setg(errp, QERR_UNSUPPORTED); 2649 2650 return 0; 2651 } 2652 2653 int64_t qmp_guest_fsfreeze_thaw(Error **errp) 2654 { 2655 error_setg(errp, QERR_UNSUPPORTED); 2656 2657 return 0; 2658 } 2659 2660 GuestDiskInfoList *qmp_guest_get_disks(Error **errp) 2661 { 2662 error_setg(errp, QERR_UNSUPPORTED); 2663 return NULL; 2664 } 2665 2666 GuestDiskStatsInfoList *qmp_guest_get_diskstats(Error **errp) 2667 { 2668 error_setg(errp, QERR_UNSUPPORTED); 2669 return NULL; 2670 } 2671 2672 GuestCpuStatsList *qmp_guest_get_cpustats(Error **errp) 2673 { 2674 error_setg(errp, QERR_UNSUPPORTED); 2675 return NULL; 2676 } 2677 2678 #endif /* CONFIG_FSFREEZE */ 2679 2680 #if !defined(CONFIG_FSTRIM) 2681 GuestFilesystemTrimResponse * 2682 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp) 2683 { 2684 error_setg(errp, QERR_UNSUPPORTED); 2685 return NULL; 2686 } 2687 #endif 2688 2689 /* add unsupported commands to the list of blocked RPCs */ 2690 GList *ga_command_init_blockedrpcs(GList *blockedrpcs) 2691 { 2692 #if !defined(__linux__) 2693 { 2694 const char *list[] = { 2695 "guest-suspend-disk", "guest-suspend-ram", 2696 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus", 2697 "guest-get-memory-blocks", "guest-set-memory-blocks", 2698 "guest-get-memory-block-info", 2699 NULL}; 2700 char **p = (char **)list; 2701 2702 while (*p) { 2703 blockedrpcs = g_list_append(blockedrpcs, g_strdup(*p++)); 2704 } 2705 } 2706 #endif 2707 2708 #if !defined(HAVE_GETIFADDRS) 2709 blockedrpcs = g_list_append(blockedrpcs, 2710 g_strdup("guest-network-get-interfaces")); 2711 #endif 2712 2713 #if !defined(CONFIG_FSFREEZE) 2714 { 2715 const char *list[] = { 2716 "guest-get-fsinfo", "guest-fsfreeze-status", 2717 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list", 2718 "guest-fsfreeze-thaw", "guest-get-fsinfo", 2719 "guest-get-disks", NULL}; 2720 char **p = (char **)list; 2721 2722 while (*p) { 2723 blockedrpcs = g_list_append(blockedrpcs, g_strdup(*p++)); 2724 } 2725 } 2726 #endif 2727 2728 #if !defined(CONFIG_FSTRIM) 2729 blockedrpcs = g_list_append(blockedrpcs, g_strdup("guest-fstrim")); 2730 #endif 2731 2732 blockedrpcs = g_list_append(blockedrpcs, g_strdup("guest-get-devices")); 2733 2734 return blockedrpcs; 2735 } 2736 2737 /* register init/cleanup routines for stateful command groups */ 2738 void ga_command_state_init(GAState *s, GACommandState *cs) 2739 { 2740 #if defined(CONFIG_FSFREEZE) 2741 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup); 2742 #endif 2743 } 2744 2745 #ifdef HAVE_UTMPX 2746 2747 #define QGA_MICRO_SECOND_TO_SECOND 1000000 2748 2749 static double ga_get_login_time(struct utmpx *user_info) 2750 { 2751 double seconds = (double)user_info->ut_tv.tv_sec; 2752 double useconds = (double)user_info->ut_tv.tv_usec; 2753 useconds /= QGA_MICRO_SECOND_TO_SECOND; 2754 return seconds + useconds; 2755 } 2756 2757 GuestUserList *qmp_guest_get_users(Error **errp) 2758 { 2759 GHashTable *cache = NULL; 2760 GuestUserList *head = NULL, **tail = &head; 2761 struct utmpx *user_info = NULL; 2762 gpointer value = NULL; 2763 GuestUser *user = NULL; 2764 double login_time = 0; 2765 2766 cache = g_hash_table_new(g_str_hash, g_str_equal); 2767 setutxent(); 2768 2769 for (;;) { 2770 user_info = getutxent(); 2771 if (user_info == NULL) { 2772 break; 2773 } else if (user_info->ut_type != USER_PROCESS) { 2774 continue; 2775 } else if (g_hash_table_contains(cache, user_info->ut_user)) { 2776 value = g_hash_table_lookup(cache, user_info->ut_user); 2777 user = (GuestUser *)value; 2778 login_time = ga_get_login_time(user_info); 2779 /* We're ensuring the earliest login time to be sent */ 2780 if (login_time < user->login_time) { 2781 user->login_time = login_time; 2782 } 2783 continue; 2784 } 2785 2786 user = g_new0(GuestUser, 1); 2787 user->user = g_strdup(user_info->ut_user); 2788 user->login_time = ga_get_login_time(user_info); 2789 2790 g_hash_table_insert(cache, user->user, user); 2791 2792 QAPI_LIST_APPEND(tail, user); 2793 } 2794 endutxent(); 2795 g_hash_table_destroy(cache); 2796 return head; 2797 } 2798 2799 #else 2800 2801 GuestUserList *qmp_guest_get_users(Error **errp) 2802 { 2803 error_setg(errp, QERR_UNSUPPORTED); 2804 return NULL; 2805 } 2806 2807 #endif 2808 2809 /* Replace escaped special characters with their real values. The replacement 2810 * is done in place -- returned value is in the original string. 2811 */ 2812 static void ga_osrelease_replace_special(gchar *value) 2813 { 2814 gchar *p, *p2, quote; 2815 2816 /* Trim the string at first space or semicolon if it is not enclosed in 2817 * single or double quotes. */ 2818 if ((value[0] != '"') || (value[0] == '\'')) { 2819 p = strchr(value, ' '); 2820 if (p != NULL) { 2821 *p = 0; 2822 } 2823 p = strchr(value, ';'); 2824 if (p != NULL) { 2825 *p = 0; 2826 } 2827 return; 2828 } 2829 2830 quote = value[0]; 2831 p2 = value; 2832 p = value + 1; 2833 while (*p != 0) { 2834 if (*p == '\\') { 2835 p++; 2836 switch (*p) { 2837 case '$': 2838 case '\'': 2839 case '"': 2840 case '\\': 2841 case '`': 2842 break; 2843 default: 2844 /* Keep literal backslash followed by whatever is there */ 2845 p--; 2846 break; 2847 } 2848 } else if (*p == quote) { 2849 *p2 = 0; 2850 break; 2851 } 2852 *(p2++) = *(p++); 2853 } 2854 } 2855 2856 static GKeyFile *ga_parse_osrelease(const char *fname) 2857 { 2858 gchar *content = NULL; 2859 gchar *content2 = NULL; 2860 GError *err = NULL; 2861 GKeyFile *keys = g_key_file_new(); 2862 const char *group = "[os-release]\n"; 2863 2864 if (!g_file_get_contents(fname, &content, NULL, &err)) { 2865 slog("failed to read '%s', error: %s", fname, err->message); 2866 goto fail; 2867 } 2868 2869 if (!g_utf8_validate(content, -1, NULL)) { 2870 slog("file is not utf-8 encoded: %s", fname); 2871 goto fail; 2872 } 2873 content2 = g_strdup_printf("%s%s", group, content); 2874 2875 if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE, 2876 &err)) { 2877 slog("failed to parse file '%s', error: %s", fname, err->message); 2878 goto fail; 2879 } 2880 2881 g_free(content); 2882 g_free(content2); 2883 return keys; 2884 2885 fail: 2886 g_error_free(err); 2887 g_free(content); 2888 g_free(content2); 2889 g_key_file_free(keys); 2890 return NULL; 2891 } 2892 2893 GuestOSInfo *qmp_guest_get_osinfo(Error **errp) 2894 { 2895 GuestOSInfo *info = NULL; 2896 struct utsname kinfo; 2897 GKeyFile *osrelease = NULL; 2898 const char *qga_os_release = g_getenv("QGA_OS_RELEASE"); 2899 2900 info = g_new0(GuestOSInfo, 1); 2901 2902 if (uname(&kinfo) != 0) { 2903 error_setg_errno(errp, errno, "uname failed"); 2904 } else { 2905 info->kernel_version = g_strdup(kinfo.version); 2906 info->kernel_release = g_strdup(kinfo.release); 2907 info->machine = g_strdup(kinfo.machine); 2908 } 2909 2910 if (qga_os_release != NULL) { 2911 osrelease = ga_parse_osrelease(qga_os_release); 2912 } else { 2913 osrelease = ga_parse_osrelease("/etc/os-release"); 2914 if (osrelease == NULL) { 2915 osrelease = ga_parse_osrelease("/usr/lib/os-release"); 2916 } 2917 } 2918 2919 if (osrelease != NULL) { 2920 char *value; 2921 2922 #define GET_FIELD(field, osfield) do { \ 2923 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \ 2924 if (value != NULL) { \ 2925 ga_osrelease_replace_special(value); \ 2926 info->field = value; \ 2927 } \ 2928 } while (0) 2929 GET_FIELD(id, "ID"); 2930 GET_FIELD(name, "NAME"); 2931 GET_FIELD(pretty_name, "PRETTY_NAME"); 2932 GET_FIELD(version, "VERSION"); 2933 GET_FIELD(version_id, "VERSION_ID"); 2934 GET_FIELD(variant, "VARIANT"); 2935 GET_FIELD(variant_id, "VARIANT_ID"); 2936 #undef GET_FIELD 2937 2938 g_key_file_free(osrelease); 2939 } 2940 2941 return info; 2942 } 2943 2944 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp) 2945 { 2946 error_setg(errp, QERR_UNSUPPORTED); 2947 2948 return NULL; 2949 } 2950 2951 #ifndef HOST_NAME_MAX 2952 # ifdef _POSIX_HOST_NAME_MAX 2953 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX 2954 # else 2955 # define HOST_NAME_MAX 255 2956 # endif 2957 #endif 2958 2959 char *qga_get_host_name(Error **errp) 2960 { 2961 long len = -1; 2962 g_autofree char *hostname = NULL; 2963 2964 #ifdef _SC_HOST_NAME_MAX 2965 len = sysconf(_SC_HOST_NAME_MAX); 2966 #endif /* _SC_HOST_NAME_MAX */ 2967 2968 if (len < 0) { 2969 len = HOST_NAME_MAX; 2970 } 2971 2972 /* Unfortunately, gethostname() below does not guarantee a 2973 * NULL terminated string. Therefore, allocate one byte more 2974 * to be sure. */ 2975 hostname = g_new0(char, len + 1); 2976 2977 if (gethostname(hostname, len) < 0) { 2978 error_setg_errno(errp, errno, 2979 "cannot get hostname"); 2980 return NULL; 2981 } 2982 2983 return g_steal_pointer(&hostname); 2984 } 2985