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 "qga-qapi-commands.h"
20 #include "qapi/error.h"
21 #include "qapi/qmp/qerror.h"
22 #include "qemu/host-utils.h"
23 #include "qemu/sockets.h"
24 #include "qemu/base64.h"
25 #include "qemu/cutils.h"
26 #include "commands-common.h"
33 #ifdef HAVE_GETIFADDRS
34 #include <arpa/inet.h>
35 #include <sys/socket.h>
37 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(CONFIG_SOLARIS)
38 #include <net/if_arp.h>
39 #include <netinet/if_ether.h>
40 #if !defined(ETHER_ADDR_LEN) && defined(ETHERADDRL)
41 #define ETHER_ADDR_LEN ETHERADDRL
44 #include <net/ethernet.h>
47 #include <sys/sockio.h>
51 static bool ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
57 rpid
= RETRY_ON_EINTR(waitpid(pid
, status
, 0));
60 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
65 g_assert(rpid
== pid
);
69 static ssize_t
ga_pipe_read_str(int fd
[2], char **str
)
76 while ((n
= read(fd
[0], buf
, sizeof(buf
))) != 0) {
85 *str
= g_realloc(*str
, len
+ n
+ 1);
86 memcpy(*str
+ len
, buf
, n
);
97 * Helper to run command with input/output redirection,
98 * sending string to stdin and taking error message from
101 static int ga_run_command(const char *argv
[], const char *in_str
,
102 const char *action
, Error
**errp
)
107 int infd
[2] = { -1, -1 };
108 int outfd
[2] = { -1, -1 };
112 if ((in_str
&& !g_unix_open_pipe(infd
, FD_CLOEXEC
, NULL
)) ||
113 !g_unix_open_pipe(outfd
, FD_CLOEXEC
, NULL
)) {
114 error_setg(errp
, "cannot create pipe FDs");
125 /* Redirect stdin to infd. */
130 reopen_fd_to_null(0);
133 /* Redirect stdout/stderr to outfd. */
139 execvp(argv
[0], (char *const *)argv
);
141 /* Write the cause of failed exec to pipe for the parent to read it. */
142 cherr
= g_strdup_printf("failed to exec '%s'", argv
[0]);
146 } else if (pid
< 0) {
147 error_setg_errno(errp
, errno
, "failed to create child process");
154 if (qemu_write_full(infd
[1], in_str
, strlen(in_str
)) !=
156 error_setg_errno(errp
, errno
, "%s: cannot write to stdin pipe",
164 len
= ga_pipe_read_str(outfd
, &str
);
166 error_setg_errno(errp
, -len
, "%s: cannot read from stdout/stderr pipe",
171 if (!ga_wait_child(pid
, &status
, errp
)) {
175 if (!WIFEXITED(status
)) {
177 error_setg(errp
, "child process has terminated abnormally: %s",
180 error_setg(errp
, "child process has terminated abnormally");
185 retcode
= WEXITSTATUS(status
);
187 if (WEXITSTATUS(status
)) {
189 error_setg(errp
, "child process has failed to %s: %s",
192 error_setg(errp
, "child process has failed to %s: exit status %d",
193 action
, WEXITSTATUS(status
));
207 if (outfd
[0] != -1) {
210 if (outfd
[1] != -1) {
217 void qmp_guest_shutdown(const char *mode
, Error
**errp
)
219 const char *shutdown_flag
;
220 Error
*local_err
= NULL
;
222 #ifdef CONFIG_SOLARIS
223 const char *powerdown_flag
= "-i5";
224 const char *halt_flag
= "-i0";
225 const char *reboot_flag
= "-i6";
226 #elif defined(CONFIG_BSD)
227 const char *powerdown_flag
= "-p";
228 const char *halt_flag
= "-h";
229 const char *reboot_flag
= "-r";
231 const char *powerdown_flag
= "-P";
232 const char *halt_flag
= "-H";
233 const char *reboot_flag
= "-r";
236 slog("guest-shutdown called, mode: %s", mode
);
237 if (!mode
|| strcmp(mode
, "powerdown") == 0) {
238 shutdown_flag
= powerdown_flag
;
239 } else if (strcmp(mode
, "halt") == 0) {
240 shutdown_flag
= halt_flag
;
241 } else if (strcmp(mode
, "reboot") == 0) {
242 shutdown_flag
= reboot_flag
;
245 "mode is invalid (valid values are: halt|powerdown|reboot");
249 const char *argv
[] = {"/sbin/shutdown",
250 #ifdef CONFIG_SOLARIS
251 shutdown_flag
, "-g0", "-y",
252 #elif defined(CONFIG_BSD)
255 "-h", shutdown_flag
, "+0",
257 "hypervisor initiated shutdown", (char *) NULL
};
259 ga_run_command(argv
, NULL
, "shutdown", &local_err
);
261 error_propagate(errp
, local_err
);
268 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
271 Error
*local_err
= NULL
;
273 const char *argv
[] = {"/sbin/hwclock", has_time
? "-w" : "-s", NULL
};
275 /* If user has passed a time, validate and set it. */
279 /* year-2038 will overflow in case time_t is 32bit */
280 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
281 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
285 tv
.tv_sec
= time_ns
/ 1000000000;
286 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
287 g_date_set_time_t(&date
, tv
.tv_sec
);
288 if (date
.year
< 1970 || date
.year
>= 2070) {
289 error_setg_errno(errp
, errno
, "Invalid time");
293 ret
= settimeofday(&tv
, NULL
);
295 error_setg_errno(errp
, errno
, "Failed to set time to guest");
300 /* Now, if user has passed a time to set and the system time is set, we
301 * just need to synchronize the hardware clock. However, if no time was
302 * passed, user is requesting the opposite: set the system time from the
303 * hardware clock (RTC). */
304 ga_run_command(argv
, NULL
, "set hardware clock to system time",
307 error_propagate(errp
, local_err
);
318 struct GuestFileHandle
{
322 QTAILQ_ENTRY(GuestFileHandle
) next
;
326 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
327 } guest_file_state
= {
328 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
331 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
333 GuestFileHandle
*gfh
;
336 handle
= ga_get_fd_handle(ga_state
, errp
);
341 gfh
= g_new0(GuestFileHandle
, 1);
344 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
349 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
351 GuestFileHandle
*gfh
;
353 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
360 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
364 typedef const char * const ccpc
;
370 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
371 static const struct {
374 } guest_file_open_modes
[] = {
375 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
376 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
377 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
378 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
379 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
380 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
381 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
382 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
383 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
384 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
385 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
386 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
390 find_open_flag(const char *mode_str
, Error
**errp
)
394 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
397 form
= guest_file_open_modes
[mode
].forms
;
398 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
406 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
407 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
410 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
413 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
414 S_IRGRP | S_IWGRP | \
418 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
424 oflag
= find_open_flag(mode
, errp
);
429 /* If the caller wants / allows creation of a new file, we implement it
430 * with a two step process: open() + (open() / fchmod()).
432 * First we insist on creating the file exclusively as a new file. If
433 * that succeeds, we're free to set any file-mode bits on it. (The
434 * motivation is that we want to set those file-mode bits independently
435 * of the current umask.)
437 * If the exclusive creation fails because the file already exists
438 * (EEXIST is not possible for any other reason), we just attempt to
439 * open the file, but in this case we won't be allowed to change the
440 * file-mode bits on the preexistent file.
442 * The pathname should never disappear between the two open()s in
443 * practice. If it happens, then someone very likely tried to race us.
444 * In this case just go ahead and report the ENOENT from the second
445 * open() to the caller.
447 * If the caller wants to open a preexistent file, then the first
448 * open() is decisive and its third argument is ignored, and the second
449 * open() and the fchmod() are never called.
451 fd
= qga_open_cloexec(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
452 if (fd
== -1 && errno
== EEXIST
) {
453 oflag
&= ~(unsigned)O_CREAT
;
454 fd
= qga_open_cloexec(path
, oflag
, 0);
457 error_setg_errno(errp
, errno
,
458 "failed to open file '%s' (mode: '%s')",
463 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
464 error_setg_errno(errp
, errno
, "failed to set permission "
465 "0%03o on new file '%s' (mode: '%s')",
466 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
470 f
= fdopen(fd
, mode
);
472 error_setg_errno(errp
, errno
, "failed to associate stdio stream with "
473 "file descriptor %d, file '%s' (mode: '%s')",
478 if (f
== NULL
&& fd
!= -1) {
480 if (oflag
& O_CREAT
) {
487 int64_t qmp_guest_file_open(const char *path
, const char *mode
,
491 Error
*local_err
= NULL
;
497 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
498 fh
= safe_open_or_create(path
, mode
, &local_err
);
499 if (local_err
!= NULL
) {
500 error_propagate(errp
, local_err
);
504 /* set fd non-blocking to avoid common use cases (like reading from a
505 * named pipe) from hanging the agent
507 if (!g_unix_set_fd_nonblocking(fileno(fh
), true, NULL
)) {
509 error_setg_errno(errp
, errno
, "Failed to set FD nonblocking");
513 handle
= guest_file_handle_add(fh
, errp
);
519 slog("guest-file-open, handle: %" PRId64
, handle
);
523 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
525 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
528 slog("guest-file-close called, handle: %" PRId64
, handle
);
533 ret
= fclose(gfh
->fh
);
535 error_setg_errno(errp
, errno
, "failed to close handle");
539 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
543 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
544 int64_t count
, Error
**errp
)
546 GuestFileRead
*read_data
= NULL
;
551 /* explicitly flush when switching from writing to reading */
552 if (gfh
->state
== RW_STATE_WRITING
) {
553 int ret
= fflush(fh
);
555 error_setg_errno(errp
, errno
, "failed to flush file");
558 gfh
->state
= RW_STATE_NEW
;
561 buf
= g_malloc0(count
+ 1);
562 read_count
= fread(buf
, 1, count
, fh
);
564 error_setg_errno(errp
, errno
, "failed to read file");
567 read_data
= g_new0(GuestFileRead
, 1);
568 read_data
->count
= read_count
;
569 read_data
->eof
= feof(fh
);
571 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
573 gfh
->state
= RW_STATE_READING
;
581 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
582 bool has_count
, int64_t count
,
585 GuestFileWrite
*write_data
= NULL
;
589 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
598 if (gfh
->state
== RW_STATE_READING
) {
599 int ret
= fseek(fh
, 0, SEEK_CUR
);
601 error_setg_errno(errp
, errno
, "failed to seek file");
604 gfh
->state
= RW_STATE_NEW
;
607 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
614 } else if (count
< 0 || count
> buf_len
) {
615 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
621 write_count
= fwrite(buf
, 1, count
, fh
);
623 error_setg_errno(errp
, errno
, "failed to write to file");
624 slog("guest-file-write failed, handle: %" PRId64
, handle
);
626 write_data
= g_new0(GuestFileWrite
, 1);
627 write_data
->count
= write_count
;
628 write_data
->eof
= feof(fh
);
629 gfh
->state
= RW_STATE_WRITING
;
637 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
638 GuestFileWhence
*whence_code
,
641 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
642 GuestFileSeek
*seek_data
= NULL
;
652 /* We stupidly exposed 'whence':'int' in our qapi */
653 whence
= ga_parse_whence(whence_code
, &err
);
655 error_propagate(errp
, err
);
660 ret
= fseek(fh
, offset
, whence
);
662 error_setg_errno(errp
, errno
, "failed to seek file");
663 if (errno
== ESPIPE
) {
664 /* file is non-seekable, stdio shouldn't be buffering anyways */
665 gfh
->state
= RW_STATE_NEW
;
668 seek_data
= g_new0(GuestFileSeek
, 1);
669 seek_data
->position
= ftell(fh
);
670 seek_data
->eof
= feof(fh
);
671 gfh
->state
= RW_STATE_NEW
;
678 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
680 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
691 error_setg_errno(errp
, errno
, "failed to flush file");
693 gfh
->state
= RW_STATE_NEW
;
697 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
698 void free_fs_mount_list(FsMountList
*mounts
)
700 FsMount
*mount
, *temp
;
706 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
707 QTAILQ_REMOVE(mounts
, mount
, next
);
708 g_free(mount
->dirname
);
709 g_free(mount
->devtype
);
715 #if defined(CONFIG_FSFREEZE)
717 FSFREEZE_HOOK_THAW
= 0,
718 FSFREEZE_HOOK_FREEZE
,
721 static const char *fsfreeze_hook_arg_string
[] = {
726 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
729 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
730 Error
*local_err
= NULL
;
732 hook
= ga_fsfreeze_hook(ga_state
);
737 const char *argv
[] = {hook
, arg_str
, NULL
};
739 slog("executing fsfreeze hook with arg '%s'", arg_str
);
740 ga_run_command(argv
, NULL
, "execute fsfreeze hook", &local_err
);
742 error_propagate(errp
, local_err
);
748 * Return status of freeze/thaw
750 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
752 if (ga_is_frozen(ga_state
)) {
753 return GUEST_FSFREEZE_STATUS_FROZEN
;
756 return GUEST_FSFREEZE_STATUS_THAWED
;
759 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
761 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
764 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
765 strList
*mountpoints
,
770 Error
*local_err
= NULL
;
772 slog("guest-fsfreeze called");
774 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
776 error_propagate(errp
, local_err
);
780 QTAILQ_INIT(&mounts
);
781 if (!build_fs_mount_list(&mounts
, &local_err
)) {
782 error_propagate(errp
, local_err
);
786 /* cannot risk guest agent blocking itself on a write in this state */
787 ga_set_frozen(ga_state
);
789 ret
= qmp_guest_fsfreeze_do_freeze_list(has_mountpoints
, mountpoints
,
792 free_fs_mount_list(&mounts
);
793 /* We may not issue any FIFREEZE here.
794 * Just unset ga_state here and ready for the next call.
797 ga_unset_frozen(ga_state
);
798 } else if (ret
< 0) {
799 qmp_guest_fsfreeze_thaw(NULL
);
804 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
808 ret
= qmp_guest_fsfreeze_do_thaw(errp
);
810 ga_unset_frozen(ga_state
);
811 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
819 static void guest_fsfreeze_cleanup(void)
823 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
824 qmp_guest_fsfreeze_thaw(&err
);
826 slog("failed to clean up frozen filesystems: %s",
827 error_get_pretty(err
));
834 #if defined(__linux__) || defined(__FreeBSD__)
835 void qmp_guest_set_user_password(const char *username
,
836 const char *password
,
840 Error
*local_err
= NULL
;
841 g_autofree
char *rawpasswddata
= NULL
;
844 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
845 if (!rawpasswddata
) {
848 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
849 rawpasswddata
[rawpasswdlen
] = '\0';
851 if (strchr(rawpasswddata
, '\n')) {
852 error_setg(errp
, "forbidden characters in raw password");
856 if (strchr(username
, '\n') ||
857 strchr(username
, ':')) {
858 error_setg(errp
, "forbidden characters in username");
863 g_autofree
char *chpasswddata
= g_strdup(rawpasswddata
);
864 const char *crypt_flag
= crypted
? "-H" : "-h";
865 const char *argv
[] = {"pw", "usermod", "-n", username
,
866 crypt_flag
, "0", NULL
};
868 g_autofree
char *chpasswddata
= g_strdup_printf("%s:%s\n", username
,
870 const char *crypt_flag
= crypted
? "-e" : NULL
;
871 const char *argv
[] = {"chpasswd", crypt_flag
, NULL
};
874 ga_run_command(argv
, chpasswddata
, "set user password", &local_err
);
876 error_propagate(errp
, local_err
);
880 #endif /* __linux__ || __FreeBSD__ */
882 #ifdef HAVE_GETIFADDRS
883 static GuestNetworkInterface
*
884 guest_find_interface(GuestNetworkInterfaceList
*head
,
887 for (; head
; head
= head
->next
) {
888 if (strcmp(head
->value
->name
, name
) == 0) {
896 static int guest_get_network_stats(const char *name
,
897 GuestNetworkInterfaceStat
*stats
)
901 char const *devinfo
= "/proc/net/dev";
903 char *line
= NULL
, *colon
;
905 fp
= fopen(devinfo
, "r");
907 g_debug("failed to open network stats %s: %s", devinfo
,
911 name_len
= strlen(name
);
912 while (getline(&line
, &n
, fp
) != -1) {
915 long long rx_packets
;
917 long long rx_dropped
;
919 long long tx_packets
;
921 long long tx_dropped
;
923 trim_line
= g_strchug(line
);
924 if (trim_line
[0] == '\0') {
927 colon
= strchr(trim_line
, ':');
931 if (colon
- name_len
== trim_line
&&
932 strncmp(trim_line
, name
, name_len
) == 0) {
933 if (sscanf(colon
+ 1,
934 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
935 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
936 &dummy
, &dummy
, &dummy
, &dummy
,
937 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
938 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
941 stats
->rx_bytes
= rx_bytes
;
942 stats
->rx_packets
= rx_packets
;
943 stats
->rx_errs
= rx_errs
;
944 stats
->rx_dropped
= rx_dropped
;
945 stats
->tx_bytes
= tx_bytes
;
946 stats
->tx_packets
= tx_packets
;
947 stats
->tx_errs
= tx_errs
;
948 stats
->tx_dropped
= tx_dropped
;
956 g_debug("/proc/net/dev: Interface '%s' not found", name
);
957 #else /* !CONFIG_LINUX */
958 g_debug("Network stats reporting available only for Linux");
959 #endif /* !CONFIG_LINUX */
965 * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
966 * buffer with ETHER_ADDR_LEN length at least.
968 * Returns false in case of an error, otherwise true. "obtained" argument
969 * is true if a MAC address was obtained successful, otherwise false.
971 bool guest_get_hw_addr(struct ifaddrs
*ifa
, unsigned char *buf
,
972 bool *obtained
, Error
**errp
)
979 /* we haven't obtained HW address yet */
980 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
982 error_setg_errno(errp
, errno
, "failed to create socket");
986 memset(&ifr
, 0, sizeof(ifr
));
987 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, ifa
->ifa_name
);
988 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
990 * We can't get the hw addr of this interface, but that's not a
993 if (errno
== EADDRNOTAVAIL
) {
994 /* The interface doesn't have a hw addr (e.g. loopback). */
995 g_debug("failed to get MAC address of %s: %s",
996 ifa
->ifa_name
, strerror(errno
));
998 g_warning("failed to get MAC address of %s: %s",
999 ifa
->ifa_name
, strerror(errno
));
1002 #ifdef CONFIG_SOLARIS
1003 memcpy(buf
, &ifr
.ifr_addr
.sa_data
, ETHER_ADDR_LEN
);
1005 memcpy(buf
, &ifr
.ifr_hwaddr
.sa_data
, ETHER_ADDR_LEN
);
1012 #endif /* CONFIG_BSD */
1015 * Build information about guest interfaces
1017 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1019 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
1020 struct ifaddrs
*ifap
, *ifa
;
1022 if (getifaddrs(&ifap
) < 0) {
1023 error_setg_errno(errp
, errno
, "getifaddrs failed");
1027 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1028 GuestNetworkInterface
*info
;
1029 GuestIpAddressList
**address_tail
;
1030 GuestIpAddress
*address_item
= NULL
;
1031 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
1032 char addr4
[INET_ADDRSTRLEN
];
1033 char addr6
[INET6_ADDRSTRLEN
];
1034 unsigned char mac_addr
[ETHER_ADDR_LEN
];
1038 g_debug("Processing %s interface", ifa
->ifa_name
);
1040 info
= guest_find_interface(head
, ifa
->ifa_name
);
1043 info
= g_malloc0(sizeof(*info
));
1044 info
->name
= g_strdup(ifa
->ifa_name
);
1046 QAPI_LIST_APPEND(tail
, info
);
1049 if (!info
->hardware_address
) {
1050 if (!guest_get_hw_addr(ifa
, mac_addr
, &obtained
, errp
)) {
1054 info
->hardware_address
=
1055 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1056 (int) mac_addr
[0], (int) mac_addr
[1],
1057 (int) mac_addr
[2], (int) mac_addr
[3],
1058 (int) mac_addr
[4], (int) mac_addr
[5]);
1062 if (ifa
->ifa_addr
&&
1063 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1064 /* interface with IPv4 address */
1065 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1066 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1067 error_setg_errno(errp
, errno
, "inet_ntop failed");
1071 address_item
= g_malloc0(sizeof(*address_item
));
1072 address_item
->ip_address
= g_strdup(addr4
);
1073 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1075 if (ifa
->ifa_netmask
) {
1076 /* Count the number of set bits in netmask.
1077 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1078 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1079 address_item
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1081 } else if (ifa
->ifa_addr
&&
1082 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1083 /* interface with IPv6 address */
1084 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1085 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1086 error_setg_errno(errp
, errno
, "inet_ntop failed");
1090 address_item
= g_malloc0(sizeof(*address_item
));
1091 address_item
->ip_address
= g_strdup(addr6
);
1092 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1094 if (ifa
->ifa_netmask
) {
1095 /* Count the number of set bits in netmask.
1096 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1097 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1098 address_item
->prefix
=
1099 ctpop32(((uint32_t *) p
)[0]) +
1100 ctpop32(((uint32_t *) p
)[1]) +
1101 ctpop32(((uint32_t *) p
)[2]) +
1102 ctpop32(((uint32_t *) p
)[3]);
1106 if (!address_item
) {
1110 address_tail
= &info
->ip_addresses
;
1111 while (*address_tail
) {
1112 address_tail
= &(*address_tail
)->next
;
1114 QAPI_LIST_APPEND(address_tail
, address_item
);
1116 info
->has_ip_addresses
= true;
1118 if (!info
->statistics
) {
1119 interface_stat
= g_malloc0(sizeof(*interface_stat
));
1120 if (guest_get_network_stats(info
->name
, interface_stat
) == -1) {
1121 g_free(interface_stat
);
1123 info
->statistics
= interface_stat
;
1133 qapi_free_GuestNetworkInterfaceList(head
);
1137 #endif /* HAVE_GETIFADDRS */
1139 /* register init/cleanup routines for stateful command groups */
1140 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1142 #if defined(CONFIG_FSFREEZE)
1143 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1149 #define QGA_MICRO_SECOND_TO_SECOND 1000000
1151 static double ga_get_login_time(struct utmpx
*user_info
)
1153 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
1154 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
1155 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
1156 return seconds
+ useconds
;
1159 GuestUserList
*qmp_guest_get_users(Error
**errp
)
1161 GHashTable
*cache
= NULL
;
1162 GuestUserList
*head
= NULL
, **tail
= &head
;
1163 struct utmpx
*user_info
= NULL
;
1164 gpointer value
= NULL
;
1165 GuestUser
*user
= NULL
;
1166 double login_time
= 0;
1168 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
1172 user_info
= getutxent();
1173 if (user_info
== NULL
) {
1175 } else if (user_info
->ut_type
!= USER_PROCESS
) {
1177 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
1178 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
1179 user
= (GuestUser
*)value
;
1180 login_time
= ga_get_login_time(user_info
);
1181 /* We're ensuring the earliest login time to be sent */
1182 if (login_time
< user
->login_time
) {
1183 user
->login_time
= login_time
;
1188 user
= g_new0(GuestUser
, 1);
1189 user
->user
= g_strdup(user_info
->ut_user
);
1190 user
->login_time
= ga_get_login_time(user_info
);
1192 g_hash_table_insert(cache
, user
->user
, user
);
1194 QAPI_LIST_APPEND(tail
, user
);
1197 g_hash_table_destroy(cache
);
1201 #endif /* HAVE_UTMPX */
1203 /* Replace escaped special characters with their real values. The replacement
1204 * is done in place -- returned value is in the original string.
1206 static void ga_osrelease_replace_special(gchar
*value
)
1208 gchar
*p
, *p2
, quote
;
1210 /* Trim the string at first space or semicolon if it is not enclosed in
1211 * single or double quotes. */
1212 if ((value
[0] != '"') || (value
[0] == '\'')) {
1213 p
= strchr(value
, ' ');
1217 p
= strchr(value
, ';');
1238 /* Keep literal backslash followed by whatever is there */
1242 } else if (*p
== quote
) {
1250 static GKeyFile
*ga_parse_osrelease(const char *fname
)
1252 gchar
*content
= NULL
;
1253 gchar
*content2
= NULL
;
1255 GKeyFile
*keys
= g_key_file_new();
1256 const char *group
= "[os-release]\n";
1258 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
1259 slog("failed to read '%s', error: %s", fname
, err
->message
);
1263 if (!g_utf8_validate(content
, -1, NULL
)) {
1264 slog("file is not utf-8 encoded: %s", fname
);
1267 content2
= g_strdup_printf("%s%s", group
, content
);
1269 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
1271 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
1283 g_key_file_free(keys
);
1287 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
1289 GuestOSInfo
*info
= NULL
;
1290 struct utsname kinfo
;
1291 GKeyFile
*osrelease
= NULL
;
1292 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
1294 info
= g_new0(GuestOSInfo
, 1);
1296 if (uname(&kinfo
) != 0) {
1297 error_setg_errno(errp
, errno
, "uname failed");
1299 info
->kernel_version
= g_strdup(kinfo
.version
);
1300 info
->kernel_release
= g_strdup(kinfo
.release
);
1301 info
->machine
= g_strdup(kinfo
.machine
);
1304 if (qga_os_release
!= NULL
) {
1305 osrelease
= ga_parse_osrelease(qga_os_release
);
1307 osrelease
= ga_parse_osrelease("/etc/os-release");
1308 if (osrelease
== NULL
) {
1309 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
1313 if (osrelease
!= NULL
) {
1316 #define GET_FIELD(field, osfield) do { \
1317 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
1318 if (value != NULL) { \
1319 ga_osrelease_replace_special(value); \
1320 info->field = value; \
1323 GET_FIELD(id
, "ID");
1324 GET_FIELD(name
, "NAME");
1325 GET_FIELD(pretty_name
, "PRETTY_NAME");
1326 GET_FIELD(version
, "VERSION");
1327 GET_FIELD(version_id
, "VERSION_ID");
1328 GET_FIELD(variant
, "VARIANT");
1329 GET_FIELD(variant_id
, "VARIANT_ID");
1332 g_key_file_free(osrelease
);
1338 #ifndef HOST_NAME_MAX
1339 # ifdef _POSIX_HOST_NAME_MAX
1340 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
1342 # define HOST_NAME_MAX 255
1346 char *qga_get_host_name(Error
**errp
)
1349 g_autofree
char *hostname
= NULL
;
1351 #ifdef _SC_HOST_NAME_MAX
1352 len
= sysconf(_SC_HOST_NAME_MAX
);
1353 #endif /* _SC_HOST_NAME_MAX */
1356 len
= HOST_NAME_MAX
;
1359 /* Unfortunately, gethostname() below does not guarantee a
1360 * NULL terminated string. Therefore, allocate one byte more
1362 hostname
= g_new0(char, len
+ 1);
1364 if (gethostname(hostname
, len
) < 0) {
1365 error_setg_errno(errp
, errno
,
1366 "cannot get hostname");
1370 return g_steal_pointer(&hostname
);