2 * QEMU Guest Agent POSIX-specific command implementations
4 * Copyright IBM Corp. 2011
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.
14 #include "qemu/osdep.h"
15 #include <sys/ioctl.h>
16 #include <sys/utsname.h>
19 #include "qga/guest-agent-core.h"
20 #include "qga-qmp-commands.h"
21 #include "qapi/qmp/qerror.h"
22 #include "qemu/queue.h"
23 #include "qemu/host-utils.h"
24 #include "qemu/sockets.h"
25 #include "qemu/base64.h"
26 #include "qemu/cutils.h"
32 #ifndef CONFIG_HAS_ENVIRON
34 #include <crt_externs.h>
35 #define environ (*_NSGetEnviron())
37 extern char **environ;
41 #if defined(__linux__)
45 #include <arpa/inet.h>
46 #include <sys/socket.h>
50 #define CONFIG_FSFREEZE
57 static void ga_wait_child(pid_t pid, int *status, Error **errp)
64 rpid = waitpid(pid, status, 0);
65 } while (rpid == -1 && errno == EINTR);
68 error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
73 g_assert(rpid == pid);
76 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
78 const char *shutdown_flag;
79 Error *local_err = NULL;
83 slog("guest-shutdown called, mode: %s", mode);
84 if (!has_mode || strcmp(mode, "powerdown") == 0) {
86 } else if (strcmp(mode, "halt") == 0) {
88 } else if (strcmp(mode, "reboot") == 0) {
92 "mode is invalid (valid values are: halt|powerdown|reboot");
98 /* child, start the shutdown */
100 reopen_fd_to_null(0);
101 reopen_fd_to_null(1);
102 reopen_fd_to_null(2);
104 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
105 "hypervisor initiated shutdown", (char*)NULL, environ);
107 } else if (pid < 0) {
108 error_setg_errno(errp, errno, "failed to create child process");
112 ga_wait_child(pid, &status, &local_err);
114 error_propagate(errp, local_err);
118 if (!WIFEXITED(status)) {
119 error_setg(errp, "child process has terminated abnormally");
123 if (WEXITSTATUS(status)) {
124 error_setg(errp, "child process has failed to shutdown");
131 int64_t qmp_guest_get_time(Error **errp)
136 ret = qemu_gettimeofday(&tq);
138 error_setg_errno(errp, errno, "Failed to get time");
142 return tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
145 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
150 Error *local_err = NULL;
153 /* If user has passed a time, validate and set it. */
157 /* year-2038 will overflow in case time_t is 32bit */
158 if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
159 error_setg(errp, "Time %" PRId64 " is too large", time_ns);
163 tv.tv_sec = time_ns / 1000000000;
164 tv.tv_usec = (time_ns % 1000000000) / 1000;
165 g_date_set_time_t(&date, tv.tv_sec);
166 if (date.year < 1970 || date.year >= 2070) {
167 error_setg_errno(errp, errno, "Invalid time");
171 ret = settimeofday(&tv, NULL);
173 error_setg_errno(errp, errno, "Failed to set time to guest");
178 /* Now, if user has passed a time to set and the system time is set, we
179 * just need to synchronize the hardware clock. However, if no time was
180 * passed, user is requesting the opposite: set the system time from the
181 * hardware clock (RTC). */
185 reopen_fd_to_null(0);
186 reopen_fd_to_null(1);
187 reopen_fd_to_null(2);
189 /* Use '/sbin/hwclock -w' to set RTC from the system time,
190 * or '/sbin/hwclock -s' to set the system time from RTC. */
191 execle("/sbin/hwclock", "hwclock", has_time ? "-w" : "-s",
194 } else if (pid < 0) {
195 error_setg_errno(errp, errno, "failed to create child process");
199 ga_wait_child(pid, &status, &local_err);
201 error_propagate(errp, local_err);
205 if (!WIFEXITED(status)) {
206 error_setg(errp, "child process has terminated abnormally");
210 if (WEXITSTATUS(status)) {
211 error_setg(errp, "hwclock failed to set hardware clock to system time");
222 typedef struct GuestFileHandle {
226 QTAILQ_ENTRY(GuestFileHandle) next;
230 QTAILQ_HEAD(, GuestFileHandle) filehandles;
231 } guest_file_state = {
232 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
235 static int64_t guest_file_handle_add(FILE *fh, Error **errp)
237 GuestFileHandle *gfh;
240 handle = ga_get_fd_handle(ga_state, errp);
245 gfh = g_new0(GuestFileHandle, 1);
248 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
253 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
255 GuestFileHandle *gfh;
257 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
264 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
268 typedef const char * const ccpc;
274 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
275 static const struct {
278 } guest_file_open_modes[] = {
279 { (ccpc[]){ "r", NULL }, O_RDONLY },
280 { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
281 { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
282 { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
283 { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
284 { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
285 { (ccpc[]){ "r+", NULL }, O_RDWR },
286 { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
287 { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
288 { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
289 { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
290 { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
294 find_open_flag(const char *mode_str, Error **errp)
298 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
301 form = guest_file_open_modes[mode].forms;
302 while (*form != NULL && strcmp(*form, mode_str) != 0) {
310 if (mode == ARRAY_SIZE(guest_file_open_modes)) {
311 error_setg(errp, "invalid file open mode '%s'", mode_str);
314 return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
317 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
318 S_IRGRP | S_IWGRP | \
322 safe_open_or_create(const char *path, const char *mode, Error **errp)
324 Error *local_err = NULL;
327 oflag = find_open_flag(mode, &local_err);
328 if (local_err == NULL) {
331 /* If the caller wants / allows creation of a new file, we implement it
332 * with a two step process: open() + (open() / fchmod()).
334 * First we insist on creating the file exclusively as a new file. If
335 * that succeeds, we're free to set any file-mode bits on it. (The
336 * motivation is that we want to set those file-mode bits independently
337 * of the current umask.)
339 * If the exclusive creation fails because the file already exists
340 * (EEXIST is not possible for any other reason), we just attempt to
341 * open the file, but in this case we won't be allowed to change the
342 * file-mode bits on the preexistent file.
344 * The pathname should never disappear between the two open()s in
345 * practice. If it happens, then someone very likely tried to race us.
346 * In this case just go ahead and report the ENOENT from the second
347 * open() to the caller.
349 * If the caller wants to open a preexistent file, then the first
350 * open() is decisive and its third argument is ignored, and the second
351 * open() and the fchmod() are never called.
353 fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
354 if (fd == -1 && errno == EEXIST) {
355 oflag &= ~(unsigned)O_CREAT;
356 fd = open(path, oflag);
360 error_setg_errno(&local_err, errno, "failed to open file '%s' "
361 "(mode: '%s')", path, mode);
363 qemu_set_cloexec(fd);
365 if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
366 error_setg_errno(&local_err, errno, "failed to set permission "
367 "0%03o on new file '%s' (mode: '%s')",
368 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
372 f = fdopen(fd, mode);
374 error_setg_errno(&local_err, errno, "failed to associate "
375 "stdio stream with file descriptor %d, "
376 "file '%s' (mode: '%s')", fd, path, mode);
383 if (oflag & O_CREAT) {
389 error_propagate(errp, local_err);
393 int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
397 Error *local_err = NULL;
403 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
404 fh = safe_open_or_create(path, mode, &local_err);
405 if (local_err != NULL) {
406 error_propagate(errp, local_err);
410 /* set fd non-blocking to avoid common use cases (like reading from a
411 * named pipe) from hanging the agent
413 qemu_set_nonblock(fileno(fh));
415 handle = guest_file_handle_add(fh, errp);
421 slog("guest-file-open, handle: %" PRId64, handle);
425 void qmp_guest_file_close(int64_t handle, Error **errp)
427 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
430 slog("guest-file-close called, handle: %" PRId64, handle);
435 ret = fclose(gfh->fh);
437 error_setg_errno(errp, errno, "failed to close handle");
441 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
445 struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
446 int64_t count, Error **errp)
448 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
449 GuestFileRead *read_data = NULL;
459 count = QGA_READ_COUNT_DEFAULT;
460 } else if (count < 0) {
461 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
468 /* explicitly flush when switching from writing to reading */
469 if (gfh->state == RW_STATE_WRITING) {
470 int ret = fflush(fh);
472 error_setg_errno(errp, errno, "failed to flush file");
475 gfh->state = RW_STATE_NEW;
478 buf = g_malloc0(count+1);
479 read_count = fread(buf, 1, count, fh);
481 error_setg_errno(errp, errno, "failed to read file");
482 slog("guest-file-read failed, handle: %" PRId64, handle);
485 read_data = g_new0(GuestFileRead, 1);
486 read_data->count = read_count;
487 read_data->eof = feof(fh);
489 read_data->buf_b64 = g_base64_encode(buf, read_count);
491 gfh->state = RW_STATE_READING;
499 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
500 bool has_count, int64_t count,
503 GuestFileWrite *write_data = NULL;
507 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
516 if (gfh->state == RW_STATE_READING) {
517 int ret = fseek(fh, 0, SEEK_CUR);
519 error_setg_errno(errp, errno, "failed to seek file");
522 gfh->state = RW_STATE_NEW;
525 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
532 } else if (count < 0 || count > buf_len) {
533 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
539 write_count = fwrite(buf, 1, count, fh);
541 error_setg_errno(errp, errno, "failed to write to file");
542 slog("guest-file-write failed, handle: %" PRId64, handle);
544 write_data = g_new0(GuestFileWrite, 1);
545 write_data->count = write_count;
546 write_data->eof = feof(fh);
547 gfh->state = RW_STATE_WRITING;
555 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
556 GuestFileWhence *whence_code,
559 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
560 GuestFileSeek *seek_data = NULL;
570 /* We stupidly exposed 'whence':'int' in our qapi */
571 whence = ga_parse_whence(whence_code, &err);
573 error_propagate(errp, err);
578 ret = fseek(fh, offset, whence);
580 error_setg_errno(errp, errno, "failed to seek file");
581 if (errno == ESPIPE) {
582 /* file is non-seekable, stdio shouldn't be buffering anyways */
583 gfh->state = RW_STATE_NEW;
586 seek_data = g_new0(GuestFileSeek, 1);
587 seek_data->position = ftell(fh);
588 seek_data->eof = feof(fh);
589 gfh->state = RW_STATE_NEW;
596 void qmp_guest_file_flush(int64_t handle, Error **errp)
598 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
609 error_setg_errno(errp, errno, "failed to flush file");
611 gfh->state = RW_STATE_NEW;
615 /* linux-specific implementations. avoid this if at all possible. */
616 #if defined(__linux__)
618 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
619 typedef struct FsMount {
622 unsigned int devmajor, devminor;
623 QTAILQ_ENTRY(FsMount) next;
626 typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
628 static void free_fs_mount_list(FsMountList *mounts)
630 FsMount *mount, *temp;
636 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
637 QTAILQ_REMOVE(mounts, mount, next);
638 g_free(mount->dirname);
639 g_free(mount->devtype);
644 static int dev_major_minor(const char *devpath,
645 unsigned int *devmajor, unsigned int *devminor)
652 if (stat(devpath, &st) < 0) {
653 slog("failed to stat device file '%s': %s", devpath, strerror(errno));
656 if (S_ISDIR(st.st_mode)) {
657 /* It is bind mount */
660 if (S_ISBLK(st.st_mode)) {
661 *devmajor = major(st.st_rdev);
662 *devminor = minor(st.st_rdev);
669 * Walk the mount table and build a list of local file systems
671 static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
675 char const *mtab = "/proc/self/mounts";
677 unsigned int devmajor, devminor;
679 fp = setmntent(mtab, "r");
681 error_setg(errp, "failed to open mtab file: '%s'", mtab);
685 while ((ment = getmntent(fp))) {
687 * An entry which device name doesn't start with a '/' is
688 * either a dummy file system or a network file system.
689 * Add special handling for smbfs and cifs as is done by
692 if ((ment->mnt_fsname[0] != '/') ||
693 (strcmp(ment->mnt_type, "smbfs") == 0) ||
694 (strcmp(ment->mnt_type, "cifs") == 0)) {
697 if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
698 /* Skip bind mounts */
702 mount = g_new0(FsMount, 1);
703 mount->dirname = g_strdup(ment->mnt_dir);
704 mount->devtype = g_strdup(ment->mnt_type);
705 mount->devmajor = devmajor;
706 mount->devminor = devminor;
708 QTAILQ_INSERT_TAIL(mounts, mount, next);
714 static void decode_mntname(char *name, int len)
717 for (i = 0; i <= len; i++) {
718 if (name[i] != '\\') {
720 } else if (name[i + 1] == '\\') {
723 } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
724 name[i + 2] >= '0' && name[i + 2] <= '7' &&
725 name[i + 3] >= '0' && name[i + 3] <= '7') {
726 name[j++] = (name[i + 1] - '0') * 64 +
727 (name[i + 2] - '0') * 8 +
736 static void build_fs_mount_list(FsMountList *mounts, Error **errp)
739 char const *mountinfo = "/proc/self/mountinfo";
741 char *line = NULL, *dash;
744 unsigned int devmajor, devminor;
745 int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
747 fp = fopen(mountinfo, "r");
749 build_fs_mount_list_from_mtab(mounts, errp);
753 while (getline(&line, &n, fp) != -1) {
754 ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
755 &devmajor, &devminor, &dir_s, &dir_e, &check);
759 dash = strstr(line + dir_e, " - ");
763 ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
764 &type_s, &type_e, &dev_s, &dev_e, &check);
771 decode_mntname(line + dir_s, dir_e - dir_s);
772 decode_mntname(dash + dev_s, dev_e - dev_s);
774 /* btrfs reports major number = 0 */
775 if (strcmp("btrfs", dash + type_s) != 0 ||
776 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
781 mount = g_new0(FsMount, 1);
782 mount->dirname = g_strdup(line + dir_s);
783 mount->devtype = g_strdup(dash + type_s);
784 mount->devmajor = devmajor;
785 mount->devminor = devminor;
787 QTAILQ_INSERT_TAIL(mounts, mount, next);
795 #if defined(CONFIG_FSFREEZE)
797 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
805 path = g_strndup(syspath, pathlen);
806 dpath = g_strdup_printf("%s/driver", path);
807 len = readlink(dpath, buf, sizeof(buf) - 1);
810 driver = g_strdup(basename(buf));
817 static int compare_uint(const void *_a, const void *_b)
819 unsigned int a = *(unsigned int *)_a;
820 unsigned int b = *(unsigned int *)_b;
822 return a < b ? -1 : a > b ? 1 : 0;
825 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
826 static int build_hosts(char const *syspath, char const *host, bool ata,
827 unsigned int *hosts, int hosts_max, Error **errp)
831 struct dirent *entry;
834 path = g_strndup(syspath, host - syspath);
837 error_setg_errno(errp, errno, "opendir(\"%s\")", path);
842 while (i < hosts_max) {
843 entry = readdir(dir);
847 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
849 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
854 qsort(hosts, i, sizeof(hosts[0]), compare_uint);
861 /* Store disk device info specified by @sysfs into @fs */
862 static void build_guest_fsinfo_for_real_device(char const *syspath,
863 GuestFilesystemInfo *fs,
866 unsigned int pci[4], host, hosts[8], tgt[3];
867 int i, nhosts = 0, pcilen;
868 GuestDiskAddress *disk;
869 GuestPCIAddress *pciaddr;
870 GuestDiskAddressList *list = NULL;
871 bool has_ata = false, has_host = false, has_tgt = false;
872 char *p, *q, *driver = NULL;
874 p = strstr(syspath, "/devices/pci");
875 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
876 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
877 g_debug("only pci device is supported: sysfs path \"%s\"", syspath);
881 driver = get_pci_driver(syspath, (p + 12 + pcilen) - syspath, errp);
886 p = strstr(syspath, "/target");
887 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
888 tgt, tgt + 1, tgt + 2) == 3) {
892 p = strstr(syspath, "/ata");
897 p = strstr(syspath, "/host");
900 if (p && sscanf(q, "%u", &host) == 1) {
902 nhosts = build_hosts(syspath, p, has_ata, hosts,
903 sizeof(hosts) / sizeof(hosts[0]), errp);
909 pciaddr = g_malloc0(sizeof(*pciaddr));
910 pciaddr->domain = pci[0];
911 pciaddr->bus = pci[1];
912 pciaddr->slot = pci[2];
913 pciaddr->function = pci[3];
915 disk = g_malloc0(sizeof(*disk));
916 disk->pci_controller = pciaddr;
918 list = g_malloc0(sizeof(*list));
921 if (strcmp(driver, "ata_piix") == 0) {
922 /* a host per ide bus, target*:0:<unit>:0 */
923 if (!has_host || !has_tgt) {
924 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
927 for (i = 0; i < nhosts; i++) {
928 if (host == hosts[i]) {
929 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
936 g_debug("no host for '%s' (driver '%s')", syspath, driver);
939 } else if (strcmp(driver, "sym53c8xx") == 0) {
940 /* scsi(LSI Logic): target*:0:<unit>:0 */
942 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
945 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
947 } else if (strcmp(driver, "virtio-pci") == 0) {
949 /* virtio-scsi: target*:0:0:<unit> */
950 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
953 /* virtio-blk: 1 disk per 1 device */
954 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
956 } else if (strcmp(driver, "ahci") == 0) {
957 /* ahci: 1 host per 1 unit */
958 if (!has_host || !has_tgt) {
959 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
962 for (i = 0; i < nhosts; i++) {
963 if (host == hosts[i]) {
965 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
970 g_debug("no host for '%s' (driver '%s')", syspath, driver);
974 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
978 list->next = fs->disk;
985 qapi_free_GuestDiskAddressList(list);
990 static void build_guest_fsinfo_for_device(char const *devpath,
991 GuestFilesystemInfo *fs,
994 /* Store a list of slave devices of virtual volume specified by @syspath into
996 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
997 GuestFilesystemInfo *fs,
1002 struct dirent *entry;
1004 dirpath = g_strdup_printf("%s/slaves", syspath);
1005 dir = opendir(dirpath);
1007 if (errno != ENOENT) {
1008 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
1016 entry = readdir(dir);
1017 if (entry == NULL) {
1019 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1024 if (entry->d_type == DT_LNK) {
1027 g_debug(" slave device '%s'", entry->d_name);
1028 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1029 build_guest_fsinfo_for_device(path, fs, errp);
1042 /* Dispatch to functions for virtual/real device */
1043 static void build_guest_fsinfo_for_device(char const *devpath,
1044 GuestFilesystemInfo *fs,
1047 char *syspath = realpath(devpath, NULL);
1050 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1055 fs->name = g_strdup(basename(syspath));
1058 g_debug(" parse sysfs path '%s'", syspath);
1060 if (strstr(syspath, "/devices/virtual/block/")) {
1061 build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1063 build_guest_fsinfo_for_real_device(syspath, fs, errp);
1069 /* Return a list of the disk device(s)' info which @mount lies on */
1070 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1073 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1074 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1075 mount->devmajor, mount->devminor);
1077 fs->mountpoint = g_strdup(mount->dirname);
1078 fs->type = g_strdup(mount->devtype);
1079 build_guest_fsinfo_for_device(devpath, fs, errp);
1085 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1088 struct FsMount *mount;
1089 GuestFilesystemInfoList *new, *ret = NULL;
1090 Error *local_err = NULL;
1092 QTAILQ_INIT(&mounts);
1093 build_fs_mount_list(&mounts, &local_err);
1095 error_propagate(errp, local_err);
1099 QTAILQ_FOREACH(mount, &mounts, next) {
1100 g_debug("Building guest fsinfo for '%s'", mount->dirname);
1102 new = g_malloc0(sizeof(*ret));
1103 new->value = build_guest_fsinfo(mount, &local_err);
1107 error_propagate(errp, local_err);
1108 qapi_free_GuestFilesystemInfoList(ret);
1114 free_fs_mount_list(&mounts);
1120 FSFREEZE_HOOK_THAW = 0,
1121 FSFREEZE_HOOK_FREEZE,
1124 static const char *fsfreeze_hook_arg_string[] = {
1129 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
1134 const char *arg_str = fsfreeze_hook_arg_string[arg];
1135 Error *local_err = NULL;
1137 hook = ga_fsfreeze_hook(ga_state);
1141 if (access(hook, X_OK) != 0) {
1142 error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
1146 slog("executing fsfreeze hook with arg '%s'", arg_str);
1150 reopen_fd_to_null(0);
1151 reopen_fd_to_null(1);
1152 reopen_fd_to_null(2);
1154 execle(hook, hook, arg_str, NULL, environ);
1155 _exit(EXIT_FAILURE);
1156 } else if (pid < 0) {
1157 error_setg_errno(errp, errno, "failed to create child process");
1161 ga_wait_child(pid, &status, &local_err);
1163 error_propagate(errp, local_err);
1167 if (!WIFEXITED(status)) {
1168 error_setg(errp, "fsfreeze hook has terminated abnormally");
1172 status = WEXITSTATUS(status);
1174 error_setg(errp, "fsfreeze hook has failed with status %d", status);
1180 * Return status of freeze/thaw
1182 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1184 if (ga_is_frozen(ga_state)) {
1185 return GUEST_FSFREEZE_STATUS_FROZEN;
1188 return GUEST_FSFREEZE_STATUS_THAWED;
1191 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1193 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1197 * Walk list of mounted file systems in the guest, and freeze the ones which
1198 * are real local file systems.
1200 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1201 strList *mountpoints,
1207 struct FsMount *mount;
1208 Error *local_err = NULL;
1211 slog("guest-fsfreeze called");
1213 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
1215 error_propagate(errp, local_err);
1219 QTAILQ_INIT(&mounts);
1220 build_fs_mount_list(&mounts, &local_err);
1222 error_propagate(errp, local_err);
1226 /* cannot risk guest agent blocking itself on a write in this state */
1227 ga_set_frozen(ga_state);
1229 QTAILQ_FOREACH_REVERSE(mount, &mounts, FsMountList, next) {
1230 /* To issue fsfreeze in the reverse order of mounts, check if the
1231 * mount is listed in the list here */
1232 if (has_mountpoints) {
1233 for (list = mountpoints; list; list = list->next) {
1234 if (strcmp(list->value, mount->dirname) == 0) {
1243 fd = qemu_open(mount->dirname, O_RDONLY);
1245 error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
1249 /* we try to cull filesystems we know won't work in advance, but other
1250 * filesystems may not implement fsfreeze for less obvious reasons.
1251 * these will report EOPNOTSUPP. we simply ignore these when tallying
1252 * the number of frozen filesystems.
1253 * if a filesystem is mounted more than once (aka bind mount) a
1254 * consecutive attempt to freeze an already frozen filesystem will
1257 * any other error means a failure to freeze a filesystem we
1258 * expect to be freezable, so return an error in those cases
1259 * and return system to thawed state.
1261 ret = ioctl(fd, FIFREEZE);
1263 if (errno != EOPNOTSUPP && errno != EBUSY) {
1264 error_setg_errno(errp, errno, "failed to freeze %s",
1275 free_fs_mount_list(&mounts);
1279 free_fs_mount_list(&mounts);
1280 qmp_guest_fsfreeze_thaw(NULL);
1285 * Walk list of frozen file systems in the guest, and thaw them.
1287 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1292 int fd, i = 0, logged;
1293 Error *local_err = NULL;
1295 QTAILQ_INIT(&mounts);
1296 build_fs_mount_list(&mounts, &local_err);
1298 error_propagate(errp, local_err);
1302 QTAILQ_FOREACH(mount, &mounts, next) {
1304 fd = qemu_open(mount->dirname, O_RDONLY);
1308 /* we have no way of knowing whether a filesystem was actually unfrozen
1309 * as a result of a successful call to FITHAW, only that if an error
1310 * was returned the filesystem was *not* unfrozen by that particular
1313 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1314 * to unfreeze, continuing issuing FITHAW until an error is returned,
1315 * in which case either the filesystem is in an unfreezable state, or,
1316 * more likely, it was thawed previously (and remains so afterward).
1318 * also, since the most recent successful call is the one that did
1319 * the actual unfreeze, we can use this to provide an accurate count
1320 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1321 * may * be useful for determining whether a filesystem was unfrozen
1322 * during the freeze/thaw phase by a process other than qemu-ga.
1325 ret = ioctl(fd, FITHAW);
1326 if (ret == 0 && !logged) {
1334 ga_unset_frozen(ga_state);
1335 free_fs_mount_list(&mounts);
1337 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
1342 static void guest_fsfreeze_cleanup(void)
1346 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1347 qmp_guest_fsfreeze_thaw(&err);
1349 slog("failed to clean up frozen filesystems: %s",
1350 error_get_pretty(err));
1355 #endif /* CONFIG_FSFREEZE */
1357 #if defined(CONFIG_FSTRIM)
1359 * Walk list of mounted file systems in the guest, and trim them.
1361 GuestFilesystemTrimResponse *
1362 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1364 GuestFilesystemTrimResponse *response;
1365 GuestFilesystemTrimResultList *list;
1366 GuestFilesystemTrimResult *result;
1369 struct FsMount *mount;
1371 Error *local_err = NULL;
1372 struct fstrim_range r;
1374 slog("guest-fstrim called");
1376 QTAILQ_INIT(&mounts);
1377 build_fs_mount_list(&mounts, &local_err);
1379 error_propagate(errp, local_err);
1383 response = g_malloc0(sizeof(*response));
1385 QTAILQ_FOREACH(mount, &mounts, next) {
1386 result = g_malloc0(sizeof(*result));
1387 result->path = g_strdup(mount->dirname);
1389 list = g_malloc0(sizeof(*list));
1390 list->value = result;
1391 list->next = response->paths;
1392 response->paths = list;
1394 fd = qemu_open(mount->dirname, O_RDONLY);
1396 result->error = g_strdup_printf("failed to open: %s",
1398 result->has_error = true;
1402 /* We try to cull filesystems we know won't work in advance, but other
1403 * filesystems may not implement fstrim for less obvious reasons.
1404 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1405 * will be reported (e.g. CD-ROMs).
1406 * Any other error means an unexpected error.
1410 r.minlen = has_minimum ? minimum : 0;
1411 ret = ioctl(fd, FITRIM, &r);
1413 result->has_error = true;
1414 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1415 result->error = g_strdup("trim not supported");
1417 result->error = g_strdup_printf("failed to trim: %s",
1424 result->has_minimum = true;
1425 result->minimum = r.minlen;
1426 result->has_trimmed = true;
1427 result->trimmed = r.len;
1431 free_fs_mount_list(&mounts);
1434 #endif /* CONFIG_FSTRIM */
1437 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1438 #define SUSPEND_SUPPORTED 0
1439 #define SUSPEND_NOT_SUPPORTED 1
1441 static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,
1442 const char *sysfile_str, Error **errp)
1444 Error *local_err = NULL;
1449 pmutils_path = g_find_program_in_path(pmutils_bin);
1453 char buf[32]; /* hopefully big enough */
1458 reopen_fd_to_null(0);
1459 reopen_fd_to_null(1);
1460 reopen_fd_to_null(2);
1463 execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
1467 * If we get here either pm-utils is not installed or execle() has
1468 * failed. Let's try the manual method if the caller wants it.
1472 _exit(SUSPEND_NOT_SUPPORTED);
1475 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
1477 _exit(SUSPEND_NOT_SUPPORTED);
1480 ret = read(fd, buf, sizeof(buf)-1);
1482 _exit(SUSPEND_NOT_SUPPORTED);
1486 if (strstr(buf, sysfile_str)) {
1487 _exit(SUSPEND_SUPPORTED);
1490 _exit(SUSPEND_NOT_SUPPORTED);
1491 } else if (pid < 0) {
1492 error_setg_errno(errp, errno, "failed to create child process");
1496 ga_wait_child(pid, &status, &local_err);
1498 error_propagate(errp, local_err);
1502 if (!WIFEXITED(status)) {
1503 error_setg(errp, "child process has terminated abnormally");
1507 switch (WEXITSTATUS(status)) {
1508 case SUSPEND_SUPPORTED:
1510 case SUSPEND_NOT_SUPPORTED:
1512 "the requested suspend mode is not supported by the guest");
1516 "the helper program '%s' returned an unexpected exit status"
1517 " code (%d)", pmutils_path, WEXITSTATUS(status));
1522 g_free(pmutils_path);
1525 static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
1528 Error *local_err = NULL;
1533 pmutils_path = g_find_program_in_path(pmutils_bin);
1541 reopen_fd_to_null(0);
1542 reopen_fd_to_null(1);
1543 reopen_fd_to_null(2);
1546 execle(pmutils_path, pmutils_bin, NULL, environ);
1550 * If we get here either pm-utils is not installed or execle() has
1551 * failed. Let's try the manual method if the caller wants it.
1555 _exit(EXIT_FAILURE);
1558 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
1560 _exit(EXIT_FAILURE);
1563 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
1564 _exit(EXIT_FAILURE);
1567 _exit(EXIT_SUCCESS);
1568 } else if (pid < 0) {
1569 error_setg_errno(errp, errno, "failed to create child process");
1573 ga_wait_child(pid, &status, &local_err);
1575 error_propagate(errp, local_err);
1579 if (!WIFEXITED(status)) {
1580 error_setg(errp, "child process has terminated abnormally");
1584 if (WEXITSTATUS(status)) {
1585 error_setg(errp, "child process has failed to suspend");
1590 g_free(pmutils_path);
1593 void qmp_guest_suspend_disk(Error **errp)
1595 Error *local_err = NULL;
1597 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err);
1599 error_propagate(errp, local_err);
1603 guest_suspend("pm-hibernate", "disk", errp);
1606 void qmp_guest_suspend_ram(Error **errp)
1608 Error *local_err = NULL;
1610 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err);
1612 error_propagate(errp, local_err);
1616 guest_suspend("pm-suspend", "mem", errp);
1619 void qmp_guest_suspend_hybrid(Error **errp)
1621 Error *local_err = NULL;
1623 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL,
1626 error_propagate(errp, local_err);
1630 guest_suspend("pm-suspend-hybrid", NULL, errp);
1633 static GuestNetworkInterfaceList *
1634 guest_find_interface(GuestNetworkInterfaceList *head,
1637 for (; head; head = head->next) {
1638 if (strcmp(head->value->name, name) == 0) {
1646 static int guest_get_network_stats(const char *name,
1647 GuestNetworkInterfaceStat *stats)
1650 char const *devinfo = "/proc/net/dev";
1652 char *line = NULL, *colon;
1654 fp = fopen(devinfo, "r");
1658 name_len = strlen(name);
1659 while (getline(&line, &n, fp) != -1) {
1662 long long rx_packets;
1664 long long rx_dropped;
1666 long long tx_packets;
1668 long long tx_dropped;
1670 trim_line = g_strchug(line);
1671 if (trim_line[0] == '\0') {
1674 colon = strchr(trim_line, ':');
1678 if (colon - name_len == trim_line &&
1679 strncmp(trim_line, name, name_len) == 0) {
1680 if (sscanf(colon + 1,
1681 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
1682 &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
1683 &dummy, &dummy, &dummy, &dummy,
1684 &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
1685 &dummy, &dummy, &dummy, &dummy) != 16) {
1688 stats->rx_bytes = rx_bytes;
1689 stats->rx_packets = rx_packets;
1690 stats->rx_errs = rx_errs;
1691 stats->rx_dropped = rx_dropped;
1692 stats->tx_bytes = tx_bytes;
1693 stats->tx_packets = tx_packets;
1694 stats->tx_errs = tx_errs;
1695 stats->tx_dropped = tx_dropped;
1703 g_debug("/proc/net/dev: Interface '%s' not found", name);
1708 * Build information about guest interfaces
1710 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1712 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1713 struct ifaddrs *ifap, *ifa;
1715 if (getifaddrs(&ifap) < 0) {
1716 error_setg_errno(errp, errno, "getifaddrs failed");
1720 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1721 GuestNetworkInterfaceList *info;
1722 GuestIpAddressList **address_list = NULL, *address_item = NULL;
1723 GuestNetworkInterfaceStat *interface_stat = NULL;
1724 char addr4[INET_ADDRSTRLEN];
1725 char addr6[INET6_ADDRSTRLEN];
1728 unsigned char *mac_addr;
1731 g_debug("Processing %s interface", ifa->ifa_name);
1733 info = guest_find_interface(head, ifa->ifa_name);
1736 info = g_malloc0(sizeof(*info));
1737 info->value = g_malloc0(sizeof(*info->value));
1738 info->value->name = g_strdup(ifa->ifa_name);
1741 head = cur_item = info;
1743 cur_item->next = info;
1748 if (!info->value->has_hardware_address &&
1749 ifa->ifa_flags & SIOCGIFHWADDR) {
1750 /* we haven't obtained HW address yet */
1751 sock = socket(PF_INET, SOCK_STREAM, 0);
1753 error_setg_errno(errp, errno, "failed to create socket");
1757 memset(&ifr, 0, sizeof(ifr));
1758 pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
1759 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
1760 error_setg_errno(errp, errno,
1761 "failed to get MAC address of %s",
1768 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
1770 info->value->hardware_address =
1771 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1772 (int) mac_addr[0], (int) mac_addr[1],
1773 (int) mac_addr[2], (int) mac_addr[3],
1774 (int) mac_addr[4], (int) mac_addr[5]);
1776 info->value->has_hardware_address = true;
1779 if (ifa->ifa_addr &&
1780 ifa->ifa_addr->sa_family == AF_INET) {
1781 /* interface with IPv4 address */
1782 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1783 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
1784 error_setg_errno(errp, errno, "inet_ntop failed");
1788 address_item = g_malloc0(sizeof(*address_item));
1789 address_item->value = g_malloc0(sizeof(*address_item->value));
1790 address_item->value->ip_address = g_strdup(addr4);
1791 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1793 if (ifa->ifa_netmask) {
1794 /* Count the number of set bits in netmask.
1795 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1796 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
1797 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
1799 } else if (ifa->ifa_addr &&
1800 ifa->ifa_addr->sa_family == AF_INET6) {
1801 /* interface with IPv6 address */
1802 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
1803 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
1804 error_setg_errno(errp, errno, "inet_ntop failed");
1808 address_item = g_malloc0(sizeof(*address_item));
1809 address_item->value = g_malloc0(sizeof(*address_item->value));
1810 address_item->value->ip_address = g_strdup(addr6);
1811 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1813 if (ifa->ifa_netmask) {
1814 /* Count the number of set bits in netmask.
1815 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1816 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
1817 address_item->value->prefix =
1818 ctpop32(((uint32_t *) p)[0]) +
1819 ctpop32(((uint32_t *) p)[1]) +
1820 ctpop32(((uint32_t *) p)[2]) +
1821 ctpop32(((uint32_t *) p)[3]);
1825 if (!address_item) {
1829 address_list = &info->value->ip_addresses;
1831 while (*address_list && (*address_list)->next) {
1832 address_list = &(*address_list)->next;
1835 if (!*address_list) {
1836 *address_list = address_item;
1838 (*address_list)->next = address_item;
1841 info->value->has_ip_addresses = true;
1843 if (!info->value->has_statistics) {
1844 interface_stat = g_malloc0(sizeof(*interface_stat));
1845 if (guest_get_network_stats(info->value->name,
1846 interface_stat) == -1) {
1847 info->value->has_statistics = false;
1848 g_free(interface_stat);
1850 info->value->statistics = interface_stat;
1851 info->value->has_statistics = true;
1861 qapi_free_GuestNetworkInterfaceList(head);
1865 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1867 static long sysconf_exact(int name, const char *name_str, Error **errp)
1872 ret = sysconf(name);
1875 error_setg(errp, "sysconf(%s): value indefinite", name_str);
1877 error_setg_errno(errp, errno, "sysconf(%s)", name_str);
1883 /* Transfer online/offline status between @vcpu and the guest system.
1885 * On input either @errp or *@errp must be NULL.
1887 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1888 * - R: vcpu->logical_id
1890 * - W: vcpu->can_offline
1892 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1893 * - R: vcpu->logical_id
1896 * Written members remain unmodified on error.
1898 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
1904 dirpath = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
1906 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
1908 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
1910 static const char fn[] = "online";
1914 fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
1916 if (errno != ENOENT) {
1917 error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
1918 } else if (sys2vcpu) {
1919 vcpu->online = true;
1920 vcpu->can_offline = false;
1921 } else if (!vcpu->online) {
1922 error_setg(errp, "logical processor #%" PRId64 " can't be "
1923 "offlined", vcpu->logical_id);
1924 } /* otherwise pretend successful re-onlining */
1926 unsigned char status;
1928 res = pread(fd, &status, 1, 0);
1930 error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
1931 } else if (res == 0) {
1932 error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
1934 } else if (sys2vcpu) {
1935 vcpu->online = (status != '0');
1936 vcpu->can_offline = true;
1937 } else if (vcpu->online != (status != '0')) {
1938 status = '0' + vcpu->online;
1939 if (pwrite(fd, &status, 1, 0) == -1) {
1940 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
1943 } /* otherwise pretend successful re-(on|off)-lining */
1956 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1959 GuestLogicalProcessorList *head, **link;
1961 Error *local_err = NULL;
1966 sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);
1968 while (local_err == NULL && current < sc_max) {
1969 GuestLogicalProcessor *vcpu;
1970 GuestLogicalProcessorList *entry;
1972 vcpu = g_malloc0(sizeof *vcpu);
1973 vcpu->logical_id = current++;
1974 vcpu->has_can_offline = true; /* lolspeak ftw */
1975 transfer_vcpu(vcpu, true, &local_err);
1977 entry = g_malloc0(sizeof *entry);
1978 entry->value = vcpu;
1981 link = &entry->next;
1984 if (local_err == NULL) {
1985 /* there's no guest with zero VCPUs */
1986 g_assert(head != NULL);
1990 qapi_free_GuestLogicalProcessorList(head);
1991 error_propagate(errp, local_err);
1995 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1998 Error *local_err = NULL;
2001 while (vcpus != NULL) {
2002 transfer_vcpu(vcpus->value, false, &local_err);
2003 if (local_err != NULL) {
2007 vcpus = vcpus->next;
2010 if (local_err != NULL) {
2011 if (processed == 0) {
2012 error_propagate(errp, local_err);
2014 error_free(local_err);
2021 void qmp_guest_set_user_password(const char *username,
2022 const char *password,
2026 Error *local_err = NULL;
2027 char *passwd_path = NULL;
2030 int datafd[2] = { -1, -1 };
2031 char *rawpasswddata = NULL;
2032 size_t rawpasswdlen;
2033 char *chpasswddata = NULL;
2036 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
2037 if (!rawpasswddata) {
2040 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
2041 rawpasswddata[rawpasswdlen] = '\0';
2043 if (strchr(rawpasswddata, '\n')) {
2044 error_setg(errp, "forbidden characters in raw password");
2048 if (strchr(username, '\n') ||
2049 strchr(username, ':')) {
2050 error_setg(errp, "forbidden characters in username");
2054 chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
2055 chpasswdlen = strlen(chpasswddata);
2057 passwd_path = g_find_program_in_path("chpasswd");
2060 error_setg(errp, "cannot find 'passwd' program in PATH");
2064 if (pipe(datafd) < 0) {
2065 error_setg(errp, "cannot create pipe FDs");
2075 reopen_fd_to_null(1);
2076 reopen_fd_to_null(2);
2079 execle(passwd_path, "chpasswd", "-e", NULL, environ);
2081 execle(passwd_path, "chpasswd", NULL, environ);
2083 _exit(EXIT_FAILURE);
2084 } else if (pid < 0) {
2085 error_setg_errno(errp, errno, "failed to create child process");
2091 if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2092 error_setg_errno(errp, errno, "cannot write new account password");
2098 ga_wait_child(pid, &status, &local_err);
2100 error_propagate(errp, local_err);
2104 if (!WIFEXITED(status)) {
2105 error_setg(errp, "child process has terminated abnormally");
2109 if (WEXITSTATUS(status)) {
2110 error_setg(errp, "child process has failed to set user password");
2115 g_free(chpasswddata);
2116 g_free(rawpasswddata);
2117 g_free(passwd_path);
2118 if (datafd[0] != -1) {
2121 if (datafd[1] != -1) {
2126 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2127 int size, Error **errp)
2133 fd = openat(dirfd, pathname, O_RDONLY);
2135 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2139 res = pread(fd, buf, size, 0);
2141 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2142 } else if (res == 0) {
2143 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2148 static void ga_write_sysfs_file(int dirfd, const char *pathname,
2149 const char *buf, int size, Error **errp)
2154 fd = openat(dirfd, pathname, O_WRONLY);
2156 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2160 if (pwrite(fd, buf, size, 0) == -1) {
2161 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2167 /* Transfer online/offline status between @mem_blk and the guest system.
2169 * On input either @errp or *@errp must be NULL.
2171 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2172 * - R: mem_blk->phys_index
2173 * - W: mem_blk->online
2174 * - W: mem_blk->can_offline
2176 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2177 * - R: mem_blk->phys_index
2178 * - R: mem_blk->online
2179 *- R: mem_blk->can_offline
2180 * Written members remain unmodified on error.
2182 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2183 GuestMemoryBlockResponse *result,
2189 Error *local_err = NULL;
2195 error_setg(errp, "Internal error, 'result' should not be NULL");
2199 dp = opendir("/sys/devices/system/memory/");
2200 /* if there is no 'memory' directory in sysfs,
2201 * we think this VM does not support online/offline memory block,
2202 * any other solution?
2205 if (errno == ENOENT) {
2207 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2214 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2215 mem_blk->phys_index);
2216 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2219 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2221 if (errno == ENOENT) {
2222 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2225 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2233 status = g_malloc0(10);
2234 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2236 /* treat with sysfs file that not exist in old kernel */
2237 if (errno == ENOENT) {
2238 error_free(local_err);
2240 mem_blk->online = true;
2241 mem_blk->can_offline = false;
2242 } else if (!mem_blk->online) {
2244 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2248 error_propagate(errp, local_err);
2251 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2258 char removable = '0';
2260 mem_blk->online = (strncmp(status, "online", 6) == 0);
2262 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2264 /* if no 'removable' file, it doesn't support offline mem blk */
2265 if (errno == ENOENT) {
2266 error_free(local_err);
2267 mem_blk->can_offline = false;
2269 error_propagate(errp, local_err);
2272 mem_blk->can_offline = (removable != '0');
2275 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2276 const char *new_state = mem_blk->online ? "online" : "offline";
2278 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2281 error_free(local_err);
2283 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2287 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2288 result->has_error_code = false;
2289 } /* otherwise pretend successful re-(on|off)-lining */
2300 result->has_error_code = true;
2301 result->error_code = errno;
2305 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2307 GuestMemoryBlockList *head, **link;
2308 Error *local_err = NULL;
2315 dp = opendir("/sys/devices/system/memory/");
2317 /* it's ok if this happens to be a system that doesn't expose
2318 * memory blocks via sysfs, but otherwise we should report
2321 if (errno != ENOENT) {
2322 error_setg_errno(errp, errno, "Can't open directory"
2323 "\"/sys/devices/system/memory/\"");
2328 /* Note: the phys_index of memory block may be discontinuous,
2329 * this is because a memblk is the unit of the Sparse Memory design, which
2330 * allows discontinuous memory ranges (ex. NUMA), so here we should
2331 * traverse the memory block directory.
2333 while ((de = readdir(dp)) != NULL) {
2334 GuestMemoryBlock *mem_blk;
2335 GuestMemoryBlockList *entry;
2337 if ((strncmp(de->d_name, "memory", 6) != 0) ||
2338 !(de->d_type & DT_DIR)) {
2342 mem_blk = g_malloc0(sizeof *mem_blk);
2343 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2344 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2345 mem_blk->has_can_offline = true; /* lolspeak ftw */
2346 transfer_memory_block(mem_blk, true, NULL, &local_err);
2348 entry = g_malloc0(sizeof *entry);
2349 entry->value = mem_blk;
2352 link = &entry->next;
2356 if (local_err == NULL) {
2357 /* there's no guest with zero memory blocks */
2359 error_setg(errp, "guest reported zero memory blocks!");
2364 qapi_free_GuestMemoryBlockList(head);
2365 error_propagate(errp, local_err);
2369 GuestMemoryBlockResponseList *
2370 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2372 GuestMemoryBlockResponseList *head, **link;
2373 Error *local_err = NULL;
2378 while (mem_blks != NULL) {
2379 GuestMemoryBlockResponse *result;
2380 GuestMemoryBlockResponseList *entry;
2381 GuestMemoryBlock *current_mem_blk = mem_blks->value;
2383 result = g_malloc0(sizeof(*result));
2384 result->phys_index = current_mem_blk->phys_index;
2385 transfer_memory_block(current_mem_blk, false, result, &local_err);
2386 if (local_err) { /* should never happen */
2389 entry = g_malloc0(sizeof *entry);
2390 entry->value = result;
2393 link = &entry->next;
2394 mem_blks = mem_blks->next;
2399 qapi_free_GuestMemoryBlockResponseList(head);
2400 error_propagate(errp, local_err);
2404 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2406 Error *local_err = NULL;
2410 GuestMemoryBlockInfo *info;
2412 dirpath = g_strdup_printf("/sys/devices/system/memory/");
2413 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2415 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2421 buf = g_malloc0(20);
2422 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2426 error_propagate(errp, local_err);
2430 info = g_new0(GuestMemoryBlockInfo, 1);
2431 info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2438 #else /* defined(__linux__) */
2440 void qmp_guest_suspend_disk(Error **errp)
2442 error_setg(errp, QERR_UNSUPPORTED);
2445 void qmp_guest_suspend_ram(Error **errp)
2447 error_setg(errp, QERR_UNSUPPORTED);
2450 void qmp_guest_suspend_hybrid(Error **errp)
2452 error_setg(errp, QERR_UNSUPPORTED);
2455 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2457 error_setg(errp, QERR_UNSUPPORTED);
2461 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2463 error_setg(errp, QERR_UNSUPPORTED);
2467 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2469 error_setg(errp, QERR_UNSUPPORTED);
2473 void qmp_guest_set_user_password(const char *username,
2474 const char *password,
2478 error_setg(errp, QERR_UNSUPPORTED);
2481 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2483 error_setg(errp, QERR_UNSUPPORTED);
2487 GuestMemoryBlockResponseList *
2488 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2490 error_setg(errp, QERR_UNSUPPORTED);
2494 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2496 error_setg(errp, QERR_UNSUPPORTED);
2502 #if !defined(CONFIG_FSFREEZE)
2504 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
2506 error_setg(errp, QERR_UNSUPPORTED);
2510 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
2512 error_setg(errp, QERR_UNSUPPORTED);
2517 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
2519 error_setg(errp, QERR_UNSUPPORTED);
2524 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
2525 strList *mountpoints,
2528 error_setg(errp, QERR_UNSUPPORTED);
2533 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
2535 error_setg(errp, QERR_UNSUPPORTED);
2539 #endif /* CONFIG_FSFREEZE */
2541 #if !defined(CONFIG_FSTRIM)
2542 GuestFilesystemTrimResponse *
2543 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
2545 error_setg(errp, QERR_UNSUPPORTED);
2550 /* add unsupported commands to the blacklist */
2551 GList *ga_command_blacklist_init(GList *blacklist)
2553 #if !defined(__linux__)
2555 const char *list[] = {
2556 "guest-suspend-disk", "guest-suspend-ram",
2557 "guest-suspend-hybrid", "guest-network-get-interfaces",
2558 "guest-get-vcpus", "guest-set-vcpus",
2559 "guest-get-memory-blocks", "guest-set-memory-blocks",
2560 "guest-get-memory-block-size", NULL};
2561 char **p = (char **)list;
2564 blacklist = g_list_append(blacklist, g_strdup(*p++));
2569 #if !defined(CONFIG_FSFREEZE)
2571 const char *list[] = {
2572 "guest-get-fsinfo", "guest-fsfreeze-status",
2573 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2574 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL};
2575 char **p = (char **)list;
2578 blacklist = g_list_append(blacklist, g_strdup(*p++));
2583 #if !defined(CONFIG_FSTRIM)
2584 blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
2590 /* register init/cleanup routines for stateful command groups */
2591 void ga_command_state_init(GAState *s, GACommandState *cs)
2593 #if defined(CONFIG_FSFREEZE)
2594 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2600 #define QGA_MICRO_SECOND_TO_SECOND 1000000
2602 static double ga_get_login_time(struct utmpx *user_info)
2604 double seconds = (double)user_info->ut_tv.tv_sec;
2605 double useconds = (double)user_info->ut_tv.tv_usec;
2606 useconds /= QGA_MICRO_SECOND_TO_SECOND;
2607 return seconds + useconds;
2610 GuestUserList *qmp_guest_get_users(Error **err)
2612 GHashTable *cache = NULL;
2613 GuestUserList *head = NULL, *cur_item = NULL;
2614 struct utmpx *user_info = NULL;
2615 gpointer value = NULL;
2616 GuestUser *user = NULL;
2617 GuestUserList *item = NULL;
2618 double login_time = 0;
2620 cache = g_hash_table_new(g_str_hash, g_str_equal);
2624 user_info = getutxent();
2625 if (user_info == NULL) {
2627 } else if (user_info->ut_type != USER_PROCESS) {
2629 } else if (g_hash_table_contains(cache, user_info->ut_user)) {
2630 value = g_hash_table_lookup(cache, user_info->ut_user);
2631 user = (GuestUser *)value;
2632 login_time = ga_get_login_time(user_info);
2633 /* We're ensuring the earliest login time to be sent */
2634 if (login_time < user->login_time) {
2635 user->login_time = login_time;
2640 item = g_new0(GuestUserList, 1);
2641 item->value = g_new0(GuestUser, 1);
2642 item->value->user = g_strdup(user_info->ut_user);
2643 item->value->login_time = ga_get_login_time(user_info);
2645 g_hash_table_insert(cache, item->value->user, item->value);
2648 head = cur_item = item;
2650 cur_item->next = item;
2655 g_hash_table_destroy(cache);
2661 GuestUserList *qmp_guest_get_users(Error **errp)
2663 error_setg(errp, QERR_UNSUPPORTED);
2669 /* Replace escaped special characters with theire real values. The replacement
2670 * is done in place -- returned value is in the original string.
2672 static void ga_osrelease_replace_special(gchar *value)
2674 gchar *p, *p2, quote;
2676 /* Trim the string at first space or semicolon if it is not enclosed in
2677 * single or double quotes. */
2678 if ((value[0] != '"') || (value[0] == '\'')) {
2679 p = strchr(value, ' ');
2683 p = strchr(value, ';');
2704 /* Keep literal backslash followed by whatever is there */
2708 } else if (*p == quote) {
2716 static GKeyFile *ga_parse_osrelease(const char *fname)
2718 gchar *content = NULL;
2719 gchar *content2 = NULL;
2721 GKeyFile *keys = g_key_file_new();
2722 const char *group = "[os-release]\n";
2724 if (!g_file_get_contents(fname, &content, NULL, &err)) {
2725 slog("failed to read '%s', error: %s", fname, err->message);
2729 if (!g_utf8_validate(content, -1, NULL)) {
2730 slog("file is not utf-8 encoded: %s", fname);
2733 content2 = g_strdup_printf("%s%s", group, content);
2735 if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
2737 slog("failed to parse file '%s', error: %s", fname, err->message);
2749 g_key_file_free(keys);
2753 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2755 GuestOSInfo *info = NULL;
2756 struct utsname kinfo;
2757 GKeyFile *osrelease = NULL;
2758 const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
2760 info = g_new0(GuestOSInfo, 1);
2762 if (uname(&kinfo) != 0) {
2763 error_setg_errno(errp, errno, "uname failed");
2765 info->has_kernel_version = true;
2766 info->kernel_version = g_strdup(kinfo.version);
2767 info->has_kernel_release = true;
2768 info->kernel_release = g_strdup(kinfo.release);
2769 info->has_machine = true;
2770 info->machine = g_strdup(kinfo.machine);
2773 if (qga_os_release != NULL) {
2774 osrelease = ga_parse_osrelease(qga_os_release);
2776 osrelease = ga_parse_osrelease("/etc/os-release");
2777 if (osrelease == NULL) {
2778 osrelease = ga_parse_osrelease("/usr/lib/os-release");
2782 if (osrelease != NULL) {
2785 #define GET_FIELD(field, osfield) do { \
2786 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
2787 if (value != NULL) { \
2788 ga_osrelease_replace_special(value); \
2789 info->has_ ## field = true; \
2790 info->field = value; \
2793 GET_FIELD(id, "ID");
2794 GET_FIELD(name, "NAME");
2795 GET_FIELD(pretty_name, "PRETTY_NAME");
2796 GET_FIELD(version, "VERSION");
2797 GET_FIELD(version_id, "VERSION_ID");
2798 GET_FIELD(variant, "VARIANT");
2799 GET_FIELD(variant_id, "VARIANT_ID");
2802 g_key_file_free(osrelease);