backup: Remove nodes from job in .clean()
[qemu/ar7.git] / qga / commands-posix.c
blob3f18df1bb6d1c9011ec0f7104ddd122ccc8ef3fb
1 /*
2 * QEMU Guest Agent POSIX-specific command implementations
4 * Copyright IBM Corp. 2011
6 * Authors:
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Michal Privoznik <mprivozn@redhat.com>
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>
17 #include <sys/wait.h>
18 #include <dirent.h>
19 #include "qemu-common.h"
20 #include "guest-agent-core.h"
21 #include "qga-qapi-commands.h"
22 #include "qapi/error.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/queue.h"
25 #include "qemu/host-utils.h"
26 #include "qemu/sockets.h"
27 #include "qemu/base64.h"
28 #include "qemu/cutils.h"
29 #include "commands-common.h"
31 #ifdef HAVE_UTMPX
32 #include <utmpx.h>
33 #endif
35 #ifndef CONFIG_HAS_ENVIRON
36 #ifdef __APPLE__
37 #include <crt_externs.h>
38 #define environ (*_NSGetEnviron())
39 #else
40 extern char **environ;
41 #endif
42 #endif
44 #if defined(__linux__)
45 #include <mntent.h>
46 #include <linux/fs.h>
47 #include <ifaddrs.h>
48 #include <arpa/inet.h>
49 #include <sys/socket.h>
50 #include <net/if.h>
51 #include <sys/statvfs.h>
53 #ifdef CONFIG_LIBUDEV
54 #include <libudev.h>
55 #endif
57 #ifdef FIFREEZE
58 #define CONFIG_FSFREEZE
59 #endif
60 #ifdef FITRIM
61 #define CONFIG_FSTRIM
62 #endif
63 #endif
65 static void ga_wait_child(pid_t pid, int *status, Error **errp)
67 pid_t rpid;
69 *status = 0;
71 do {
72 rpid = waitpid(pid, status, 0);
73 } while (rpid == -1 && errno == EINTR);
75 if (rpid == -1) {
76 error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
77 pid);
78 return;
81 g_assert(rpid == pid);
84 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
86 const char *shutdown_flag;
87 Error *local_err = NULL;
88 pid_t pid;
89 int status;
91 slog("guest-shutdown called, mode: %s", mode);
92 if (!has_mode || strcmp(mode, "powerdown") == 0) {
93 shutdown_flag = "-P";
94 } else if (strcmp(mode, "halt") == 0) {
95 shutdown_flag = "-H";
96 } else if (strcmp(mode, "reboot") == 0) {
97 shutdown_flag = "-r";
98 } else {
99 error_setg(errp,
100 "mode is invalid (valid values are: halt|powerdown|reboot");
101 return;
104 pid = fork();
105 if (pid == 0) {
106 /* child, start the shutdown */
107 setsid();
108 reopen_fd_to_null(0);
109 reopen_fd_to_null(1);
110 reopen_fd_to_null(2);
112 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
113 "hypervisor initiated shutdown", (char*)NULL, environ);
114 _exit(EXIT_FAILURE);
115 } else if (pid < 0) {
116 error_setg_errno(errp, errno, "failed to create child process");
117 return;
120 ga_wait_child(pid, &status, &local_err);
121 if (local_err) {
122 error_propagate(errp, local_err);
123 return;
126 if (!WIFEXITED(status)) {
127 error_setg(errp, "child process has terminated abnormally");
128 return;
131 if (WEXITSTATUS(status)) {
132 error_setg(errp, "child process has failed to shutdown");
133 return;
136 /* succeeded */
139 int64_t qmp_guest_get_time(Error **errp)
141 int ret;
142 qemu_timeval tq;
144 ret = qemu_gettimeofday(&tq);
145 if (ret < 0) {
146 error_setg_errno(errp, errno, "Failed to get time");
147 return -1;
150 return tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
153 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
155 int ret;
156 int status;
157 pid_t pid;
158 Error *local_err = NULL;
159 struct timeval tv;
160 static const char hwclock_path[] = "/sbin/hwclock";
161 static int hwclock_available = -1;
163 if (hwclock_available < 0) {
164 hwclock_available = (access(hwclock_path, X_OK) == 0);
167 if (!hwclock_available) {
168 error_setg(errp, QERR_UNSUPPORTED);
169 return;
172 /* If user has passed a time, validate and set it. */
173 if (has_time) {
174 GDate date = { 0, };
176 /* year-2038 will overflow in case time_t is 32bit */
177 if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
178 error_setg(errp, "Time %" PRId64 " is too large", time_ns);
179 return;
182 tv.tv_sec = time_ns / 1000000000;
183 tv.tv_usec = (time_ns % 1000000000) / 1000;
184 g_date_set_time_t(&date, tv.tv_sec);
185 if (date.year < 1970 || date.year >= 2070) {
186 error_setg_errno(errp, errno, "Invalid time");
187 return;
190 ret = settimeofday(&tv, NULL);
191 if (ret < 0) {
192 error_setg_errno(errp, errno, "Failed to set time to guest");
193 return;
197 /* Now, if user has passed a time to set and the system time is set, we
198 * just need to synchronize the hardware clock. However, if no time was
199 * passed, user is requesting the opposite: set the system time from the
200 * hardware clock (RTC). */
201 pid = fork();
202 if (pid == 0) {
203 setsid();
204 reopen_fd_to_null(0);
205 reopen_fd_to_null(1);
206 reopen_fd_to_null(2);
208 /* Use '/sbin/hwclock -w' to set RTC from the system time,
209 * or '/sbin/hwclock -s' to set the system time from RTC. */
210 execle(hwclock_path, "hwclock", has_time ? "-w" : "-s",
211 NULL, environ);
212 _exit(EXIT_FAILURE);
213 } else if (pid < 0) {
214 error_setg_errno(errp, errno, "failed to create child process");
215 return;
218 ga_wait_child(pid, &status, &local_err);
219 if (local_err) {
220 error_propagate(errp, local_err);
221 return;
224 if (!WIFEXITED(status)) {
225 error_setg(errp, "child process has terminated abnormally");
226 return;
229 if (WEXITSTATUS(status)) {
230 error_setg(errp, "hwclock failed to set hardware clock to system time");
231 return;
235 typedef enum {
236 RW_STATE_NEW,
237 RW_STATE_READING,
238 RW_STATE_WRITING,
239 } RwState;
241 struct GuestFileHandle {
242 uint64_t id;
243 FILE *fh;
244 RwState state;
245 QTAILQ_ENTRY(GuestFileHandle) next;
248 static struct {
249 QTAILQ_HEAD(, GuestFileHandle) filehandles;
250 } guest_file_state = {
251 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
254 static int64_t guest_file_handle_add(FILE *fh, Error **errp)
256 GuestFileHandle *gfh;
257 int64_t handle;
259 handle = ga_get_fd_handle(ga_state, errp);
260 if (handle < 0) {
261 return -1;
264 gfh = g_new0(GuestFileHandle, 1);
265 gfh->id = handle;
266 gfh->fh = fh;
267 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
269 return handle;
272 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
274 GuestFileHandle *gfh;
276 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
278 if (gfh->id == id) {
279 return gfh;
283 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
284 return NULL;
287 typedef const char * const ccpc;
289 #ifndef O_BINARY
290 #define O_BINARY 0
291 #endif
293 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
294 static const struct {
295 ccpc *forms;
296 int oflag_base;
297 } guest_file_open_modes[] = {
298 { (ccpc[]){ "r", NULL }, O_RDONLY },
299 { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
300 { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
301 { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
302 { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
303 { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
304 { (ccpc[]){ "r+", NULL }, O_RDWR },
305 { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
306 { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
307 { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
308 { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
309 { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
312 static int
313 find_open_flag(const char *mode_str, Error **errp)
315 unsigned mode;
317 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
318 ccpc *form;
320 form = guest_file_open_modes[mode].forms;
321 while (*form != NULL && strcmp(*form, mode_str) != 0) {
322 ++form;
324 if (*form != NULL) {
325 break;
329 if (mode == ARRAY_SIZE(guest_file_open_modes)) {
330 error_setg(errp, "invalid file open mode '%s'", mode_str);
331 return -1;
333 return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
336 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
337 S_IRGRP | S_IWGRP | \
338 S_IROTH | S_IWOTH)
340 static FILE *
341 safe_open_or_create(const char *path, const char *mode, Error **errp)
343 Error *local_err = NULL;
344 int oflag;
346 oflag = find_open_flag(mode, &local_err);
347 if (local_err == NULL) {
348 int fd;
350 /* If the caller wants / allows creation of a new file, we implement it
351 * with a two step process: open() + (open() / fchmod()).
353 * First we insist on creating the file exclusively as a new file. If
354 * that succeeds, we're free to set any file-mode bits on it. (The
355 * motivation is that we want to set those file-mode bits independently
356 * of the current umask.)
358 * If the exclusive creation fails because the file already exists
359 * (EEXIST is not possible for any other reason), we just attempt to
360 * open the file, but in this case we won't be allowed to change the
361 * file-mode bits on the preexistent file.
363 * The pathname should never disappear between the two open()s in
364 * practice. If it happens, then someone very likely tried to race us.
365 * In this case just go ahead and report the ENOENT from the second
366 * open() to the caller.
368 * If the caller wants to open a preexistent file, then the first
369 * open() is decisive and its third argument is ignored, and the second
370 * open() and the fchmod() are never called.
372 fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
373 if (fd == -1 && errno == EEXIST) {
374 oflag &= ~(unsigned)O_CREAT;
375 fd = open(path, oflag);
378 if (fd == -1) {
379 error_setg_errno(&local_err, errno, "failed to open file '%s' "
380 "(mode: '%s')", path, mode);
381 } else {
382 qemu_set_cloexec(fd);
384 if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
385 error_setg_errno(&local_err, errno, "failed to set permission "
386 "0%03o on new file '%s' (mode: '%s')",
387 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
388 } else {
389 FILE *f;
391 f = fdopen(fd, mode);
392 if (f == NULL) {
393 error_setg_errno(&local_err, errno, "failed to associate "
394 "stdio stream with file descriptor %d, "
395 "file '%s' (mode: '%s')", fd, path, mode);
396 } else {
397 return f;
401 close(fd);
402 if (oflag & O_CREAT) {
403 unlink(path);
408 error_propagate(errp, local_err);
409 return NULL;
412 int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
413 Error **errp)
415 FILE *fh;
416 Error *local_err = NULL;
417 int64_t handle;
419 if (!has_mode) {
420 mode = "r";
422 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
423 fh = safe_open_or_create(path, mode, &local_err);
424 if (local_err != NULL) {
425 error_propagate(errp, local_err);
426 return -1;
429 /* set fd non-blocking to avoid common use cases (like reading from a
430 * named pipe) from hanging the agent
432 qemu_set_nonblock(fileno(fh));
434 handle = guest_file_handle_add(fh, errp);
435 if (handle < 0) {
436 fclose(fh);
437 return -1;
440 slog("guest-file-open, handle: %" PRId64, handle);
441 return handle;
444 void qmp_guest_file_close(int64_t handle, Error **errp)
446 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
447 int ret;
449 slog("guest-file-close called, handle: %" PRId64, handle);
450 if (!gfh) {
451 return;
454 ret = fclose(gfh->fh);
455 if (ret == EOF) {
456 error_setg_errno(errp, errno, "failed to close handle");
457 return;
460 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
461 g_free(gfh);
464 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
465 int64_t count, Error **errp)
467 GuestFileRead *read_data = NULL;
468 guchar *buf;
469 FILE *fh = gfh->fh;
470 size_t read_count;
472 /* explicitly flush when switching from writing to reading */
473 if (gfh->state == RW_STATE_WRITING) {
474 int ret = fflush(fh);
475 if (ret == EOF) {
476 error_setg_errno(errp, errno, "failed to flush file");
477 return NULL;
479 gfh->state = RW_STATE_NEW;
482 buf = g_malloc0(count+1);
483 read_count = fread(buf, 1, count, fh);
484 if (ferror(fh)) {
485 error_setg_errno(errp, errno, "failed to read file");
486 } else {
487 buf[read_count] = 0;
488 read_data = g_new0(GuestFileRead, 1);
489 read_data->count = read_count;
490 read_data->eof = feof(fh);
491 if (read_count) {
492 read_data->buf_b64 = g_base64_encode(buf, read_count);
494 gfh->state = RW_STATE_READING;
496 g_free(buf);
497 clearerr(fh);
499 return read_data;
502 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
503 bool has_count, int64_t count,
504 Error **errp)
506 GuestFileWrite *write_data = NULL;
507 guchar *buf;
508 gsize buf_len;
509 int write_count;
510 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
511 FILE *fh;
513 if (!gfh) {
514 return NULL;
517 fh = gfh->fh;
519 if (gfh->state == RW_STATE_READING) {
520 int ret = fseek(fh, 0, SEEK_CUR);
521 if (ret == -1) {
522 error_setg_errno(errp, errno, "failed to seek file");
523 return NULL;
525 gfh->state = RW_STATE_NEW;
528 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
529 if (!buf) {
530 return NULL;
533 if (!has_count) {
534 count = buf_len;
535 } else if (count < 0 || count > buf_len) {
536 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
537 count);
538 g_free(buf);
539 return NULL;
542 write_count = fwrite(buf, 1, count, fh);
543 if (ferror(fh)) {
544 error_setg_errno(errp, errno, "failed to write to file");
545 slog("guest-file-write failed, handle: %" PRId64, handle);
546 } else {
547 write_data = g_new0(GuestFileWrite, 1);
548 write_data->count = write_count;
549 write_data->eof = feof(fh);
550 gfh->state = RW_STATE_WRITING;
552 g_free(buf);
553 clearerr(fh);
555 return write_data;
558 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
559 GuestFileWhence *whence_code,
560 Error **errp)
562 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
563 GuestFileSeek *seek_data = NULL;
564 FILE *fh;
565 int ret;
566 int whence;
567 Error *err = NULL;
569 if (!gfh) {
570 return NULL;
573 /* We stupidly exposed 'whence':'int' in our qapi */
574 whence = ga_parse_whence(whence_code, &err);
575 if (err) {
576 error_propagate(errp, err);
577 return NULL;
580 fh = gfh->fh;
581 ret = fseek(fh, offset, whence);
582 if (ret == -1) {
583 error_setg_errno(errp, errno, "failed to seek file");
584 if (errno == ESPIPE) {
585 /* file is non-seekable, stdio shouldn't be buffering anyways */
586 gfh->state = RW_STATE_NEW;
588 } else {
589 seek_data = g_new0(GuestFileSeek, 1);
590 seek_data->position = ftell(fh);
591 seek_data->eof = feof(fh);
592 gfh->state = RW_STATE_NEW;
594 clearerr(fh);
596 return seek_data;
599 void qmp_guest_file_flush(int64_t handle, Error **errp)
601 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
602 FILE *fh;
603 int ret;
605 if (!gfh) {
606 return;
609 fh = gfh->fh;
610 ret = fflush(fh);
611 if (ret == EOF) {
612 error_setg_errno(errp, errno, "failed to flush file");
613 } else {
614 gfh->state = RW_STATE_NEW;
618 /* linux-specific implementations. avoid this if at all possible. */
619 #if defined(__linux__)
621 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
622 typedef struct FsMount {
623 char *dirname;
624 char *devtype;
625 unsigned int devmajor, devminor;
626 QTAILQ_ENTRY(FsMount) next;
627 } FsMount;
629 typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
631 static void free_fs_mount_list(FsMountList *mounts)
633 FsMount *mount, *temp;
635 if (!mounts) {
636 return;
639 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
640 QTAILQ_REMOVE(mounts, mount, next);
641 g_free(mount->dirname);
642 g_free(mount->devtype);
643 g_free(mount);
647 static int dev_major_minor(const char *devpath,
648 unsigned int *devmajor, unsigned int *devminor)
650 struct stat st;
652 *devmajor = 0;
653 *devminor = 0;
655 if (stat(devpath, &st) < 0) {
656 slog("failed to stat device file '%s': %s", devpath, strerror(errno));
657 return -1;
659 if (S_ISDIR(st.st_mode)) {
660 /* It is bind mount */
661 return -2;
663 if (S_ISBLK(st.st_mode)) {
664 *devmajor = major(st.st_rdev);
665 *devminor = minor(st.st_rdev);
666 return 0;
668 return -1;
672 * Walk the mount table and build a list of local file systems
674 static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
676 struct mntent *ment;
677 FsMount *mount;
678 char const *mtab = "/proc/self/mounts";
679 FILE *fp;
680 unsigned int devmajor, devminor;
682 fp = setmntent(mtab, "r");
683 if (!fp) {
684 error_setg(errp, "failed to open mtab file: '%s'", mtab);
685 return;
688 while ((ment = getmntent(fp))) {
690 * An entry which device name doesn't start with a '/' is
691 * either a dummy file system or a network file system.
692 * Add special handling for smbfs and cifs as is done by
693 * coreutils as well.
695 if ((ment->mnt_fsname[0] != '/') ||
696 (strcmp(ment->mnt_type, "smbfs") == 0) ||
697 (strcmp(ment->mnt_type, "cifs") == 0)) {
698 continue;
700 if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
701 /* Skip bind mounts */
702 continue;
705 mount = g_new0(FsMount, 1);
706 mount->dirname = g_strdup(ment->mnt_dir);
707 mount->devtype = g_strdup(ment->mnt_type);
708 mount->devmajor = devmajor;
709 mount->devminor = devminor;
711 QTAILQ_INSERT_TAIL(mounts, mount, next);
714 endmntent(fp);
717 static void decode_mntname(char *name, int len)
719 int i, j = 0;
720 for (i = 0; i <= len; i++) {
721 if (name[i] != '\\') {
722 name[j++] = name[i];
723 } else if (name[i + 1] == '\\') {
724 name[j++] = '\\';
725 i++;
726 } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
727 name[i + 2] >= '0' && name[i + 2] <= '7' &&
728 name[i + 3] >= '0' && name[i + 3] <= '7') {
729 name[j++] = (name[i + 1] - '0') * 64 +
730 (name[i + 2] - '0') * 8 +
731 (name[i + 3] - '0');
732 i += 3;
733 } else {
734 name[j++] = name[i];
739 static void build_fs_mount_list(FsMountList *mounts, Error **errp)
741 FsMount *mount;
742 char const *mountinfo = "/proc/self/mountinfo";
743 FILE *fp;
744 char *line = NULL, *dash;
745 size_t n;
746 char check;
747 unsigned int devmajor, devminor;
748 int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
750 fp = fopen(mountinfo, "r");
751 if (!fp) {
752 build_fs_mount_list_from_mtab(mounts, errp);
753 return;
756 while (getline(&line, &n, fp) != -1) {
757 ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
758 &devmajor, &devminor, &dir_s, &dir_e, &check);
759 if (ret < 3) {
760 continue;
762 dash = strstr(line + dir_e, " - ");
763 if (!dash) {
764 continue;
766 ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
767 &type_s, &type_e, &dev_s, &dev_e, &check);
768 if (ret < 1) {
769 continue;
771 line[dir_e] = 0;
772 dash[type_e] = 0;
773 dash[dev_e] = 0;
774 decode_mntname(line + dir_s, dir_e - dir_s);
775 decode_mntname(dash + dev_s, dev_e - dev_s);
776 if (devmajor == 0) {
777 /* btrfs reports major number = 0 */
778 if (strcmp("btrfs", dash + type_s) != 0 ||
779 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
780 continue;
784 mount = g_new0(FsMount, 1);
785 mount->dirname = g_strdup(line + dir_s);
786 mount->devtype = g_strdup(dash + type_s);
787 mount->devmajor = devmajor;
788 mount->devminor = devminor;
790 QTAILQ_INSERT_TAIL(mounts, mount, next);
792 free(line);
794 fclose(fp);
796 #endif
798 #if defined(CONFIG_FSFREEZE)
800 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
802 char *path;
803 char *dpath;
804 char *driver = NULL;
805 char buf[PATH_MAX];
806 ssize_t len;
808 path = g_strndup(syspath, pathlen);
809 dpath = g_strdup_printf("%s/driver", path);
810 len = readlink(dpath, buf, sizeof(buf) - 1);
811 if (len != -1) {
812 buf[len] = 0;
813 driver = g_path_get_basename(buf);
815 g_free(dpath);
816 g_free(path);
817 return driver;
820 static int compare_uint(const void *_a, const void *_b)
822 unsigned int a = *(unsigned int *)_a;
823 unsigned int b = *(unsigned int *)_b;
825 return a < b ? -1 : a > b ? 1 : 0;
828 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
829 static int build_hosts(char const *syspath, char const *host, bool ata,
830 unsigned int *hosts, int hosts_max, Error **errp)
832 char *path;
833 DIR *dir;
834 struct dirent *entry;
835 int i = 0;
837 path = g_strndup(syspath, host - syspath);
838 dir = opendir(path);
839 if (!dir) {
840 error_setg_errno(errp, errno, "opendir(\"%s\")", path);
841 g_free(path);
842 return -1;
845 while (i < hosts_max) {
846 entry = readdir(dir);
847 if (!entry) {
848 break;
850 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
851 ++i;
852 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
853 ++i;
857 qsort(hosts, i, sizeof(hosts[0]), compare_uint);
859 g_free(path);
860 closedir(dir);
861 return i;
865 * Store disk device info for devices on the PCI bus.
866 * Returns true if information has been stored, or false for failure.
868 static bool build_guest_fsinfo_for_pci_dev(char const *syspath,
869 GuestDiskAddress *disk,
870 Error **errp)
872 unsigned int pci[4], host, hosts[8], tgt[3];
873 int i, nhosts = 0, pcilen;
874 GuestPCIAddress *pciaddr = disk->pci_controller;
875 bool has_ata = false, has_host = false, has_tgt = false;
876 char *p, *q, *driver = NULL;
877 bool ret = false;
879 p = strstr(syspath, "/devices/pci");
880 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
881 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
882 g_debug("only pci device is supported: sysfs path '%s'", syspath);
883 return false;
886 p += 12 + pcilen;
887 while (true) {
888 driver = get_pci_driver(syspath, p - syspath, errp);
889 if (driver && (g_str_equal(driver, "ata_piix") ||
890 g_str_equal(driver, "sym53c8xx") ||
891 g_str_equal(driver, "virtio-pci") ||
892 g_str_equal(driver, "ahci"))) {
893 break;
896 g_free(driver);
897 if (sscanf(p, "/%x:%x:%x.%x%n",
898 pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
899 p += pcilen;
900 continue;
903 g_debug("unsupported driver or sysfs path '%s'", syspath);
904 return false;
907 p = strstr(syspath, "/target");
908 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
909 tgt, tgt + 1, tgt + 2) == 3) {
910 has_tgt = true;
913 p = strstr(syspath, "/ata");
914 if (p) {
915 q = p + 4;
916 has_ata = true;
917 } else {
918 p = strstr(syspath, "/host");
919 q = p + 5;
921 if (p && sscanf(q, "%u", &host) == 1) {
922 has_host = true;
923 nhosts = build_hosts(syspath, p, has_ata, hosts,
924 ARRAY_SIZE(hosts), errp);
925 if (nhosts < 0) {
926 goto cleanup;
930 pciaddr->domain = pci[0];
931 pciaddr->bus = pci[1];
932 pciaddr->slot = pci[2];
933 pciaddr->function = pci[3];
935 if (strcmp(driver, "ata_piix") == 0) {
936 /* a host per ide bus, target*:0:<unit>:0 */
937 if (!has_host || !has_tgt) {
938 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
939 goto cleanup;
941 for (i = 0; i < nhosts; i++) {
942 if (host == hosts[i]) {
943 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
944 disk->bus = i;
945 disk->unit = tgt[1];
946 break;
949 if (i >= nhosts) {
950 g_debug("no host for '%s' (driver '%s')", syspath, driver);
951 goto cleanup;
953 } else if (strcmp(driver, "sym53c8xx") == 0) {
954 /* scsi(LSI Logic): target*:0:<unit>:0 */
955 if (!has_tgt) {
956 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
957 goto cleanup;
959 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
960 disk->unit = tgt[1];
961 } else if (strcmp(driver, "virtio-pci") == 0) {
962 if (has_tgt) {
963 /* virtio-scsi: target*:0:0:<unit> */
964 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
965 disk->unit = tgt[2];
966 } else {
967 /* virtio-blk: 1 disk per 1 device */
968 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
970 } else if (strcmp(driver, "ahci") == 0) {
971 /* ahci: 1 host per 1 unit */
972 if (!has_host || !has_tgt) {
973 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
974 goto cleanup;
976 for (i = 0; i < nhosts; i++) {
977 if (host == hosts[i]) {
978 disk->unit = i;
979 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
980 break;
983 if (i >= nhosts) {
984 g_debug("no host for '%s' (driver '%s')", syspath, driver);
985 goto cleanup;
987 } else {
988 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
989 goto cleanup;
992 ret = true;
994 cleanup:
995 g_free(driver);
996 return ret;
1000 * Store disk device info for non-PCI virtio devices (for example s390x
1001 * channel I/O devices). Returns true if information has been stored, or
1002 * false for failure.
1004 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath,
1005 GuestDiskAddress *disk,
1006 Error **errp)
1008 unsigned int tgt[3];
1009 char *p;
1011 if (!strstr(syspath, "/virtio") || !strstr(syspath, "/block")) {
1012 g_debug("Unsupported virtio device '%s'", syspath);
1013 return false;
1016 p = strstr(syspath, "/target");
1017 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1018 &tgt[0], &tgt[1], &tgt[2]) == 3) {
1019 /* virtio-scsi: target*:0:<target>:<unit> */
1020 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
1021 disk->bus = tgt[0];
1022 disk->target = tgt[1];
1023 disk->unit = tgt[2];
1024 } else {
1025 /* virtio-blk: 1 disk per 1 device */
1026 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
1029 return true;
1033 * Store disk device info for CCW devices (s390x channel I/O devices).
1034 * Returns true if information has been stored, or false for failure.
1036 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath,
1037 GuestDiskAddress *disk,
1038 Error **errp)
1040 unsigned int cssid, ssid, subchno, devno;
1041 char *p;
1043 p = strstr(syspath, "/devices/css");
1044 if (!p || sscanf(p + 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1045 &cssid, &ssid, &subchno, &devno) < 4) {
1046 g_debug("could not parse ccw device sysfs path: %s", syspath);
1047 return false;
1050 disk->has_ccw_address = true;
1051 disk->ccw_address = g_new0(GuestCCWAddress, 1);
1052 disk->ccw_address->cssid = cssid;
1053 disk->ccw_address->ssid = ssid;
1054 disk->ccw_address->subchno = subchno;
1055 disk->ccw_address->devno = devno;
1057 if (strstr(p, "/virtio")) {
1058 build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
1061 return true;
1064 /* Store disk device info specified by @sysfs into @fs */
1065 static void build_guest_fsinfo_for_real_device(char const *syspath,
1066 GuestFilesystemInfo *fs,
1067 Error **errp)
1069 GuestDiskAddress *disk;
1070 GuestPCIAddress *pciaddr;
1071 bool has_hwinf;
1072 #ifdef CONFIG_LIBUDEV
1073 struct udev *udev = NULL;
1074 struct udev_device *udevice = NULL;
1075 #endif
1077 pciaddr = g_new0(GuestPCIAddress, 1);
1078 pciaddr->domain = -1; /* -1 means field is invalid */
1079 pciaddr->bus = -1;
1080 pciaddr->slot = -1;
1081 pciaddr->function = -1;
1083 disk = g_new0(GuestDiskAddress, 1);
1084 disk->pci_controller = pciaddr;
1085 disk->bus_type = GUEST_DISK_BUS_TYPE_UNKNOWN;
1087 #ifdef CONFIG_LIBUDEV
1088 udev = udev_new();
1089 udevice = udev_device_new_from_syspath(udev, syspath);
1090 if (udev == NULL || udevice == NULL) {
1091 g_debug("failed to query udev");
1092 } else {
1093 const char *devnode, *serial;
1094 devnode = udev_device_get_devnode(udevice);
1095 if (devnode != NULL) {
1096 disk->dev = g_strdup(devnode);
1097 disk->has_dev = true;
1099 serial = udev_device_get_property_value(udevice, "ID_SERIAL");
1100 if (serial != NULL && *serial != 0) {
1101 disk->serial = g_strdup(serial);
1102 disk->has_serial = true;
1106 udev_unref(udev);
1107 udev_device_unref(udevice);
1108 #endif
1110 if (strstr(syspath, "/devices/pci")) {
1111 has_hwinf = build_guest_fsinfo_for_pci_dev(syspath, disk, errp);
1112 } else if (strstr(syspath, "/devices/css")) {
1113 has_hwinf = build_guest_fsinfo_for_ccw_dev(syspath, disk, errp);
1114 } else if (strstr(syspath, "/virtio")) {
1115 has_hwinf = build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
1116 } else {
1117 g_debug("Unsupported device type for '%s'", syspath);
1118 has_hwinf = false;
1121 if (has_hwinf || disk->has_dev || disk->has_serial) {
1122 QAPI_LIST_PREPEND(fs->disk, disk);
1123 } else {
1124 qapi_free_GuestDiskAddress(disk);
1128 static void build_guest_fsinfo_for_device(char const *devpath,
1129 GuestFilesystemInfo *fs,
1130 Error **errp);
1132 /* Store a list of slave devices of virtual volume specified by @syspath into
1133 * @fs */
1134 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
1135 GuestFilesystemInfo *fs,
1136 Error **errp)
1138 Error *err = NULL;
1139 DIR *dir;
1140 char *dirpath;
1141 struct dirent *entry;
1143 dirpath = g_strdup_printf("%s/slaves", syspath);
1144 dir = opendir(dirpath);
1145 if (!dir) {
1146 if (errno != ENOENT) {
1147 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
1149 g_free(dirpath);
1150 return;
1153 for (;;) {
1154 errno = 0;
1155 entry = readdir(dir);
1156 if (entry == NULL) {
1157 if (errno) {
1158 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1160 break;
1163 if (entry->d_type == DT_LNK) {
1164 char *path;
1166 g_debug(" slave device '%s'", entry->d_name);
1167 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1168 build_guest_fsinfo_for_device(path, fs, &err);
1169 g_free(path);
1171 if (err) {
1172 error_propagate(errp, err);
1173 break;
1178 g_free(dirpath);
1179 closedir(dir);
1182 static bool is_disk_virtual(const char *devpath, Error **errp)
1184 g_autofree char *syspath = realpath(devpath, NULL);
1186 if (!syspath) {
1187 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1188 return false;
1190 return strstr(syspath, "/devices/virtual/block/") != NULL;
1193 /* Dispatch to functions for virtual/real device */
1194 static void build_guest_fsinfo_for_device(char const *devpath,
1195 GuestFilesystemInfo *fs,
1196 Error **errp)
1198 ERRP_GUARD();
1199 g_autofree char *syspath = NULL;
1200 bool is_virtual = false;
1202 syspath = realpath(devpath, NULL);
1203 if (!syspath) {
1204 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1205 return;
1208 if (!fs->name) {
1209 fs->name = g_path_get_basename(syspath);
1212 g_debug(" parse sysfs path '%s'", syspath);
1213 is_virtual = is_disk_virtual(syspath, errp);
1214 if (*errp != NULL) {
1215 return;
1217 if (is_virtual) {
1218 build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1219 } else {
1220 build_guest_fsinfo_for_real_device(syspath, fs, errp);
1224 #ifdef CONFIG_LIBUDEV
1227 * Wrapper around build_guest_fsinfo_for_device() for getting just
1228 * the disk address.
1230 static GuestDiskAddress *get_disk_address(const char *syspath, Error **errp)
1232 g_autoptr(GuestFilesystemInfo) fs = NULL;
1234 fs = g_new0(GuestFilesystemInfo, 1);
1235 build_guest_fsinfo_for_device(syspath, fs, errp);
1236 if (fs->disk != NULL) {
1237 return g_steal_pointer(&fs->disk->value);
1239 return NULL;
1242 static char *get_alias_for_syspath(const char *syspath)
1244 struct udev *udev = NULL;
1245 struct udev_device *udevice = NULL;
1246 char *ret = NULL;
1248 udev = udev_new();
1249 if (udev == NULL) {
1250 g_debug("failed to query udev");
1251 goto out;
1253 udevice = udev_device_new_from_syspath(udev, syspath);
1254 if (udevice == NULL) {
1255 g_debug("failed to query udev for path: %s", syspath);
1256 goto out;
1257 } else {
1258 const char *alias = udev_device_get_property_value(
1259 udevice, "DM_NAME");
1261 * NULL means there was an error and empty string means there is no
1262 * alias. In case of no alias we return NULL instead of empty string.
1264 if (alias == NULL) {
1265 g_debug("failed to query udev for device alias for: %s",
1266 syspath);
1267 } else if (*alias != 0) {
1268 ret = g_strdup(alias);
1272 out:
1273 udev_unref(udev);
1274 udev_device_unref(udevice);
1275 return ret;
1278 static char *get_device_for_syspath(const char *syspath)
1280 struct udev *udev = NULL;
1281 struct udev_device *udevice = NULL;
1282 char *ret = NULL;
1284 udev = udev_new();
1285 if (udev == NULL) {
1286 g_debug("failed to query udev");
1287 goto out;
1289 udevice = udev_device_new_from_syspath(udev, syspath);
1290 if (udevice == NULL) {
1291 g_debug("failed to query udev for path: %s", syspath);
1292 goto out;
1293 } else {
1294 ret = g_strdup(udev_device_get_devnode(udevice));
1297 out:
1298 udev_unref(udev);
1299 udev_device_unref(udevice);
1300 return ret;
1303 static void get_disk_deps(const char *disk_dir, GuestDiskInfo *disk)
1305 g_autofree char *deps_dir = NULL;
1306 const gchar *dep;
1307 GDir *dp_deps = NULL;
1309 /* List dependent disks */
1310 deps_dir = g_strdup_printf("%s/slaves", disk_dir);
1311 g_debug(" listing entries in: %s", deps_dir);
1312 dp_deps = g_dir_open(deps_dir, 0, NULL);
1313 if (dp_deps == NULL) {
1314 g_debug("failed to list entries in %s", deps_dir);
1315 return;
1317 disk->has_dependencies = true;
1318 while ((dep = g_dir_read_name(dp_deps)) != NULL) {
1319 g_autofree char *dep_dir = NULL;
1320 char *dev_name;
1322 /* Add dependent disks */
1323 dep_dir = g_strdup_printf("%s/%s", deps_dir, dep);
1324 dev_name = get_device_for_syspath(dep_dir);
1325 if (dev_name != NULL) {
1326 g_debug(" adding dependent device: %s", dev_name);
1327 QAPI_LIST_PREPEND(disk->dependencies, dev_name);
1330 g_dir_close(dp_deps);
1334 * Detect partitions subdirectory, name is "<disk_name><number>" or
1335 * "<disk_name>p<number>"
1337 * @disk_name -- last component of /sys path (e.g. sda)
1338 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1339 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1341 static GuestDiskInfoList *get_disk_partitions(
1342 GuestDiskInfoList *list,
1343 const char *disk_name, const char *disk_dir,
1344 const char *disk_dev)
1346 GuestDiskInfoList *ret = list;
1347 struct dirent *de_disk;
1348 DIR *dp_disk = NULL;
1349 size_t len = strlen(disk_name);
1351 dp_disk = opendir(disk_dir);
1352 while ((de_disk = readdir(dp_disk)) != NULL) {
1353 g_autofree char *partition_dir = NULL;
1354 char *dev_name;
1355 GuestDiskInfo *partition;
1357 if (!(de_disk->d_type & DT_DIR)) {
1358 continue;
1361 if (!(strncmp(disk_name, de_disk->d_name, len) == 0 &&
1362 ((*(de_disk->d_name + len) == 'p' &&
1363 isdigit(*(de_disk->d_name + len + 1))) ||
1364 isdigit(*(de_disk->d_name + len))))) {
1365 continue;
1368 partition_dir = g_strdup_printf("%s/%s",
1369 disk_dir, de_disk->d_name);
1370 dev_name = get_device_for_syspath(partition_dir);
1371 if (dev_name == NULL) {
1372 g_debug("Failed to get device name for syspath: %s",
1373 disk_dir);
1374 continue;
1376 partition = g_new0(GuestDiskInfo, 1);
1377 partition->name = dev_name;
1378 partition->partition = true;
1379 /* Add parent disk as dependent for easier tracking of hierarchy */
1380 QAPI_LIST_PREPEND(partition->dependencies, g_strdup(disk_dev));
1382 QAPI_LIST_PREPEND(ret, partition);
1384 closedir(dp_disk);
1386 return ret;
1389 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1391 GuestDiskInfoList *ret = NULL;
1392 GuestDiskInfo *disk;
1393 DIR *dp = NULL;
1394 struct dirent *de = NULL;
1396 g_debug("listing /sys/block directory");
1397 dp = opendir("/sys/block");
1398 if (dp == NULL) {
1399 error_setg_errno(errp, errno, "Can't open directory \"/sys/block\"");
1400 return NULL;
1402 while ((de = readdir(dp)) != NULL) {
1403 g_autofree char *disk_dir = NULL, *line = NULL,
1404 *size_path = NULL;
1405 char *dev_name;
1406 Error *local_err = NULL;
1407 if (de->d_type != DT_LNK) {
1408 g_debug(" skipping entry: %s", de->d_name);
1409 continue;
1412 /* Check size and skip zero-sized disks */
1413 g_debug(" checking disk size");
1414 size_path = g_strdup_printf("/sys/block/%s/size", de->d_name);
1415 if (!g_file_get_contents(size_path, &line, NULL, NULL)) {
1416 g_debug(" failed to read disk size");
1417 continue;
1419 if (g_strcmp0(line, "0\n") == 0) {
1420 g_debug(" skipping zero-sized disk");
1421 continue;
1424 g_debug(" adding %s", de->d_name);
1425 disk_dir = g_strdup_printf("/sys/block/%s", de->d_name);
1426 dev_name = get_device_for_syspath(disk_dir);
1427 if (dev_name == NULL) {
1428 g_debug("Failed to get device name for syspath: %s",
1429 disk_dir);
1430 continue;
1432 disk = g_new0(GuestDiskInfo, 1);
1433 disk->name = dev_name;
1434 disk->partition = false;
1435 disk->alias = get_alias_for_syspath(disk_dir);
1436 disk->has_alias = (disk->alias != NULL);
1437 QAPI_LIST_PREPEND(ret, disk);
1439 /* Get address for non-virtual devices */
1440 bool is_virtual = is_disk_virtual(disk_dir, &local_err);
1441 if (local_err != NULL) {
1442 g_debug(" failed to check disk path, ignoring error: %s",
1443 error_get_pretty(local_err));
1444 error_free(local_err);
1445 local_err = NULL;
1446 /* Don't try to get the address */
1447 is_virtual = true;
1449 if (!is_virtual) {
1450 disk->address = get_disk_address(disk_dir, &local_err);
1451 if (local_err != NULL) {
1452 g_debug(" failed to get device info, ignoring error: %s",
1453 error_get_pretty(local_err));
1454 error_free(local_err);
1455 local_err = NULL;
1456 } else if (disk->address != NULL) {
1457 disk->has_address = true;
1461 get_disk_deps(disk_dir, disk);
1462 ret = get_disk_partitions(ret, de->d_name, disk_dir, dev_name);
1465 closedir(dp);
1467 return ret;
1470 #else
1472 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1474 error_setg(errp, QERR_UNSUPPORTED);
1475 return NULL;
1478 #endif
1480 /* Return a list of the disk device(s)' info which @mount lies on */
1481 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1482 Error **errp)
1484 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1485 struct statvfs buf;
1486 unsigned long used, nonroot_total, fr_size;
1487 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1488 mount->devmajor, mount->devminor);
1490 fs->mountpoint = g_strdup(mount->dirname);
1491 fs->type = g_strdup(mount->devtype);
1492 build_guest_fsinfo_for_device(devpath, fs, errp);
1494 if (statvfs(fs->mountpoint, &buf) == 0) {
1495 fr_size = buf.f_frsize;
1496 used = buf.f_blocks - buf.f_bfree;
1497 nonroot_total = used + buf.f_bavail;
1498 fs->used_bytes = used * fr_size;
1499 fs->total_bytes = nonroot_total * fr_size;
1501 fs->has_total_bytes = true;
1502 fs->has_used_bytes = true;
1505 g_free(devpath);
1507 return fs;
1510 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1512 FsMountList mounts;
1513 struct FsMount *mount;
1514 GuestFilesystemInfoList *ret = NULL;
1515 Error *local_err = NULL;
1517 QTAILQ_INIT(&mounts);
1518 build_fs_mount_list(&mounts, &local_err);
1519 if (local_err) {
1520 error_propagate(errp, local_err);
1521 return NULL;
1524 QTAILQ_FOREACH(mount, &mounts, next) {
1525 g_debug("Building guest fsinfo for '%s'", mount->dirname);
1527 QAPI_LIST_PREPEND(ret, build_guest_fsinfo(mount, &local_err));
1528 if (local_err) {
1529 error_propagate(errp, local_err);
1530 qapi_free_GuestFilesystemInfoList(ret);
1531 ret = NULL;
1532 break;
1536 free_fs_mount_list(&mounts);
1537 return ret;
1541 typedef enum {
1542 FSFREEZE_HOOK_THAW = 0,
1543 FSFREEZE_HOOK_FREEZE,
1544 } FsfreezeHookArg;
1546 static const char *fsfreeze_hook_arg_string[] = {
1547 "thaw",
1548 "freeze",
1551 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
1553 int status;
1554 pid_t pid;
1555 const char *hook;
1556 const char *arg_str = fsfreeze_hook_arg_string[arg];
1557 Error *local_err = NULL;
1559 hook = ga_fsfreeze_hook(ga_state);
1560 if (!hook) {
1561 return;
1563 if (access(hook, X_OK) != 0) {
1564 error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
1565 return;
1568 slog("executing fsfreeze hook with arg '%s'", arg_str);
1569 pid = fork();
1570 if (pid == 0) {
1571 setsid();
1572 reopen_fd_to_null(0);
1573 reopen_fd_to_null(1);
1574 reopen_fd_to_null(2);
1576 execle(hook, hook, arg_str, NULL, environ);
1577 _exit(EXIT_FAILURE);
1578 } else if (pid < 0) {
1579 error_setg_errno(errp, errno, "failed to create child process");
1580 return;
1583 ga_wait_child(pid, &status, &local_err);
1584 if (local_err) {
1585 error_propagate(errp, local_err);
1586 return;
1589 if (!WIFEXITED(status)) {
1590 error_setg(errp, "fsfreeze hook has terminated abnormally");
1591 return;
1594 status = WEXITSTATUS(status);
1595 if (status) {
1596 error_setg(errp, "fsfreeze hook has failed with status %d", status);
1597 return;
1602 * Return status of freeze/thaw
1604 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1606 if (ga_is_frozen(ga_state)) {
1607 return GUEST_FSFREEZE_STATUS_FROZEN;
1610 return GUEST_FSFREEZE_STATUS_THAWED;
1613 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1615 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1619 * Walk list of mounted file systems in the guest, and freeze the ones which
1620 * are real local file systems.
1622 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1623 strList *mountpoints,
1624 Error **errp)
1626 int ret = 0, i = 0;
1627 strList *list;
1628 FsMountList mounts;
1629 struct FsMount *mount;
1630 Error *local_err = NULL;
1631 int fd;
1633 slog("guest-fsfreeze called");
1635 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
1636 if (local_err) {
1637 error_propagate(errp, local_err);
1638 return -1;
1641 QTAILQ_INIT(&mounts);
1642 build_fs_mount_list(&mounts, &local_err);
1643 if (local_err) {
1644 error_propagate(errp, local_err);
1645 return -1;
1648 /* cannot risk guest agent blocking itself on a write in this state */
1649 ga_set_frozen(ga_state);
1651 QTAILQ_FOREACH_REVERSE(mount, &mounts, next) {
1652 /* To issue fsfreeze in the reverse order of mounts, check if the
1653 * mount is listed in the list here */
1654 if (has_mountpoints) {
1655 for (list = mountpoints; list; list = list->next) {
1656 if (strcmp(list->value, mount->dirname) == 0) {
1657 break;
1660 if (!list) {
1661 continue;
1665 fd = qemu_open_old(mount->dirname, O_RDONLY);
1666 if (fd == -1) {
1667 error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
1668 goto error;
1671 /* we try to cull filesystems we know won't work in advance, but other
1672 * filesystems may not implement fsfreeze for less obvious reasons.
1673 * these will report EOPNOTSUPP. we simply ignore these when tallying
1674 * the number of frozen filesystems.
1675 * if a filesystem is mounted more than once (aka bind mount) a
1676 * consecutive attempt to freeze an already frozen filesystem will
1677 * return EBUSY.
1679 * any other error means a failure to freeze a filesystem we
1680 * expect to be freezable, so return an error in those cases
1681 * and return system to thawed state.
1683 ret = ioctl(fd, FIFREEZE);
1684 if (ret == -1) {
1685 if (errno != EOPNOTSUPP && errno != EBUSY) {
1686 error_setg_errno(errp, errno, "failed to freeze %s",
1687 mount->dirname);
1688 close(fd);
1689 goto error;
1691 } else {
1692 i++;
1694 close(fd);
1697 free_fs_mount_list(&mounts);
1698 /* We may not issue any FIFREEZE here.
1699 * Just unset ga_state here and ready for the next call.
1701 if (i == 0) {
1702 ga_unset_frozen(ga_state);
1704 return i;
1706 error:
1707 free_fs_mount_list(&mounts);
1708 qmp_guest_fsfreeze_thaw(NULL);
1709 return 0;
1713 * Walk list of frozen file systems in the guest, and thaw them.
1715 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1717 int ret;
1718 FsMountList mounts;
1719 FsMount *mount;
1720 int fd, i = 0, logged;
1721 Error *local_err = NULL;
1723 QTAILQ_INIT(&mounts);
1724 build_fs_mount_list(&mounts, &local_err);
1725 if (local_err) {
1726 error_propagate(errp, local_err);
1727 return 0;
1730 QTAILQ_FOREACH(mount, &mounts, next) {
1731 logged = false;
1732 fd = qemu_open_old(mount->dirname, O_RDONLY);
1733 if (fd == -1) {
1734 continue;
1736 /* we have no way of knowing whether a filesystem was actually unfrozen
1737 * as a result of a successful call to FITHAW, only that if an error
1738 * was returned the filesystem was *not* unfrozen by that particular
1739 * call.
1741 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1742 * to unfreeze, continuing issuing FITHAW until an error is returned,
1743 * in which case either the filesystem is in an unfreezable state, or,
1744 * more likely, it was thawed previously (and remains so afterward).
1746 * also, since the most recent successful call is the one that did
1747 * the actual unfreeze, we can use this to provide an accurate count
1748 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1749 * may * be useful for determining whether a filesystem was unfrozen
1750 * during the freeze/thaw phase by a process other than qemu-ga.
1752 do {
1753 ret = ioctl(fd, FITHAW);
1754 if (ret == 0 && !logged) {
1755 i++;
1756 logged = true;
1758 } while (ret == 0);
1759 close(fd);
1762 ga_unset_frozen(ga_state);
1763 free_fs_mount_list(&mounts);
1765 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
1767 return i;
1770 static void guest_fsfreeze_cleanup(void)
1772 Error *err = NULL;
1774 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1775 qmp_guest_fsfreeze_thaw(&err);
1776 if (err) {
1777 slog("failed to clean up frozen filesystems: %s",
1778 error_get_pretty(err));
1779 error_free(err);
1783 #endif /* CONFIG_FSFREEZE */
1785 #if defined(CONFIG_FSTRIM)
1787 * Walk list of mounted file systems in the guest, and trim them.
1789 GuestFilesystemTrimResponse *
1790 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1792 GuestFilesystemTrimResponse *response;
1793 GuestFilesystemTrimResult *result;
1794 int ret = 0;
1795 FsMountList mounts;
1796 struct FsMount *mount;
1797 int fd;
1798 Error *local_err = NULL;
1799 struct fstrim_range r;
1801 slog("guest-fstrim called");
1803 QTAILQ_INIT(&mounts);
1804 build_fs_mount_list(&mounts, &local_err);
1805 if (local_err) {
1806 error_propagate(errp, local_err);
1807 return NULL;
1810 response = g_malloc0(sizeof(*response));
1812 QTAILQ_FOREACH(mount, &mounts, next) {
1813 result = g_malloc0(sizeof(*result));
1814 result->path = g_strdup(mount->dirname);
1816 QAPI_LIST_PREPEND(response->paths, result);
1818 fd = qemu_open_old(mount->dirname, O_RDONLY);
1819 if (fd == -1) {
1820 result->error = g_strdup_printf("failed to open: %s",
1821 strerror(errno));
1822 result->has_error = true;
1823 continue;
1826 /* We try to cull filesystems we know won't work in advance, but other
1827 * filesystems may not implement fstrim for less obvious reasons.
1828 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1829 * will be reported (e.g. CD-ROMs).
1830 * Any other error means an unexpected error.
1832 r.start = 0;
1833 r.len = -1;
1834 r.minlen = has_minimum ? minimum : 0;
1835 ret = ioctl(fd, FITRIM, &r);
1836 if (ret == -1) {
1837 result->has_error = true;
1838 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1839 result->error = g_strdup("trim not supported");
1840 } else {
1841 result->error = g_strdup_printf("failed to trim: %s",
1842 strerror(errno));
1844 close(fd);
1845 continue;
1848 result->has_minimum = true;
1849 result->minimum = r.minlen;
1850 result->has_trimmed = true;
1851 result->trimmed = r.len;
1852 close(fd);
1855 free_fs_mount_list(&mounts);
1856 return response;
1858 #endif /* CONFIG_FSTRIM */
1861 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1862 #define SUSPEND_SUPPORTED 0
1863 #define SUSPEND_NOT_SUPPORTED 1
1865 typedef enum {
1866 SUSPEND_MODE_DISK = 0,
1867 SUSPEND_MODE_RAM = 1,
1868 SUSPEND_MODE_HYBRID = 2,
1869 } SuspendMode;
1872 * Executes a command in a child process using g_spawn_sync,
1873 * returning an int >= 0 representing the exit status of the
1874 * process.
1876 * If the program wasn't found in path, returns -1.
1878 * If a problem happened when creating the child process,
1879 * returns -1 and errp is set.
1881 static int run_process_child(const char *command[], Error **errp)
1883 int exit_status, spawn_flag;
1884 GError *g_err = NULL;
1885 bool success;
1887 spawn_flag = G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL |
1888 G_SPAWN_STDERR_TO_DEV_NULL;
1890 success = g_spawn_sync(NULL, (char **)command, environ, spawn_flag,
1891 NULL, NULL, NULL, NULL,
1892 &exit_status, &g_err);
1894 if (success) {
1895 return WEXITSTATUS(exit_status);
1898 if (g_err && (g_err->code != G_SPAWN_ERROR_NOENT)) {
1899 error_setg(errp, "failed to create child process, error '%s'",
1900 g_err->message);
1903 g_error_free(g_err);
1904 return -1;
1907 static bool systemd_supports_mode(SuspendMode mode, Error **errp)
1909 const char *systemctl_args[3] = {"systemd-hibernate", "systemd-suspend",
1910 "systemd-hybrid-sleep"};
1911 const char *cmd[4] = {"systemctl", "status", systemctl_args[mode], NULL};
1912 int status;
1914 status = run_process_child(cmd, errp);
1917 * systemctl status uses LSB return codes so we can expect
1918 * status > 0 and be ok. To assert if the guest has support
1919 * for the selected suspend mode, status should be < 4. 4 is
1920 * the code for unknown service status, the return value when
1921 * the service does not exist. A common value is status = 3
1922 * (program is not running).
1924 if (status > 0 && status < 4) {
1925 return true;
1928 return false;
1931 static void systemd_suspend(SuspendMode mode, Error **errp)
1933 Error *local_err = NULL;
1934 const char *systemctl_args[3] = {"hibernate", "suspend", "hybrid-sleep"};
1935 const char *cmd[3] = {"systemctl", systemctl_args[mode], NULL};
1936 int status;
1938 status = run_process_child(cmd, &local_err);
1940 if (status == 0) {
1941 return;
1944 if ((status == -1) && !local_err) {
1945 error_setg(errp, "the helper program 'systemctl %s' was not found",
1946 systemctl_args[mode]);
1947 return;
1950 if (local_err) {
1951 error_propagate(errp, local_err);
1952 } else {
1953 error_setg(errp, "the helper program 'systemctl %s' returned an "
1954 "unexpected exit status code (%d)",
1955 systemctl_args[mode], status);
1959 static bool pmutils_supports_mode(SuspendMode mode, Error **errp)
1961 Error *local_err = NULL;
1962 const char *pmutils_args[3] = {"--hibernate", "--suspend",
1963 "--suspend-hybrid"};
1964 const char *cmd[3] = {"pm-is-supported", pmutils_args[mode], NULL};
1965 int status;
1967 status = run_process_child(cmd, &local_err);
1969 if (status == SUSPEND_SUPPORTED) {
1970 return true;
1973 if ((status == -1) && !local_err) {
1974 return false;
1977 if (local_err) {
1978 error_propagate(errp, local_err);
1979 } else {
1980 error_setg(errp,
1981 "the helper program '%s' returned an unexpected exit"
1982 " status code (%d)", "pm-is-supported", status);
1985 return false;
1988 static void pmutils_suspend(SuspendMode mode, Error **errp)
1990 Error *local_err = NULL;
1991 const char *pmutils_binaries[3] = {"pm-hibernate", "pm-suspend",
1992 "pm-suspend-hybrid"};
1993 const char *cmd[2] = {pmutils_binaries[mode], NULL};
1994 int status;
1996 status = run_process_child(cmd, &local_err);
1998 if (status == 0) {
1999 return;
2002 if ((status == -1) && !local_err) {
2003 error_setg(errp, "the helper program '%s' was not found",
2004 pmutils_binaries[mode]);
2005 return;
2008 if (local_err) {
2009 error_propagate(errp, local_err);
2010 } else {
2011 error_setg(errp,
2012 "the helper program '%s' returned an unexpected exit"
2013 " status code (%d)", pmutils_binaries[mode], status);
2017 static bool linux_sys_state_supports_mode(SuspendMode mode, Error **errp)
2019 const char *sysfile_strs[3] = {"disk", "mem", NULL};
2020 const char *sysfile_str = sysfile_strs[mode];
2021 char buf[32]; /* hopefully big enough */
2022 int fd;
2023 ssize_t ret;
2025 if (!sysfile_str) {
2026 error_setg(errp, "unknown guest suspend mode");
2027 return false;
2030 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
2031 if (fd < 0) {
2032 return false;
2035 ret = read(fd, buf, sizeof(buf) - 1);
2036 close(fd);
2037 if (ret <= 0) {
2038 return false;
2040 buf[ret] = '\0';
2042 if (strstr(buf, sysfile_str)) {
2043 return true;
2045 return false;
2048 static void linux_sys_state_suspend(SuspendMode mode, Error **errp)
2050 Error *local_err = NULL;
2051 const char *sysfile_strs[3] = {"disk", "mem", NULL};
2052 const char *sysfile_str = sysfile_strs[mode];
2053 pid_t pid;
2054 int status;
2056 if (!sysfile_str) {
2057 error_setg(errp, "unknown guest suspend mode");
2058 return;
2061 pid = fork();
2062 if (!pid) {
2063 /* child */
2064 int fd;
2066 setsid();
2067 reopen_fd_to_null(0);
2068 reopen_fd_to_null(1);
2069 reopen_fd_to_null(2);
2071 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
2072 if (fd < 0) {
2073 _exit(EXIT_FAILURE);
2076 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
2077 _exit(EXIT_FAILURE);
2080 _exit(EXIT_SUCCESS);
2081 } else if (pid < 0) {
2082 error_setg_errno(errp, errno, "failed to create child process");
2083 return;
2086 ga_wait_child(pid, &status, &local_err);
2087 if (local_err) {
2088 error_propagate(errp, local_err);
2089 return;
2092 if (WEXITSTATUS(status)) {
2093 error_setg(errp, "child process has failed to suspend");
2098 static void guest_suspend(SuspendMode mode, Error **errp)
2100 Error *local_err = NULL;
2101 bool mode_supported = false;
2103 if (systemd_supports_mode(mode, &local_err)) {
2104 mode_supported = true;
2105 systemd_suspend(mode, &local_err);
2108 if (!local_err) {
2109 return;
2112 error_free(local_err);
2113 local_err = NULL;
2115 if (pmutils_supports_mode(mode, &local_err)) {
2116 mode_supported = true;
2117 pmutils_suspend(mode, &local_err);
2120 if (!local_err) {
2121 return;
2124 error_free(local_err);
2125 local_err = NULL;
2127 if (linux_sys_state_supports_mode(mode, &local_err)) {
2128 mode_supported = true;
2129 linux_sys_state_suspend(mode, &local_err);
2132 if (!mode_supported) {
2133 error_free(local_err);
2134 error_setg(errp,
2135 "the requested suspend mode is not supported by the guest");
2136 } else {
2137 error_propagate(errp, local_err);
2141 void qmp_guest_suspend_disk(Error **errp)
2143 guest_suspend(SUSPEND_MODE_DISK, errp);
2146 void qmp_guest_suspend_ram(Error **errp)
2148 guest_suspend(SUSPEND_MODE_RAM, errp);
2151 void qmp_guest_suspend_hybrid(Error **errp)
2153 guest_suspend(SUSPEND_MODE_HYBRID, errp);
2156 static GuestNetworkInterface *
2157 guest_find_interface(GuestNetworkInterfaceList *head,
2158 const char *name)
2160 for (; head; head = head->next) {
2161 if (strcmp(head->value->name, name) == 0) {
2162 return head->value;
2166 return NULL;
2169 static int guest_get_network_stats(const char *name,
2170 GuestNetworkInterfaceStat *stats)
2172 int name_len;
2173 char const *devinfo = "/proc/net/dev";
2174 FILE *fp;
2175 char *line = NULL, *colon;
2176 size_t n = 0;
2177 fp = fopen(devinfo, "r");
2178 if (!fp) {
2179 return -1;
2181 name_len = strlen(name);
2182 while (getline(&line, &n, fp) != -1) {
2183 long long dummy;
2184 long long rx_bytes;
2185 long long rx_packets;
2186 long long rx_errs;
2187 long long rx_dropped;
2188 long long tx_bytes;
2189 long long tx_packets;
2190 long long tx_errs;
2191 long long tx_dropped;
2192 char *trim_line;
2193 trim_line = g_strchug(line);
2194 if (trim_line[0] == '\0') {
2195 continue;
2197 colon = strchr(trim_line, ':');
2198 if (!colon) {
2199 continue;
2201 if (colon - name_len == trim_line &&
2202 strncmp(trim_line, name, name_len) == 0) {
2203 if (sscanf(colon + 1,
2204 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2205 &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
2206 &dummy, &dummy, &dummy, &dummy,
2207 &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
2208 &dummy, &dummy, &dummy, &dummy) != 16) {
2209 continue;
2211 stats->rx_bytes = rx_bytes;
2212 stats->rx_packets = rx_packets;
2213 stats->rx_errs = rx_errs;
2214 stats->rx_dropped = rx_dropped;
2215 stats->tx_bytes = tx_bytes;
2216 stats->tx_packets = tx_packets;
2217 stats->tx_errs = tx_errs;
2218 stats->tx_dropped = tx_dropped;
2219 fclose(fp);
2220 g_free(line);
2221 return 0;
2224 fclose(fp);
2225 g_free(line);
2226 g_debug("/proc/net/dev: Interface '%s' not found", name);
2227 return -1;
2231 * Build information about guest interfaces
2233 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2235 GuestNetworkInterfaceList *head = NULL, **tail = &head;
2236 struct ifaddrs *ifap, *ifa;
2238 if (getifaddrs(&ifap) < 0) {
2239 error_setg_errno(errp, errno, "getifaddrs failed");
2240 goto error;
2243 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
2244 GuestNetworkInterface *info;
2245 GuestIpAddressList **address_tail;
2246 GuestIpAddress *address_item = NULL;
2247 GuestNetworkInterfaceStat *interface_stat = NULL;
2248 char addr4[INET_ADDRSTRLEN];
2249 char addr6[INET6_ADDRSTRLEN];
2250 int sock;
2251 struct ifreq ifr;
2252 unsigned char *mac_addr;
2253 void *p;
2255 g_debug("Processing %s interface", ifa->ifa_name);
2257 info = guest_find_interface(head, ifa->ifa_name);
2259 if (!info) {
2260 info = g_malloc0(sizeof(*info));
2261 info->name = g_strdup(ifa->ifa_name);
2263 QAPI_LIST_APPEND(tail, info);
2266 if (!info->has_hardware_address && ifa->ifa_flags & SIOCGIFHWADDR) {
2267 /* we haven't obtained HW address yet */
2268 sock = socket(PF_INET, SOCK_STREAM, 0);
2269 if (sock == -1) {
2270 error_setg_errno(errp, errno, "failed to create socket");
2271 goto error;
2274 memset(&ifr, 0, sizeof(ifr));
2275 pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->name);
2276 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
2277 error_setg_errno(errp, errno,
2278 "failed to get MAC address of %s",
2279 ifa->ifa_name);
2280 close(sock);
2281 goto error;
2284 close(sock);
2285 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
2287 info->hardware_address =
2288 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2289 (int) mac_addr[0], (int) mac_addr[1],
2290 (int) mac_addr[2], (int) mac_addr[3],
2291 (int) mac_addr[4], (int) mac_addr[5]);
2293 info->has_hardware_address = true;
2296 if (ifa->ifa_addr &&
2297 ifa->ifa_addr->sa_family == AF_INET) {
2298 /* interface with IPv4 address */
2299 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
2300 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
2301 error_setg_errno(errp, errno, "inet_ntop failed");
2302 goto error;
2305 address_item = g_malloc0(sizeof(*address_item));
2306 address_item->ip_address = g_strdup(addr4);
2307 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
2309 if (ifa->ifa_netmask) {
2310 /* Count the number of set bits in netmask.
2311 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2312 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
2313 address_item->prefix = ctpop32(((uint32_t *) p)[0]);
2315 } else if (ifa->ifa_addr &&
2316 ifa->ifa_addr->sa_family == AF_INET6) {
2317 /* interface with IPv6 address */
2318 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
2319 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
2320 error_setg_errno(errp, errno, "inet_ntop failed");
2321 goto error;
2324 address_item = g_malloc0(sizeof(*address_item));
2325 address_item->ip_address = g_strdup(addr6);
2326 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
2328 if (ifa->ifa_netmask) {
2329 /* Count the number of set bits in netmask.
2330 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2331 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
2332 address_item->prefix =
2333 ctpop32(((uint32_t *) p)[0]) +
2334 ctpop32(((uint32_t *) p)[1]) +
2335 ctpop32(((uint32_t *) p)[2]) +
2336 ctpop32(((uint32_t *) p)[3]);
2340 if (!address_item) {
2341 continue;
2344 address_tail = &info->ip_addresses;
2345 while (*address_tail) {
2346 address_tail = &(*address_tail)->next;
2348 QAPI_LIST_APPEND(address_tail, address_item);
2350 info->has_ip_addresses = true;
2352 if (!info->has_statistics) {
2353 interface_stat = g_malloc0(sizeof(*interface_stat));
2354 if (guest_get_network_stats(info->name, interface_stat) == -1) {
2355 info->has_statistics = false;
2356 g_free(interface_stat);
2357 } else {
2358 info->statistics = interface_stat;
2359 info->has_statistics = true;
2364 freeifaddrs(ifap);
2365 return head;
2367 error:
2368 freeifaddrs(ifap);
2369 qapi_free_GuestNetworkInterfaceList(head);
2370 return NULL;
2373 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
2375 static long sysconf_exact(int name, const char *name_str, Error **errp)
2377 long ret;
2379 errno = 0;
2380 ret = sysconf(name);
2381 if (ret == -1) {
2382 if (errno == 0) {
2383 error_setg(errp, "sysconf(%s): value indefinite", name_str);
2384 } else {
2385 error_setg_errno(errp, errno, "sysconf(%s)", name_str);
2388 return ret;
2391 /* Transfer online/offline status between @vcpu and the guest system.
2393 * On input either @errp or *@errp must be NULL.
2395 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2396 * - R: vcpu->logical_id
2397 * - W: vcpu->online
2398 * - W: vcpu->can_offline
2400 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2401 * - R: vcpu->logical_id
2402 * - R: vcpu->online
2404 * Written members remain unmodified on error.
2406 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
2407 char *dirpath, Error **errp)
2409 int fd;
2410 int res;
2411 int dirfd;
2412 static const char fn[] = "online";
2414 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2415 if (dirfd == -1) {
2416 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2417 return;
2420 fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
2421 if (fd == -1) {
2422 if (errno != ENOENT) {
2423 error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
2424 } else if (sys2vcpu) {
2425 vcpu->online = true;
2426 vcpu->can_offline = false;
2427 } else if (!vcpu->online) {
2428 error_setg(errp, "logical processor #%" PRId64 " can't be "
2429 "offlined", vcpu->logical_id);
2430 } /* otherwise pretend successful re-onlining */
2431 } else {
2432 unsigned char status;
2434 res = pread(fd, &status, 1, 0);
2435 if (res == -1) {
2436 error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
2437 } else if (res == 0) {
2438 error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
2439 fn);
2440 } else if (sys2vcpu) {
2441 vcpu->online = (status != '0');
2442 vcpu->can_offline = true;
2443 } else if (vcpu->online != (status != '0')) {
2444 status = '0' + vcpu->online;
2445 if (pwrite(fd, &status, 1, 0) == -1) {
2446 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
2447 fn);
2449 } /* otherwise pretend successful re-(on|off)-lining */
2451 res = close(fd);
2452 g_assert(res == 0);
2455 res = close(dirfd);
2456 g_assert(res == 0);
2459 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2461 int64_t current;
2462 GuestLogicalProcessorList *head, **tail;
2463 long sc_max;
2464 Error *local_err = NULL;
2466 current = 0;
2467 head = NULL;
2468 tail = &head;
2469 sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);
2471 while (local_err == NULL && current < sc_max) {
2472 GuestLogicalProcessor *vcpu;
2473 int64_t id = current++;
2474 char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
2475 id);
2477 if (g_file_test(path, G_FILE_TEST_EXISTS)) {
2478 vcpu = g_malloc0(sizeof *vcpu);
2479 vcpu->logical_id = id;
2480 vcpu->has_can_offline = true; /* lolspeak ftw */
2481 transfer_vcpu(vcpu, true, path, &local_err);
2482 QAPI_LIST_APPEND(tail, vcpu);
2484 g_free(path);
2487 if (local_err == NULL) {
2488 /* there's no guest with zero VCPUs */
2489 g_assert(head != NULL);
2490 return head;
2493 qapi_free_GuestLogicalProcessorList(head);
2494 error_propagate(errp, local_err);
2495 return NULL;
2498 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2500 int64_t processed;
2501 Error *local_err = NULL;
2503 processed = 0;
2504 while (vcpus != NULL) {
2505 char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
2506 vcpus->value->logical_id);
2508 transfer_vcpu(vcpus->value, false, path, &local_err);
2509 g_free(path);
2510 if (local_err != NULL) {
2511 break;
2513 ++processed;
2514 vcpus = vcpus->next;
2517 if (local_err != NULL) {
2518 if (processed == 0) {
2519 error_propagate(errp, local_err);
2520 } else {
2521 error_free(local_err);
2525 return processed;
2528 void qmp_guest_set_user_password(const char *username,
2529 const char *password,
2530 bool crypted,
2531 Error **errp)
2533 Error *local_err = NULL;
2534 char *passwd_path = NULL;
2535 pid_t pid;
2536 int status;
2537 int datafd[2] = { -1, -1 };
2538 char *rawpasswddata = NULL;
2539 size_t rawpasswdlen;
2540 char *chpasswddata = NULL;
2541 size_t chpasswdlen;
2543 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
2544 if (!rawpasswddata) {
2545 return;
2547 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
2548 rawpasswddata[rawpasswdlen] = '\0';
2550 if (strchr(rawpasswddata, '\n')) {
2551 error_setg(errp, "forbidden characters in raw password");
2552 goto out;
2555 if (strchr(username, '\n') ||
2556 strchr(username, ':')) {
2557 error_setg(errp, "forbidden characters in username");
2558 goto out;
2561 chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
2562 chpasswdlen = strlen(chpasswddata);
2564 passwd_path = g_find_program_in_path("chpasswd");
2566 if (!passwd_path) {
2567 error_setg(errp, "cannot find 'passwd' program in PATH");
2568 goto out;
2571 if (pipe(datafd) < 0) {
2572 error_setg(errp, "cannot create pipe FDs");
2573 goto out;
2576 pid = fork();
2577 if (pid == 0) {
2578 close(datafd[1]);
2579 /* child */
2580 setsid();
2581 dup2(datafd[0], 0);
2582 reopen_fd_to_null(1);
2583 reopen_fd_to_null(2);
2585 if (crypted) {
2586 execle(passwd_path, "chpasswd", "-e", NULL, environ);
2587 } else {
2588 execle(passwd_path, "chpasswd", NULL, environ);
2590 _exit(EXIT_FAILURE);
2591 } else if (pid < 0) {
2592 error_setg_errno(errp, errno, "failed to create child process");
2593 goto out;
2595 close(datafd[0]);
2596 datafd[0] = -1;
2598 if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2599 error_setg_errno(errp, errno, "cannot write new account password");
2600 goto out;
2602 close(datafd[1]);
2603 datafd[1] = -1;
2605 ga_wait_child(pid, &status, &local_err);
2606 if (local_err) {
2607 error_propagate(errp, local_err);
2608 goto out;
2611 if (!WIFEXITED(status)) {
2612 error_setg(errp, "child process has terminated abnormally");
2613 goto out;
2616 if (WEXITSTATUS(status)) {
2617 error_setg(errp, "child process has failed to set user password");
2618 goto out;
2621 out:
2622 g_free(chpasswddata);
2623 g_free(rawpasswddata);
2624 g_free(passwd_path);
2625 if (datafd[0] != -1) {
2626 close(datafd[0]);
2628 if (datafd[1] != -1) {
2629 close(datafd[1]);
2633 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2634 int size, Error **errp)
2636 int fd;
2637 int res;
2639 errno = 0;
2640 fd = openat(dirfd, pathname, O_RDONLY);
2641 if (fd == -1) {
2642 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2643 return;
2646 res = pread(fd, buf, size, 0);
2647 if (res == -1) {
2648 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2649 } else if (res == 0) {
2650 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2652 close(fd);
2655 static void ga_write_sysfs_file(int dirfd, const char *pathname,
2656 const char *buf, int size, Error **errp)
2658 int fd;
2660 errno = 0;
2661 fd = openat(dirfd, pathname, O_WRONLY);
2662 if (fd == -1) {
2663 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2664 return;
2667 if (pwrite(fd, buf, size, 0) == -1) {
2668 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2671 close(fd);
2674 /* Transfer online/offline status between @mem_blk and the guest system.
2676 * On input either @errp or *@errp must be NULL.
2678 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2679 * - R: mem_blk->phys_index
2680 * - W: mem_blk->online
2681 * - W: mem_blk->can_offline
2683 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2684 * - R: mem_blk->phys_index
2685 * - R: mem_blk->online
2686 *- R: mem_blk->can_offline
2687 * Written members remain unmodified on error.
2689 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2690 GuestMemoryBlockResponse *result,
2691 Error **errp)
2693 char *dirpath;
2694 int dirfd;
2695 char *status;
2696 Error *local_err = NULL;
2698 if (!sys2memblk) {
2699 DIR *dp;
2701 if (!result) {
2702 error_setg(errp, "Internal error, 'result' should not be NULL");
2703 return;
2705 errno = 0;
2706 dp = opendir("/sys/devices/system/memory/");
2707 /* if there is no 'memory' directory in sysfs,
2708 * we think this VM does not support online/offline memory block,
2709 * any other solution?
2711 if (!dp) {
2712 if (errno == ENOENT) {
2713 result->response =
2714 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2716 goto out1;
2718 closedir(dp);
2721 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2722 mem_blk->phys_index);
2723 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2724 if (dirfd == -1) {
2725 if (sys2memblk) {
2726 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2727 } else {
2728 if (errno == ENOENT) {
2729 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2730 } else {
2731 result->response =
2732 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2735 g_free(dirpath);
2736 goto out1;
2738 g_free(dirpath);
2740 status = g_malloc0(10);
2741 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2742 if (local_err) {
2743 /* treat with sysfs file that not exist in old kernel */
2744 if (errno == ENOENT) {
2745 error_free(local_err);
2746 if (sys2memblk) {
2747 mem_blk->online = true;
2748 mem_blk->can_offline = false;
2749 } else if (!mem_blk->online) {
2750 result->response =
2751 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2753 } else {
2754 if (sys2memblk) {
2755 error_propagate(errp, local_err);
2756 } else {
2757 error_free(local_err);
2758 result->response =
2759 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2762 goto out2;
2765 if (sys2memblk) {
2766 char removable = '0';
2768 mem_blk->online = (strncmp(status, "online", 6) == 0);
2770 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2771 if (local_err) {
2772 /* if no 'removable' file, it doesn't support offline mem blk */
2773 if (errno == ENOENT) {
2774 error_free(local_err);
2775 mem_blk->can_offline = false;
2776 } else {
2777 error_propagate(errp, local_err);
2779 } else {
2780 mem_blk->can_offline = (removable != '0');
2782 } else {
2783 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2784 const char *new_state = mem_blk->online ? "online" : "offline";
2786 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2787 &local_err);
2788 if (local_err) {
2789 error_free(local_err);
2790 result->response =
2791 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2792 goto out2;
2795 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2796 result->has_error_code = false;
2797 } /* otherwise pretend successful re-(on|off)-lining */
2799 g_free(status);
2800 close(dirfd);
2801 return;
2803 out2:
2804 g_free(status);
2805 close(dirfd);
2806 out1:
2807 if (!sys2memblk) {
2808 result->has_error_code = true;
2809 result->error_code = errno;
2813 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2815 GuestMemoryBlockList *head, **tail;
2816 Error *local_err = NULL;
2817 struct dirent *de;
2818 DIR *dp;
2820 head = NULL;
2821 tail = &head;
2823 dp = opendir("/sys/devices/system/memory/");
2824 if (!dp) {
2825 /* it's ok if this happens to be a system that doesn't expose
2826 * memory blocks via sysfs, but otherwise we should report
2827 * an error
2829 if (errno != ENOENT) {
2830 error_setg_errno(errp, errno, "Can't open directory"
2831 "\"/sys/devices/system/memory/\"");
2833 return NULL;
2836 /* Note: the phys_index of memory block may be discontinuous,
2837 * this is because a memblk is the unit of the Sparse Memory design, which
2838 * allows discontinuous memory ranges (ex. NUMA), so here we should
2839 * traverse the memory block directory.
2841 while ((de = readdir(dp)) != NULL) {
2842 GuestMemoryBlock *mem_blk;
2844 if ((strncmp(de->d_name, "memory", 6) != 0) ||
2845 !(de->d_type & DT_DIR)) {
2846 continue;
2849 mem_blk = g_malloc0(sizeof *mem_blk);
2850 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2851 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2852 mem_blk->has_can_offline = true; /* lolspeak ftw */
2853 transfer_memory_block(mem_blk, true, NULL, &local_err);
2854 if (local_err) {
2855 break;
2858 QAPI_LIST_APPEND(tail, mem_blk);
2861 closedir(dp);
2862 if (local_err == NULL) {
2863 /* there's no guest with zero memory blocks */
2864 if (head == NULL) {
2865 error_setg(errp, "guest reported zero memory blocks!");
2867 return head;
2870 qapi_free_GuestMemoryBlockList(head);
2871 error_propagate(errp, local_err);
2872 return NULL;
2875 GuestMemoryBlockResponseList *
2876 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2878 GuestMemoryBlockResponseList *head, **tail;
2879 Error *local_err = NULL;
2881 head = NULL;
2882 tail = &head;
2884 while (mem_blks != NULL) {
2885 GuestMemoryBlockResponse *result;
2886 GuestMemoryBlock *current_mem_blk = mem_blks->value;
2888 result = g_malloc0(sizeof(*result));
2889 result->phys_index = current_mem_blk->phys_index;
2890 transfer_memory_block(current_mem_blk, false, result, &local_err);
2891 if (local_err) { /* should never happen */
2892 goto err;
2895 QAPI_LIST_APPEND(tail, result);
2896 mem_blks = mem_blks->next;
2899 return head;
2900 err:
2901 qapi_free_GuestMemoryBlockResponseList(head);
2902 error_propagate(errp, local_err);
2903 return NULL;
2906 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2908 Error *local_err = NULL;
2909 char *dirpath;
2910 int dirfd;
2911 char *buf;
2912 GuestMemoryBlockInfo *info;
2914 dirpath = g_strdup_printf("/sys/devices/system/memory/");
2915 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2916 if (dirfd == -1) {
2917 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2918 g_free(dirpath);
2919 return NULL;
2921 g_free(dirpath);
2923 buf = g_malloc0(20);
2924 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2925 close(dirfd);
2926 if (local_err) {
2927 g_free(buf);
2928 error_propagate(errp, local_err);
2929 return NULL;
2932 info = g_new0(GuestMemoryBlockInfo, 1);
2933 info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2935 g_free(buf);
2937 return info;
2940 #else /* defined(__linux__) */
2942 void qmp_guest_suspend_disk(Error **errp)
2944 error_setg(errp, QERR_UNSUPPORTED);
2947 void qmp_guest_suspend_ram(Error **errp)
2949 error_setg(errp, QERR_UNSUPPORTED);
2952 void qmp_guest_suspend_hybrid(Error **errp)
2954 error_setg(errp, QERR_UNSUPPORTED);
2957 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2959 error_setg(errp, QERR_UNSUPPORTED);
2960 return NULL;
2963 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2965 error_setg(errp, QERR_UNSUPPORTED);
2966 return NULL;
2969 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2971 error_setg(errp, QERR_UNSUPPORTED);
2972 return -1;
2975 void qmp_guest_set_user_password(const char *username,
2976 const char *password,
2977 bool crypted,
2978 Error **errp)
2980 error_setg(errp, QERR_UNSUPPORTED);
2983 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2985 error_setg(errp, QERR_UNSUPPORTED);
2986 return NULL;
2989 GuestMemoryBlockResponseList *
2990 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2992 error_setg(errp, QERR_UNSUPPORTED);
2993 return NULL;
2996 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2998 error_setg(errp, QERR_UNSUPPORTED);
2999 return NULL;
3002 #endif
3004 #if !defined(CONFIG_FSFREEZE)
3006 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
3008 error_setg(errp, QERR_UNSUPPORTED);
3009 return NULL;
3012 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
3014 error_setg(errp, QERR_UNSUPPORTED);
3016 return 0;
3019 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
3021 error_setg(errp, QERR_UNSUPPORTED);
3023 return 0;
3026 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
3027 strList *mountpoints,
3028 Error **errp)
3030 error_setg(errp, QERR_UNSUPPORTED);
3032 return 0;
3035 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
3037 error_setg(errp, QERR_UNSUPPORTED);
3039 return 0;
3042 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
3044 error_setg(errp, QERR_UNSUPPORTED);
3045 return NULL;
3048 #endif /* CONFIG_FSFREEZE */
3050 #if !defined(CONFIG_FSTRIM)
3051 GuestFilesystemTrimResponse *
3052 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
3054 error_setg(errp, QERR_UNSUPPORTED);
3055 return NULL;
3057 #endif
3059 /* add unsupported commands to the blacklist */
3060 GList *ga_command_blacklist_init(GList *blacklist)
3062 #if !defined(__linux__)
3064 const char *list[] = {
3065 "guest-suspend-disk", "guest-suspend-ram",
3066 "guest-suspend-hybrid", "guest-network-get-interfaces",
3067 "guest-get-vcpus", "guest-set-vcpus",
3068 "guest-get-memory-blocks", "guest-set-memory-blocks",
3069 "guest-get-memory-block-size", "guest-get-memory-block-info",
3070 NULL};
3071 char **p = (char **)list;
3073 while (*p) {
3074 blacklist = g_list_append(blacklist, g_strdup(*p++));
3077 #endif
3079 #if !defined(CONFIG_FSFREEZE)
3081 const char *list[] = {
3082 "guest-get-fsinfo", "guest-fsfreeze-status",
3083 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3084 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3085 "guest-get-disks", NULL};
3086 char **p = (char **)list;
3088 while (*p) {
3089 blacklist = g_list_append(blacklist, g_strdup(*p++));
3092 #endif
3094 #if !defined(CONFIG_FSTRIM)
3095 blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
3096 #endif
3098 blacklist = g_list_append(blacklist, g_strdup("guest-get-devices"));
3100 return blacklist;
3103 /* register init/cleanup routines for stateful command groups */
3104 void ga_command_state_init(GAState *s, GACommandState *cs)
3106 #if defined(CONFIG_FSFREEZE)
3107 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
3108 #endif
3111 #ifdef HAVE_UTMPX
3113 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3115 static double ga_get_login_time(struct utmpx *user_info)
3117 double seconds = (double)user_info->ut_tv.tv_sec;
3118 double useconds = (double)user_info->ut_tv.tv_usec;
3119 useconds /= QGA_MICRO_SECOND_TO_SECOND;
3120 return seconds + useconds;
3123 GuestUserList *qmp_guest_get_users(Error **errp)
3125 GHashTable *cache = NULL;
3126 GuestUserList *head = NULL, **tail = &head;
3127 struct utmpx *user_info = NULL;
3128 gpointer value = NULL;
3129 GuestUser *user = NULL;
3130 double login_time = 0;
3132 cache = g_hash_table_new(g_str_hash, g_str_equal);
3133 setutxent();
3135 for (;;) {
3136 user_info = getutxent();
3137 if (user_info == NULL) {
3138 break;
3139 } else if (user_info->ut_type != USER_PROCESS) {
3140 continue;
3141 } else if (g_hash_table_contains(cache, user_info->ut_user)) {
3142 value = g_hash_table_lookup(cache, user_info->ut_user);
3143 user = (GuestUser *)value;
3144 login_time = ga_get_login_time(user_info);
3145 /* We're ensuring the earliest login time to be sent */
3146 if (login_time < user->login_time) {
3147 user->login_time = login_time;
3149 continue;
3152 user = g_new0(GuestUser, 1);
3153 user->user = g_strdup(user_info->ut_user);
3154 user->login_time = ga_get_login_time(user_info);
3156 g_hash_table_insert(cache, user->user, user);
3158 QAPI_LIST_APPEND(tail, user);
3160 endutxent();
3161 g_hash_table_destroy(cache);
3162 return head;
3165 #else
3167 GuestUserList *qmp_guest_get_users(Error **errp)
3169 error_setg(errp, QERR_UNSUPPORTED);
3170 return NULL;
3173 #endif
3175 /* Replace escaped special characters with theire real values. The replacement
3176 * is done in place -- returned value is in the original string.
3178 static void ga_osrelease_replace_special(gchar *value)
3180 gchar *p, *p2, quote;
3182 /* Trim the string at first space or semicolon if it is not enclosed in
3183 * single or double quotes. */
3184 if ((value[0] != '"') || (value[0] == '\'')) {
3185 p = strchr(value, ' ');
3186 if (p != NULL) {
3187 *p = 0;
3189 p = strchr(value, ';');
3190 if (p != NULL) {
3191 *p = 0;
3193 return;
3196 quote = value[0];
3197 p2 = value;
3198 p = value + 1;
3199 while (*p != 0) {
3200 if (*p == '\\') {
3201 p++;
3202 switch (*p) {
3203 case '$':
3204 case '\'':
3205 case '"':
3206 case '\\':
3207 case '`':
3208 break;
3209 default:
3210 /* Keep literal backslash followed by whatever is there */
3211 p--;
3212 break;
3214 } else if (*p == quote) {
3215 *p2 = 0;
3216 break;
3218 *(p2++) = *(p++);
3222 static GKeyFile *ga_parse_osrelease(const char *fname)
3224 gchar *content = NULL;
3225 gchar *content2 = NULL;
3226 GError *err = NULL;
3227 GKeyFile *keys = g_key_file_new();
3228 const char *group = "[os-release]\n";
3230 if (!g_file_get_contents(fname, &content, NULL, &err)) {
3231 slog("failed to read '%s', error: %s", fname, err->message);
3232 goto fail;
3235 if (!g_utf8_validate(content, -1, NULL)) {
3236 slog("file is not utf-8 encoded: %s", fname);
3237 goto fail;
3239 content2 = g_strdup_printf("%s%s", group, content);
3241 if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
3242 &err)) {
3243 slog("failed to parse file '%s', error: %s", fname, err->message);
3244 goto fail;
3247 g_free(content);
3248 g_free(content2);
3249 return keys;
3251 fail:
3252 g_error_free(err);
3253 g_free(content);
3254 g_free(content2);
3255 g_key_file_free(keys);
3256 return NULL;
3259 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
3261 GuestOSInfo *info = NULL;
3262 struct utsname kinfo;
3263 GKeyFile *osrelease = NULL;
3264 const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
3266 info = g_new0(GuestOSInfo, 1);
3268 if (uname(&kinfo) != 0) {
3269 error_setg_errno(errp, errno, "uname failed");
3270 } else {
3271 info->has_kernel_version = true;
3272 info->kernel_version = g_strdup(kinfo.version);
3273 info->has_kernel_release = true;
3274 info->kernel_release = g_strdup(kinfo.release);
3275 info->has_machine = true;
3276 info->machine = g_strdup(kinfo.machine);
3279 if (qga_os_release != NULL) {
3280 osrelease = ga_parse_osrelease(qga_os_release);
3281 } else {
3282 osrelease = ga_parse_osrelease("/etc/os-release");
3283 if (osrelease == NULL) {
3284 osrelease = ga_parse_osrelease("/usr/lib/os-release");
3288 if (osrelease != NULL) {
3289 char *value;
3291 #define GET_FIELD(field, osfield) do { \
3292 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3293 if (value != NULL) { \
3294 ga_osrelease_replace_special(value); \
3295 info->has_ ## field = true; \
3296 info->field = value; \
3298 } while (0)
3299 GET_FIELD(id, "ID");
3300 GET_FIELD(name, "NAME");
3301 GET_FIELD(pretty_name, "PRETTY_NAME");
3302 GET_FIELD(version, "VERSION");
3303 GET_FIELD(version_id, "VERSION_ID");
3304 GET_FIELD(variant, "VARIANT");
3305 GET_FIELD(variant_id, "VARIANT_ID");
3306 #undef GET_FIELD
3308 g_key_file_free(osrelease);
3311 return info;
3314 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
3316 error_setg(errp, QERR_UNSUPPORTED);
3318 return NULL;