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 "guest-agent-core.h"
20 #include "qga-qapi-commands.h"
21 #include "qapi/error.h"
22 #include "qapi/qmp/qerror.h"
23 #include "qemu/queue.h"
24 #include "qemu/host-utils.h"
25 #include "qemu/sockets.h"
26 #include "qemu/base64.h"
27 #include "qemu/cutils.h"
33 #ifndef CONFIG_HAS_ENVIRON
35 #include <crt_externs.h>
36 #define environ (*_NSGetEnviron())
38 extern char **environ;
42 #if defined(__linux__)
46 #include <arpa/inet.h>
47 #include <sys/socket.h>
51 #define CONFIG_FSFREEZE
58 static void ga_wait_child(pid_t pid, int *status, Error **errp)
65 rpid = waitpid(pid, status, 0);
66 } while (rpid == -1 && errno == EINTR);
69 error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
74 g_assert(rpid == pid);
77 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
79 const char *shutdown_flag;
80 Error *local_err = NULL;
84 slog("guest-shutdown called, mode: %s", mode);
85 if (!has_mode || strcmp(mode, "powerdown") == 0) {
87 } else if (strcmp(mode, "halt") == 0) {
89 } else if (strcmp(mode, "reboot") == 0) {
93 "mode is invalid (valid values are: halt|powerdown|reboot");
99 /* child, start the shutdown */
101 reopen_fd_to_null(0);
102 reopen_fd_to_null(1);
103 reopen_fd_to_null(2);
105 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
106 "hypervisor initiated shutdown", (char*)NULL, environ);
108 } else if (pid < 0) {
109 error_setg_errno(errp, errno, "failed to create child process");
113 ga_wait_child(pid, &status, &local_err);
115 error_propagate(errp, local_err);
119 if (!WIFEXITED(status)) {
120 error_setg(errp, "child process has terminated abnormally");
124 if (WEXITSTATUS(status)) {
125 error_setg(errp, "child process has failed to shutdown");
132 int64_t qmp_guest_get_time(Error **errp)
137 ret = qemu_gettimeofday(&tq);
139 error_setg_errno(errp, errno, "Failed to get time");
143 return tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
146 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
151 Error *local_err = NULL;
154 /* If user has passed a time, validate and set it. */
158 /* year-2038 will overflow in case time_t is 32bit */
159 if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
160 error_setg(errp, "Time %" PRId64 " is too large", time_ns);
164 tv.tv_sec = time_ns / 1000000000;
165 tv.tv_usec = (time_ns % 1000000000) / 1000;
166 g_date_set_time_t(&date, tv.tv_sec);
167 if (date.year < 1970 || date.year >= 2070) {
168 error_setg_errno(errp, errno, "Invalid time");
172 ret = settimeofday(&tv, NULL);
174 error_setg_errno(errp, errno, "Failed to set time to guest");
179 /* Now, if user has passed a time to set and the system time is set, we
180 * just need to synchronize the hardware clock. However, if no time was
181 * passed, user is requesting the opposite: set the system time from the
182 * hardware clock (RTC). */
186 reopen_fd_to_null(0);
187 reopen_fd_to_null(1);
188 reopen_fd_to_null(2);
190 /* Use '/sbin/hwclock -w' to set RTC from the system time,
191 * or '/sbin/hwclock -s' to set the system time from RTC. */
192 execle("/sbin/hwclock", "hwclock", has_time ? "-w" : "-s",
195 } else if (pid < 0) {
196 error_setg_errno(errp, errno, "failed to create child process");
200 ga_wait_child(pid, &status, &local_err);
202 error_propagate(errp, local_err);
206 if (!WIFEXITED(status)) {
207 error_setg(errp, "child process has terminated abnormally");
211 if (WEXITSTATUS(status)) {
212 error_setg(errp, "hwclock failed to set hardware clock to system time");
223 typedef struct GuestFileHandle {
227 QTAILQ_ENTRY(GuestFileHandle) next;
231 QTAILQ_HEAD(, GuestFileHandle) filehandles;
232 } guest_file_state = {
233 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
236 static int64_t guest_file_handle_add(FILE *fh, Error **errp)
238 GuestFileHandle *gfh;
241 handle = ga_get_fd_handle(ga_state, errp);
246 gfh = g_new0(GuestFileHandle, 1);
249 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
254 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
256 GuestFileHandle *gfh;
258 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
265 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
269 typedef const char * const ccpc;
275 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
276 static const struct {
279 } guest_file_open_modes[] = {
280 { (ccpc[]){ "r", NULL }, O_RDONLY },
281 { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
282 { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
283 { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
284 { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
285 { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
286 { (ccpc[]){ "r+", NULL }, O_RDWR },
287 { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
288 { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
289 { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
290 { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
291 { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
295 find_open_flag(const char *mode_str, Error **errp)
299 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
302 form = guest_file_open_modes[mode].forms;
303 while (*form != NULL && strcmp(*form, mode_str) != 0) {
311 if (mode == ARRAY_SIZE(guest_file_open_modes)) {
312 error_setg(errp, "invalid file open mode '%s'", mode_str);
315 return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
318 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
319 S_IRGRP | S_IWGRP | \
323 safe_open_or_create(const char *path, const char *mode, Error **errp)
325 Error *local_err = NULL;
328 oflag = find_open_flag(mode, &local_err);
329 if (local_err == NULL) {
332 /* If the caller wants / allows creation of a new file, we implement it
333 * with a two step process: open() + (open() / fchmod()).
335 * First we insist on creating the file exclusively as a new file. If
336 * that succeeds, we're free to set any file-mode bits on it. (The
337 * motivation is that we want to set those file-mode bits independently
338 * of the current umask.)
340 * If the exclusive creation fails because the file already exists
341 * (EEXIST is not possible for any other reason), we just attempt to
342 * open the file, but in this case we won't be allowed to change the
343 * file-mode bits on the preexistent file.
345 * The pathname should never disappear between the two open()s in
346 * practice. If it happens, then someone very likely tried to race us.
347 * In this case just go ahead and report the ENOENT from the second
348 * open() to the caller.
350 * If the caller wants to open a preexistent file, then the first
351 * open() is decisive and its third argument is ignored, and the second
352 * open() and the fchmod() are never called.
354 fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
355 if (fd == -1 && errno == EEXIST) {
356 oflag &= ~(unsigned)O_CREAT;
357 fd = open(path, oflag);
361 error_setg_errno(&local_err, errno, "failed to open file '%s' "
362 "(mode: '%s')", path, mode);
364 qemu_set_cloexec(fd);
366 if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
367 error_setg_errno(&local_err, errno, "failed to set permission "
368 "0%03o on new file '%s' (mode: '%s')",
369 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
373 f = fdopen(fd, mode);
375 error_setg_errno(&local_err, errno, "failed to associate "
376 "stdio stream with file descriptor %d, "
377 "file '%s' (mode: '%s')", fd, path, mode);
384 if (oflag & O_CREAT) {
390 error_propagate(errp, local_err);
394 int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
398 Error *local_err = NULL;
404 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
405 fh = safe_open_or_create(path, mode, &local_err);
406 if (local_err != NULL) {
407 error_propagate(errp, local_err);
411 /* set fd non-blocking to avoid common use cases (like reading from a
412 * named pipe) from hanging the agent
414 qemu_set_nonblock(fileno(fh));
416 handle = guest_file_handle_add(fh, errp);
422 slog("guest-file-open, handle: %" PRId64, handle);
426 void qmp_guest_file_close(int64_t handle, Error **errp)
428 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
431 slog("guest-file-close called, handle: %" PRId64, handle);
436 ret = fclose(gfh->fh);
438 error_setg_errno(errp, errno, "failed to close handle");
442 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
446 struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
447 int64_t count, Error **errp)
449 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
450 GuestFileRead *read_data = NULL;
460 count = QGA_READ_COUNT_DEFAULT;
461 } else if (count < 0) {
462 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
469 /* explicitly flush when switching from writing to reading */
470 if (gfh->state == RW_STATE_WRITING) {
471 int ret = fflush(fh);
473 error_setg_errno(errp, errno, "failed to flush file");
476 gfh->state = RW_STATE_NEW;
479 buf = g_malloc0(count+1);
480 read_count = fread(buf, 1, count, fh);
482 error_setg_errno(errp, errno, "failed to read file");
483 slog("guest-file-read failed, handle: %" PRId64, handle);
486 read_data = g_new0(GuestFileRead, 1);
487 read_data->count = read_count;
488 read_data->eof = feof(fh);
490 read_data->buf_b64 = g_base64_encode(buf, read_count);
492 gfh->state = RW_STATE_READING;
500 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
501 bool has_count, int64_t count,
504 GuestFileWrite *write_data = NULL;
508 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
517 if (gfh->state == RW_STATE_READING) {
518 int ret = fseek(fh, 0, SEEK_CUR);
520 error_setg_errno(errp, errno, "failed to seek file");
523 gfh->state = RW_STATE_NEW;
526 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
533 } else if (count < 0 || count > buf_len) {
534 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
540 write_count = fwrite(buf, 1, count, fh);
542 error_setg_errno(errp, errno, "failed to write to file");
543 slog("guest-file-write failed, handle: %" PRId64, handle);
545 write_data = g_new0(GuestFileWrite, 1);
546 write_data->count = write_count;
547 write_data->eof = feof(fh);
548 gfh->state = RW_STATE_WRITING;
556 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
557 GuestFileWhence *whence_code,
560 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
561 GuestFileSeek *seek_data = NULL;
571 /* We stupidly exposed 'whence':'int' in our qapi */
572 whence = ga_parse_whence(whence_code, &err);
574 error_propagate(errp, err);
579 ret = fseek(fh, offset, whence);
581 error_setg_errno(errp, errno, "failed to seek file");
582 if (errno == ESPIPE) {
583 /* file is non-seekable, stdio shouldn't be buffering anyways */
584 gfh->state = RW_STATE_NEW;
587 seek_data = g_new0(GuestFileSeek, 1);
588 seek_data->position = ftell(fh);
589 seek_data->eof = feof(fh);
590 gfh->state = RW_STATE_NEW;
597 void qmp_guest_file_flush(int64_t handle, Error **errp)
599 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
610 error_setg_errno(errp, errno, "failed to flush file");
612 gfh->state = RW_STATE_NEW;
616 /* linux-specific implementations. avoid this if at all possible. */
617 #if defined(__linux__)
619 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
620 typedef struct FsMount {
623 unsigned int devmajor, devminor;
624 QTAILQ_ENTRY(FsMount) next;
627 typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
629 static void free_fs_mount_list(FsMountList *mounts)
631 FsMount *mount, *temp;
637 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
638 QTAILQ_REMOVE(mounts, mount, next);
639 g_free(mount->dirname);
640 g_free(mount->devtype);
645 static int dev_major_minor(const char *devpath,
646 unsigned int *devmajor, unsigned int *devminor)
653 if (stat(devpath, &st) < 0) {
654 slog("failed to stat device file '%s': %s", devpath, strerror(errno));
657 if (S_ISDIR(st.st_mode)) {
658 /* It is bind mount */
661 if (S_ISBLK(st.st_mode)) {
662 *devmajor = major(st.st_rdev);
663 *devminor = minor(st.st_rdev);
670 * Walk the mount table and build a list of local file systems
672 static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
676 char const *mtab = "/proc/self/mounts";
678 unsigned int devmajor, devminor;
680 fp = setmntent(mtab, "r");
682 error_setg(errp, "failed to open mtab file: '%s'", mtab);
686 while ((ment = getmntent(fp))) {
688 * An entry which device name doesn't start with a '/' is
689 * either a dummy file system or a network file system.
690 * Add special handling for smbfs and cifs as is done by
693 if ((ment->mnt_fsname[0] != '/') ||
694 (strcmp(ment->mnt_type, "smbfs") == 0) ||
695 (strcmp(ment->mnt_type, "cifs") == 0)) {
698 if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
699 /* Skip bind mounts */
703 mount = g_new0(FsMount, 1);
704 mount->dirname = g_strdup(ment->mnt_dir);
705 mount->devtype = g_strdup(ment->mnt_type);
706 mount->devmajor = devmajor;
707 mount->devminor = devminor;
709 QTAILQ_INSERT_TAIL(mounts, mount, next);
715 static void decode_mntname(char *name, int len)
718 for (i = 0; i <= len; i++) {
719 if (name[i] != '\\') {
721 } else if (name[i + 1] == '\\') {
724 } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
725 name[i + 2] >= '0' && name[i + 2] <= '7' &&
726 name[i + 3] >= '0' && name[i + 3] <= '7') {
727 name[j++] = (name[i + 1] - '0') * 64 +
728 (name[i + 2] - '0') * 8 +
737 static void build_fs_mount_list(FsMountList *mounts, Error **errp)
740 char const *mountinfo = "/proc/self/mountinfo";
742 char *line = NULL, *dash;
745 unsigned int devmajor, devminor;
746 int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
748 fp = fopen(mountinfo, "r");
750 build_fs_mount_list_from_mtab(mounts, errp);
754 while (getline(&line, &n, fp) != -1) {
755 ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
756 &devmajor, &devminor, &dir_s, &dir_e, &check);
760 dash = strstr(line + dir_e, " - ");
764 ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
765 &type_s, &type_e, &dev_s, &dev_e, &check);
772 decode_mntname(line + dir_s, dir_e - dir_s);
773 decode_mntname(dash + dev_s, dev_e - dev_s);
775 /* btrfs reports major number = 0 */
776 if (strcmp("btrfs", dash + type_s) != 0 ||
777 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
782 mount = g_new0(FsMount, 1);
783 mount->dirname = g_strdup(line + dir_s);
784 mount->devtype = g_strdup(dash + type_s);
785 mount->devmajor = devmajor;
786 mount->devminor = devminor;
788 QTAILQ_INSERT_TAIL(mounts, mount, next);
796 #if defined(CONFIG_FSFREEZE)
798 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
806 path = g_strndup(syspath, pathlen);
807 dpath = g_strdup_printf("%s/driver", path);
808 len = readlink(dpath, buf, sizeof(buf) - 1);
811 driver = g_path_get_basename(buf);
818 static int compare_uint(const void *_a, const void *_b)
820 unsigned int a = *(unsigned int *)_a;
821 unsigned int b = *(unsigned int *)_b;
823 return a < b ? -1 : a > b ? 1 : 0;
826 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
827 static int build_hosts(char const *syspath, char const *host, bool ata,
828 unsigned int *hosts, int hosts_max, Error **errp)
832 struct dirent *entry;
835 path = g_strndup(syspath, host - syspath);
838 error_setg_errno(errp, errno, "opendir(\"%s\")", path);
843 while (i < hosts_max) {
844 entry = readdir(dir);
848 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
850 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
855 qsort(hosts, i, sizeof(hosts[0]), compare_uint);
862 /* Store disk device info specified by @sysfs into @fs */
863 static void build_guest_fsinfo_for_real_device(char const *syspath,
864 GuestFilesystemInfo *fs,
867 unsigned int pci[4], host, hosts[8], tgt[3];
868 int i, nhosts = 0, pcilen;
869 GuestDiskAddress *disk;
870 GuestPCIAddress *pciaddr;
871 GuestDiskAddressList *list = NULL;
872 bool has_ata = false, has_host = false, has_tgt = false;
873 char *p, *q, *driver = NULL;
875 p = strstr(syspath, "/devices/pci");
876 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
877 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
878 g_debug("only pci device is supported: sysfs path \"%s\"", syspath);
882 driver = get_pci_driver(syspath, (p + 12 + pcilen) - syspath, errp);
887 p = strstr(syspath, "/target");
888 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
889 tgt, tgt + 1, tgt + 2) == 3) {
893 p = strstr(syspath, "/ata");
898 p = strstr(syspath, "/host");
901 if (p && sscanf(q, "%u", &host) == 1) {
903 nhosts = build_hosts(syspath, p, has_ata, hosts,
904 ARRAY_SIZE(hosts), errp);
910 pciaddr = g_malloc0(sizeof(*pciaddr));
911 pciaddr->domain = pci[0];
912 pciaddr->bus = pci[1];
913 pciaddr->slot = pci[2];
914 pciaddr->function = pci[3];
916 disk = g_malloc0(sizeof(*disk));
917 disk->pci_controller = pciaddr;
919 list = g_malloc0(sizeof(*list));
922 if (strcmp(driver, "ata_piix") == 0) {
923 /* a host per ide bus, target*:0:<unit>:0 */
924 if (!has_host || !has_tgt) {
925 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
928 for (i = 0; i < nhosts; i++) {
929 if (host == hosts[i]) {
930 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
937 g_debug("no host for '%s' (driver '%s')", syspath, driver);
940 } else if (strcmp(driver, "sym53c8xx") == 0) {
941 /* scsi(LSI Logic): target*:0:<unit>:0 */
943 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
946 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
948 } else if (strcmp(driver, "virtio-pci") == 0) {
950 /* virtio-scsi: target*:0:0:<unit> */
951 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
954 /* virtio-blk: 1 disk per 1 device */
955 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
957 } else if (strcmp(driver, "ahci") == 0) {
958 /* ahci: 1 host per 1 unit */
959 if (!has_host || !has_tgt) {
960 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
963 for (i = 0; i < nhosts; i++) {
964 if (host == hosts[i]) {
966 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
971 g_debug("no host for '%s' (driver '%s')", syspath, driver);
975 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
979 list->next = fs->disk;
986 qapi_free_GuestDiskAddressList(list);
991 static void build_guest_fsinfo_for_device(char const *devpath,
992 GuestFilesystemInfo *fs,
995 /* Store a list of slave devices of virtual volume specified by @syspath into
997 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
998 GuestFilesystemInfo *fs,
1003 struct dirent *entry;
1005 dirpath = g_strdup_printf("%s/slaves", syspath);
1006 dir = opendir(dirpath);
1008 if (errno != ENOENT) {
1009 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
1017 entry = readdir(dir);
1018 if (entry == NULL) {
1020 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1025 if (entry->d_type == DT_LNK) {
1028 g_debug(" slave device '%s'", entry->d_name);
1029 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1030 build_guest_fsinfo_for_device(path, fs, errp);
1043 /* Dispatch to functions for virtual/real device */
1044 static void build_guest_fsinfo_for_device(char const *devpath,
1045 GuestFilesystemInfo *fs,
1048 char *syspath = realpath(devpath, NULL);
1051 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1056 fs->name = g_path_get_basename(syspath);
1059 g_debug(" parse sysfs path '%s'", syspath);
1061 if (strstr(syspath, "/devices/virtual/block/")) {
1062 build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1064 build_guest_fsinfo_for_real_device(syspath, fs, errp);
1070 /* Return a list of the disk device(s)' info which @mount lies on */
1071 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1074 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1075 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1076 mount->devmajor, mount->devminor);
1078 fs->mountpoint = g_strdup(mount->dirname);
1079 fs->type = g_strdup(mount->devtype);
1080 build_guest_fsinfo_for_device(devpath, fs, errp);
1086 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1089 struct FsMount *mount;
1090 GuestFilesystemInfoList *new, *ret = NULL;
1091 Error *local_err = NULL;
1093 QTAILQ_INIT(&mounts);
1094 build_fs_mount_list(&mounts, &local_err);
1096 error_propagate(errp, local_err);
1100 QTAILQ_FOREACH(mount, &mounts, next) {
1101 g_debug("Building guest fsinfo for '%s'", mount->dirname);
1103 new = g_malloc0(sizeof(*ret));
1104 new->value = build_guest_fsinfo(mount, &local_err);
1108 error_propagate(errp, local_err);
1109 qapi_free_GuestFilesystemInfoList(ret);
1115 free_fs_mount_list(&mounts);
1121 FSFREEZE_HOOK_THAW = 0,
1122 FSFREEZE_HOOK_FREEZE,
1125 static const char *fsfreeze_hook_arg_string[] = {
1130 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
1135 const char *arg_str = fsfreeze_hook_arg_string[arg];
1136 Error *local_err = NULL;
1138 hook = ga_fsfreeze_hook(ga_state);
1142 if (access(hook, X_OK) != 0) {
1143 error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
1147 slog("executing fsfreeze hook with arg '%s'", arg_str);
1151 reopen_fd_to_null(0);
1152 reopen_fd_to_null(1);
1153 reopen_fd_to_null(2);
1155 execle(hook, hook, arg_str, NULL, environ);
1156 _exit(EXIT_FAILURE);
1157 } else if (pid < 0) {
1158 error_setg_errno(errp, errno, "failed to create child process");
1162 ga_wait_child(pid, &status, &local_err);
1164 error_propagate(errp, local_err);
1168 if (!WIFEXITED(status)) {
1169 error_setg(errp, "fsfreeze hook has terminated abnormally");
1173 status = WEXITSTATUS(status);
1175 error_setg(errp, "fsfreeze hook has failed with status %d", status);
1181 * Return status of freeze/thaw
1183 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1185 if (ga_is_frozen(ga_state)) {
1186 return GUEST_FSFREEZE_STATUS_FROZEN;
1189 return GUEST_FSFREEZE_STATUS_THAWED;
1192 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1194 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1198 * Walk list of mounted file systems in the guest, and freeze the ones which
1199 * are real local file systems.
1201 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1202 strList *mountpoints,
1208 struct FsMount *mount;
1209 Error *local_err = NULL;
1212 slog("guest-fsfreeze called");
1214 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
1216 error_propagate(errp, local_err);
1220 QTAILQ_INIT(&mounts);
1221 build_fs_mount_list(&mounts, &local_err);
1223 error_propagate(errp, local_err);
1227 /* cannot risk guest agent blocking itself on a write in this state */
1228 ga_set_frozen(ga_state);
1230 QTAILQ_FOREACH_REVERSE(mount, &mounts, FsMountList, next) {
1231 /* To issue fsfreeze in the reverse order of mounts, check if the
1232 * mount is listed in the list here */
1233 if (has_mountpoints) {
1234 for (list = mountpoints; list; list = list->next) {
1235 if (strcmp(list->value, mount->dirname) == 0) {
1244 fd = qemu_open(mount->dirname, O_RDONLY);
1246 error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
1250 /* we try to cull filesystems we know won't work in advance, but other
1251 * filesystems may not implement fsfreeze for less obvious reasons.
1252 * these will report EOPNOTSUPP. we simply ignore these when tallying
1253 * the number of frozen filesystems.
1254 * if a filesystem is mounted more than once (aka bind mount) a
1255 * consecutive attempt to freeze an already frozen filesystem will
1258 * any other error means a failure to freeze a filesystem we
1259 * expect to be freezable, so return an error in those cases
1260 * and return system to thawed state.
1262 ret = ioctl(fd, FIFREEZE);
1264 if (errno != EOPNOTSUPP && errno != EBUSY) {
1265 error_setg_errno(errp, errno, "failed to freeze %s",
1276 free_fs_mount_list(&mounts);
1280 free_fs_mount_list(&mounts);
1281 qmp_guest_fsfreeze_thaw(NULL);
1286 * Walk list of frozen file systems in the guest, and thaw them.
1288 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1293 int fd, i = 0, logged;
1294 Error *local_err = NULL;
1296 QTAILQ_INIT(&mounts);
1297 build_fs_mount_list(&mounts, &local_err);
1299 error_propagate(errp, local_err);
1303 QTAILQ_FOREACH(mount, &mounts, next) {
1305 fd = qemu_open(mount->dirname, O_RDONLY);
1309 /* we have no way of knowing whether a filesystem was actually unfrozen
1310 * as a result of a successful call to FITHAW, only that if an error
1311 * was returned the filesystem was *not* unfrozen by that particular
1314 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1315 * to unfreeze, continuing issuing FITHAW until an error is returned,
1316 * in which case either the filesystem is in an unfreezable state, or,
1317 * more likely, it was thawed previously (and remains so afterward).
1319 * also, since the most recent successful call is the one that did
1320 * the actual unfreeze, we can use this to provide an accurate count
1321 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1322 * may * be useful for determining whether a filesystem was unfrozen
1323 * during the freeze/thaw phase by a process other than qemu-ga.
1326 ret = ioctl(fd, FITHAW);
1327 if (ret == 0 && !logged) {
1335 ga_unset_frozen(ga_state);
1336 free_fs_mount_list(&mounts);
1338 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
1343 static void guest_fsfreeze_cleanup(void)
1347 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1348 qmp_guest_fsfreeze_thaw(&err);
1350 slog("failed to clean up frozen filesystems: %s",
1351 error_get_pretty(err));
1356 #endif /* CONFIG_FSFREEZE */
1358 #if defined(CONFIG_FSTRIM)
1360 * Walk list of mounted file systems in the guest, and trim them.
1362 GuestFilesystemTrimResponse *
1363 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1365 GuestFilesystemTrimResponse *response;
1366 GuestFilesystemTrimResultList *list;
1367 GuestFilesystemTrimResult *result;
1370 struct FsMount *mount;
1372 Error *local_err = NULL;
1373 struct fstrim_range r;
1375 slog("guest-fstrim called");
1377 QTAILQ_INIT(&mounts);
1378 build_fs_mount_list(&mounts, &local_err);
1380 error_propagate(errp, local_err);
1384 response = g_malloc0(sizeof(*response));
1386 QTAILQ_FOREACH(mount, &mounts, next) {
1387 result = g_malloc0(sizeof(*result));
1388 result->path = g_strdup(mount->dirname);
1390 list = g_malloc0(sizeof(*list));
1391 list->value = result;
1392 list->next = response->paths;
1393 response->paths = list;
1395 fd = qemu_open(mount->dirname, O_RDONLY);
1397 result->error = g_strdup_printf("failed to open: %s",
1399 result->has_error = true;
1403 /* We try to cull filesystems we know won't work in advance, but other
1404 * filesystems may not implement fstrim for less obvious reasons.
1405 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1406 * will be reported (e.g. CD-ROMs).
1407 * Any other error means an unexpected error.
1411 r.minlen = has_minimum ? minimum : 0;
1412 ret = ioctl(fd, FITRIM, &r);
1414 result->has_error = true;
1415 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1416 result->error = g_strdup("trim not supported");
1418 result->error = g_strdup_printf("failed to trim: %s",
1425 result->has_minimum = true;
1426 result->minimum = r.minlen;
1427 result->has_trimmed = true;
1428 result->trimmed = r.len;
1432 free_fs_mount_list(&mounts);
1435 #endif /* CONFIG_FSTRIM */
1438 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1439 #define SUSPEND_SUPPORTED 0
1440 #define SUSPEND_NOT_SUPPORTED 1
1442 static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,
1443 const char *sysfile_str, Error **errp)
1445 Error *local_err = NULL;
1450 pmutils_path = g_find_program_in_path(pmutils_bin);
1454 char buf[32]; /* hopefully big enough */
1459 reopen_fd_to_null(0);
1460 reopen_fd_to_null(1);
1461 reopen_fd_to_null(2);
1464 execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
1468 * If we get here either pm-utils is not installed or execle() has
1469 * failed. Let's try the manual method if the caller wants it.
1473 _exit(SUSPEND_NOT_SUPPORTED);
1476 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
1478 _exit(SUSPEND_NOT_SUPPORTED);
1481 ret = read(fd, buf, sizeof(buf)-1);
1483 _exit(SUSPEND_NOT_SUPPORTED);
1487 if (strstr(buf, sysfile_str)) {
1488 _exit(SUSPEND_SUPPORTED);
1491 _exit(SUSPEND_NOT_SUPPORTED);
1492 } else if (pid < 0) {
1493 error_setg_errno(errp, errno, "failed to create child process");
1497 ga_wait_child(pid, &status, &local_err);
1499 error_propagate(errp, local_err);
1503 if (!WIFEXITED(status)) {
1504 error_setg(errp, "child process has terminated abnormally");
1508 switch (WEXITSTATUS(status)) {
1509 case SUSPEND_SUPPORTED:
1511 case SUSPEND_NOT_SUPPORTED:
1513 "the requested suspend mode is not supported by the guest");
1517 "the helper program '%s' returned an unexpected exit status"
1518 " code (%d)", pmutils_path, WEXITSTATUS(status));
1523 g_free(pmutils_path);
1526 static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
1529 Error *local_err = NULL;
1534 pmutils_path = g_find_program_in_path(pmutils_bin);
1542 reopen_fd_to_null(0);
1543 reopen_fd_to_null(1);
1544 reopen_fd_to_null(2);
1547 execle(pmutils_path, pmutils_bin, NULL, environ);
1551 * If we get here either pm-utils is not installed or execle() has
1552 * failed. Let's try the manual method if the caller wants it.
1556 _exit(EXIT_FAILURE);
1559 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
1561 _exit(EXIT_FAILURE);
1564 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
1565 _exit(EXIT_FAILURE);
1568 _exit(EXIT_SUCCESS);
1569 } else if (pid < 0) {
1570 error_setg_errno(errp, errno, "failed to create child process");
1574 ga_wait_child(pid, &status, &local_err);
1576 error_propagate(errp, local_err);
1580 if (!WIFEXITED(status)) {
1581 error_setg(errp, "child process has terminated abnormally");
1585 if (WEXITSTATUS(status)) {
1586 error_setg(errp, "child process has failed to suspend");
1591 g_free(pmutils_path);
1594 void qmp_guest_suspend_disk(Error **errp)
1596 Error *local_err = NULL;
1598 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err);
1600 error_propagate(errp, local_err);
1604 guest_suspend("pm-hibernate", "disk", errp);
1607 void qmp_guest_suspend_ram(Error **errp)
1609 Error *local_err = NULL;
1611 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err);
1613 error_propagate(errp, local_err);
1617 guest_suspend("pm-suspend", "mem", errp);
1620 void qmp_guest_suspend_hybrid(Error **errp)
1622 Error *local_err = NULL;
1624 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL,
1627 error_propagate(errp, local_err);
1631 guest_suspend("pm-suspend-hybrid", NULL, errp);
1634 static GuestNetworkInterfaceList *
1635 guest_find_interface(GuestNetworkInterfaceList *head,
1638 for (; head; head = head->next) {
1639 if (strcmp(head->value->name, name) == 0) {
1647 static int guest_get_network_stats(const char *name,
1648 GuestNetworkInterfaceStat *stats)
1651 char const *devinfo = "/proc/net/dev";
1653 char *line = NULL, *colon;
1655 fp = fopen(devinfo, "r");
1659 name_len = strlen(name);
1660 while (getline(&line, &n, fp) != -1) {
1663 long long rx_packets;
1665 long long rx_dropped;
1667 long long tx_packets;
1669 long long tx_dropped;
1671 trim_line = g_strchug(line);
1672 if (trim_line[0] == '\0') {
1675 colon = strchr(trim_line, ':');
1679 if (colon - name_len == trim_line &&
1680 strncmp(trim_line, name, name_len) == 0) {
1681 if (sscanf(colon + 1,
1682 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
1683 &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
1684 &dummy, &dummy, &dummy, &dummy,
1685 &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
1686 &dummy, &dummy, &dummy, &dummy) != 16) {
1689 stats->rx_bytes = rx_bytes;
1690 stats->rx_packets = rx_packets;
1691 stats->rx_errs = rx_errs;
1692 stats->rx_dropped = rx_dropped;
1693 stats->tx_bytes = tx_bytes;
1694 stats->tx_packets = tx_packets;
1695 stats->tx_errs = tx_errs;
1696 stats->tx_dropped = tx_dropped;
1704 g_debug("/proc/net/dev: Interface '%s' not found", name);
1709 * Build information about guest interfaces
1711 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1713 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1714 struct ifaddrs *ifap, *ifa;
1716 if (getifaddrs(&ifap) < 0) {
1717 error_setg_errno(errp, errno, "getifaddrs failed");
1721 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1722 GuestNetworkInterfaceList *info;
1723 GuestIpAddressList **address_list = NULL, *address_item = NULL;
1724 GuestNetworkInterfaceStat *interface_stat = NULL;
1725 char addr4[INET_ADDRSTRLEN];
1726 char addr6[INET6_ADDRSTRLEN];
1729 unsigned char *mac_addr;
1732 g_debug("Processing %s interface", ifa->ifa_name);
1734 info = guest_find_interface(head, ifa->ifa_name);
1737 info = g_malloc0(sizeof(*info));
1738 info->value = g_malloc0(sizeof(*info->value));
1739 info->value->name = g_strdup(ifa->ifa_name);
1742 head = cur_item = info;
1744 cur_item->next = info;
1749 if (!info->value->has_hardware_address &&
1750 ifa->ifa_flags & SIOCGIFHWADDR) {
1751 /* we haven't obtained HW address yet */
1752 sock = socket(PF_INET, SOCK_STREAM, 0);
1754 error_setg_errno(errp, errno, "failed to create socket");
1758 memset(&ifr, 0, sizeof(ifr));
1759 pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
1760 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
1761 error_setg_errno(errp, errno,
1762 "failed to get MAC address of %s",
1769 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
1771 info->value->hardware_address =
1772 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1773 (int) mac_addr[0], (int) mac_addr[1],
1774 (int) mac_addr[2], (int) mac_addr[3],
1775 (int) mac_addr[4], (int) mac_addr[5]);
1777 info->value->has_hardware_address = true;
1780 if (ifa->ifa_addr &&
1781 ifa->ifa_addr->sa_family == AF_INET) {
1782 /* interface with IPv4 address */
1783 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1784 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
1785 error_setg_errno(errp, errno, "inet_ntop failed");
1789 address_item = g_malloc0(sizeof(*address_item));
1790 address_item->value = g_malloc0(sizeof(*address_item->value));
1791 address_item->value->ip_address = g_strdup(addr4);
1792 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1794 if (ifa->ifa_netmask) {
1795 /* Count the number of set bits in netmask.
1796 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1797 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
1798 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
1800 } else if (ifa->ifa_addr &&
1801 ifa->ifa_addr->sa_family == AF_INET6) {
1802 /* interface with IPv6 address */
1803 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
1804 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
1805 error_setg_errno(errp, errno, "inet_ntop failed");
1809 address_item = g_malloc0(sizeof(*address_item));
1810 address_item->value = g_malloc0(sizeof(*address_item->value));
1811 address_item->value->ip_address = g_strdup(addr6);
1812 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1814 if (ifa->ifa_netmask) {
1815 /* Count the number of set bits in netmask.
1816 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1817 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
1818 address_item->value->prefix =
1819 ctpop32(((uint32_t *) p)[0]) +
1820 ctpop32(((uint32_t *) p)[1]) +
1821 ctpop32(((uint32_t *) p)[2]) +
1822 ctpop32(((uint32_t *) p)[3]);
1826 if (!address_item) {
1830 address_list = &info->value->ip_addresses;
1832 while (*address_list && (*address_list)->next) {
1833 address_list = &(*address_list)->next;
1836 if (!*address_list) {
1837 *address_list = address_item;
1839 (*address_list)->next = address_item;
1842 info->value->has_ip_addresses = true;
1844 if (!info->value->has_statistics) {
1845 interface_stat = g_malloc0(sizeof(*interface_stat));
1846 if (guest_get_network_stats(info->value->name,
1847 interface_stat) == -1) {
1848 info->value->has_statistics = false;
1849 g_free(interface_stat);
1851 info->value->statistics = interface_stat;
1852 info->value->has_statistics = true;
1862 qapi_free_GuestNetworkInterfaceList(head);
1866 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1868 static long sysconf_exact(int name, const char *name_str, Error **errp)
1873 ret = sysconf(name);
1876 error_setg(errp, "sysconf(%s): value indefinite", name_str);
1878 error_setg_errno(errp, errno, "sysconf(%s)", name_str);
1884 /* Transfer online/offline status between @vcpu and the guest system.
1886 * On input either @errp or *@errp must be NULL.
1888 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1889 * - R: vcpu->logical_id
1891 * - W: vcpu->can_offline
1893 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1894 * - R: vcpu->logical_id
1897 * Written members remain unmodified on error.
1899 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
1905 dirpath = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
1907 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
1909 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
1911 static const char fn[] = "online";
1915 fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
1917 if (errno != ENOENT) {
1918 error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
1919 } else if (sys2vcpu) {
1920 vcpu->online = true;
1921 vcpu->can_offline = false;
1922 } else if (!vcpu->online) {
1923 error_setg(errp, "logical processor #%" PRId64 " can't be "
1924 "offlined", vcpu->logical_id);
1925 } /* otherwise pretend successful re-onlining */
1927 unsigned char status;
1929 res = pread(fd, &status, 1, 0);
1931 error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
1932 } else if (res == 0) {
1933 error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
1935 } else if (sys2vcpu) {
1936 vcpu->online = (status != '0');
1937 vcpu->can_offline = true;
1938 } else if (vcpu->online != (status != '0')) {
1939 status = '0' + vcpu->online;
1940 if (pwrite(fd, &status, 1, 0) == -1) {
1941 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
1944 } /* otherwise pretend successful re-(on|off)-lining */
1957 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1960 GuestLogicalProcessorList *head, **link;
1962 Error *local_err = NULL;
1967 sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);
1969 while (local_err == NULL && current < sc_max) {
1970 GuestLogicalProcessor *vcpu;
1971 GuestLogicalProcessorList *entry;
1973 vcpu = g_malloc0(sizeof *vcpu);
1974 vcpu->logical_id = current++;
1975 vcpu->has_can_offline = true; /* lolspeak ftw */
1976 transfer_vcpu(vcpu, true, &local_err);
1978 entry = g_malloc0(sizeof *entry);
1979 entry->value = vcpu;
1982 link = &entry->next;
1985 if (local_err == NULL) {
1986 /* there's no guest with zero VCPUs */
1987 g_assert(head != NULL);
1991 qapi_free_GuestLogicalProcessorList(head);
1992 error_propagate(errp, local_err);
1996 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1999 Error *local_err = NULL;
2002 while (vcpus != NULL) {
2003 transfer_vcpu(vcpus->value, false, &local_err);
2004 if (local_err != NULL) {
2008 vcpus = vcpus->next;
2011 if (local_err != NULL) {
2012 if (processed == 0) {
2013 error_propagate(errp, local_err);
2015 error_free(local_err);
2022 void qmp_guest_set_user_password(const char *username,
2023 const char *password,
2027 Error *local_err = NULL;
2028 char *passwd_path = NULL;
2031 int datafd[2] = { -1, -1 };
2032 char *rawpasswddata = NULL;
2033 size_t rawpasswdlen;
2034 char *chpasswddata = NULL;
2037 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
2038 if (!rawpasswddata) {
2041 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
2042 rawpasswddata[rawpasswdlen] = '\0';
2044 if (strchr(rawpasswddata, '\n')) {
2045 error_setg(errp, "forbidden characters in raw password");
2049 if (strchr(username, '\n') ||
2050 strchr(username, ':')) {
2051 error_setg(errp, "forbidden characters in username");
2055 chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
2056 chpasswdlen = strlen(chpasswddata);
2058 passwd_path = g_find_program_in_path("chpasswd");
2061 error_setg(errp, "cannot find 'passwd' program in PATH");
2065 if (pipe(datafd) < 0) {
2066 error_setg(errp, "cannot create pipe FDs");
2076 reopen_fd_to_null(1);
2077 reopen_fd_to_null(2);
2080 execle(passwd_path, "chpasswd", "-e", NULL, environ);
2082 execle(passwd_path, "chpasswd", NULL, environ);
2084 _exit(EXIT_FAILURE);
2085 } else if (pid < 0) {
2086 error_setg_errno(errp, errno, "failed to create child process");
2092 if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2093 error_setg_errno(errp, errno, "cannot write new account password");
2099 ga_wait_child(pid, &status, &local_err);
2101 error_propagate(errp, local_err);
2105 if (!WIFEXITED(status)) {
2106 error_setg(errp, "child process has terminated abnormally");
2110 if (WEXITSTATUS(status)) {
2111 error_setg(errp, "child process has failed to set user password");
2116 g_free(chpasswddata);
2117 g_free(rawpasswddata);
2118 g_free(passwd_path);
2119 if (datafd[0] != -1) {
2122 if (datafd[1] != -1) {
2127 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2128 int size, Error **errp)
2134 fd = openat(dirfd, pathname, O_RDONLY);
2136 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2140 res = pread(fd, buf, size, 0);
2142 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2143 } else if (res == 0) {
2144 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2149 static void ga_write_sysfs_file(int dirfd, const char *pathname,
2150 const char *buf, int size, Error **errp)
2155 fd = openat(dirfd, pathname, O_WRONLY);
2157 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2161 if (pwrite(fd, buf, size, 0) == -1) {
2162 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2168 /* Transfer online/offline status between @mem_blk and the guest system.
2170 * On input either @errp or *@errp must be NULL.
2172 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2173 * - R: mem_blk->phys_index
2174 * - W: mem_blk->online
2175 * - W: mem_blk->can_offline
2177 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2178 * - R: mem_blk->phys_index
2179 * - R: mem_blk->online
2180 *- R: mem_blk->can_offline
2181 * Written members remain unmodified on error.
2183 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2184 GuestMemoryBlockResponse *result,
2190 Error *local_err = NULL;
2196 error_setg(errp, "Internal error, 'result' should not be NULL");
2200 dp = opendir("/sys/devices/system/memory/");
2201 /* if there is no 'memory' directory in sysfs,
2202 * we think this VM does not support online/offline memory block,
2203 * any other solution?
2206 if (errno == ENOENT) {
2208 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2215 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2216 mem_blk->phys_index);
2217 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2220 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2222 if (errno == ENOENT) {
2223 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2226 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2234 status = g_malloc0(10);
2235 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2237 /* treat with sysfs file that not exist in old kernel */
2238 if (errno == ENOENT) {
2239 error_free(local_err);
2241 mem_blk->online = true;
2242 mem_blk->can_offline = false;
2243 } else if (!mem_blk->online) {
2245 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2249 error_propagate(errp, local_err);
2252 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2259 char removable = '0';
2261 mem_blk->online = (strncmp(status, "online", 6) == 0);
2263 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2265 /* if no 'removable' file, it doesn't support offline mem blk */
2266 if (errno == ENOENT) {
2267 error_free(local_err);
2268 mem_blk->can_offline = false;
2270 error_propagate(errp, local_err);
2273 mem_blk->can_offline = (removable != '0');
2276 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2277 const char *new_state = mem_blk->online ? "online" : "offline";
2279 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2282 error_free(local_err);
2284 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2288 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2289 result->has_error_code = false;
2290 } /* otherwise pretend successful re-(on|off)-lining */
2301 result->has_error_code = true;
2302 result->error_code = errno;
2306 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2308 GuestMemoryBlockList *head, **link;
2309 Error *local_err = NULL;
2316 dp = opendir("/sys/devices/system/memory/");
2318 /* it's ok if this happens to be a system that doesn't expose
2319 * memory blocks via sysfs, but otherwise we should report
2322 if (errno != ENOENT) {
2323 error_setg_errno(errp, errno, "Can't open directory"
2324 "\"/sys/devices/system/memory/\"");
2329 /* Note: the phys_index of memory block may be discontinuous,
2330 * this is because a memblk is the unit of the Sparse Memory design, which
2331 * allows discontinuous memory ranges (ex. NUMA), so here we should
2332 * traverse the memory block directory.
2334 while ((de = readdir(dp)) != NULL) {
2335 GuestMemoryBlock *mem_blk;
2336 GuestMemoryBlockList *entry;
2338 if ((strncmp(de->d_name, "memory", 6) != 0) ||
2339 !(de->d_type & DT_DIR)) {
2343 mem_blk = g_malloc0(sizeof *mem_blk);
2344 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2345 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2346 mem_blk->has_can_offline = true; /* lolspeak ftw */
2347 transfer_memory_block(mem_blk, true, NULL, &local_err);
2349 entry = g_malloc0(sizeof *entry);
2350 entry->value = mem_blk;
2353 link = &entry->next;
2357 if (local_err == NULL) {
2358 /* there's no guest with zero memory blocks */
2360 error_setg(errp, "guest reported zero memory blocks!");
2365 qapi_free_GuestMemoryBlockList(head);
2366 error_propagate(errp, local_err);
2370 GuestMemoryBlockResponseList *
2371 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2373 GuestMemoryBlockResponseList *head, **link;
2374 Error *local_err = NULL;
2379 while (mem_blks != NULL) {
2380 GuestMemoryBlockResponse *result;
2381 GuestMemoryBlockResponseList *entry;
2382 GuestMemoryBlock *current_mem_blk = mem_blks->value;
2384 result = g_malloc0(sizeof(*result));
2385 result->phys_index = current_mem_blk->phys_index;
2386 transfer_memory_block(current_mem_blk, false, result, &local_err);
2387 if (local_err) { /* should never happen */
2390 entry = g_malloc0(sizeof *entry);
2391 entry->value = result;
2394 link = &entry->next;
2395 mem_blks = mem_blks->next;
2400 qapi_free_GuestMemoryBlockResponseList(head);
2401 error_propagate(errp, local_err);
2405 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2407 Error *local_err = NULL;
2411 GuestMemoryBlockInfo *info;
2413 dirpath = g_strdup_printf("/sys/devices/system/memory/");
2414 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2416 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2422 buf = g_malloc0(20);
2423 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2427 error_propagate(errp, local_err);
2431 info = g_new0(GuestMemoryBlockInfo, 1);
2432 info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2439 #else /* defined(__linux__) */
2441 void qmp_guest_suspend_disk(Error **errp)
2443 error_setg(errp, QERR_UNSUPPORTED);
2446 void qmp_guest_suspend_ram(Error **errp)
2448 error_setg(errp, QERR_UNSUPPORTED);
2451 void qmp_guest_suspend_hybrid(Error **errp)
2453 error_setg(errp, QERR_UNSUPPORTED);
2456 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2458 error_setg(errp, QERR_UNSUPPORTED);
2462 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2464 error_setg(errp, QERR_UNSUPPORTED);
2468 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2470 error_setg(errp, QERR_UNSUPPORTED);
2474 void qmp_guest_set_user_password(const char *username,
2475 const char *password,
2479 error_setg(errp, QERR_UNSUPPORTED);
2482 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2484 error_setg(errp, QERR_UNSUPPORTED);
2488 GuestMemoryBlockResponseList *
2489 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2491 error_setg(errp, QERR_UNSUPPORTED);
2495 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2497 error_setg(errp, QERR_UNSUPPORTED);
2503 #if !defined(CONFIG_FSFREEZE)
2505 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
2507 error_setg(errp, QERR_UNSUPPORTED);
2511 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
2513 error_setg(errp, QERR_UNSUPPORTED);
2518 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
2520 error_setg(errp, QERR_UNSUPPORTED);
2525 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
2526 strList *mountpoints,
2529 error_setg(errp, QERR_UNSUPPORTED);
2534 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
2536 error_setg(errp, QERR_UNSUPPORTED);
2540 #endif /* CONFIG_FSFREEZE */
2542 #if !defined(CONFIG_FSTRIM)
2543 GuestFilesystemTrimResponse *
2544 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
2546 error_setg(errp, QERR_UNSUPPORTED);
2551 /* add unsupported commands to the blacklist */
2552 GList *ga_command_blacklist_init(GList *blacklist)
2554 #if !defined(__linux__)
2556 const char *list[] = {
2557 "guest-suspend-disk", "guest-suspend-ram",
2558 "guest-suspend-hybrid", "guest-network-get-interfaces",
2559 "guest-get-vcpus", "guest-set-vcpus",
2560 "guest-get-memory-blocks", "guest-set-memory-blocks",
2561 "guest-get-memory-block-size", NULL};
2562 char **p = (char **)list;
2565 blacklist = g_list_append(blacklist, g_strdup(*p++));
2570 #if !defined(CONFIG_FSFREEZE)
2572 const char *list[] = {
2573 "guest-get-fsinfo", "guest-fsfreeze-status",
2574 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2575 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL};
2576 char **p = (char **)list;
2579 blacklist = g_list_append(blacklist, g_strdup(*p++));
2584 #if !defined(CONFIG_FSTRIM)
2585 blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
2591 /* register init/cleanup routines for stateful command groups */
2592 void ga_command_state_init(GAState *s, GACommandState *cs)
2594 #if defined(CONFIG_FSFREEZE)
2595 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2601 #define QGA_MICRO_SECOND_TO_SECOND 1000000
2603 static double ga_get_login_time(struct utmpx *user_info)
2605 double seconds = (double)user_info->ut_tv.tv_sec;
2606 double useconds = (double)user_info->ut_tv.tv_usec;
2607 useconds /= QGA_MICRO_SECOND_TO_SECOND;
2608 return seconds + useconds;
2611 GuestUserList *qmp_guest_get_users(Error **err)
2613 GHashTable *cache = NULL;
2614 GuestUserList *head = NULL, *cur_item = NULL;
2615 struct utmpx *user_info = NULL;
2616 gpointer value = NULL;
2617 GuestUser *user = NULL;
2618 GuestUserList *item = NULL;
2619 double login_time = 0;
2621 cache = g_hash_table_new(g_str_hash, g_str_equal);
2625 user_info = getutxent();
2626 if (user_info == NULL) {
2628 } else if (user_info->ut_type != USER_PROCESS) {
2630 } else if (g_hash_table_contains(cache, user_info->ut_user)) {
2631 value = g_hash_table_lookup(cache, user_info->ut_user);
2632 user = (GuestUser *)value;
2633 login_time = ga_get_login_time(user_info);
2634 /* We're ensuring the earliest login time to be sent */
2635 if (login_time < user->login_time) {
2636 user->login_time = login_time;
2641 item = g_new0(GuestUserList, 1);
2642 item->value = g_new0(GuestUser, 1);
2643 item->value->user = g_strdup(user_info->ut_user);
2644 item->value->login_time = ga_get_login_time(user_info);
2646 g_hash_table_insert(cache, item->value->user, item->value);
2649 head = cur_item = item;
2651 cur_item->next = item;
2656 g_hash_table_destroy(cache);
2662 GuestUserList *qmp_guest_get_users(Error **errp)
2664 error_setg(errp, QERR_UNSUPPORTED);
2670 /* Replace escaped special characters with theire real values. The replacement
2671 * is done in place -- returned value is in the original string.
2673 static void ga_osrelease_replace_special(gchar *value)
2675 gchar *p, *p2, quote;
2677 /* Trim the string at first space or semicolon if it is not enclosed in
2678 * single or double quotes. */
2679 if ((value[0] != '"') || (value[0] == '\'')) {
2680 p = strchr(value, ' ');
2684 p = strchr(value, ';');
2705 /* Keep literal backslash followed by whatever is there */
2709 } else if (*p == quote) {
2717 static GKeyFile *ga_parse_osrelease(const char *fname)
2719 gchar *content = NULL;
2720 gchar *content2 = NULL;
2722 GKeyFile *keys = g_key_file_new();
2723 const char *group = "[os-release]\n";
2725 if (!g_file_get_contents(fname, &content, NULL, &err)) {
2726 slog("failed to read '%s', error: %s", fname, err->message);
2730 if (!g_utf8_validate(content, -1, NULL)) {
2731 slog("file is not utf-8 encoded: %s", fname);
2734 content2 = g_strdup_printf("%s%s", group, content);
2736 if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
2738 slog("failed to parse file '%s', error: %s", fname, err->message);
2750 g_key_file_free(keys);
2754 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2756 GuestOSInfo *info = NULL;
2757 struct utsname kinfo;
2758 GKeyFile *osrelease = NULL;
2759 const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
2761 info = g_new0(GuestOSInfo, 1);
2763 if (uname(&kinfo) != 0) {
2764 error_setg_errno(errp, errno, "uname failed");
2766 info->has_kernel_version = true;
2767 info->kernel_version = g_strdup(kinfo.version);
2768 info->has_kernel_release = true;
2769 info->kernel_release = g_strdup(kinfo.release);
2770 info->has_machine = true;
2771 info->machine = g_strdup(kinfo.machine);
2774 if (qga_os_release != NULL) {
2775 osrelease = ga_parse_osrelease(qga_os_release);
2777 osrelease = ga_parse_osrelease("/etc/os-release");
2778 if (osrelease == NULL) {
2779 osrelease = ga_parse_osrelease("/usr/lib/os-release");
2783 if (osrelease != NULL) {
2786 #define GET_FIELD(field, osfield) do { \
2787 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
2788 if (value != NULL) { \
2789 ga_osrelease_replace_special(value); \
2790 info->has_ ## field = true; \
2791 info->field = value; \
2794 GET_FIELD(id, "ID");
2795 GET_FIELD(name, "NAME");
2796 GET_FIELD(pretty_name, "PRETTY_NAME");
2797 GET_FIELD(version, "VERSION");
2798 GET_FIELD(version_id, "VERSION_ID");
2799 GET_FIELD(variant, "VARIANT");
2800 GET_FIELD(variant_id, "VARIANT_ID");
2803 g_key_file_free(osrelease);