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.
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
18 #include "qga/guest-agent-core.h"
19 #include "qga-qmp-commands.h"
21 #include "qemu-queue.h"
22 #include "host-utils.h"
24 #ifndef CONFIG_HAS_ENVIRON
26 #include <crt_externs.h>
27 #define environ (*_NSGetEnviron())
29 extern char **environ
;
33 #if defined(__linux__)
37 #include <arpa/inet.h>
38 #include <sys/socket.h>
41 #if defined(__linux__) && defined(FIFREEZE)
42 #define CONFIG_FSFREEZE
46 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**err
)
48 const char *shutdown_flag
;
52 slog("guest-shutdown called, mode: %s", mode
);
53 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
55 } else if (strcmp(mode
, "halt") == 0) {
57 } else if (strcmp(mode
, "reboot") == 0) {
60 error_set(err
, QERR_INVALID_PARAMETER_VALUE
, "mode",
61 "halt|powerdown|reboot");
67 /* child, start the shutdown */
73 execle("/sbin/shutdown", "shutdown", shutdown_flag
, "+0",
74 "hypervisor initiated shutdown", (char*)NULL
, environ
);
81 rpid
= waitpid(pid
, &status
, 0);
82 } while (rpid
== -1 && errno
== EINTR
);
83 if (rpid
== pid
&& WIFEXITED(status
) && !WEXITSTATUS(status
)) {
88 error_set(err
, QERR_UNDEFINED_ERROR
);
91 typedef struct GuestFileHandle
{
94 QTAILQ_ENTRY(GuestFileHandle
) next
;
98 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
101 static void guest_file_handle_add(FILE *fh
)
103 GuestFileHandle
*gfh
;
105 gfh
= g_malloc0(sizeof(GuestFileHandle
));
106 gfh
->id
= fileno(fh
);
108 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
111 static GuestFileHandle
*guest_file_handle_find(int64_t id
)
113 GuestFileHandle
*gfh
;
115 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
125 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
, Error
**err
)
134 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
135 fh
= fopen(path
, mode
);
137 error_set(err
, QERR_OPEN_FILE_FAILED
, path
);
141 /* set fd non-blocking to avoid common use cases (like reading from a
142 * named pipe) from hanging the agent
145 ret
= fcntl(fd
, F_GETFL
);
146 ret
= fcntl(fd
, F_SETFL
, ret
| O_NONBLOCK
);
148 error_set(err
, QERR_QGA_COMMAND_FAILED
, "fcntl() failed");
153 guest_file_handle_add(fh
);
154 slog("guest-file-open, handle: %d", fd
);
158 void qmp_guest_file_close(int64_t handle
, Error
**err
)
160 GuestFileHandle
*gfh
= guest_file_handle_find(handle
);
163 slog("guest-file-close called, handle: %ld", handle
);
165 error_set(err
, QERR_FD_NOT_FOUND
, "handle");
169 ret
= fclose(gfh
->fh
);
171 error_set(err
, QERR_QGA_COMMAND_FAILED
, "fclose() failed");
175 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
179 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
180 int64_t count
, Error
**err
)
182 GuestFileHandle
*gfh
= guest_file_handle_find(handle
);
183 GuestFileRead
*read_data
= NULL
;
189 error_set(err
, QERR_FD_NOT_FOUND
, "handle");
194 count
= QGA_READ_COUNT_DEFAULT
;
195 } else if (count
< 0) {
196 error_set(err
, QERR_INVALID_PARAMETER
, "count");
201 buf
= g_malloc0(count
+1);
202 read_count
= fread(buf
, 1, count
, fh
);
204 slog("guest-file-read failed, handle: %ld", handle
);
205 error_set(err
, QERR_QGA_COMMAND_FAILED
, "fread() failed");
208 read_data
= g_malloc0(sizeof(GuestFileRead
));
209 read_data
->count
= read_count
;
210 read_data
->eof
= feof(fh
);
212 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
221 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
222 bool has_count
, int64_t count
, Error
**err
)
224 GuestFileWrite
*write_data
= NULL
;
228 GuestFileHandle
*gfh
= guest_file_handle_find(handle
);
232 error_set(err
, QERR_FD_NOT_FOUND
, "handle");
237 buf
= g_base64_decode(buf_b64
, &buf_len
);
241 } else if (count
< 0 || count
> buf_len
) {
243 error_set(err
, QERR_INVALID_PARAMETER
, "count");
247 write_count
= fwrite(buf
, 1, count
, fh
);
249 slog("guest-file-write failed, handle: %ld", handle
);
250 error_set(err
, QERR_QGA_COMMAND_FAILED
, "fwrite() error");
252 write_data
= g_malloc0(sizeof(GuestFileWrite
));
253 write_data
->count
= write_count
;
254 write_data
->eof
= feof(fh
);
262 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
263 int64_t whence
, Error
**err
)
265 GuestFileHandle
*gfh
= guest_file_handle_find(handle
);
266 GuestFileSeek
*seek_data
= NULL
;
271 error_set(err
, QERR_FD_NOT_FOUND
, "handle");
276 ret
= fseek(fh
, offset
, whence
);
278 error_set(err
, QERR_QGA_COMMAND_FAILED
, strerror(errno
));
280 seek_data
= g_malloc0(sizeof(GuestFileRead
));
281 seek_data
->position
= ftell(fh
);
282 seek_data
->eof
= feof(fh
);
289 void qmp_guest_file_flush(int64_t handle
, Error
**err
)
291 GuestFileHandle
*gfh
= guest_file_handle_find(handle
);
296 error_set(err
, QERR_FD_NOT_FOUND
, "handle");
303 error_set(err
, QERR_QGA_COMMAND_FAILED
, strerror(errno
));
307 static void guest_file_init(void)
309 QTAILQ_INIT(&guest_file_state
.filehandles
);
312 /* linux-specific implementations. avoid this if at all possible. */
313 #if defined(__linux__)
315 #if defined(CONFIG_FSFREEZE)
317 typedef struct GuestFsfreezeMount
{
320 QTAILQ_ENTRY(GuestFsfreezeMount
) next
;
321 } GuestFsfreezeMount
;
323 typedef QTAILQ_HEAD(, GuestFsfreezeMount
) GuestFsfreezeMountList
;
325 static void guest_fsfreeze_free_mount_list(GuestFsfreezeMountList
*mounts
)
327 GuestFsfreezeMount
*mount
, *temp
;
333 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
334 QTAILQ_REMOVE(mounts
, mount
, next
);
335 g_free(mount
->dirname
);
336 g_free(mount
->devtype
);
342 * Walk the mount table and build a list of local file systems
344 static int guest_fsfreeze_build_mount_list(GuestFsfreezeMountList
*mounts
)
347 GuestFsfreezeMount
*mount
;
348 char const *mtab
= "/proc/self/mounts";
351 fp
= setmntent(mtab
, "r");
353 g_warning("fsfreeze: unable to read mtab");
357 while ((ment
= getmntent(fp
))) {
359 * An entry which device name doesn't start with a '/' is
360 * either a dummy file system or a network file system.
361 * Add special handling for smbfs and cifs as is done by
364 if ((ment
->mnt_fsname
[0] != '/') ||
365 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
366 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
370 mount
= g_malloc0(sizeof(GuestFsfreezeMount
));
371 mount
->dirname
= g_strdup(ment
->mnt_dir
);
372 mount
->devtype
= g_strdup(ment
->mnt_type
);
374 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
383 * Return status of freeze/thaw
385 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**err
)
387 if (ga_is_frozen(ga_state
)) {
388 return GUEST_FSFREEZE_STATUS_FROZEN
;
391 return GUEST_FSFREEZE_STATUS_THAWED
;
395 * Walk list of mounted file systems in the guest, and freeze the ones which
396 * are real local file systems.
398 int64_t qmp_guest_fsfreeze_freeze(Error
**err
)
401 GuestFsfreezeMountList mounts
;
402 struct GuestFsfreezeMount
*mount
;
406 slog("guest-fsfreeze called");
408 QTAILQ_INIT(&mounts
);
409 ret
= guest_fsfreeze_build_mount_list(&mounts
);
414 /* cannot risk guest agent blocking itself on a write in this state */
415 ga_set_frozen(ga_state
);
417 QTAILQ_FOREACH(mount
, &mounts
, next
) {
418 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
420 sprintf(err_msg
, "failed to open %s, %s", mount
->dirname
,
422 error_set(err
, QERR_QGA_COMMAND_FAILED
, err_msg
);
426 /* we try to cull filesytems we know won't work in advance, but other
427 * filesytems may not implement fsfreeze for less obvious reasons.
428 * these will report EOPNOTSUPP. we simply ignore these when tallying
429 * the number of frozen filesystems.
431 * any other error means a failure to freeze a filesystem we
432 * expect to be freezable, so return an error in those cases
433 * and return system to thawed state.
435 ret
= ioctl(fd
, FIFREEZE
);
437 if (errno
!= EOPNOTSUPP
) {
438 sprintf(err_msg
, "failed to freeze %s, %s",
439 mount
->dirname
, strerror(errno
));
440 error_set(err
, QERR_QGA_COMMAND_FAILED
, err_msg
);
450 guest_fsfreeze_free_mount_list(&mounts
);
454 guest_fsfreeze_free_mount_list(&mounts
);
455 qmp_guest_fsfreeze_thaw(NULL
);
460 * Walk list of frozen file systems in the guest, and thaw them.
462 int64_t qmp_guest_fsfreeze_thaw(Error
**err
)
465 GuestFsfreezeMountList mounts
;
466 GuestFsfreezeMount
*mount
;
467 int fd
, i
= 0, logged
;
469 QTAILQ_INIT(&mounts
);
470 ret
= guest_fsfreeze_build_mount_list(&mounts
);
472 error_set(err
, QERR_QGA_COMMAND_FAILED
,
473 "failed to enumerate filesystems");
477 QTAILQ_FOREACH(mount
, &mounts
, next
) {
479 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
483 /* we have no way of knowing whether a filesystem was actually unfrozen
484 * as a result of a successful call to FITHAW, only that if an error
485 * was returned the filesystem was *not* unfrozen by that particular
488 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
489 * to unfreeze, continuing issuing FITHAW until an error is returned,
490 * in which case either the filesystem is in an unfreezable state, or,
491 * more likely, it was thawed previously (and remains so afterward).
493 * also, since the most recent successful call is the one that did
494 * the actual unfreeze, we can use this to provide an accurate count
495 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
496 * may * be useful for determining whether a filesystem was unfrozen
497 * during the freeze/thaw phase by a process other than qemu-ga.
500 ret
= ioctl(fd
, FITHAW
);
501 if (ret
== 0 && !logged
) {
509 ga_unset_frozen(ga_state
);
510 guest_fsfreeze_free_mount_list(&mounts
);
514 static void guest_fsfreeze_cleanup(void)
519 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
520 ret
= qmp_guest_fsfreeze_thaw(&err
);
521 if (ret
< 0 || err
) {
522 slog("failed to clean up frozen filesystems");
526 #endif /* CONFIG_FSFREEZE */
528 #define LINUX_SYS_STATE_FILE "/sys/power/state"
529 #define SUSPEND_SUPPORTED 0
530 #define SUSPEND_NOT_SUPPORTED 1
532 static void bios_supports_mode(const char *pmutils_bin
, const char *pmutils_arg
,
533 const char *sysfile_str
, Error
**err
)
539 pmutils_path
= g_find_program_in_path(pmutils_bin
);
543 char buf
[32]; /* hopefully big enough */
548 reopen_fd_to_null(0);
549 reopen_fd_to_null(1);
550 reopen_fd_to_null(2);
553 execle(pmutils_path
, pmutils_bin
, pmutils_arg
, NULL
, environ
);
557 * If we get here either pm-utils is not installed or execle() has
558 * failed. Let's try the manual method if the caller wants it.
562 _exit(SUSPEND_NOT_SUPPORTED
);
565 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
567 _exit(SUSPEND_NOT_SUPPORTED
);
570 ret
= read(fd
, buf
, sizeof(buf
)-1);
572 _exit(SUSPEND_NOT_SUPPORTED
);
576 if (strstr(buf
, sysfile_str
)) {
577 _exit(SUSPEND_SUPPORTED
);
580 _exit(SUSPEND_NOT_SUPPORTED
);
583 g_free(pmutils_path
);
590 rpid
= waitpid(pid
, &status
, 0);
591 } while (rpid
== -1 && errno
== EINTR
);
592 if (rpid
== pid
&& WIFEXITED(status
)) {
593 switch (WEXITSTATUS(status
)) {
594 case SUSPEND_SUPPORTED
:
596 case SUSPEND_NOT_SUPPORTED
:
597 error_set(err
, QERR_UNSUPPORTED
);
605 error_set(err
, QERR_UNDEFINED_ERROR
);
608 static void guest_suspend(const char *pmutils_bin
, const char *sysfile_str
,
615 pmutils_path
= g_find_program_in_path(pmutils_bin
);
623 reopen_fd_to_null(0);
624 reopen_fd_to_null(1);
625 reopen_fd_to_null(2);
628 execle(pmutils_path
, pmutils_bin
, NULL
, environ
);
632 * If we get here either pm-utils is not installed or execle() has
633 * failed. Let's try the manual method if the caller wants it.
640 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
645 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
652 g_free(pmutils_path
);
659 rpid
= waitpid(pid
, &status
, 0);
660 } while (rpid
== -1 && errno
== EINTR
);
661 if (rpid
== pid
&& WIFEXITED(status
) && !WEXITSTATUS(status
)) {
666 error_set(err
, QERR_UNDEFINED_ERROR
);
669 void qmp_guest_suspend_disk(Error
**err
)
671 bios_supports_mode("pm-is-supported", "--hibernate", "disk", err
);
672 if (error_is_set(err
)) {
676 guest_suspend("pm-hibernate", "disk", err
);
679 void qmp_guest_suspend_ram(Error
**err
)
681 bios_supports_mode("pm-is-supported", "--suspend", "mem", err
);
682 if (error_is_set(err
)) {
686 guest_suspend("pm-suspend", "mem", err
);
689 void qmp_guest_suspend_hybrid(Error
**err
)
691 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL
, err
);
692 if (error_is_set(err
)) {
696 guest_suspend("pm-suspend-hybrid", NULL
, err
);
699 static GuestNetworkInterfaceList
*
700 guest_find_interface(GuestNetworkInterfaceList
*head
,
703 for (; head
; head
= head
->next
) {
704 if (strcmp(head
->value
->name
, name
) == 0) {
713 * Build information about guest interfaces
715 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
717 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
718 struct ifaddrs
*ifap
, *ifa
;
721 if (getifaddrs(&ifap
) < 0) {
722 snprintf(err_msg
, sizeof(err_msg
),
723 "getifaddrs failed: %s", strerror(errno
));
724 error_set(errp
, QERR_QGA_COMMAND_FAILED
, err_msg
);
728 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
729 GuestNetworkInterfaceList
*info
;
730 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
731 char addr4
[INET_ADDRSTRLEN
];
732 char addr6
[INET6_ADDRSTRLEN
];
735 unsigned char *mac_addr
;
738 g_debug("Processing %s interface", ifa
->ifa_name
);
740 info
= guest_find_interface(head
, ifa
->ifa_name
);
743 info
= g_malloc0(sizeof(*info
));
744 info
->value
= g_malloc0(sizeof(*info
->value
));
745 info
->value
->name
= g_strdup(ifa
->ifa_name
);
748 head
= cur_item
= info
;
750 cur_item
->next
= info
;
755 if (!info
->value
->has_hardware_address
&&
756 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
757 /* we haven't obtained HW address yet */
758 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
760 snprintf(err_msg
, sizeof(err_msg
),
761 "failed to create socket: %s", strerror(errno
));
762 error_set(errp
, QERR_QGA_COMMAND_FAILED
, err_msg
);
766 memset(&ifr
, 0, sizeof(ifr
));
767 strncpy(ifr
.ifr_name
, info
->value
->name
, IF_NAMESIZE
);
768 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
769 snprintf(err_msg
, sizeof(err_msg
),
770 "failed to get MAC address of %s: %s",
773 error_set(errp
, QERR_QGA_COMMAND_FAILED
, err_msg
);
777 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
779 if (asprintf(&info
->value
->hardware_address
,
780 "%02x:%02x:%02x:%02x:%02x:%02x",
781 (int) mac_addr
[0], (int) mac_addr
[1],
782 (int) mac_addr
[2], (int) mac_addr
[3],
783 (int) mac_addr
[4], (int) mac_addr
[5]) == -1) {
784 snprintf(err_msg
, sizeof(err_msg
),
785 "failed to format MAC: %s", strerror(errno
));
786 error_set(errp
, QERR_QGA_COMMAND_FAILED
, err_msg
);
790 info
->value
->has_hardware_address
= true;
795 ifa
->ifa_addr
->sa_family
== AF_INET
) {
796 /* interface with IPv4 address */
797 address_item
= g_malloc0(sizeof(*address_item
));
798 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
799 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
800 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
801 snprintf(err_msg
, sizeof(err_msg
),
802 "inet_ntop failed : %s", strerror(errno
));
803 error_set(errp
, QERR_QGA_COMMAND_FAILED
, err_msg
);
807 address_item
->value
->ip_address
= g_strdup(addr4
);
808 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
810 if (ifa
->ifa_netmask
) {
811 /* Count the number of set bits in netmask.
812 * This is safe as '1' and '0' cannot be shuffled in netmask. */
813 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
814 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
816 } else if (ifa
->ifa_addr
&&
817 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
818 /* interface with IPv6 address */
819 address_item
= g_malloc0(sizeof(*address_item
));
820 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
821 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
822 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
823 snprintf(err_msg
, sizeof(err_msg
),
824 "inet_ntop failed : %s", strerror(errno
));
825 error_set(errp
, QERR_QGA_COMMAND_FAILED
, err_msg
);
829 address_item
->value
->ip_address
= g_strdup(addr6
);
830 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
832 if (ifa
->ifa_netmask
) {
833 /* Count the number of set bits in netmask.
834 * This is safe as '1' and '0' cannot be shuffled in netmask. */
835 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
836 address_item
->value
->prefix
=
837 ctpop32(((uint32_t *) p
)[0]) +
838 ctpop32(((uint32_t *) p
)[1]) +
839 ctpop32(((uint32_t *) p
)[2]) +
840 ctpop32(((uint32_t *) p
)[3]);
848 address_list
= &info
->value
->ip_addresses
;
850 while (*address_list
&& (*address_list
)->next
) {
851 address_list
= &(*address_list
)->next
;
854 if (!*address_list
) {
855 *address_list
= address_item
;
857 (*address_list
)->next
= address_item
;
860 info
->value
->has_ip_addresses
= true;
870 qapi_free_GuestNetworkInterfaceList(head
);
874 #else /* defined(__linux__) */
876 void qmp_guest_suspend_disk(Error
**err
)
878 error_set(err
, QERR_UNSUPPORTED
);
881 void qmp_guest_suspend_ram(Error
**err
)
883 error_set(err
, QERR_UNSUPPORTED
);
886 void qmp_guest_suspend_hybrid(Error
**err
)
888 error_set(err
, QERR_UNSUPPORTED
);
891 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
893 error_set(errp
, QERR_UNSUPPORTED
);
899 #if !defined(CONFIG_FSFREEZE)
901 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**err
)
903 error_set(err
, QERR_UNSUPPORTED
);
908 int64_t qmp_guest_fsfreeze_freeze(Error
**err
)
910 error_set(err
, QERR_UNSUPPORTED
);
915 int64_t qmp_guest_fsfreeze_thaw(Error
**err
)
917 error_set(err
, QERR_UNSUPPORTED
);
924 /* register init/cleanup routines for stateful command groups */
925 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
927 #if defined(CONFIG_FSFREEZE)
928 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
930 ga_command_state_add(cs
, guest_file_init
, NULL
);