2 * QEMU Guest Agent POSIX-specific command implementations
4 * Copyright IBM Corp. 2011
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.
16 #if defined(__linux__)
20 #if defined(__linux__) && defined(FIFREEZE)
21 #define CONFIG_FSFREEZE
25 #include <sys/types.h>
26 #include <sys/ioctl.h>
28 #include <arpa/inet.h>
29 #include <sys/socket.h>
32 #include "qga/guest-agent-core.h"
33 #include "qga-qmp-commands.h"
35 #include "qemu-queue.h"
36 #include "host-utils.h"
38 static void reopen_fd_to_null(int fd)
42 nullfd = open("/dev/null", O_RDWR);
54 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **err)
57 const char *shutdown_flag;
59 slog("guest-shutdown called, mode: %s", mode);
60 if (!has_mode || strcmp(mode, "powerdown") == 0) {
62 } else if (strcmp(mode, "halt") == 0) {
64 } else if (strcmp(mode, "reboot") == 0) {
67 error_set(err, QERR_INVALID_PARAMETER_VALUE, "mode",
68 "halt|powerdown|reboot");
74 /* child, start the shutdown */
80 ret = execl("/sbin/shutdown", "shutdown", shutdown_flag, "+0",
81 "hypervisor initiated shutdown", (char*)NULL);
83 slog("guest-shutdown failed: %s", strerror(errno));
87 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 #if defined(CONFIG_FSFREEZE)
313 static void disable_logging(void)
315 ga_disable_logging(ga_state);
318 static void enable_logging(void)
320 ga_enable_logging(ga_state);
323 typedef struct GuestFsfreezeMount {
326 QTAILQ_ENTRY(GuestFsfreezeMount) next;
327 } GuestFsfreezeMount;
330 GuestFsfreezeStatus status;
331 QTAILQ_HEAD(, GuestFsfreezeMount) mount_list;
332 } guest_fsfreeze_state;
335 * Walk the mount table and build a list of local file systems
337 static int guest_fsfreeze_build_mount_list(void)
340 GuestFsfreezeMount *mount, *temp;
341 char const *mtab = MOUNTED;
344 QTAILQ_FOREACH_SAFE(mount, &guest_fsfreeze_state.mount_list, next, temp) {
345 QTAILQ_REMOVE(&guest_fsfreeze_state.mount_list, mount, next);
346 g_free(mount->dirname);
347 g_free(mount->devtype);
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(&guest_fsfreeze_state.mount_list, mount, next);
383 * Return status of freeze/thaw
385 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
387 return guest_fsfreeze_state.status;
391 * Walk list of mounted file systems in the guest, and freeze the ones which
392 * are real local file systems.
394 int64_t qmp_guest_fsfreeze_freeze(Error **err)
397 struct GuestFsfreezeMount *mount, *temp;
401 slog("guest-fsfreeze called");
403 if (guest_fsfreeze_state.status == GUEST_FSFREEZE_STATUS_FROZEN) {
407 ret = guest_fsfreeze_build_mount_list();
412 /* cannot risk guest agent blocking itself on a write in this state */
415 QTAILQ_FOREACH_SAFE(mount, &guest_fsfreeze_state.mount_list, next, temp) {
416 fd = qemu_open(mount->dirname, O_RDONLY);
418 sprintf(err_msg, "failed to open %s, %s", mount->dirname, strerror(errno));
419 error_set(err, QERR_QGA_COMMAND_FAILED, err_msg);
423 /* we try to cull filesytems we know won't work in advance, but other
424 * filesytems may not implement fsfreeze for less obvious reasons.
425 * these will report EOPNOTSUPP, so we simply ignore them. when
426 * thawing, these filesystems will return an EINVAL instead, due to
427 * not being in a frozen state. Other filesystem-specific
428 * errors may result in EINVAL, however, so the user should check the
429 * number * of filesystems returned here against those returned by the
430 * thaw operation to determine whether everything completed
433 ret = ioctl(fd, FIFREEZE);
434 if (ret < 0 && errno != EOPNOTSUPP) {
435 sprintf(err_msg, "failed to freeze %s, %s", mount->dirname, strerror(errno));
436 error_set(err, QERR_QGA_COMMAND_FAILED, err_msg);
445 guest_fsfreeze_state.status = GUEST_FSFREEZE_STATUS_FROZEN;
450 qmp_guest_fsfreeze_thaw(NULL);
456 * Walk list of frozen file systems in the guest, and thaw them.
458 int64_t qmp_guest_fsfreeze_thaw(Error **err)
461 GuestFsfreezeMount *mount, *temp;
463 bool has_error = false;
465 QTAILQ_FOREACH_SAFE(mount, &guest_fsfreeze_state.mount_list, next, temp) {
466 fd = qemu_open(mount->dirname, O_RDONLY);
471 ret = ioctl(fd, FITHAW);
472 if (ret < 0 && errno != EOPNOTSUPP && errno != EINVAL) {
482 guest_fsfreeze_state.status = GUEST_FSFREEZE_STATUS_ERROR;
484 guest_fsfreeze_state.status = GUEST_FSFREEZE_STATUS_THAWED;
490 static void guest_fsfreeze_init(void)
492 guest_fsfreeze_state.status = GUEST_FSFREEZE_STATUS_THAWED;
493 QTAILQ_INIT(&guest_fsfreeze_state.mount_list);
496 static void guest_fsfreeze_cleanup(void)
501 if (guest_fsfreeze_state.status == GUEST_FSFREEZE_STATUS_FROZEN) {
502 ret = qmp_guest_fsfreeze_thaw(&err);
503 if (ret < 0 || err) {
504 slog("failed to clean up frozen filesystems");
510 * Return status of freeze/thaw
512 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
514 error_set(err, QERR_UNSUPPORTED);
520 * Walk list of mounted file systems in the guest, and freeze the ones which
521 * are real local file systems.
523 int64_t qmp_guest_fsfreeze_freeze(Error **err)
525 error_set(err, QERR_UNSUPPORTED);
531 * Walk list of frozen file systems in the guest, and thaw them.
533 int64_t qmp_guest_fsfreeze_thaw(Error **err)
535 error_set(err, QERR_UNSUPPORTED);
541 #define LINUX_SYS_STATE_FILE "/sys/power/state"
542 #define SUSPEND_SUPPORTED 0
543 #define SUSPEND_NOT_SUPPORTED 1
546 * This function forks twice and the information about the mode support
547 * status is passed to the qemu-ga process via a pipe.
549 * This approach allows us to keep the way we reap terminated children
550 * in qemu-ga quite simple.
552 static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,
553 const char *sysfile_str, Error **err)
558 int status, pipefds[2];
560 if (pipe(pipefds) < 0) {
561 error_set(err, QERR_UNDEFINED_ERROR);
565 pmutils_path = g_find_program_in_path(pmutils_bin);
569 struct sigaction act;
571 memset(&act, 0, sizeof(act));
572 act.sa_handler = SIG_DFL;
573 sigaction(SIGCHLD, &act, NULL);
577 reopen_fd_to_null(0);
578 reopen_fd_to_null(1);
579 reopen_fd_to_null(2);
584 char buf[32]; /* hopefully big enough */
587 execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
591 * If we get here either pm-utils is not installed or execle() has
592 * failed. Let's try the manual method if the caller wants it.
596 _exit(SUSPEND_NOT_SUPPORTED);
599 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
601 _exit(SUSPEND_NOT_SUPPORTED);
604 ret = read(fd, buf, sizeof(buf)-1);
606 _exit(SUSPEND_NOT_SUPPORTED);
610 if (strstr(buf, sysfile_str)) {
611 _exit(SUSPEND_SUPPORTED);
614 _exit(SUSPEND_NOT_SUPPORTED);
620 status = SUSPEND_NOT_SUPPORTED;
623 ret = write(pipefds[1], &status, sizeof(status));
624 if (ret != sizeof(status)) {
632 g_free(pmutils_path);
635 error_set(err, QERR_UNDEFINED_ERROR);
639 ret = read(pipefds[0], &status, sizeof(status));
640 if (ret == sizeof(status) && WIFEXITED(status) &&
641 WEXITSTATUS(status) == SUSPEND_SUPPORTED) {
645 error_set(err, QERR_UNSUPPORTED);
651 static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
657 pmutils_path = g_find_program_in_path(pmutils_bin);
665 reopen_fd_to_null(0);
666 reopen_fd_to_null(1);
667 reopen_fd_to_null(2);
670 execle(pmutils_path, pmutils_bin, NULL, environ);
674 * If we get here either pm-utils is not installed or execle() has
675 * failed. Let's try the manual method if the caller wants it.
682 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
687 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
694 g_free(pmutils_path);
697 error_set(err, QERR_UNDEFINED_ERROR);
702 void qmp_guest_suspend_disk(Error **err)
704 bios_supports_mode("pm-is-supported", "--hibernate", "disk", err);
705 if (error_is_set(err)) {
709 guest_suspend("pm-hibernate", "disk", err);
712 void qmp_guest_suspend_ram(Error **err)
714 bios_supports_mode("pm-is-supported", "--suspend", "mem", err);
715 if (error_is_set(err)) {
719 guest_suspend("pm-suspend", "mem", err);
722 void qmp_guest_suspend_hybrid(Error **err)
724 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL, err);
725 if (error_is_set(err)) {
729 guest_suspend("pm-suspend-hybrid", NULL, err);
732 static GuestNetworkInterfaceList *
733 guest_find_interface(GuestNetworkInterfaceList *head,
736 for (; head; head = head->next) {
737 if (strcmp(head->value->name, name) == 0) {
746 * Build information about guest interfaces
748 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
750 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
751 struct ifaddrs *ifap, *ifa;
754 if (getifaddrs(&ifap) < 0) {
755 snprintf(err_msg, sizeof(err_msg),
756 "getifaddrs failed: %s", strerror(errno));
757 error_set(errp, QERR_QGA_COMMAND_FAILED, err_msg);
761 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
762 GuestNetworkInterfaceList *info;
763 GuestIpAddressList **address_list = NULL, *address_item = NULL;
764 char addr4[INET_ADDRSTRLEN];
765 char addr6[INET6_ADDRSTRLEN];
768 unsigned char *mac_addr;
771 g_debug("Processing %s interface", ifa->ifa_name);
773 info = guest_find_interface(head, ifa->ifa_name);
776 info = g_malloc0(sizeof(*info));
777 info->value = g_malloc0(sizeof(*info->value));
778 info->value->name = g_strdup(ifa->ifa_name);
781 head = cur_item = info;
783 cur_item->next = info;
788 if (!info->value->has_hardware_address &&
789 ifa->ifa_flags & SIOCGIFHWADDR) {
790 /* we haven't obtained HW address yet */
791 sock = socket(PF_INET, SOCK_STREAM, 0);
793 snprintf(err_msg, sizeof(err_msg),
794 "failed to create socket: %s", strerror(errno));
795 error_set(errp, QERR_QGA_COMMAND_FAILED, err_msg);
799 memset(&ifr, 0, sizeof(ifr));
800 strncpy(ifr.ifr_name, info->value->name, IF_NAMESIZE);
801 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
802 snprintf(err_msg, sizeof(err_msg),
803 "failed to get MAC addres of %s: %s",
806 error_set(errp, QERR_QGA_COMMAND_FAILED, err_msg);
810 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
812 if (asprintf(&info->value->hardware_address,
813 "%02x:%02x:%02x:%02x:%02x:%02x",
814 (int) mac_addr[0], (int) mac_addr[1],
815 (int) mac_addr[2], (int) mac_addr[3],
816 (int) mac_addr[4], (int) mac_addr[5]) == -1) {
817 snprintf(err_msg, sizeof(err_msg),
818 "failed to format MAC: %s", strerror(errno));
819 error_set(errp, QERR_QGA_COMMAND_FAILED, err_msg);
823 info->value->has_hardware_address = true;
828 ifa->ifa_addr->sa_family == AF_INET) {
829 /* interface with IPv4 address */
830 address_item = g_malloc0(sizeof(*address_item));
831 address_item->value = g_malloc0(sizeof(*address_item->value));
832 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
833 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
834 snprintf(err_msg, sizeof(err_msg),
835 "inet_ntop failed : %s", strerror(errno));
836 error_set(errp, QERR_QGA_COMMAND_FAILED, err_msg);
840 address_item->value->ip_address = g_strdup(addr4);
841 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
843 if (ifa->ifa_netmask) {
844 /* Count the number of set bits in netmask.
845 * This is safe as '1' and '0' cannot be shuffled in netmask. */
846 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
847 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
849 } else if (ifa->ifa_addr &&
850 ifa->ifa_addr->sa_family == AF_INET6) {
851 /* interface with IPv6 address */
852 address_item = g_malloc0(sizeof(*address_item));
853 address_item->value = g_malloc0(sizeof(*address_item->value));
854 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
855 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
856 snprintf(err_msg, sizeof(err_msg),
857 "inet_ntop failed : %s", strerror(errno));
858 error_set(errp, QERR_QGA_COMMAND_FAILED, err_msg);
862 address_item->value->ip_address = g_strdup(addr6);
863 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
865 if (ifa->ifa_netmask) {
866 /* Count the number of set bits in netmask.
867 * This is safe as '1' and '0' cannot be shuffled in netmask. */
868 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
869 address_item->value->prefix =
870 ctpop32(((uint32_t *) p)[0]) +
871 ctpop32(((uint32_t *) p)[1]) +
872 ctpop32(((uint32_t *) p)[2]) +
873 ctpop32(((uint32_t *) p)[3]);
881 address_list = &info->value->ip_addresses;
883 while (*address_list && (*address_list)->next) {
884 address_list = &(*address_list)->next;
887 if (!*address_list) {
888 *address_list = address_item;
890 (*address_list)->next = address_item;
893 info->value->has_ip_addresses = true;
903 qapi_free_GuestNetworkInterfaceList(head);
907 /* register init/cleanup routines for stateful command groups */
908 void ga_command_state_init(GAState *s, GACommandState *cs)
910 #if defined(CONFIG_FSFREEZE)
911 ga_command_state_add(cs, guest_fsfreeze_init, guest_fsfreeze_cleanup);
913 ga_command_state_add(cs, guest_file_init, NULL);