2 * QEMU Guest Agent POSIX-specific command implementations
4 * Copyright IBM Corp. 2011
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>
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"
35 #ifndef CONFIG_HAS_ENVIRON
37 #include <crt_externs.h>
38 #define environ (*_NSGetEnviron())
40 extern char **environ
;
44 #if defined(__linux__)
48 #include <arpa/inet.h>
49 #include <sys/socket.h>
51 #include <sys/statvfs.h>
58 #define CONFIG_FSFREEZE
65 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
72 rpid
= waitpid(pid
, status
, 0);
73 } while (rpid
== -1 && errno
== EINTR
);
76 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
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
;
91 slog("guest-shutdown called, mode: %s", mode
);
92 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
94 } else if (strcmp(mode
, "halt") == 0) {
96 } else if (strcmp(mode
, "reboot") == 0) {
100 "mode is invalid (valid values are: halt|powerdown|reboot");
106 /* child, start the shutdown */
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
);
115 } else if (pid
< 0) {
116 error_setg_errno(errp
, errno
, "failed to create child process");
120 ga_wait_child(pid
, &status
, &local_err
);
122 error_propagate(errp
, local_err
);
126 if (!WIFEXITED(status
)) {
127 error_setg(errp
, "child process has terminated abnormally");
131 if (WEXITSTATUS(status
)) {
132 error_setg(errp
, "child process has failed to shutdown");
139 int64_t qmp_guest_get_time(Error
**errp
)
144 ret
= qemu_gettimeofday(&tq
);
146 error_setg_errno(errp
, errno
, "Failed to get time");
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
)
158 Error
*local_err
= NULL
;
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
);
172 /* If user has passed a time, validate and set it. */
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
);
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");
190 ret
= settimeofday(&tv
, NULL
);
192 error_setg_errno(errp
, errno
, "Failed to set time to guest");
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). */
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",
213 } else if (pid
< 0) {
214 error_setg_errno(errp
, errno
, "failed to create child process");
218 ga_wait_child(pid
, &status
, &local_err
);
220 error_propagate(errp
, local_err
);
224 if (!WIFEXITED(status
)) {
225 error_setg(errp
, "child process has terminated abnormally");
229 if (WEXITSTATUS(status
)) {
230 error_setg(errp
, "hwclock failed to set hardware clock to system time");
241 struct GuestFileHandle
{
245 QTAILQ_ENTRY(GuestFileHandle
) next
;
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
;
259 handle
= ga_get_fd_handle(ga_state
, errp
);
264 gfh
= g_new0(GuestFileHandle
, 1);
267 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
272 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
274 GuestFileHandle
*gfh
;
276 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
283 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
287 typedef const char * const ccpc
;
293 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
294 static const struct {
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
}
313 find_open_flag(const char *mode_str
, Error
**errp
)
317 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
320 form
= guest_file_open_modes
[mode
].forms
;
321 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
329 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
330 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
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 | \
341 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
343 Error
*local_err
= NULL
;
346 oflag
= find_open_flag(mode
, &local_err
);
347 if (local_err
== NULL
) {
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
);
379 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
380 "(mode: '%s')", path
, mode
);
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
);
391 f
= fdopen(fd
, mode
);
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
);
402 if (oflag
& O_CREAT
) {
408 error_propagate(errp
, local_err
);
412 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
416 Error
*local_err
= NULL
;
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
);
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
);
440 slog("guest-file-open, handle: %" PRId64
, handle
);
444 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
446 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
449 slog("guest-file-close called, handle: %" PRId64
, handle
);
454 ret
= fclose(gfh
->fh
);
456 error_setg_errno(errp
, errno
, "failed to close handle");
460 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
464 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
465 int64_t count
, Error
**errp
)
467 GuestFileRead
*read_data
= NULL
;
472 /* explicitly flush when switching from writing to reading */
473 if (gfh
->state
== RW_STATE_WRITING
) {
474 int ret
= fflush(fh
);
476 error_setg_errno(errp
, errno
, "failed to flush file");
479 gfh
->state
= RW_STATE_NEW
;
482 buf
= g_malloc0(count
+1);
483 read_count
= fread(buf
, 1, count
, fh
);
485 error_setg_errno(errp
, errno
, "failed to read file");
488 read_data
= g_new0(GuestFileRead
, 1);
489 read_data
->count
= read_count
;
490 read_data
->eof
= feof(fh
);
492 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
494 gfh
->state
= RW_STATE_READING
;
502 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
503 bool has_count
, int64_t count
,
506 GuestFileWrite
*write_data
= NULL
;
510 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
519 if (gfh
->state
== RW_STATE_READING
) {
520 int ret
= fseek(fh
, 0, SEEK_CUR
);
522 error_setg_errno(errp
, errno
, "failed to seek file");
525 gfh
->state
= RW_STATE_NEW
;
528 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
535 } else if (count
< 0 || count
> buf_len
) {
536 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
542 write_count
= fwrite(buf
, 1, count
, fh
);
544 error_setg_errno(errp
, errno
, "failed to write to file");
545 slog("guest-file-write failed, handle: %" PRId64
, handle
);
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
;
558 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
559 GuestFileWhence
*whence_code
,
562 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
563 GuestFileSeek
*seek_data
= NULL
;
573 /* We stupidly exposed 'whence':'int' in our qapi */
574 whence
= ga_parse_whence(whence_code
, &err
);
576 error_propagate(errp
, err
);
581 ret
= fseek(fh
, offset
, whence
);
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
;
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
;
599 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
601 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
612 error_setg_errno(errp
, errno
, "failed to flush file");
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
{
625 unsigned int devmajor
, devminor
;
626 QTAILQ_ENTRY(FsMount
) next
;
629 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
631 static void free_fs_mount_list(FsMountList
*mounts
)
633 FsMount
*mount
, *temp
;
639 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
640 QTAILQ_REMOVE(mounts
, mount
, next
);
641 g_free(mount
->dirname
);
642 g_free(mount
->devtype
);
647 static int dev_major_minor(const char *devpath
,
648 unsigned int *devmajor
, unsigned int *devminor
)
655 if (stat(devpath
, &st
) < 0) {
656 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
659 if (S_ISDIR(st
.st_mode
)) {
660 /* It is bind mount */
663 if (S_ISBLK(st
.st_mode
)) {
664 *devmajor
= major(st
.st_rdev
);
665 *devminor
= minor(st
.st_rdev
);
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
)
678 char const *mtab
= "/proc/self/mounts";
680 unsigned int devmajor
, devminor
;
682 fp
= setmntent(mtab
, "r");
684 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
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
695 if ((ment
->mnt_fsname
[0] != '/') ||
696 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
697 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
700 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
701 /* Skip bind mounts */
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
);
717 static void decode_mntname(char *name
, int len
)
720 for (i
= 0; i
<= len
; i
++) {
721 if (name
[i
] != '\\') {
723 } else if (name
[i
+ 1] == '\\') {
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 +
739 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
742 char const *mountinfo
= "/proc/self/mountinfo";
744 char *line
= NULL
, *dash
;
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");
752 build_fs_mount_list_from_mtab(mounts
, errp
);
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
);
762 dash
= strstr(line
+ dir_e
, " - ");
766 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
767 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
774 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
775 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
777 /* btrfs reports major number = 0 */
778 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
779 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
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
);
798 #if defined(CONFIG_FSFREEZE)
800 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
808 path
= g_strndup(syspath
, pathlen
);
809 dpath
= g_strdup_printf("%s/driver", path
);
810 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
813 driver
= g_path_get_basename(buf
);
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
)
834 struct dirent
*entry
;
837 path
= g_strndup(syspath
, host
- syspath
);
840 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
845 while (i
< hosts_max
) {
846 entry
= readdir(dir
);
850 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
852 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
857 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
864 /* Store disk device info specified by @sysfs into @fs */
865 static void build_guest_fsinfo_for_real_device(char const *syspath
,
866 GuestFilesystemInfo
*fs
,
869 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
870 int i
, nhosts
= 0, pcilen
;
871 GuestDiskAddress
*disk
;
872 GuestPCIAddress
*pciaddr
;
873 GuestDiskAddressList
*list
= NULL
;
874 bool has_ata
= false, has_host
= false, has_tgt
= false;
875 char *p
, *q
, *driver
= NULL
;
876 #ifdef CONFIG_LIBUDEV
877 struct udev
*udev
= NULL
;
878 struct udev_device
*udevice
= NULL
;
881 p
= strstr(syspath
, "/devices/pci");
882 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
883 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
884 g_debug("only pci device is supported: sysfs path '%s'", syspath
);
890 driver
= get_pci_driver(syspath
, p
- syspath
, errp
);
891 if (driver
&& (g_str_equal(driver
, "ata_piix") ||
892 g_str_equal(driver
, "sym53c8xx") ||
893 g_str_equal(driver
, "virtio-pci") ||
894 g_str_equal(driver
, "ahci"))) {
899 if (sscanf(p
, "/%x:%x:%x.%x%n",
900 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
905 g_debug("unsupported driver or sysfs path '%s'", syspath
);
909 p
= strstr(syspath
, "/target");
910 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
911 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
915 p
= strstr(syspath
, "/ata");
920 p
= strstr(syspath
, "/host");
923 if (p
&& sscanf(q
, "%u", &host
) == 1) {
925 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
926 ARRAY_SIZE(hosts
), errp
);
932 pciaddr
= g_malloc0(sizeof(*pciaddr
));
933 pciaddr
->domain
= pci
[0];
934 pciaddr
->bus
= pci
[1];
935 pciaddr
->slot
= pci
[2];
936 pciaddr
->function
= pci
[3];
938 disk
= g_malloc0(sizeof(*disk
));
939 disk
->pci_controller
= pciaddr
;
941 list
= g_malloc0(sizeof(*list
));
944 #ifdef CONFIG_LIBUDEV
946 udevice
= udev_device_new_from_syspath(udev
, syspath
);
947 if (udev
== NULL
|| udevice
== NULL
) {
948 g_debug("failed to query udev");
950 const char *devnode
, *serial
;
951 devnode
= udev_device_get_devnode(udevice
);
952 if (devnode
!= NULL
) {
953 disk
->dev
= g_strdup(devnode
);
954 disk
->has_dev
= true;
956 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
957 if (serial
!= NULL
&& *serial
!= 0) {
958 disk
->serial
= g_strdup(serial
);
959 disk
->has_serial
= true;
964 if (strcmp(driver
, "ata_piix") == 0) {
965 /* a host per ide bus, target*:0:<unit>:0 */
966 if (!has_host
|| !has_tgt
) {
967 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
970 for (i
= 0; i
< nhosts
; i
++) {
971 if (host
== hosts
[i
]) {
972 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
979 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
982 } else if (strcmp(driver
, "sym53c8xx") == 0) {
983 /* scsi(LSI Logic): target*:0:<unit>:0 */
985 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
988 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
990 } else if (strcmp(driver
, "virtio-pci") == 0) {
992 /* virtio-scsi: target*:0:0:<unit> */
993 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
996 /* virtio-blk: 1 disk per 1 device */
997 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
999 } else if (strcmp(driver
, "ahci") == 0) {
1000 /* ahci: 1 host per 1 unit */
1001 if (!has_host
|| !has_tgt
) {
1002 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
1005 for (i
= 0; i
< nhosts
; i
++) {
1006 if (host
== hosts
[i
]) {
1008 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
1013 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
1017 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
1021 list
->next
= fs
->disk
;
1027 qapi_free_GuestDiskAddressList(list
);
1031 #ifdef CONFIG_LIBUDEV
1033 udev_device_unref(udevice
);
1038 static void build_guest_fsinfo_for_device(char const *devpath
,
1039 GuestFilesystemInfo
*fs
,
1042 /* Store a list of slave devices of virtual volume specified by @syspath into
1044 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1045 GuestFilesystemInfo
*fs
,
1051 struct dirent
*entry
;
1053 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1054 dir
= opendir(dirpath
);
1056 if (errno
!= ENOENT
) {
1057 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1065 entry
= readdir(dir
);
1066 if (entry
== NULL
) {
1068 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1073 if (entry
->d_type
== DT_LNK
) {
1076 g_debug(" slave device '%s'", entry
->d_name
);
1077 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1078 build_guest_fsinfo_for_device(path
, fs
, &err
);
1082 error_propagate(errp
, err
);
1092 /* Dispatch to functions for virtual/real device */
1093 static void build_guest_fsinfo_for_device(char const *devpath
,
1094 GuestFilesystemInfo
*fs
,
1097 char *syspath
= realpath(devpath
, NULL
);
1100 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1105 fs
->name
= g_path_get_basename(syspath
);
1108 g_debug(" parse sysfs path '%s'", syspath
);
1110 if (strstr(syspath
, "/devices/virtual/block/")) {
1111 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1113 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1119 /* Return a list of the disk device(s)' info which @mount lies on */
1120 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1123 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1125 unsigned long used
, nonroot_total
, fr_size
;
1126 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1127 mount
->devmajor
, mount
->devminor
);
1129 fs
->mountpoint
= g_strdup(mount
->dirname
);
1130 fs
->type
= g_strdup(mount
->devtype
);
1131 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1133 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1134 fr_size
= buf
.f_frsize
;
1135 used
= buf
.f_blocks
- buf
.f_bfree
;
1136 nonroot_total
= used
+ buf
.f_bavail
;
1137 fs
->used_bytes
= used
* fr_size
;
1138 fs
->total_bytes
= nonroot_total
* fr_size
;
1140 fs
->has_total_bytes
= true;
1141 fs
->has_used_bytes
= true;
1149 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1152 struct FsMount
*mount
;
1153 GuestFilesystemInfoList
*new, *ret
= NULL
;
1154 Error
*local_err
= NULL
;
1156 QTAILQ_INIT(&mounts
);
1157 build_fs_mount_list(&mounts
, &local_err
);
1159 error_propagate(errp
, local_err
);
1163 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1164 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1166 new = g_malloc0(sizeof(*ret
));
1167 new->value
= build_guest_fsinfo(mount
, &local_err
);
1171 error_propagate(errp
, local_err
);
1172 qapi_free_GuestFilesystemInfoList(ret
);
1178 free_fs_mount_list(&mounts
);
1184 FSFREEZE_HOOK_THAW
= 0,
1185 FSFREEZE_HOOK_FREEZE
,
1188 static const char *fsfreeze_hook_arg_string
[] = {
1193 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1198 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1199 Error
*local_err
= NULL
;
1201 hook
= ga_fsfreeze_hook(ga_state
);
1205 if (access(hook
, X_OK
) != 0) {
1206 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1210 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1214 reopen_fd_to_null(0);
1215 reopen_fd_to_null(1);
1216 reopen_fd_to_null(2);
1218 execle(hook
, hook
, arg_str
, NULL
, environ
);
1219 _exit(EXIT_FAILURE
);
1220 } else if (pid
< 0) {
1221 error_setg_errno(errp
, errno
, "failed to create child process");
1225 ga_wait_child(pid
, &status
, &local_err
);
1227 error_propagate(errp
, local_err
);
1231 if (!WIFEXITED(status
)) {
1232 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1236 status
= WEXITSTATUS(status
);
1238 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1244 * Return status of freeze/thaw
1246 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1248 if (ga_is_frozen(ga_state
)) {
1249 return GUEST_FSFREEZE_STATUS_FROZEN
;
1252 return GUEST_FSFREEZE_STATUS_THAWED
;
1255 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1257 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1261 * Walk list of mounted file systems in the guest, and freeze the ones which
1262 * are real local file systems.
1264 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1265 strList
*mountpoints
,
1271 struct FsMount
*mount
;
1272 Error
*local_err
= NULL
;
1275 slog("guest-fsfreeze called");
1277 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1279 error_propagate(errp
, local_err
);
1283 QTAILQ_INIT(&mounts
);
1284 build_fs_mount_list(&mounts
, &local_err
);
1286 error_propagate(errp
, local_err
);
1290 /* cannot risk guest agent blocking itself on a write in this state */
1291 ga_set_frozen(ga_state
);
1293 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, next
) {
1294 /* To issue fsfreeze in the reverse order of mounts, check if the
1295 * mount is listed in the list here */
1296 if (has_mountpoints
) {
1297 for (list
= mountpoints
; list
; list
= list
->next
) {
1298 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1307 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1309 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1313 /* we try to cull filesystems we know won't work in advance, but other
1314 * filesystems may not implement fsfreeze for less obvious reasons.
1315 * these will report EOPNOTSUPP. we simply ignore these when tallying
1316 * the number of frozen filesystems.
1317 * if a filesystem is mounted more than once (aka bind mount) a
1318 * consecutive attempt to freeze an already frozen filesystem will
1321 * any other error means a failure to freeze a filesystem we
1322 * expect to be freezable, so return an error in those cases
1323 * and return system to thawed state.
1325 ret
= ioctl(fd
, FIFREEZE
);
1327 if (errno
!= EOPNOTSUPP
&& errno
!= EBUSY
) {
1328 error_setg_errno(errp
, errno
, "failed to freeze %s",
1339 free_fs_mount_list(&mounts
);
1340 /* We may not issue any FIFREEZE here.
1341 * Just unset ga_state here and ready for the next call.
1344 ga_unset_frozen(ga_state
);
1349 free_fs_mount_list(&mounts
);
1350 qmp_guest_fsfreeze_thaw(NULL
);
1355 * Walk list of frozen file systems in the guest, and thaw them.
1357 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1362 int fd
, i
= 0, logged
;
1363 Error
*local_err
= NULL
;
1365 QTAILQ_INIT(&mounts
);
1366 build_fs_mount_list(&mounts
, &local_err
);
1368 error_propagate(errp
, local_err
);
1372 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1374 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1378 /* we have no way of knowing whether a filesystem was actually unfrozen
1379 * as a result of a successful call to FITHAW, only that if an error
1380 * was returned the filesystem was *not* unfrozen by that particular
1383 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1384 * to unfreeze, continuing issuing FITHAW until an error is returned,
1385 * in which case either the filesystem is in an unfreezable state, or,
1386 * more likely, it was thawed previously (and remains so afterward).
1388 * also, since the most recent successful call is the one that did
1389 * the actual unfreeze, we can use this to provide an accurate count
1390 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1391 * may * be useful for determining whether a filesystem was unfrozen
1392 * during the freeze/thaw phase by a process other than qemu-ga.
1395 ret
= ioctl(fd
, FITHAW
);
1396 if (ret
== 0 && !logged
) {
1404 ga_unset_frozen(ga_state
);
1405 free_fs_mount_list(&mounts
);
1407 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1412 static void guest_fsfreeze_cleanup(void)
1416 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1417 qmp_guest_fsfreeze_thaw(&err
);
1419 slog("failed to clean up frozen filesystems: %s",
1420 error_get_pretty(err
));
1425 #endif /* CONFIG_FSFREEZE */
1427 #if defined(CONFIG_FSTRIM)
1429 * Walk list of mounted file systems in the guest, and trim them.
1431 GuestFilesystemTrimResponse
*
1432 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1434 GuestFilesystemTrimResponse
*response
;
1435 GuestFilesystemTrimResultList
*list
;
1436 GuestFilesystemTrimResult
*result
;
1439 struct FsMount
*mount
;
1441 Error
*local_err
= NULL
;
1442 struct fstrim_range r
;
1444 slog("guest-fstrim called");
1446 QTAILQ_INIT(&mounts
);
1447 build_fs_mount_list(&mounts
, &local_err
);
1449 error_propagate(errp
, local_err
);
1453 response
= g_malloc0(sizeof(*response
));
1455 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1456 result
= g_malloc0(sizeof(*result
));
1457 result
->path
= g_strdup(mount
->dirname
);
1459 list
= g_malloc0(sizeof(*list
));
1460 list
->value
= result
;
1461 list
->next
= response
->paths
;
1462 response
->paths
= list
;
1464 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1466 result
->error
= g_strdup_printf("failed to open: %s",
1468 result
->has_error
= true;
1472 /* We try to cull filesystems we know won't work in advance, but other
1473 * filesystems may not implement fstrim for less obvious reasons.
1474 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1475 * will be reported (e.g. CD-ROMs).
1476 * Any other error means an unexpected error.
1480 r
.minlen
= has_minimum
? minimum
: 0;
1481 ret
= ioctl(fd
, FITRIM
, &r
);
1483 result
->has_error
= true;
1484 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1485 result
->error
= g_strdup("trim not supported");
1487 result
->error
= g_strdup_printf("failed to trim: %s",
1494 result
->has_minimum
= true;
1495 result
->minimum
= r
.minlen
;
1496 result
->has_trimmed
= true;
1497 result
->trimmed
= r
.len
;
1501 free_fs_mount_list(&mounts
);
1504 #endif /* CONFIG_FSTRIM */
1507 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1508 #define SUSPEND_SUPPORTED 0
1509 #define SUSPEND_NOT_SUPPORTED 1
1512 SUSPEND_MODE_DISK
= 0,
1513 SUSPEND_MODE_RAM
= 1,
1514 SUSPEND_MODE_HYBRID
= 2,
1518 * Executes a command in a child process using g_spawn_sync,
1519 * returning an int >= 0 representing the exit status of the
1522 * If the program wasn't found in path, returns -1.
1524 * If a problem happened when creating the child process,
1525 * returns -1 and errp is set.
1527 static int run_process_child(const char *command
[], Error
**errp
)
1529 int exit_status
, spawn_flag
;
1530 GError
*g_err
= NULL
;
1533 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1534 G_SPAWN_STDERR_TO_DEV_NULL
;
1536 success
= g_spawn_sync(NULL
, (char **)command
, environ
, spawn_flag
,
1537 NULL
, NULL
, NULL
, NULL
,
1538 &exit_status
, &g_err
);
1541 return WEXITSTATUS(exit_status
);
1544 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1545 error_setg(errp
, "failed to create child process, error '%s'",
1549 g_error_free(g_err
);
1553 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1555 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1556 "systemd-hybrid-sleep"};
1557 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1560 status
= run_process_child(cmd
, errp
);
1563 * systemctl status uses LSB return codes so we can expect
1564 * status > 0 and be ok. To assert if the guest has support
1565 * for the selected suspend mode, status should be < 4. 4 is
1566 * the code for unknown service status, the return value when
1567 * the service does not exist. A common value is status = 3
1568 * (program is not running).
1570 if (status
> 0 && status
< 4) {
1577 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1579 Error
*local_err
= NULL
;
1580 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1581 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1584 status
= run_process_child(cmd
, &local_err
);
1590 if ((status
== -1) && !local_err
) {
1591 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1592 systemctl_args
[mode
]);
1597 error_propagate(errp
, local_err
);
1599 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1600 "unexpected exit status code (%d)",
1601 systemctl_args
[mode
], status
);
1605 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1607 Error
*local_err
= NULL
;
1608 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1609 "--suspend-hybrid"};
1610 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1613 status
= run_process_child(cmd
, &local_err
);
1615 if (status
== SUSPEND_SUPPORTED
) {
1619 if ((status
== -1) && !local_err
) {
1624 error_propagate(errp
, local_err
);
1627 "the helper program '%s' returned an unexpected exit"
1628 " status code (%d)", "pm-is-supported", status
);
1634 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1636 Error
*local_err
= NULL
;
1637 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1638 "pm-suspend-hybrid"};
1639 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
1642 status
= run_process_child(cmd
, &local_err
);
1648 if ((status
== -1) && !local_err
) {
1649 error_setg(errp
, "the helper program '%s' was not found",
1650 pmutils_binaries
[mode
]);
1655 error_propagate(errp
, local_err
);
1658 "the helper program '%s' returned an unexpected exit"
1659 " status code (%d)", pmutils_binaries
[mode
], status
);
1663 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
1665 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1666 const char *sysfile_str
= sysfile_strs
[mode
];
1667 char buf
[32]; /* hopefully big enough */
1672 error_setg(errp
, "unknown guest suspend mode");
1676 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1681 ret
= read(fd
, buf
, sizeof(buf
) - 1);
1688 if (strstr(buf
, sysfile_str
)) {
1694 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
1696 Error
*local_err
= NULL
;
1697 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1698 const char *sysfile_str
= sysfile_strs
[mode
];
1703 error_setg(errp
, "unknown guest suspend mode");
1713 reopen_fd_to_null(0);
1714 reopen_fd_to_null(1);
1715 reopen_fd_to_null(2);
1717 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1719 _exit(EXIT_FAILURE
);
1722 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1723 _exit(EXIT_FAILURE
);
1726 _exit(EXIT_SUCCESS
);
1727 } else if (pid
< 0) {
1728 error_setg_errno(errp
, errno
, "failed to create child process");
1732 ga_wait_child(pid
, &status
, &local_err
);
1734 error_propagate(errp
, local_err
);
1738 if (WEXITSTATUS(status
)) {
1739 error_setg(errp
, "child process has failed to suspend");
1744 static void guest_suspend(SuspendMode mode
, Error
**errp
)
1746 Error
*local_err
= NULL
;
1747 bool mode_supported
= false;
1749 if (systemd_supports_mode(mode
, &local_err
)) {
1750 mode_supported
= true;
1751 systemd_suspend(mode
, &local_err
);
1758 error_free(local_err
);
1761 if (pmutils_supports_mode(mode
, &local_err
)) {
1762 mode_supported
= true;
1763 pmutils_suspend(mode
, &local_err
);
1770 error_free(local_err
);
1773 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
1774 mode_supported
= true;
1775 linux_sys_state_suspend(mode
, &local_err
);
1778 if (!mode_supported
) {
1779 error_free(local_err
);
1781 "the requested suspend mode is not supported by the guest");
1783 error_propagate(errp
, local_err
);
1787 void qmp_guest_suspend_disk(Error
**errp
)
1789 guest_suspend(SUSPEND_MODE_DISK
, errp
);
1792 void qmp_guest_suspend_ram(Error
**errp
)
1794 guest_suspend(SUSPEND_MODE_RAM
, errp
);
1797 void qmp_guest_suspend_hybrid(Error
**errp
)
1799 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
1802 static GuestNetworkInterfaceList
*
1803 guest_find_interface(GuestNetworkInterfaceList
*head
,
1806 for (; head
; head
= head
->next
) {
1807 if (strcmp(head
->value
->name
, name
) == 0) {
1815 static int guest_get_network_stats(const char *name
,
1816 GuestNetworkInterfaceStat
*stats
)
1819 char const *devinfo
= "/proc/net/dev";
1821 char *line
= NULL
, *colon
;
1823 fp
= fopen(devinfo
, "r");
1827 name_len
= strlen(name
);
1828 while (getline(&line
, &n
, fp
) != -1) {
1831 long long rx_packets
;
1833 long long rx_dropped
;
1835 long long tx_packets
;
1837 long long tx_dropped
;
1839 trim_line
= g_strchug(line
);
1840 if (trim_line
[0] == '\0') {
1843 colon
= strchr(trim_line
, ':');
1847 if (colon
- name_len
== trim_line
&&
1848 strncmp(trim_line
, name
, name_len
) == 0) {
1849 if (sscanf(colon
+ 1,
1850 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
1851 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
1852 &dummy
, &dummy
, &dummy
, &dummy
,
1853 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
1854 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
1857 stats
->rx_bytes
= rx_bytes
;
1858 stats
->rx_packets
= rx_packets
;
1859 stats
->rx_errs
= rx_errs
;
1860 stats
->rx_dropped
= rx_dropped
;
1861 stats
->tx_bytes
= tx_bytes
;
1862 stats
->tx_packets
= tx_packets
;
1863 stats
->tx_errs
= tx_errs
;
1864 stats
->tx_dropped
= tx_dropped
;
1872 g_debug("/proc/net/dev: Interface '%s' not found", name
);
1877 * Build information about guest interfaces
1879 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1881 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1882 struct ifaddrs
*ifap
, *ifa
;
1884 if (getifaddrs(&ifap
) < 0) {
1885 error_setg_errno(errp
, errno
, "getifaddrs failed");
1889 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1890 GuestNetworkInterfaceList
*info
;
1891 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1892 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1893 char addr4
[INET_ADDRSTRLEN
];
1894 char addr6
[INET6_ADDRSTRLEN
];
1897 unsigned char *mac_addr
;
1900 g_debug("Processing %s interface", ifa
->ifa_name
);
1902 info
= guest_find_interface(head
, ifa
->ifa_name
);
1905 info
= g_malloc0(sizeof(*info
));
1906 info
->value
= g_malloc0(sizeof(*info
->value
));
1907 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1910 head
= cur_item
= info
;
1912 cur_item
->next
= info
;
1917 if (!info
->value
->has_hardware_address
&&
1918 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1919 /* we haven't obtained HW address yet */
1920 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1922 error_setg_errno(errp
, errno
, "failed to create socket");
1926 memset(&ifr
, 0, sizeof(ifr
));
1927 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1928 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1929 error_setg_errno(errp
, errno
,
1930 "failed to get MAC address of %s",
1937 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1939 info
->value
->hardware_address
=
1940 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1941 (int) mac_addr
[0], (int) mac_addr
[1],
1942 (int) mac_addr
[2], (int) mac_addr
[3],
1943 (int) mac_addr
[4], (int) mac_addr
[5]);
1945 info
->value
->has_hardware_address
= true;
1948 if (ifa
->ifa_addr
&&
1949 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1950 /* interface with IPv4 address */
1951 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1952 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1953 error_setg_errno(errp
, errno
, "inet_ntop failed");
1957 address_item
= g_malloc0(sizeof(*address_item
));
1958 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1959 address_item
->value
->ip_address
= g_strdup(addr4
);
1960 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1962 if (ifa
->ifa_netmask
) {
1963 /* Count the number of set bits in netmask.
1964 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1965 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1966 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1968 } else if (ifa
->ifa_addr
&&
1969 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1970 /* interface with IPv6 address */
1971 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1972 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1973 error_setg_errno(errp
, errno
, "inet_ntop failed");
1977 address_item
= g_malloc0(sizeof(*address_item
));
1978 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1979 address_item
->value
->ip_address
= g_strdup(addr6
);
1980 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1982 if (ifa
->ifa_netmask
) {
1983 /* Count the number of set bits in netmask.
1984 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1985 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1986 address_item
->value
->prefix
=
1987 ctpop32(((uint32_t *) p
)[0]) +
1988 ctpop32(((uint32_t *) p
)[1]) +
1989 ctpop32(((uint32_t *) p
)[2]) +
1990 ctpop32(((uint32_t *) p
)[3]);
1994 if (!address_item
) {
1998 address_list
= &info
->value
->ip_addresses
;
2000 while (*address_list
&& (*address_list
)->next
) {
2001 address_list
= &(*address_list
)->next
;
2004 if (!*address_list
) {
2005 *address_list
= address_item
;
2007 (*address_list
)->next
= address_item
;
2010 info
->value
->has_ip_addresses
= true;
2012 if (!info
->value
->has_statistics
) {
2013 interface_stat
= g_malloc0(sizeof(*interface_stat
));
2014 if (guest_get_network_stats(info
->value
->name
,
2015 interface_stat
) == -1) {
2016 info
->value
->has_statistics
= false;
2017 g_free(interface_stat
);
2019 info
->value
->statistics
= interface_stat
;
2020 info
->value
->has_statistics
= true;
2030 qapi_free_GuestNetworkInterfaceList(head
);
2034 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
2036 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
2041 ret
= sysconf(name
);
2044 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
2046 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
2052 /* Transfer online/offline status between @vcpu and the guest system.
2054 * On input either @errp or *@errp must be NULL.
2056 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2057 * - R: vcpu->logical_id
2059 * - W: vcpu->can_offline
2061 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2062 * - R: vcpu->logical_id
2065 * Written members remain unmodified on error.
2067 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
2068 char *dirpath
, Error
**errp
)
2073 static const char fn
[] = "online";
2075 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2077 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2081 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2083 if (errno
!= ENOENT
) {
2084 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2085 } else if (sys2vcpu
) {
2086 vcpu
->online
= true;
2087 vcpu
->can_offline
= false;
2088 } else if (!vcpu
->online
) {
2089 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2090 "offlined", vcpu
->logical_id
);
2091 } /* otherwise pretend successful re-onlining */
2093 unsigned char status
;
2095 res
= pread(fd
, &status
, 1, 0);
2097 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2098 } else if (res
== 0) {
2099 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2101 } else if (sys2vcpu
) {
2102 vcpu
->online
= (status
!= '0');
2103 vcpu
->can_offline
= true;
2104 } else if (vcpu
->online
!= (status
!= '0')) {
2105 status
= '0' + vcpu
->online
;
2106 if (pwrite(fd
, &status
, 1, 0) == -1) {
2107 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2110 } /* otherwise pretend successful re-(on|off)-lining */
2120 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2123 GuestLogicalProcessorList
*head
, **link
;
2125 Error
*local_err
= NULL
;
2130 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
2132 while (local_err
== NULL
&& current
< sc_max
) {
2133 GuestLogicalProcessor
*vcpu
;
2134 GuestLogicalProcessorList
*entry
;
2135 int64_t id
= current
++;
2136 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2139 if (g_file_test(path
, G_FILE_TEST_EXISTS
)) {
2140 vcpu
= g_malloc0(sizeof *vcpu
);
2141 vcpu
->logical_id
= id
;
2142 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2143 transfer_vcpu(vcpu
, true, path
, &local_err
);
2144 entry
= g_malloc0(sizeof *entry
);
2145 entry
->value
= vcpu
;
2147 link
= &entry
->next
;
2152 if (local_err
== NULL
) {
2153 /* there's no guest with zero VCPUs */
2154 g_assert(head
!= NULL
);
2158 qapi_free_GuestLogicalProcessorList(head
);
2159 error_propagate(errp
, local_err
);
2163 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2166 Error
*local_err
= NULL
;
2169 while (vcpus
!= NULL
) {
2170 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2171 vcpus
->value
->logical_id
);
2173 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2175 if (local_err
!= NULL
) {
2179 vcpus
= vcpus
->next
;
2182 if (local_err
!= NULL
) {
2183 if (processed
== 0) {
2184 error_propagate(errp
, local_err
);
2186 error_free(local_err
);
2193 void qmp_guest_set_user_password(const char *username
,
2194 const char *password
,
2198 Error
*local_err
= NULL
;
2199 char *passwd_path
= NULL
;
2202 int datafd
[2] = { -1, -1 };
2203 char *rawpasswddata
= NULL
;
2204 size_t rawpasswdlen
;
2205 char *chpasswddata
= NULL
;
2208 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2209 if (!rawpasswddata
) {
2212 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2213 rawpasswddata
[rawpasswdlen
] = '\0';
2215 if (strchr(rawpasswddata
, '\n')) {
2216 error_setg(errp
, "forbidden characters in raw password");
2220 if (strchr(username
, '\n') ||
2221 strchr(username
, ':')) {
2222 error_setg(errp
, "forbidden characters in username");
2226 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2227 chpasswdlen
= strlen(chpasswddata
);
2229 passwd_path
= g_find_program_in_path("chpasswd");
2232 error_setg(errp
, "cannot find 'passwd' program in PATH");
2236 if (pipe(datafd
) < 0) {
2237 error_setg(errp
, "cannot create pipe FDs");
2247 reopen_fd_to_null(1);
2248 reopen_fd_to_null(2);
2251 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
2253 execle(passwd_path
, "chpasswd", NULL
, environ
);
2255 _exit(EXIT_FAILURE
);
2256 } else if (pid
< 0) {
2257 error_setg_errno(errp
, errno
, "failed to create child process");
2263 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2264 error_setg_errno(errp
, errno
, "cannot write new account password");
2270 ga_wait_child(pid
, &status
, &local_err
);
2272 error_propagate(errp
, local_err
);
2276 if (!WIFEXITED(status
)) {
2277 error_setg(errp
, "child process has terminated abnormally");
2281 if (WEXITSTATUS(status
)) {
2282 error_setg(errp
, "child process has failed to set user password");
2287 g_free(chpasswddata
);
2288 g_free(rawpasswddata
);
2289 g_free(passwd_path
);
2290 if (datafd
[0] != -1) {
2293 if (datafd
[1] != -1) {
2298 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2299 int size
, Error
**errp
)
2305 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2307 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2311 res
= pread(fd
, buf
, size
, 0);
2313 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2314 } else if (res
== 0) {
2315 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2320 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2321 const char *buf
, int size
, Error
**errp
)
2326 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2328 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2332 if (pwrite(fd
, buf
, size
, 0) == -1) {
2333 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2339 /* Transfer online/offline status between @mem_blk and the guest system.
2341 * On input either @errp or *@errp must be NULL.
2343 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2344 * - R: mem_blk->phys_index
2345 * - W: mem_blk->online
2346 * - W: mem_blk->can_offline
2348 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2349 * - R: mem_blk->phys_index
2350 * - R: mem_blk->online
2351 *- R: mem_blk->can_offline
2352 * Written members remain unmodified on error.
2354 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2355 GuestMemoryBlockResponse
*result
,
2361 Error
*local_err
= NULL
;
2367 error_setg(errp
, "Internal error, 'result' should not be NULL");
2371 dp
= opendir("/sys/devices/system/memory/");
2372 /* if there is no 'memory' directory in sysfs,
2373 * we think this VM does not support online/offline memory block,
2374 * any other solution?
2377 if (errno
== ENOENT
) {
2379 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2386 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2387 mem_blk
->phys_index
);
2388 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2391 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2393 if (errno
== ENOENT
) {
2394 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2397 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2405 status
= g_malloc0(10);
2406 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2408 /* treat with sysfs file that not exist in old kernel */
2409 if (errno
== ENOENT
) {
2410 error_free(local_err
);
2412 mem_blk
->online
= true;
2413 mem_blk
->can_offline
= false;
2414 } else if (!mem_blk
->online
) {
2416 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2420 error_propagate(errp
, local_err
);
2422 error_free(local_err
);
2424 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2431 char removable
= '0';
2433 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2435 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2437 /* if no 'removable' file, it doesn't support offline mem blk */
2438 if (errno
== ENOENT
) {
2439 error_free(local_err
);
2440 mem_blk
->can_offline
= false;
2442 error_propagate(errp
, local_err
);
2445 mem_blk
->can_offline
= (removable
!= '0');
2448 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2449 const char *new_state
= mem_blk
->online
? "online" : "offline";
2451 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2454 error_free(local_err
);
2456 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2460 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2461 result
->has_error_code
= false;
2462 } /* otherwise pretend successful re-(on|off)-lining */
2473 result
->has_error_code
= true;
2474 result
->error_code
= errno
;
2478 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2480 GuestMemoryBlockList
*head
, **link
;
2481 Error
*local_err
= NULL
;
2488 dp
= opendir("/sys/devices/system/memory/");
2490 /* it's ok if this happens to be a system that doesn't expose
2491 * memory blocks via sysfs, but otherwise we should report
2494 if (errno
!= ENOENT
) {
2495 error_setg_errno(errp
, errno
, "Can't open directory"
2496 "\"/sys/devices/system/memory/\"");
2501 /* Note: the phys_index of memory block may be discontinuous,
2502 * this is because a memblk is the unit of the Sparse Memory design, which
2503 * allows discontinuous memory ranges (ex. NUMA), so here we should
2504 * traverse the memory block directory.
2506 while ((de
= readdir(dp
)) != NULL
) {
2507 GuestMemoryBlock
*mem_blk
;
2508 GuestMemoryBlockList
*entry
;
2510 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2511 !(de
->d_type
& DT_DIR
)) {
2515 mem_blk
= g_malloc0(sizeof *mem_blk
);
2516 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2517 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2518 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2519 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2524 entry
= g_malloc0(sizeof *entry
);
2525 entry
->value
= mem_blk
;
2528 link
= &entry
->next
;
2532 if (local_err
== NULL
) {
2533 /* there's no guest with zero memory blocks */
2535 error_setg(errp
, "guest reported zero memory blocks!");
2540 qapi_free_GuestMemoryBlockList(head
);
2541 error_propagate(errp
, local_err
);
2545 GuestMemoryBlockResponseList
*
2546 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2548 GuestMemoryBlockResponseList
*head
, **link
;
2549 Error
*local_err
= NULL
;
2554 while (mem_blks
!= NULL
) {
2555 GuestMemoryBlockResponse
*result
;
2556 GuestMemoryBlockResponseList
*entry
;
2557 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2559 result
= g_malloc0(sizeof(*result
));
2560 result
->phys_index
= current_mem_blk
->phys_index
;
2561 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2562 if (local_err
) { /* should never happen */
2565 entry
= g_malloc0(sizeof *entry
);
2566 entry
->value
= result
;
2569 link
= &entry
->next
;
2570 mem_blks
= mem_blks
->next
;
2575 qapi_free_GuestMemoryBlockResponseList(head
);
2576 error_propagate(errp
, local_err
);
2580 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2582 Error
*local_err
= NULL
;
2586 GuestMemoryBlockInfo
*info
;
2588 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2589 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2591 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2597 buf
= g_malloc0(20);
2598 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2602 error_propagate(errp
, local_err
);
2606 info
= g_new0(GuestMemoryBlockInfo
, 1);
2607 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2614 #else /* defined(__linux__) */
2616 void qmp_guest_suspend_disk(Error
**errp
)
2618 error_setg(errp
, QERR_UNSUPPORTED
);
2621 void qmp_guest_suspend_ram(Error
**errp
)
2623 error_setg(errp
, QERR_UNSUPPORTED
);
2626 void qmp_guest_suspend_hybrid(Error
**errp
)
2628 error_setg(errp
, QERR_UNSUPPORTED
);
2631 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2633 error_setg(errp
, QERR_UNSUPPORTED
);
2637 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2639 error_setg(errp
, QERR_UNSUPPORTED
);
2643 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2645 error_setg(errp
, QERR_UNSUPPORTED
);
2649 void qmp_guest_set_user_password(const char *username
,
2650 const char *password
,
2654 error_setg(errp
, QERR_UNSUPPORTED
);
2657 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2659 error_setg(errp
, QERR_UNSUPPORTED
);
2663 GuestMemoryBlockResponseList
*
2664 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2666 error_setg(errp
, QERR_UNSUPPORTED
);
2670 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2672 error_setg(errp
, QERR_UNSUPPORTED
);
2678 #if !defined(CONFIG_FSFREEZE)
2680 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
2682 error_setg(errp
, QERR_UNSUPPORTED
);
2686 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
2688 error_setg(errp
, QERR_UNSUPPORTED
);
2693 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
2695 error_setg(errp
, QERR_UNSUPPORTED
);
2700 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
2701 strList
*mountpoints
,
2704 error_setg(errp
, QERR_UNSUPPORTED
);
2709 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
2711 error_setg(errp
, QERR_UNSUPPORTED
);
2715 #endif /* CONFIG_FSFREEZE */
2717 #if !defined(CONFIG_FSTRIM)
2718 GuestFilesystemTrimResponse
*
2719 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
2721 error_setg(errp
, QERR_UNSUPPORTED
);
2726 /* add unsupported commands to the blacklist */
2727 GList
*ga_command_blacklist_init(GList
*blacklist
)
2729 #if !defined(__linux__)
2731 const char *list
[] = {
2732 "guest-suspend-disk", "guest-suspend-ram",
2733 "guest-suspend-hybrid", "guest-network-get-interfaces",
2734 "guest-get-vcpus", "guest-set-vcpus",
2735 "guest-get-memory-blocks", "guest-set-memory-blocks",
2736 "guest-get-memory-block-size", "guest-get-memory-block-info",
2738 char **p
= (char **)list
;
2741 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2746 #if !defined(CONFIG_FSFREEZE)
2748 const char *list
[] = {
2749 "guest-get-fsinfo", "guest-fsfreeze-status",
2750 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2751 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL
};
2752 char **p
= (char **)list
;
2755 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2760 #if !defined(CONFIG_FSTRIM)
2761 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
2767 /* register init/cleanup routines for stateful command groups */
2768 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2770 #if defined(CONFIG_FSFREEZE)
2771 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
2777 #define QGA_MICRO_SECOND_TO_SECOND 1000000
2779 static double ga_get_login_time(struct utmpx
*user_info
)
2781 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
2782 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
2783 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
2784 return seconds
+ useconds
;
2787 GuestUserList
*qmp_guest_get_users(Error
**errp
)
2789 GHashTable
*cache
= NULL
;
2790 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
2791 struct utmpx
*user_info
= NULL
;
2792 gpointer value
= NULL
;
2793 GuestUser
*user
= NULL
;
2794 GuestUserList
*item
= NULL
;
2795 double login_time
= 0;
2797 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
2801 user_info
= getutxent();
2802 if (user_info
== NULL
) {
2804 } else if (user_info
->ut_type
!= USER_PROCESS
) {
2806 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
2807 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
2808 user
= (GuestUser
*)value
;
2809 login_time
= ga_get_login_time(user_info
);
2810 /* We're ensuring the earliest login time to be sent */
2811 if (login_time
< user
->login_time
) {
2812 user
->login_time
= login_time
;
2817 item
= g_new0(GuestUserList
, 1);
2818 item
->value
= g_new0(GuestUser
, 1);
2819 item
->value
->user
= g_strdup(user_info
->ut_user
);
2820 item
->value
->login_time
= ga_get_login_time(user_info
);
2822 g_hash_table_insert(cache
, item
->value
->user
, item
->value
);
2825 head
= cur_item
= item
;
2827 cur_item
->next
= item
;
2832 g_hash_table_destroy(cache
);
2838 GuestUserList
*qmp_guest_get_users(Error
**errp
)
2840 error_setg(errp
, QERR_UNSUPPORTED
);
2846 /* Replace escaped special characters with theire real values. The replacement
2847 * is done in place -- returned value is in the original string.
2849 static void ga_osrelease_replace_special(gchar
*value
)
2851 gchar
*p
, *p2
, quote
;
2853 /* Trim the string at first space or semicolon if it is not enclosed in
2854 * single or double quotes. */
2855 if ((value
[0] != '"') || (value
[0] == '\'')) {
2856 p
= strchr(value
, ' ');
2860 p
= strchr(value
, ';');
2881 /* Keep literal backslash followed by whatever is there */
2885 } else if (*p
== quote
) {
2893 static GKeyFile
*ga_parse_osrelease(const char *fname
)
2895 gchar
*content
= NULL
;
2896 gchar
*content2
= NULL
;
2898 GKeyFile
*keys
= g_key_file_new();
2899 const char *group
= "[os-release]\n";
2901 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
2902 slog("failed to read '%s', error: %s", fname
, err
->message
);
2906 if (!g_utf8_validate(content
, -1, NULL
)) {
2907 slog("file is not utf-8 encoded: %s", fname
);
2910 content2
= g_strdup_printf("%s%s", group
, content
);
2912 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
2914 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
2926 g_key_file_free(keys
);
2930 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2932 GuestOSInfo
*info
= NULL
;
2933 struct utsname kinfo
;
2934 GKeyFile
*osrelease
= NULL
;
2935 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
2937 info
= g_new0(GuestOSInfo
, 1);
2939 if (uname(&kinfo
) != 0) {
2940 error_setg_errno(errp
, errno
, "uname failed");
2942 info
->has_kernel_version
= true;
2943 info
->kernel_version
= g_strdup(kinfo
.version
);
2944 info
->has_kernel_release
= true;
2945 info
->kernel_release
= g_strdup(kinfo
.release
);
2946 info
->has_machine
= true;
2947 info
->machine
= g_strdup(kinfo
.machine
);
2950 if (qga_os_release
!= NULL
) {
2951 osrelease
= ga_parse_osrelease(qga_os_release
);
2953 osrelease
= ga_parse_osrelease("/etc/os-release");
2954 if (osrelease
== NULL
) {
2955 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
2959 if (osrelease
!= NULL
) {
2962 #define GET_FIELD(field, osfield) do { \
2963 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
2964 if (value != NULL) { \
2965 ga_osrelease_replace_special(value); \
2966 info->has_ ## field = true; \
2967 info->field = value; \
2970 GET_FIELD(id
, "ID");
2971 GET_FIELD(name
, "NAME");
2972 GET_FIELD(pretty_name
, "PRETTY_NAME");
2973 GET_FIELD(version
, "VERSION");
2974 GET_FIELD(version_id
, "VERSION_ID");
2975 GET_FIELD(variant
, "VARIANT");
2976 GET_FIELD(variant_id
, "VARIANT_ID");
2979 g_key_file_free(osrelease
);