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 "guest-agent-core.h"
20 #include "qga-qapi-commands.h"
21 #include "qapi/error.h"
22 #include "qapi/qmp/qerror.h"
23 #include "qemu/queue.h"
24 #include "qemu/host-utils.h"
25 #include "qemu/sockets.h"
26 #include "qemu/base64.h"
27 #include "qemu/cutils.h"
33 #ifndef CONFIG_HAS_ENVIRON
35 #include <crt_externs.h>
36 #define environ (*_NSGetEnviron())
38 extern char **environ
;
42 #if defined(__linux__)
46 #include <arpa/inet.h>
47 #include <sys/socket.h>
49 #include <sys/statvfs.h>
52 #define CONFIG_FSFREEZE
59 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
66 rpid
= waitpid(pid
, status
, 0);
67 } while (rpid
== -1 && errno
== EINTR
);
70 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
75 g_assert(rpid
== pid
);
78 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
80 const char *shutdown_flag
;
81 Error
*local_err
= NULL
;
85 slog("guest-shutdown called, mode: %s", mode
);
86 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
88 } else if (strcmp(mode
, "halt") == 0) {
90 } else if (strcmp(mode
, "reboot") == 0) {
94 "mode is invalid (valid values are: halt|powerdown|reboot");
100 /* child, start the shutdown */
102 reopen_fd_to_null(0);
103 reopen_fd_to_null(1);
104 reopen_fd_to_null(2);
106 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
107 "hypervisor initiated shutdown", (char*)NULL
, environ
);
109 } else if (pid
< 0) {
110 error_setg_errno(errp
, errno
, "failed to create child process");
114 ga_wait_child(pid
, &status
, &local_err
);
116 error_propagate(errp
, local_err
);
120 if (!WIFEXITED(status
)) {
121 error_setg(errp
, "child process has terminated abnormally");
125 if (WEXITSTATUS(status
)) {
126 error_setg(errp
, "child process has failed to shutdown");
133 int64_t qmp_guest_get_time(Error
**errp
)
138 ret
= qemu_gettimeofday(&tq
);
140 error_setg_errno(errp
, errno
, "Failed to get time");
144 return tq
.tv_sec
* 1000000000LL + tq
.tv_usec
* 1000;
147 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
152 Error
*local_err
= NULL
;
155 /* If user has passed a time, validate and set it. */
159 /* year-2038 will overflow in case time_t is 32bit */
160 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
161 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
165 tv
.tv_sec
= time_ns
/ 1000000000;
166 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
167 g_date_set_time_t(&date
, tv
.tv_sec
);
168 if (date
.year
< 1970 || date
.year
>= 2070) {
169 error_setg_errno(errp
, errno
, "Invalid time");
173 ret
= settimeofday(&tv
, NULL
);
175 error_setg_errno(errp
, errno
, "Failed to set time to guest");
180 /* Now, if user has passed a time to set and the system time is set, we
181 * just need to synchronize the hardware clock. However, if no time was
182 * passed, user is requesting the opposite: set the system time from the
183 * hardware clock (RTC). */
187 reopen_fd_to_null(0);
188 reopen_fd_to_null(1);
189 reopen_fd_to_null(2);
191 /* Use '/sbin/hwclock -w' to set RTC from the system time,
192 * or '/sbin/hwclock -s' to set the system time from RTC. */
193 execle("/sbin/hwclock", "hwclock", has_time
? "-w" : "-s",
196 } else if (pid
< 0) {
197 error_setg_errno(errp
, errno
, "failed to create child process");
201 ga_wait_child(pid
, &status
, &local_err
);
203 error_propagate(errp
, local_err
);
207 if (!WIFEXITED(status
)) {
208 error_setg(errp
, "child process has terminated abnormally");
212 if (WEXITSTATUS(status
)) {
213 error_setg(errp
, "hwclock failed to set hardware clock to system time");
224 typedef struct GuestFileHandle
{
228 QTAILQ_ENTRY(GuestFileHandle
) next
;
232 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
233 } guest_file_state
= {
234 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
237 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
239 GuestFileHandle
*gfh
;
242 handle
= ga_get_fd_handle(ga_state
, errp
);
247 gfh
= g_new0(GuestFileHandle
, 1);
250 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
255 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
257 GuestFileHandle
*gfh
;
259 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
266 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
270 typedef const char * const ccpc
;
276 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
277 static const struct {
280 } guest_file_open_modes
[] = {
281 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
282 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
283 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
284 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
285 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
286 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
287 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
288 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
289 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
290 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
291 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
292 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
296 find_open_flag(const char *mode_str
, Error
**errp
)
300 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
303 form
= guest_file_open_modes
[mode
].forms
;
304 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
312 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
313 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
316 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
319 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
320 S_IRGRP | S_IWGRP | \
324 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
326 Error
*local_err
= NULL
;
329 oflag
= find_open_flag(mode
, &local_err
);
330 if (local_err
== NULL
) {
333 /* If the caller wants / allows creation of a new file, we implement it
334 * with a two step process: open() + (open() / fchmod()).
336 * First we insist on creating the file exclusively as a new file. If
337 * that succeeds, we're free to set any file-mode bits on it. (The
338 * motivation is that we want to set those file-mode bits independently
339 * of the current umask.)
341 * If the exclusive creation fails because the file already exists
342 * (EEXIST is not possible for any other reason), we just attempt to
343 * open the file, but in this case we won't be allowed to change the
344 * file-mode bits on the preexistent file.
346 * The pathname should never disappear between the two open()s in
347 * practice. If it happens, then someone very likely tried to race us.
348 * In this case just go ahead and report the ENOENT from the second
349 * open() to the caller.
351 * If the caller wants to open a preexistent file, then the first
352 * open() is decisive and its third argument is ignored, and the second
353 * open() and the fchmod() are never called.
355 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
356 if (fd
== -1 && errno
== EEXIST
) {
357 oflag
&= ~(unsigned)O_CREAT
;
358 fd
= open(path
, oflag
);
362 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
363 "(mode: '%s')", path
, mode
);
365 qemu_set_cloexec(fd
);
367 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
368 error_setg_errno(&local_err
, errno
, "failed to set permission "
369 "0%03o on new file '%s' (mode: '%s')",
370 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
374 f
= fdopen(fd
, mode
);
376 error_setg_errno(&local_err
, errno
, "failed to associate "
377 "stdio stream with file descriptor %d, "
378 "file '%s' (mode: '%s')", fd
, path
, mode
);
385 if (oflag
& O_CREAT
) {
391 error_propagate(errp
, local_err
);
395 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
399 Error
*local_err
= NULL
;
405 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
406 fh
= safe_open_or_create(path
, mode
, &local_err
);
407 if (local_err
!= NULL
) {
408 error_propagate(errp
, local_err
);
412 /* set fd non-blocking to avoid common use cases (like reading from a
413 * named pipe) from hanging the agent
415 qemu_set_nonblock(fileno(fh
));
417 handle
= guest_file_handle_add(fh
, errp
);
423 slog("guest-file-open, handle: %" PRId64
, handle
);
427 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
429 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
432 slog("guest-file-close called, handle: %" PRId64
, handle
);
437 ret
= fclose(gfh
->fh
);
439 error_setg_errno(errp
, errno
, "failed to close handle");
443 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
447 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
448 int64_t count
, Error
**errp
)
450 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
451 GuestFileRead
*read_data
= NULL
;
461 count
= QGA_READ_COUNT_DEFAULT
;
462 } else if (count
< 0 || count
>= UINT32_MAX
) {
463 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
470 /* explicitly flush when switching from writing to reading */
471 if (gfh
->state
== RW_STATE_WRITING
) {
472 int ret
= fflush(fh
);
474 error_setg_errno(errp
, errno
, "failed to flush file");
477 gfh
->state
= RW_STATE_NEW
;
480 buf
= g_malloc0(count
+1);
481 read_count
= fread(buf
, 1, count
, fh
);
483 error_setg_errno(errp
, errno
, "failed to read file");
484 slog("guest-file-read failed, handle: %" PRId64
, handle
);
487 read_data
= g_new0(GuestFileRead
, 1);
488 read_data
->count
= read_count
;
489 read_data
->eof
= feof(fh
);
491 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
493 gfh
->state
= RW_STATE_READING
;
501 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
502 bool has_count
, int64_t count
,
505 GuestFileWrite
*write_data
= NULL
;
509 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
518 if (gfh
->state
== RW_STATE_READING
) {
519 int ret
= fseek(fh
, 0, SEEK_CUR
);
521 error_setg_errno(errp
, errno
, "failed to seek file");
524 gfh
->state
= RW_STATE_NEW
;
527 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
534 } else if (count
< 0 || count
> buf_len
) {
535 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
541 write_count
= fwrite(buf
, 1, count
, fh
);
543 error_setg_errno(errp
, errno
, "failed to write to file");
544 slog("guest-file-write failed, handle: %" PRId64
, handle
);
546 write_data
= g_new0(GuestFileWrite
, 1);
547 write_data
->count
= write_count
;
548 write_data
->eof
= feof(fh
);
549 gfh
->state
= RW_STATE_WRITING
;
557 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
558 GuestFileWhence
*whence_code
,
561 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
562 GuestFileSeek
*seek_data
= NULL
;
572 /* We stupidly exposed 'whence':'int' in our qapi */
573 whence
= ga_parse_whence(whence_code
, &err
);
575 error_propagate(errp
, err
);
580 ret
= fseek(fh
, offset
, whence
);
582 error_setg_errno(errp
, errno
, "failed to seek file");
583 if (errno
== ESPIPE
) {
584 /* file is non-seekable, stdio shouldn't be buffering anyways */
585 gfh
->state
= RW_STATE_NEW
;
588 seek_data
= g_new0(GuestFileSeek
, 1);
589 seek_data
->position
= ftell(fh
);
590 seek_data
->eof
= feof(fh
);
591 gfh
->state
= RW_STATE_NEW
;
598 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
600 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
611 error_setg_errno(errp
, errno
, "failed to flush file");
613 gfh
->state
= RW_STATE_NEW
;
617 /* linux-specific implementations. avoid this if at all possible. */
618 #if defined(__linux__)
620 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
621 typedef struct FsMount
{
624 unsigned int devmajor
, devminor
;
625 QTAILQ_ENTRY(FsMount
) next
;
628 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
630 static void free_fs_mount_list(FsMountList
*mounts
)
632 FsMount
*mount
, *temp
;
638 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
639 QTAILQ_REMOVE(mounts
, mount
, next
);
640 g_free(mount
->dirname
);
641 g_free(mount
->devtype
);
646 static int dev_major_minor(const char *devpath
,
647 unsigned int *devmajor
, unsigned int *devminor
)
654 if (stat(devpath
, &st
) < 0) {
655 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
658 if (S_ISDIR(st
.st_mode
)) {
659 /* It is bind mount */
662 if (S_ISBLK(st
.st_mode
)) {
663 *devmajor
= major(st
.st_rdev
);
664 *devminor
= minor(st
.st_rdev
);
671 * Walk the mount table and build a list of local file systems
673 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
677 char const *mtab
= "/proc/self/mounts";
679 unsigned int devmajor
, devminor
;
681 fp
= setmntent(mtab
, "r");
683 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
687 while ((ment
= getmntent(fp
))) {
689 * An entry which device name doesn't start with a '/' is
690 * either a dummy file system or a network file system.
691 * Add special handling for smbfs and cifs as is done by
694 if ((ment
->mnt_fsname
[0] != '/') ||
695 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
696 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
699 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
700 /* Skip bind mounts */
704 mount
= g_new0(FsMount
, 1);
705 mount
->dirname
= g_strdup(ment
->mnt_dir
);
706 mount
->devtype
= g_strdup(ment
->mnt_type
);
707 mount
->devmajor
= devmajor
;
708 mount
->devminor
= devminor
;
710 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
716 static void decode_mntname(char *name
, int len
)
719 for (i
= 0; i
<= len
; i
++) {
720 if (name
[i
] != '\\') {
722 } else if (name
[i
+ 1] == '\\') {
725 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
726 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
727 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
728 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
729 (name
[i
+ 2] - '0') * 8 +
738 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
741 char const *mountinfo
= "/proc/self/mountinfo";
743 char *line
= NULL
, *dash
;
746 unsigned int devmajor
, devminor
;
747 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
749 fp
= fopen(mountinfo
, "r");
751 build_fs_mount_list_from_mtab(mounts
, errp
);
755 while (getline(&line
, &n
, fp
) != -1) {
756 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
757 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
761 dash
= strstr(line
+ dir_e
, " - ");
765 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
766 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
773 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
774 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
776 /* btrfs reports major number = 0 */
777 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
778 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
783 mount
= g_new0(FsMount
, 1);
784 mount
->dirname
= g_strdup(line
+ dir_s
);
785 mount
->devtype
= g_strdup(dash
+ type_s
);
786 mount
->devmajor
= devmajor
;
787 mount
->devminor
= devminor
;
789 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
797 #if defined(CONFIG_FSFREEZE)
799 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
807 path
= g_strndup(syspath
, pathlen
);
808 dpath
= g_strdup_printf("%s/driver", path
);
809 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
812 driver
= g_path_get_basename(buf
);
819 static int compare_uint(const void *_a
, const void *_b
)
821 unsigned int a
= *(unsigned int *)_a
;
822 unsigned int b
= *(unsigned int *)_b
;
824 return a
< b
? -1 : a
> b
? 1 : 0;
827 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
828 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
829 unsigned int *hosts
, int hosts_max
, Error
**errp
)
833 struct dirent
*entry
;
836 path
= g_strndup(syspath
, host
- syspath
);
839 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
844 while (i
< hosts_max
) {
845 entry
= readdir(dir
);
849 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
851 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
856 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
863 /* Store disk device info specified by @sysfs into @fs */
864 static void build_guest_fsinfo_for_real_device(char const *syspath
,
865 GuestFilesystemInfo
*fs
,
868 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
869 int i
, nhosts
= 0, pcilen
;
870 GuestDiskAddress
*disk
;
871 GuestPCIAddress
*pciaddr
;
872 GuestDiskAddressList
*list
= NULL
;
873 bool has_ata
= false, has_host
= false, has_tgt
= false;
874 char *p
, *q
, *driver
= NULL
;
876 p
= strstr(syspath
, "/devices/pci");
877 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
878 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
879 g_debug("only pci device is supported: sysfs path '%s'", syspath
);
885 driver
= get_pci_driver(syspath
, p
- syspath
, errp
);
886 if (driver
&& (g_str_equal(driver
, "ata_piix") ||
887 g_str_equal(driver
, "sym53c8xx") ||
888 g_str_equal(driver
, "virtio-pci") ||
889 g_str_equal(driver
, "ahci"))) {
894 if (sscanf(p
, "/%x:%x:%x.%x%n",
895 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
900 g_debug("unsupported driver or sysfs path '%s'", syspath
);
904 p
= strstr(syspath
, "/target");
905 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
906 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
910 p
= strstr(syspath
, "/ata");
915 p
= strstr(syspath
, "/host");
918 if (p
&& sscanf(q
, "%u", &host
) == 1) {
920 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
921 ARRAY_SIZE(hosts
), errp
);
927 pciaddr
= g_malloc0(sizeof(*pciaddr
));
928 pciaddr
->domain
= pci
[0];
929 pciaddr
->bus
= pci
[1];
930 pciaddr
->slot
= pci
[2];
931 pciaddr
->function
= pci
[3];
933 disk
= g_malloc0(sizeof(*disk
));
934 disk
->pci_controller
= pciaddr
;
936 list
= g_malloc0(sizeof(*list
));
939 if (strcmp(driver
, "ata_piix") == 0) {
940 /* a host per ide bus, target*:0:<unit>:0 */
941 if (!has_host
|| !has_tgt
) {
942 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
945 for (i
= 0; i
< nhosts
; i
++) {
946 if (host
== hosts
[i
]) {
947 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
954 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
957 } else if (strcmp(driver
, "sym53c8xx") == 0) {
958 /* scsi(LSI Logic): target*:0:<unit>:0 */
960 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
963 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
965 } else if (strcmp(driver
, "virtio-pci") == 0) {
967 /* virtio-scsi: target*:0:0:<unit> */
968 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
971 /* virtio-blk: 1 disk per 1 device */
972 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
974 } else if (strcmp(driver
, "ahci") == 0) {
975 /* ahci: 1 host per 1 unit */
976 if (!has_host
|| !has_tgt
) {
977 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
980 for (i
= 0; i
< nhosts
; i
++) {
981 if (host
== hosts
[i
]) {
983 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
988 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
992 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
996 list
->next
= fs
->disk
;
1003 qapi_free_GuestDiskAddressList(list
);
1008 static void build_guest_fsinfo_for_device(char const *devpath
,
1009 GuestFilesystemInfo
*fs
,
1012 /* Store a list of slave devices of virtual volume specified by @syspath into
1014 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1015 GuestFilesystemInfo
*fs
,
1020 struct dirent
*entry
;
1022 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1023 dir
= opendir(dirpath
);
1025 if (errno
!= ENOENT
) {
1026 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1034 entry
= readdir(dir
);
1035 if (entry
== NULL
) {
1037 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1042 if (entry
->d_type
== DT_LNK
) {
1045 g_debug(" slave device '%s'", entry
->d_name
);
1046 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1047 build_guest_fsinfo_for_device(path
, fs
, errp
);
1060 /* Dispatch to functions for virtual/real device */
1061 static void build_guest_fsinfo_for_device(char const *devpath
,
1062 GuestFilesystemInfo
*fs
,
1065 char *syspath
= realpath(devpath
, NULL
);
1068 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1073 fs
->name
= g_path_get_basename(syspath
);
1076 g_debug(" parse sysfs path '%s'", syspath
);
1078 if (strstr(syspath
, "/devices/virtual/block/")) {
1079 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1081 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1087 /* Return a list of the disk device(s)' info which @mount lies on */
1088 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1091 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1093 unsigned long used
, nonroot_total
, fr_size
;
1094 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1095 mount
->devmajor
, mount
->devminor
);
1097 fs
->mountpoint
= g_strdup(mount
->dirname
);
1098 fs
->type
= g_strdup(mount
->devtype
);
1099 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1101 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1102 fr_size
= buf
.f_frsize
;
1103 used
= buf
.f_blocks
- buf
.f_bfree
;
1104 nonroot_total
= used
+ buf
.f_bavail
;
1105 fs
->used_bytes
= used
* fr_size
;
1106 fs
->total_bytes
= nonroot_total
* fr_size
;
1108 fs
->has_total_bytes
= true;
1109 fs
->has_used_bytes
= true;
1117 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1120 struct FsMount
*mount
;
1121 GuestFilesystemInfoList
*new, *ret
= NULL
;
1122 Error
*local_err
= NULL
;
1124 QTAILQ_INIT(&mounts
);
1125 build_fs_mount_list(&mounts
, &local_err
);
1127 error_propagate(errp
, local_err
);
1131 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1132 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1134 new = g_malloc0(sizeof(*ret
));
1135 new->value
= build_guest_fsinfo(mount
, &local_err
);
1139 error_propagate(errp
, local_err
);
1140 qapi_free_GuestFilesystemInfoList(ret
);
1146 free_fs_mount_list(&mounts
);
1152 FSFREEZE_HOOK_THAW
= 0,
1153 FSFREEZE_HOOK_FREEZE
,
1156 static const char *fsfreeze_hook_arg_string
[] = {
1161 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1166 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1167 Error
*local_err
= NULL
;
1169 hook
= ga_fsfreeze_hook(ga_state
);
1173 if (access(hook
, X_OK
) != 0) {
1174 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1178 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1182 reopen_fd_to_null(0);
1183 reopen_fd_to_null(1);
1184 reopen_fd_to_null(2);
1186 execle(hook
, hook
, arg_str
, NULL
, environ
);
1187 _exit(EXIT_FAILURE
);
1188 } else if (pid
< 0) {
1189 error_setg_errno(errp
, errno
, "failed to create child process");
1193 ga_wait_child(pid
, &status
, &local_err
);
1195 error_propagate(errp
, local_err
);
1199 if (!WIFEXITED(status
)) {
1200 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1204 status
= WEXITSTATUS(status
);
1206 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1212 * Return status of freeze/thaw
1214 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1216 if (ga_is_frozen(ga_state
)) {
1217 return GUEST_FSFREEZE_STATUS_FROZEN
;
1220 return GUEST_FSFREEZE_STATUS_THAWED
;
1223 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1225 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1229 * Walk list of mounted file systems in the guest, and freeze the ones which
1230 * are real local file systems.
1232 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1233 strList
*mountpoints
,
1239 struct FsMount
*mount
;
1240 Error
*local_err
= NULL
;
1243 slog("guest-fsfreeze called");
1245 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1247 error_propagate(errp
, local_err
);
1251 QTAILQ_INIT(&mounts
);
1252 build_fs_mount_list(&mounts
, &local_err
);
1254 error_propagate(errp
, local_err
);
1258 /* cannot risk guest agent blocking itself on a write in this state */
1259 ga_set_frozen(ga_state
);
1261 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, FsMountList
, next
) {
1262 /* To issue fsfreeze in the reverse order of mounts, check if the
1263 * mount is listed in the list here */
1264 if (has_mountpoints
) {
1265 for (list
= mountpoints
; list
; list
= list
->next
) {
1266 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1275 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1277 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1281 /* we try to cull filesystems we know won't work in advance, but other
1282 * filesystems may not implement fsfreeze for less obvious reasons.
1283 * these will report EOPNOTSUPP. we simply ignore these when tallying
1284 * the number of frozen filesystems.
1285 * if a filesystem is mounted more than once (aka bind mount) a
1286 * consecutive attempt to freeze an already frozen filesystem will
1289 * any other error means a failure to freeze a filesystem we
1290 * expect to be freezable, so return an error in those cases
1291 * and return system to thawed state.
1293 ret
= ioctl(fd
, FIFREEZE
);
1295 if (errno
!= EOPNOTSUPP
&& errno
!= EBUSY
) {
1296 error_setg_errno(errp
, errno
, "failed to freeze %s",
1307 free_fs_mount_list(&mounts
);
1308 /* We may not issue any FIFREEZE here.
1309 * Just unset ga_state here and ready for the next call.
1312 ga_unset_frozen(ga_state
);
1317 free_fs_mount_list(&mounts
);
1318 qmp_guest_fsfreeze_thaw(NULL
);
1323 * Walk list of frozen file systems in the guest, and thaw them.
1325 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1330 int fd
, i
= 0, logged
;
1331 Error
*local_err
= NULL
;
1333 QTAILQ_INIT(&mounts
);
1334 build_fs_mount_list(&mounts
, &local_err
);
1336 error_propagate(errp
, local_err
);
1340 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1342 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1346 /* we have no way of knowing whether a filesystem was actually unfrozen
1347 * as a result of a successful call to FITHAW, only that if an error
1348 * was returned the filesystem was *not* unfrozen by that particular
1351 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1352 * to unfreeze, continuing issuing FITHAW until an error is returned,
1353 * in which case either the filesystem is in an unfreezable state, or,
1354 * more likely, it was thawed previously (and remains so afterward).
1356 * also, since the most recent successful call is the one that did
1357 * the actual unfreeze, we can use this to provide an accurate count
1358 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1359 * may * be useful for determining whether a filesystem was unfrozen
1360 * during the freeze/thaw phase by a process other than qemu-ga.
1363 ret
= ioctl(fd
, FITHAW
);
1364 if (ret
== 0 && !logged
) {
1372 ga_unset_frozen(ga_state
);
1373 free_fs_mount_list(&mounts
);
1375 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1380 static void guest_fsfreeze_cleanup(void)
1384 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1385 qmp_guest_fsfreeze_thaw(&err
);
1387 slog("failed to clean up frozen filesystems: %s",
1388 error_get_pretty(err
));
1393 #endif /* CONFIG_FSFREEZE */
1395 #if defined(CONFIG_FSTRIM)
1397 * Walk list of mounted file systems in the guest, and trim them.
1399 GuestFilesystemTrimResponse
*
1400 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1402 GuestFilesystemTrimResponse
*response
;
1403 GuestFilesystemTrimResultList
*list
;
1404 GuestFilesystemTrimResult
*result
;
1407 struct FsMount
*mount
;
1409 Error
*local_err
= NULL
;
1410 struct fstrim_range r
;
1412 slog("guest-fstrim called");
1414 QTAILQ_INIT(&mounts
);
1415 build_fs_mount_list(&mounts
, &local_err
);
1417 error_propagate(errp
, local_err
);
1421 response
= g_malloc0(sizeof(*response
));
1423 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1424 result
= g_malloc0(sizeof(*result
));
1425 result
->path
= g_strdup(mount
->dirname
);
1427 list
= g_malloc0(sizeof(*list
));
1428 list
->value
= result
;
1429 list
->next
= response
->paths
;
1430 response
->paths
= list
;
1432 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1434 result
->error
= g_strdup_printf("failed to open: %s",
1436 result
->has_error
= true;
1440 /* We try to cull filesystems we know won't work in advance, but other
1441 * filesystems may not implement fstrim for less obvious reasons.
1442 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1443 * will be reported (e.g. CD-ROMs).
1444 * Any other error means an unexpected error.
1448 r
.minlen
= has_minimum
? minimum
: 0;
1449 ret
= ioctl(fd
, FITRIM
, &r
);
1451 result
->has_error
= true;
1452 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1453 result
->error
= g_strdup("trim not supported");
1455 result
->error
= g_strdup_printf("failed to trim: %s",
1462 result
->has_minimum
= true;
1463 result
->minimum
= r
.minlen
;
1464 result
->has_trimmed
= true;
1465 result
->trimmed
= r
.len
;
1469 free_fs_mount_list(&mounts
);
1472 #endif /* CONFIG_FSTRIM */
1475 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1476 #define SUSPEND_SUPPORTED 0
1477 #define SUSPEND_NOT_SUPPORTED 1
1480 SUSPEND_MODE_DISK
= 0,
1481 SUSPEND_MODE_RAM
= 1,
1482 SUSPEND_MODE_HYBRID
= 2,
1486 * Executes a command in a child process using g_spawn_sync,
1487 * returning an int >= 0 representing the exit status of the
1490 * If the program wasn't found in path, returns -1.
1492 * If a problem happened when creating the child process,
1493 * returns -1 and errp is set.
1495 static int run_process_child(const char *command
[], Error
**errp
)
1497 int exit_status
, spawn_flag
;
1498 GError
*g_err
= NULL
;
1501 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1502 G_SPAWN_STDERR_TO_DEV_NULL
;
1504 success
= g_spawn_sync(NULL
, (char **)command
, environ
, spawn_flag
,
1505 NULL
, NULL
, NULL
, NULL
,
1506 &exit_status
, &g_err
);
1509 return WEXITSTATUS(exit_status
);
1512 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1513 error_setg(errp
, "failed to create child process, error '%s'",
1517 g_error_free(g_err
);
1521 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1523 Error
*local_err
= NULL
;
1524 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1525 "systemd-hybrid-sleep"};
1526 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1529 status
= run_process_child(cmd
, &local_err
);
1532 * systemctl status uses LSB return codes so we can expect
1533 * status > 0 and be ok. To assert if the guest has support
1534 * for the selected suspend mode, status should be < 4. 4 is
1535 * the code for unknown service status, the return value when
1536 * the service does not exist. A common value is status = 3
1537 * (program is not running).
1539 if (status
> 0 && status
< 4) {
1544 error_propagate(errp
, local_err
);
1550 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1552 Error
*local_err
= NULL
;
1553 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1554 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1557 status
= run_process_child(cmd
, &local_err
);
1563 if ((status
== -1) && !local_err
) {
1564 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1565 systemctl_args
[mode
]);
1570 error_propagate(errp
, local_err
);
1572 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1573 "unexpected exit status code (%d)",
1574 systemctl_args
[mode
], status
);
1578 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1580 Error
*local_err
= NULL
;
1581 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1582 "--suspend-hybrid"};
1583 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1586 status
= run_process_child(cmd
, &local_err
);
1588 if (status
== SUSPEND_SUPPORTED
) {
1592 if ((status
== -1) && !local_err
) {
1597 error_propagate(errp
, local_err
);
1600 "the helper program '%s' returned an unexpected exit"
1601 " status code (%d)", "pm-is-supported", status
);
1607 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1609 Error
*local_err
= NULL
;
1610 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1611 "pm-suspend-hybrid"};
1612 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
1615 status
= run_process_child(cmd
, &local_err
);
1621 if ((status
== -1) && !local_err
) {
1622 error_setg(errp
, "the helper program '%s' was not found",
1623 pmutils_binaries
[mode
]);
1628 error_propagate(errp
, local_err
);
1631 "the helper program '%s' returned an unexpected exit"
1632 " status code (%d)", pmutils_binaries
[mode
], status
);
1636 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
1638 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1639 const char *sysfile_str
= sysfile_strs
[mode
];
1640 char buf
[32]; /* hopefully big enough */
1645 error_setg(errp
, "unknown guest suspend mode");
1649 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1654 ret
= read(fd
, buf
, sizeof(buf
) - 1);
1661 if (strstr(buf
, sysfile_str
)) {
1667 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
1669 Error
*local_err
= NULL
;
1670 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1671 const char *sysfile_str
= sysfile_strs
[mode
];
1676 error_setg(errp
, "unknown guest suspend mode");
1686 reopen_fd_to_null(0);
1687 reopen_fd_to_null(1);
1688 reopen_fd_to_null(2);
1690 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1692 _exit(EXIT_FAILURE
);
1695 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1696 _exit(EXIT_FAILURE
);
1699 _exit(EXIT_SUCCESS
);
1700 } else if (pid
< 0) {
1701 error_setg_errno(errp
, errno
, "failed to create child process");
1705 ga_wait_child(pid
, &status
, &local_err
);
1707 error_propagate(errp
, local_err
);
1711 if (WEXITSTATUS(status
)) {
1712 error_setg(errp
, "child process has failed to suspend");
1717 static void guest_suspend(SuspendMode mode
, Error
**errp
)
1719 Error
*local_err
= NULL
;
1720 bool mode_supported
= false;
1722 if (systemd_supports_mode(mode
, &local_err
)) {
1723 mode_supported
= true;
1724 systemd_suspend(mode
, &local_err
);
1731 error_free(local_err
);
1733 if (pmutils_supports_mode(mode
, &local_err
)) {
1734 mode_supported
= true;
1735 pmutils_suspend(mode
, &local_err
);
1742 error_free(local_err
);
1744 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
1745 mode_supported
= true;
1746 linux_sys_state_suspend(mode
, &local_err
);
1749 if (!mode_supported
) {
1751 "the requested suspend mode is not supported by the guest");
1752 } else if (local_err
) {
1753 error_propagate(errp
, local_err
);
1757 void qmp_guest_suspend_disk(Error
**errp
)
1759 guest_suspend(SUSPEND_MODE_DISK
, errp
);
1762 void qmp_guest_suspend_ram(Error
**errp
)
1764 guest_suspend(SUSPEND_MODE_RAM
, errp
);
1767 void qmp_guest_suspend_hybrid(Error
**errp
)
1769 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
1772 static GuestNetworkInterfaceList
*
1773 guest_find_interface(GuestNetworkInterfaceList
*head
,
1776 for (; head
; head
= head
->next
) {
1777 if (strcmp(head
->value
->name
, name
) == 0) {
1785 static int guest_get_network_stats(const char *name
,
1786 GuestNetworkInterfaceStat
*stats
)
1789 char const *devinfo
= "/proc/net/dev";
1791 char *line
= NULL
, *colon
;
1793 fp
= fopen(devinfo
, "r");
1797 name_len
= strlen(name
);
1798 while (getline(&line
, &n
, fp
) != -1) {
1801 long long rx_packets
;
1803 long long rx_dropped
;
1805 long long tx_packets
;
1807 long long tx_dropped
;
1809 trim_line
= g_strchug(line
);
1810 if (trim_line
[0] == '\0') {
1813 colon
= strchr(trim_line
, ':');
1817 if (colon
- name_len
== trim_line
&&
1818 strncmp(trim_line
, name
, name_len
) == 0) {
1819 if (sscanf(colon
+ 1,
1820 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
1821 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
1822 &dummy
, &dummy
, &dummy
, &dummy
,
1823 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
1824 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
1827 stats
->rx_bytes
= rx_bytes
;
1828 stats
->rx_packets
= rx_packets
;
1829 stats
->rx_errs
= rx_errs
;
1830 stats
->rx_dropped
= rx_dropped
;
1831 stats
->tx_bytes
= tx_bytes
;
1832 stats
->tx_packets
= tx_packets
;
1833 stats
->tx_errs
= tx_errs
;
1834 stats
->tx_dropped
= tx_dropped
;
1842 g_debug("/proc/net/dev: Interface '%s' not found", name
);
1847 * Build information about guest interfaces
1849 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1851 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1852 struct ifaddrs
*ifap
, *ifa
;
1854 if (getifaddrs(&ifap
) < 0) {
1855 error_setg_errno(errp
, errno
, "getifaddrs failed");
1859 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1860 GuestNetworkInterfaceList
*info
;
1861 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1862 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1863 char addr4
[INET_ADDRSTRLEN
];
1864 char addr6
[INET6_ADDRSTRLEN
];
1867 unsigned char *mac_addr
;
1870 g_debug("Processing %s interface", ifa
->ifa_name
);
1872 info
= guest_find_interface(head
, ifa
->ifa_name
);
1875 info
= g_malloc0(sizeof(*info
));
1876 info
->value
= g_malloc0(sizeof(*info
->value
));
1877 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1880 head
= cur_item
= info
;
1882 cur_item
->next
= info
;
1887 if (!info
->value
->has_hardware_address
&&
1888 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1889 /* we haven't obtained HW address yet */
1890 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1892 error_setg_errno(errp
, errno
, "failed to create socket");
1896 memset(&ifr
, 0, sizeof(ifr
));
1897 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1898 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1899 error_setg_errno(errp
, errno
,
1900 "failed to get MAC address of %s",
1907 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1909 info
->value
->hardware_address
=
1910 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1911 (int) mac_addr
[0], (int) mac_addr
[1],
1912 (int) mac_addr
[2], (int) mac_addr
[3],
1913 (int) mac_addr
[4], (int) mac_addr
[5]);
1915 info
->value
->has_hardware_address
= true;
1918 if (ifa
->ifa_addr
&&
1919 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1920 /* interface with IPv4 address */
1921 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1922 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1923 error_setg_errno(errp
, errno
, "inet_ntop failed");
1927 address_item
= g_malloc0(sizeof(*address_item
));
1928 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1929 address_item
->value
->ip_address
= g_strdup(addr4
);
1930 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1932 if (ifa
->ifa_netmask
) {
1933 /* Count the number of set bits in netmask.
1934 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1935 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1936 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1938 } else if (ifa
->ifa_addr
&&
1939 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1940 /* interface with IPv6 address */
1941 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1942 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1943 error_setg_errno(errp
, errno
, "inet_ntop failed");
1947 address_item
= g_malloc0(sizeof(*address_item
));
1948 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1949 address_item
->value
->ip_address
= g_strdup(addr6
);
1950 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1952 if (ifa
->ifa_netmask
) {
1953 /* Count the number of set bits in netmask.
1954 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1955 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1956 address_item
->value
->prefix
=
1957 ctpop32(((uint32_t *) p
)[0]) +
1958 ctpop32(((uint32_t *) p
)[1]) +
1959 ctpop32(((uint32_t *) p
)[2]) +
1960 ctpop32(((uint32_t *) p
)[3]);
1964 if (!address_item
) {
1968 address_list
= &info
->value
->ip_addresses
;
1970 while (*address_list
&& (*address_list
)->next
) {
1971 address_list
= &(*address_list
)->next
;
1974 if (!*address_list
) {
1975 *address_list
= address_item
;
1977 (*address_list
)->next
= address_item
;
1980 info
->value
->has_ip_addresses
= true;
1982 if (!info
->value
->has_statistics
) {
1983 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1984 if (guest_get_network_stats(info
->value
->name
,
1985 interface_stat
) == -1) {
1986 info
->value
->has_statistics
= false;
1987 g_free(interface_stat
);
1989 info
->value
->statistics
= interface_stat
;
1990 info
->value
->has_statistics
= true;
2000 qapi_free_GuestNetworkInterfaceList(head
);
2004 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
2006 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
2011 ret
= sysconf(name
);
2014 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
2016 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
2022 /* Transfer online/offline status between @vcpu and the guest system.
2024 * On input either @errp or *@errp must be NULL.
2026 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2027 * - R: vcpu->logical_id
2029 * - W: vcpu->can_offline
2031 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2032 * - R: vcpu->logical_id
2035 * Written members remain unmodified on error.
2037 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
2043 dirpath
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2045 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2047 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2049 static const char fn
[] = "online";
2053 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2055 if (errno
!= ENOENT
) {
2056 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2057 } else if (sys2vcpu
) {
2058 vcpu
->online
= true;
2059 vcpu
->can_offline
= false;
2060 } else if (!vcpu
->online
) {
2061 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2062 "offlined", vcpu
->logical_id
);
2063 } /* otherwise pretend successful re-onlining */
2065 unsigned char status
;
2067 res
= pread(fd
, &status
, 1, 0);
2069 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2070 } else if (res
== 0) {
2071 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2073 } else if (sys2vcpu
) {
2074 vcpu
->online
= (status
!= '0');
2075 vcpu
->can_offline
= true;
2076 } else if (vcpu
->online
!= (status
!= '0')) {
2077 status
= '0' + vcpu
->online
;
2078 if (pwrite(fd
, &status
, 1, 0) == -1) {
2079 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2082 } /* otherwise pretend successful re-(on|off)-lining */
2095 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2098 GuestLogicalProcessorList
*head
, **link
;
2100 Error
*local_err
= NULL
;
2105 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
2107 while (local_err
== NULL
&& current
< sc_max
) {
2108 GuestLogicalProcessor
*vcpu
;
2109 GuestLogicalProcessorList
*entry
;
2111 vcpu
= g_malloc0(sizeof *vcpu
);
2112 vcpu
->logical_id
= current
++;
2113 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2114 transfer_vcpu(vcpu
, true, &local_err
);
2116 entry
= g_malloc0(sizeof *entry
);
2117 entry
->value
= vcpu
;
2120 link
= &entry
->next
;
2123 if (local_err
== NULL
) {
2124 /* there's no guest with zero VCPUs */
2125 g_assert(head
!= NULL
);
2129 qapi_free_GuestLogicalProcessorList(head
);
2130 error_propagate(errp
, local_err
);
2134 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2137 Error
*local_err
= NULL
;
2140 while (vcpus
!= NULL
) {
2141 transfer_vcpu(vcpus
->value
, false, &local_err
);
2142 if (local_err
!= NULL
) {
2146 vcpus
= vcpus
->next
;
2149 if (local_err
!= NULL
) {
2150 if (processed
== 0) {
2151 error_propagate(errp
, local_err
);
2153 error_free(local_err
);
2160 void qmp_guest_set_user_password(const char *username
,
2161 const char *password
,
2165 Error
*local_err
= NULL
;
2166 char *passwd_path
= NULL
;
2169 int datafd
[2] = { -1, -1 };
2170 char *rawpasswddata
= NULL
;
2171 size_t rawpasswdlen
;
2172 char *chpasswddata
= NULL
;
2175 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2176 if (!rawpasswddata
) {
2179 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2180 rawpasswddata
[rawpasswdlen
] = '\0';
2182 if (strchr(rawpasswddata
, '\n')) {
2183 error_setg(errp
, "forbidden characters in raw password");
2187 if (strchr(username
, '\n') ||
2188 strchr(username
, ':')) {
2189 error_setg(errp
, "forbidden characters in username");
2193 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2194 chpasswdlen
= strlen(chpasswddata
);
2196 passwd_path
= g_find_program_in_path("chpasswd");
2199 error_setg(errp
, "cannot find 'passwd' program in PATH");
2203 if (pipe(datafd
) < 0) {
2204 error_setg(errp
, "cannot create pipe FDs");
2214 reopen_fd_to_null(1);
2215 reopen_fd_to_null(2);
2218 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
2220 execle(passwd_path
, "chpasswd", NULL
, environ
);
2222 _exit(EXIT_FAILURE
);
2223 } else if (pid
< 0) {
2224 error_setg_errno(errp
, errno
, "failed to create child process");
2230 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2231 error_setg_errno(errp
, errno
, "cannot write new account password");
2237 ga_wait_child(pid
, &status
, &local_err
);
2239 error_propagate(errp
, local_err
);
2243 if (!WIFEXITED(status
)) {
2244 error_setg(errp
, "child process has terminated abnormally");
2248 if (WEXITSTATUS(status
)) {
2249 error_setg(errp
, "child process has failed to set user password");
2254 g_free(chpasswddata
);
2255 g_free(rawpasswddata
);
2256 g_free(passwd_path
);
2257 if (datafd
[0] != -1) {
2260 if (datafd
[1] != -1) {
2265 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2266 int size
, Error
**errp
)
2272 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2274 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2278 res
= pread(fd
, buf
, size
, 0);
2280 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2281 } else if (res
== 0) {
2282 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2287 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2288 const char *buf
, int size
, Error
**errp
)
2293 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2295 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2299 if (pwrite(fd
, buf
, size
, 0) == -1) {
2300 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2306 /* Transfer online/offline status between @mem_blk and the guest system.
2308 * On input either @errp or *@errp must be NULL.
2310 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2311 * - R: mem_blk->phys_index
2312 * - W: mem_blk->online
2313 * - W: mem_blk->can_offline
2315 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2316 * - R: mem_blk->phys_index
2317 * - R: mem_blk->online
2318 *- R: mem_blk->can_offline
2319 * Written members remain unmodified on error.
2321 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2322 GuestMemoryBlockResponse
*result
,
2328 Error
*local_err
= NULL
;
2334 error_setg(errp
, "Internal error, 'result' should not be NULL");
2338 dp
= opendir("/sys/devices/system/memory/");
2339 /* if there is no 'memory' directory in sysfs,
2340 * we think this VM does not support online/offline memory block,
2341 * any other solution?
2344 if (errno
== ENOENT
) {
2346 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2353 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2354 mem_blk
->phys_index
);
2355 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2358 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2360 if (errno
== ENOENT
) {
2361 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2364 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2372 status
= g_malloc0(10);
2373 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2375 /* treat with sysfs file that not exist in old kernel */
2376 if (errno
== ENOENT
) {
2377 error_free(local_err
);
2379 mem_blk
->online
= true;
2380 mem_blk
->can_offline
= false;
2381 } else if (!mem_blk
->online
) {
2383 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2387 error_propagate(errp
, local_err
);
2390 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2397 char removable
= '0';
2399 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2401 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2403 /* if no 'removable' file, it doesn't support offline mem blk */
2404 if (errno
== ENOENT
) {
2405 error_free(local_err
);
2406 mem_blk
->can_offline
= false;
2408 error_propagate(errp
, local_err
);
2411 mem_blk
->can_offline
= (removable
!= '0');
2414 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2415 const char *new_state
= mem_blk
->online
? "online" : "offline";
2417 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2420 error_free(local_err
);
2422 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2426 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2427 result
->has_error_code
= false;
2428 } /* otherwise pretend successful re-(on|off)-lining */
2439 result
->has_error_code
= true;
2440 result
->error_code
= errno
;
2444 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2446 GuestMemoryBlockList
*head
, **link
;
2447 Error
*local_err
= NULL
;
2454 dp
= opendir("/sys/devices/system/memory/");
2456 /* it's ok if this happens to be a system that doesn't expose
2457 * memory blocks via sysfs, but otherwise we should report
2460 if (errno
!= ENOENT
) {
2461 error_setg_errno(errp
, errno
, "Can't open directory"
2462 "\"/sys/devices/system/memory/\"");
2467 /* Note: the phys_index of memory block may be discontinuous,
2468 * this is because a memblk is the unit of the Sparse Memory design, which
2469 * allows discontinuous memory ranges (ex. NUMA), so here we should
2470 * traverse the memory block directory.
2472 while ((de
= readdir(dp
)) != NULL
) {
2473 GuestMemoryBlock
*mem_blk
;
2474 GuestMemoryBlockList
*entry
;
2476 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2477 !(de
->d_type
& DT_DIR
)) {
2481 mem_blk
= g_malloc0(sizeof *mem_blk
);
2482 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2483 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2484 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2485 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2487 entry
= g_malloc0(sizeof *entry
);
2488 entry
->value
= mem_blk
;
2491 link
= &entry
->next
;
2495 if (local_err
== NULL
) {
2496 /* there's no guest with zero memory blocks */
2498 error_setg(errp
, "guest reported zero memory blocks!");
2503 qapi_free_GuestMemoryBlockList(head
);
2504 error_propagate(errp
, local_err
);
2508 GuestMemoryBlockResponseList
*
2509 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2511 GuestMemoryBlockResponseList
*head
, **link
;
2512 Error
*local_err
= NULL
;
2517 while (mem_blks
!= NULL
) {
2518 GuestMemoryBlockResponse
*result
;
2519 GuestMemoryBlockResponseList
*entry
;
2520 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2522 result
= g_malloc0(sizeof(*result
));
2523 result
->phys_index
= current_mem_blk
->phys_index
;
2524 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2525 if (local_err
) { /* should never happen */
2528 entry
= g_malloc0(sizeof *entry
);
2529 entry
->value
= result
;
2532 link
= &entry
->next
;
2533 mem_blks
= mem_blks
->next
;
2538 qapi_free_GuestMemoryBlockResponseList(head
);
2539 error_propagate(errp
, local_err
);
2543 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2545 Error
*local_err
= NULL
;
2549 GuestMemoryBlockInfo
*info
;
2551 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2552 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2554 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2560 buf
= g_malloc0(20);
2561 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2565 error_propagate(errp
, local_err
);
2569 info
= g_new0(GuestMemoryBlockInfo
, 1);
2570 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2577 #else /* defined(__linux__) */
2579 void qmp_guest_suspend_disk(Error
**errp
)
2581 error_setg(errp
, QERR_UNSUPPORTED
);
2584 void qmp_guest_suspend_ram(Error
**errp
)
2586 error_setg(errp
, QERR_UNSUPPORTED
);
2589 void qmp_guest_suspend_hybrid(Error
**errp
)
2591 error_setg(errp
, QERR_UNSUPPORTED
);
2594 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2596 error_setg(errp
, QERR_UNSUPPORTED
);
2600 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2602 error_setg(errp
, QERR_UNSUPPORTED
);
2606 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2608 error_setg(errp
, QERR_UNSUPPORTED
);
2612 void qmp_guest_set_user_password(const char *username
,
2613 const char *password
,
2617 error_setg(errp
, QERR_UNSUPPORTED
);
2620 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2622 error_setg(errp
, QERR_UNSUPPORTED
);
2626 GuestMemoryBlockResponseList
*
2627 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2629 error_setg(errp
, QERR_UNSUPPORTED
);
2633 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2635 error_setg(errp
, QERR_UNSUPPORTED
);
2641 #if !defined(CONFIG_FSFREEZE)
2643 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
2645 error_setg(errp
, QERR_UNSUPPORTED
);
2649 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
2651 error_setg(errp
, QERR_UNSUPPORTED
);
2656 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
2658 error_setg(errp
, QERR_UNSUPPORTED
);
2663 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
2664 strList
*mountpoints
,
2667 error_setg(errp
, QERR_UNSUPPORTED
);
2672 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
2674 error_setg(errp
, QERR_UNSUPPORTED
);
2678 #endif /* CONFIG_FSFREEZE */
2680 #if !defined(CONFIG_FSTRIM)
2681 GuestFilesystemTrimResponse
*
2682 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
2684 error_setg(errp
, QERR_UNSUPPORTED
);
2689 /* add unsupported commands to the blacklist */
2690 GList
*ga_command_blacklist_init(GList
*blacklist
)
2692 #if !defined(__linux__)
2694 const char *list
[] = {
2695 "guest-suspend-disk", "guest-suspend-ram",
2696 "guest-suspend-hybrid", "guest-network-get-interfaces",
2697 "guest-get-vcpus", "guest-set-vcpus",
2698 "guest-get-memory-blocks", "guest-set-memory-blocks",
2699 "guest-get-memory-block-size", NULL
};
2700 char **p
= (char **)list
;
2703 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2708 #if !defined(CONFIG_FSFREEZE)
2710 const char *list
[] = {
2711 "guest-get-fsinfo", "guest-fsfreeze-status",
2712 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2713 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL
};
2714 char **p
= (char **)list
;
2717 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2722 #if !defined(CONFIG_FSTRIM)
2723 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
2729 /* register init/cleanup routines for stateful command groups */
2730 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2732 #if defined(CONFIG_FSFREEZE)
2733 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
2739 #define QGA_MICRO_SECOND_TO_SECOND 1000000
2741 static double ga_get_login_time(struct utmpx
*user_info
)
2743 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
2744 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
2745 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
2746 return seconds
+ useconds
;
2749 GuestUserList
*qmp_guest_get_users(Error
**err
)
2751 GHashTable
*cache
= NULL
;
2752 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
2753 struct utmpx
*user_info
= NULL
;
2754 gpointer value
= NULL
;
2755 GuestUser
*user
= NULL
;
2756 GuestUserList
*item
= NULL
;
2757 double login_time
= 0;
2759 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
2763 user_info
= getutxent();
2764 if (user_info
== NULL
) {
2766 } else if (user_info
->ut_type
!= USER_PROCESS
) {
2768 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
2769 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
2770 user
= (GuestUser
*)value
;
2771 login_time
= ga_get_login_time(user_info
);
2772 /* We're ensuring the earliest login time to be sent */
2773 if (login_time
< user
->login_time
) {
2774 user
->login_time
= login_time
;
2779 item
= g_new0(GuestUserList
, 1);
2780 item
->value
= g_new0(GuestUser
, 1);
2781 item
->value
->user
= g_strdup(user_info
->ut_user
);
2782 item
->value
->login_time
= ga_get_login_time(user_info
);
2784 g_hash_table_insert(cache
, item
->value
->user
, item
->value
);
2787 head
= cur_item
= item
;
2789 cur_item
->next
= item
;
2794 g_hash_table_destroy(cache
);
2800 GuestUserList
*qmp_guest_get_users(Error
**errp
)
2802 error_setg(errp
, QERR_UNSUPPORTED
);
2808 /* Replace escaped special characters with theire real values. The replacement
2809 * is done in place -- returned value is in the original string.
2811 static void ga_osrelease_replace_special(gchar
*value
)
2813 gchar
*p
, *p2
, quote
;
2815 /* Trim the string at first space or semicolon if it is not enclosed in
2816 * single or double quotes. */
2817 if ((value
[0] != '"') || (value
[0] == '\'')) {
2818 p
= strchr(value
, ' ');
2822 p
= strchr(value
, ';');
2843 /* Keep literal backslash followed by whatever is there */
2847 } else if (*p
== quote
) {
2855 static GKeyFile
*ga_parse_osrelease(const char *fname
)
2857 gchar
*content
= NULL
;
2858 gchar
*content2
= NULL
;
2860 GKeyFile
*keys
= g_key_file_new();
2861 const char *group
= "[os-release]\n";
2863 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
2864 slog("failed to read '%s', error: %s", fname
, err
->message
);
2868 if (!g_utf8_validate(content
, -1, NULL
)) {
2869 slog("file is not utf-8 encoded: %s", fname
);
2872 content2
= g_strdup_printf("%s%s", group
, content
);
2874 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
2876 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
2888 g_key_file_free(keys
);
2892 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2894 GuestOSInfo
*info
= NULL
;
2895 struct utsname kinfo
;
2896 GKeyFile
*osrelease
= NULL
;
2897 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
2899 info
= g_new0(GuestOSInfo
, 1);
2901 if (uname(&kinfo
) != 0) {
2902 error_setg_errno(errp
, errno
, "uname failed");
2904 info
->has_kernel_version
= true;
2905 info
->kernel_version
= g_strdup(kinfo
.version
);
2906 info
->has_kernel_release
= true;
2907 info
->kernel_release
= g_strdup(kinfo
.release
);
2908 info
->has_machine
= true;
2909 info
->machine
= g_strdup(kinfo
.machine
);
2912 if (qga_os_release
!= NULL
) {
2913 osrelease
= ga_parse_osrelease(qga_os_release
);
2915 osrelease
= ga_parse_osrelease("/etc/os-release");
2916 if (osrelease
== NULL
) {
2917 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
2921 if (osrelease
!= NULL
) {
2924 #define GET_FIELD(field, osfield) do { \
2925 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
2926 if (value != NULL) { \
2927 ga_osrelease_replace_special(value); \
2928 info->has_ ## field = true; \
2929 info->field = value; \
2932 GET_FIELD(id
, "ID");
2933 GET_FIELD(name
, "NAME");
2934 GET_FIELD(pretty_name
, "PRETTY_NAME");
2935 GET_FIELD(version
, "VERSION");
2936 GET_FIELD(version_id
, "VERSION_ID");
2937 GET_FIELD(variant
, "VARIANT");
2938 GET_FIELD(variant_id
, "VARIANT_ID");
2941 g_key_file_free(osrelease
);