qemu/qga/commands-posix.c

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1371 lines
37 KiB
C
Raw Permalink Normal View History

/*
* QEMU Guest Agent POSIX-specific command implementations
*
* Copyright IBM Corp. 2011
*
* Authors:
* Michael Roth <mdroth@linux.vnet.ibm.com>
* Michal Privoznik <mprivozn@redhat.com>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*/
#include "qemu/osdep.h"
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <sys/wait.h>
qga: Add guest-get-fsinfo command Add command to get mounted filesystems information in the guest. The returned value contains a list of mountpoint paths and corresponding disks info such as disk bus type, drive address, and the disk controllers' PCI addresses, so that management layer such as libvirt can resolve the disk backends. For example, when `lsblk' result is: NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sdb 8:16 0 1G 0 disk `-sdb1 8:17 0 1024M 0 part `-vg0-lv0 253:1 0 1.4G 0 lvm /mnt/test sdc 8:32 0 1G 0 disk `-sdc1 8:33 0 512M 0 part `-vg0-lv0 253:1 0 1.4G 0 lvm /mnt/test vda 252:0 0 25G 0 disk `-vda1 252:1 0 25G 0 part / where sdb is a SCSI disk with PCI controller 0000:00:0a.0 and ID=1, sdc is an IDE disk with PCI controller 0000:00:01.1, and vda is a virtio-blk disk with PCI device 0000:00:06.0, guest-get-fsinfo command will return the following result: {"return": [{"name":"dm-1", "mountpoint":"/mnt/test", "disk":[ {"bus-type":"scsi","bus":0,"unit":1,"target":0, "pci-controller":{"bus":0,"slot":10,"domain":0,"function":0}}, {"bus-type":"ide","bus":0,"unit":0,"target":0, "pci-controller":{"bus":0,"slot":1,"domain":0,"function":1}}], "type":"xfs"}, {"name":"vda1", "mountpoint":"/", "disk":[ {"bus-type":"virtio","bus":0,"unit":0,"target":0, "pci-controller":{"bus":0,"slot":6,"domain":0,"function":0}}], "type":"ext4"}]} In Linux guest, the disk information is resolved from sysfs. So far, it only supports virtio-blk, virtio-scsi, IDE, SATA, SCSI disks on x86 hosts, and "disk" parameter may be empty for unsupported disk types. Signed-off-by: Tomoki Sekiyama <tomoki.sekiyama@hds.com> *updated schema to report 2.2 as initial supported version Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2014-07-01 01:51:34 +04:00
#include <dirent.h>
#include "qga-qapi-commands.h"
#include "qapi/error.h"
#include "qemu/host-utils.h"
#include "qemu/sockets.h"
#include "qemu/base64.h"
#include "qemu/cutils.h"
#include "commands-common.h"
#include "cutils.h"
#ifdef HAVE_UTMPX
#include <utmpx.h>
#endif
#ifdef HAVE_GETIFADDRS
#include <arpa/inet.h>
#include <sys/socket.h>
#include <net/if.h>
#if defined(__NetBSD__) || defined(__OpenBSD__) || defined(CONFIG_SOLARIS)
#include <net/if_arp.h>
#include <netinet/if_ether.h>
#if !defined(ETHER_ADDR_LEN) && defined(ETHERADDRL)
#define ETHER_ADDR_LEN ETHERADDRL
#endif
#else
#include <net/ethernet.h>
#endif
#ifdef CONFIG_SOLARIS
#include <sys/sockio.h>
#endif
#endif
static bool ga_wait_child(pid_t pid, int *status, Error **errp)
{
pid_t rpid;
*status = 0;
rpid = RETRY_ON_EINTR(waitpid(pid, status, 0));
if (rpid == -1) {
error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
pid);
return false;
}
g_assert(rpid == pid);
return true;
}
static ssize_t ga_pipe_read_str(int fd[2], char **str)
{
ssize_t n, len = 0;
char buf[1024];
close(fd[1]);
fd[1] = -1;
while ((n = read(fd[0], buf, sizeof(buf))) != 0) {
if (n < 0) {
if (errno == EINTR) {
continue;
} else {
len = -errno;
break;
}
}
*str = g_realloc(*str, len + n + 1);
memcpy(*str + len, buf, n);
len += n;
qemu-ga: Fix a SIGSEGV in ga_run_command() helper qemu-ga on a NetBSD -current VM terminates with a SIGSEGV upon receiving 'guest-set-time' command... Core was generated by `qemu-ga'. Program terminated with signal SIGSEGV, Segmentation fault. #0 0x000000000cd37a40 in ga_pipe_read_str (fd=fd@entry=0xffffff922a20, str=str@entry=0xffffff922a18) at ../qga/commands-posix.c:88 88 *str[len] = '\0'; [Current thread is 1 (process 1112)] (gdb) bt #0 0x000000000cd37a40 in ga_pipe_read_str (fd=fd@entry=0xffffff922a20, str=str@entry=0xffffff922a18) at ../qga/commands-posix.c:88 #1 0x000000000cd37b60 in ga_run_command (argv=argv@entry=0xffffff922a90, action=action@entry=0xcda34b8 "set hardware clock to system time", errp=errp@entry=0xffffff922a70, in_str=0x0) at ../qga/commands-posix.c:164 #2 0x000000000cd380c4 in qmp_guest_set_time (has_time=<optimized out>, time_ns=<optimized out>, errp=errp@entry=0xffffff922ad0) at ../qga/commands-posix.c:304 #3 0x000000000cd253d8 in qmp_marshal_guest_set_time (args=<optimized out>, ret=<optimized out>, errp=0xffffff922b48) at qga/qga-qapi-commands.c:193 #4 0x000000000cd4e71c in qmp_dispatch (cmds=cmds@entry=0xcdf5b18 <ga_commands>, request=request@entry=0xf3c711a4b000, allow_oob=allow_oob@entry=false, cur_mon=cur_mon@entry=0x0) at ../qapi/qmp-dispatch.c:220 #5 0x000000000cd36524 in process_event (opaque=0xf3c711a79000, obj=0xf3c711a4b000, err=0x0) at ../qga/main.c:677 #6 0x000000000cd526f0 in json_message_process_token (lexer=lexer@entry=0xf3c711a79018, input=0xf3c712072480, type=type@entry=JSON_RCURLY, x=28, y=1) at ../qobject/json-streamer.c:99 #7 0x000000000cd93860 in json_lexer_feed_char (lexer=lexer@entry=0xf3c711a79018, ch=125 '}', flush=flush@entry=false) at ../qobject/json-lexer.c:313 #8 0x000000000cd93a00 in json_lexer_feed (lexer=lexer@entry=0xf3c711a79018, buffer=buffer@entry=0xffffff922d10 "{\"execute\":\"guest-set-time\"}\n", size=<optimized out>) at ../qobject/json-lexer.c:350 #9 0x000000000cd5290c in json_message_parser_feed (parser=parser@entry=0xf3c711a79000, buffer=buffer@entry=0xffffff922d10 "{\"execute\":\"guest-set-time\"}\n", size=<optimized out>) at ../qobject/json-streamer.c:121 #10 0x000000000cd361fc in channel_event_cb (condition=<optimized out>, data=0xf3c711a79000) at ../qga/main.c:703 #11 0x000000000cd3710c in ga_channel_client_event (channel=<optimized out>, condition=<optimized out>, data=0xf3c711b2d300) at ../qga/channel-posix.c:94 #12 0x0000f3c7120d9bec in g_main_dispatch () from /usr/pkg/lib/libglib-2.0.so.0 #13 0x0000f3c7120dd25c in g_main_context_iterate_unlocked.constprop () from /usr/pkg/lib/libglib-2.0.so.0 #14 0x0000f3c7120ddbf0 in g_main_loop_run () from /usr/pkg/lib/libglib-2.0.so.0 #15 0x000000000cda00d8 in run_agent_once (s=0xf3c711a79000) at ../qga/main.c:1522 #16 run_agent (s=0xf3c711a79000) at ../qga/main.c:1559 #17 main (argc=<optimized out>, argv=<optimized out>) at ../qga/main.c:1671 (gdb) The commandline options used on the host machine... qemu-system-aarch64 \ -machine type=virt,pflash0=rom \ -m 8G \ -cpu host \ -smp 8 \ -accel hvf \ -device virtio-net-pci,netdev=unet \ -device virtio-blk-pci,drive=hd \ -drive file=netbsd.qcow2,if=none,id=hd \ -netdev user,id=unet,hostfwd=tcp::2223-:22 \ -object rng-random,filename=/dev/urandom,id=viornd0 \ -device virtio-rng-pci,rng=viornd0 \ -serial mon:stdio \ -display none \ -blockdev node-name=rom,driver=file,filename=/opt/homebrew/Cellar/qemu/9.0.2/share/qemu/edk2-aarch64-code.fd,read-only=true \ -chardev socket,path=/tmp/qga_netbsd.sock,server=on,wait=off,id=qga0 \ -device virtio-serial \ -device virtconsole,chardev=qga0,name=org.qemu.guest_agent.0 This patch rectifies the operator precedence while assigning the NUL terminator. Fixes: c3f32c13a325f1ca9a0b08c19fefe9e5cc04289d Signed-off-by: Sunil Nimmagadda <sunil@nimmagadda.net> Reviewed-by: Konstantin Kostiuk <kkostiuk@redhat.com> Reviewed-by: Daniel P. Berrangé <berrange@redhat.com> Link: https://lore.kernel.org/r/m15xppk9qg.fsf@nimmagadda.net Signed-off-by: Konstantin Kostiuk <kkostiuk@redhat.com>
2024-10-18 13:04:39 +03:00
(*str)[len] = '\0';
}
close(fd[0]);
fd[0] = -1;
return len;
}
/*
* Helper to run command with input/output redirection,
* sending string to stdin and taking error message from
* stdout/err.
*/
static int ga_run_command(const char *argv[], const char *in_str,
const char *action, Error **errp)
{
pid_t pid;
int status;
int retcode = -1;
int infd[2] = { -1, -1 };
int outfd[2] = { -1, -1 };
char *str = NULL;
ssize_t len = 0;
if ((in_str && !g_unix_open_pipe(infd, FD_CLOEXEC, NULL)) ||
!g_unix_open_pipe(outfd, FD_CLOEXEC, NULL)) {
error_setg(errp, "cannot create pipe FDs");
goto out;
}
pid = fork();
if (pid == 0) {
char *cherr = NULL;
setsid();
if (in_str) {
/* Redirect stdin to infd. */
close(infd[1]);
dup2(infd[0], 0);
close(infd[0]);
} else {
reopen_fd_to_null(0);
}
/* Redirect stdout/stderr to outfd. */
close(outfd[0]);
dup2(outfd[1], 1);
dup2(outfd[1], 2);
close(outfd[1]);
execvp(argv[0], (char *const *)argv);
/* Write the cause of failed exec to pipe for the parent to read it. */
cherr = g_strdup_printf("failed to exec '%s'", argv[0]);
perror(cherr);
g_free(cherr);
_exit(EXIT_FAILURE);
} else if (pid < 0) {
error_setg_errno(errp, errno, "failed to create child process");
goto out;
}
if (in_str) {
close(infd[0]);
infd[0] = -1;
if (qemu_write_full(infd[1], in_str, strlen(in_str)) !=
strlen(in_str)) {
error_setg_errno(errp, errno, "%s: cannot write to stdin pipe",
action);
goto out;
}
close(infd[1]);
infd[1] = -1;
}
len = ga_pipe_read_str(outfd, &str);
if (len < 0) {
error_setg_errno(errp, -len, "%s: cannot read from stdout/stderr pipe",
action);
goto out;
}
if (!ga_wait_child(pid, &status, errp)) {
goto out;
}
if (!WIFEXITED(status)) {
if (len) {
error_setg(errp, "child process has terminated abnormally: %s",
str);
} else {
error_setg(errp, "child process has terminated abnormally");
}
goto out;
}
retcode = WEXITSTATUS(status);
if (WEXITSTATUS(status)) {
if (len) {
error_setg(errp, "child process has failed to %s: %s",
action, str);
} else {
error_setg(errp, "child process has failed to %s: exit status %d",
action, WEXITSTATUS(status));
}
goto out;
}
out:
g_free(str);
if (infd[0] != -1) {
close(infd[0]);
}
if (infd[1] != -1) {
close(infd[1]);
}
if (outfd[0] != -1) {
close(outfd[0]);
}
if (outfd[1] != -1) {
close(outfd[1]);
}
return retcode;
}
void qmp_guest_shutdown(const char *mode, Error **errp)
{
const char *shutdown_flag;
Error *local_err = NULL;
#ifdef CONFIG_SOLARIS
const char *powerdown_flag = "-i5";
const char *halt_flag = "-i0";
const char *reboot_flag = "-i6";
#elif defined(CONFIG_BSD)
const char *powerdown_flag = "-p";
const char *halt_flag = "-h";
const char *reboot_flag = "-r";
#else
const char *powerdown_flag = "-P";
const char *halt_flag = "-H";
const char *reboot_flag = "-r";
#endif
slog("guest-shutdown called, mode: %s", mode);
if (!mode || strcmp(mode, "powerdown") == 0) {
shutdown_flag = powerdown_flag;
} else if (strcmp(mode, "halt") == 0) {
shutdown_flag = halt_flag;
} else if (strcmp(mode, "reboot") == 0) {
shutdown_flag = reboot_flag;
} else {
error_setg(errp,
"mode is invalid (valid values are: halt|powerdown|reboot");
return;
}
const char *argv[] = {"/sbin/shutdown",
#ifdef CONFIG_SOLARIS
shutdown_flag, "-g0", "-y",
#elif defined(CONFIG_BSD)
shutdown_flag, "+0",
#else
"-h", shutdown_flag, "+0",
#endif
"hypervisor initiated shutdown", (char *) NULL};
ga_run_command(argv, NULL, "shutdown", &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
/* succeeded */
}
void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
{
int ret;
Error *local_err = NULL;
struct timeval tv;
const char *argv[] = {"/sbin/hwclock", has_time ? "-w" : "-s", NULL};
/* If user has passed a time, validate and set it. */
if (has_time) {
GDate date = { 0, };
/* year-2038 will overflow in case time_t is 32bit */
if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
error_setg(errp, "Time %" PRId64 " is too large", time_ns);
return;
}
tv.tv_sec = time_ns / 1000000000;
tv.tv_usec = (time_ns % 1000000000) / 1000;
g_date_set_time_t(&date, tv.tv_sec);
if (date.year < 1970 || date.year >= 2070) {
error_setg_errno(errp, errno, "Invalid time");
return;
}
ret = settimeofday(&tv, NULL);
if (ret < 0) {
error_setg_errno(errp, errno, "Failed to set time to guest");
return;
}
}
/* Now, if user has passed a time to set and the system time is set, we
* just need to synchronize the hardware clock. However, if no time was
* passed, user is requesting the opposite: set the system time from the
* hardware clock (RTC). */
ga_run_command(argv, NULL, "set hardware clock to system time",
&local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
}
typedef enum {
RW_STATE_NEW,
RW_STATE_READING,
RW_STATE_WRITING,
} RwState;
struct GuestFileHandle {
uint64_t id;
FILE *fh;
RwState state;
QTAILQ_ENTRY(GuestFileHandle) next;
};
static struct {
QTAILQ_HEAD(, GuestFileHandle) filehandles;
} guest_file_state = {
.filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
};
static int64_t guest_file_handle_add(FILE *fh, Error **errp)
{
GuestFileHandle *gfh;
int64_t handle;
handle = ga_get_fd_handle(ga_state, errp);
if (handle < 0) {
return -1;
}
gfh = g_new0(GuestFileHandle, 1);
gfh->id = handle;
gfh->fh = fh;
QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
return handle;
}
GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
{
GuestFileHandle *gfh;
QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
{
if (gfh->id == id) {
return gfh;
}
}
error_setg(errp, "handle '%" PRId64 "' has not been found", id);
return NULL;
}
typedef const char * const ccpc;
#ifndef O_BINARY
#define O_BINARY 0
#endif
/* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
static const struct {
ccpc *forms;
int oflag_base;
} guest_file_open_modes[] = {
{ (ccpc[]){ "r", NULL }, O_RDONLY },
{ (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
{ (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
{ (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
{ (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
{ (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
{ (ccpc[]){ "r+", NULL }, O_RDWR },
{ (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
{ (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
{ (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
{ (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
{ (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
};
static int
find_open_flag(const char *mode_str, Error **errp)
{
unsigned mode;
for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
ccpc *form;
form = guest_file_open_modes[mode].forms;
while (*form != NULL && strcmp(*form, mode_str) != 0) {
++form;
}
if (*form != NULL) {
break;
}
}
if (mode == ARRAY_SIZE(guest_file_open_modes)) {
error_setg(errp, "invalid file open mode '%s'", mode_str);
return -1;
}
return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
}
#define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
S_IRGRP | S_IWGRP | \
S_IROTH | S_IWOTH)
static FILE *
safe_open_or_create(const char *path, const char *mode, Error **errp)
{
int oflag;
int fd = -1;
FILE *f = NULL;
oflag = find_open_flag(mode, errp);
if (oflag < 0) {
goto end;
}
/* If the caller wants / allows creation of a new file, we implement it
* with a two step process: open() + (open() / fchmod()).
*
* First we insist on creating the file exclusively as a new file. If
* that succeeds, we're free to set any file-mode bits on it. (The
* motivation is that we want to set those file-mode bits independently
* of the current umask.)
*
* If the exclusive creation fails because the file already exists
* (EEXIST is not possible for any other reason), we just attempt to
* open the file, but in this case we won't be allowed to change the
* file-mode bits on the preexistent file.
*
* The pathname should never disappear between the two open()s in
* practice. If it happens, then someone very likely tried to race us.
* In this case just go ahead and report the ENOENT from the second
* open() to the caller.
*
* If the caller wants to open a preexistent file, then the first
* open() is decisive and its third argument is ignored, and the second
* open() and the fchmod() are never called.
*/
fd = qga_open_cloexec(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
if (fd == -1 && errno == EEXIST) {
oflag &= ~(unsigned)O_CREAT;
fd = qga_open_cloexec(path, oflag, 0);
}
if (fd == -1) {
error_setg_errno(errp, errno,
"failed to open file '%s' (mode: '%s')",
path, mode);
goto end;
}
if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
error_setg_errno(errp, errno, "failed to set permission "
"0%03o on new file '%s' (mode: '%s')",
(unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
goto end;
}
f = fdopen(fd, mode);
if (f == NULL) {
error_setg_errno(errp, errno, "failed to associate stdio stream with "
"file descriptor %d, file '%s' (mode: '%s')",
fd, path, mode);
}
end:
if (f == NULL && fd != -1) {
close(fd);
if (oflag & O_CREAT) {
unlink(path);
}
}
return f;
}
int64_t qmp_guest_file_open(const char *path, const char *mode,
Error **errp)
{
FILE *fh;
Error *local_err = NULL;
int64_t handle;
if (!mode) {
mode = "r";
}
slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
fh = safe_open_or_create(path, mode, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
return -1;
}
/* set fd non-blocking to avoid common use cases (like reading from a
* named pipe) from hanging the agent
*/
if (!g_unix_set_fd_nonblocking(fileno(fh), true, NULL)) {
fclose(fh);
error_setg_errno(errp, errno, "Failed to set FD nonblocking");
return -1;
}
handle = guest_file_handle_add(fh, errp);
if (handle < 0) {
fclose(fh);
return -1;
}
slog("guest-file-open, handle: %" PRId64, handle);
return handle;
}
void qmp_guest_file_close(int64_t handle, Error **errp)
{
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
int ret;
slog("guest-file-close called, handle: %" PRId64, handle);
if (!gfh) {
return;
}
ret = fclose(gfh->fh);
if (ret == EOF) {
error_setg_errno(errp, errno, "failed to close handle");
return;
}
QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
g_free(gfh);
}
GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
int64_t count, Error **errp)
{
GuestFileRead *read_data = NULL;
guchar *buf;
FILE *fh = gfh->fh;
size_t read_count;
/* explicitly flush when switching from writing to reading */
if (gfh->state == RW_STATE_WRITING) {
int ret = fflush(fh);
if (ret == EOF) {
error_setg_errno(errp, errno, "failed to flush file");
return NULL;
}
gfh->state = RW_STATE_NEW;
}
buf = g_malloc0(count + 1);
read_count = fread(buf, 1, count, fh);
if (ferror(fh)) {
error_setg_errno(errp, errno, "failed to read file");
} else {
buf[read_count] = 0;
read_data = g_new0(GuestFileRead, 1);
read_data->count = read_count;
read_data->eof = feof(fh);
if (read_count) {
read_data->buf_b64 = g_base64_encode(buf, read_count);
}
gfh->state = RW_STATE_READING;
}
g_free(buf);
clearerr(fh);
return read_data;
}
GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
bool has_count, int64_t count,
Error **errp)
{
GuestFileWrite *write_data = NULL;
guchar *buf;
gsize buf_len;
int write_count;
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
FILE *fh;
if (!gfh) {
return NULL;
}
fh = gfh->fh;
if (gfh->state == RW_STATE_READING) {
int ret = fseek(fh, 0, SEEK_CUR);
if (ret == -1) {
error_setg_errno(errp, errno, "failed to seek file");
return NULL;
}
gfh->state = RW_STATE_NEW;
}
buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
if (!buf) {
return NULL;
}
if (!has_count) {
count = buf_len;
} else if (count < 0 || count > buf_len) {
error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
count);
g_free(buf);
return NULL;
}
write_count = fwrite(buf, 1, count, fh);
if (ferror(fh)) {
error_setg_errno(errp, errno, "failed to write to file");
slog("guest-file-write failed, handle: %" PRId64, handle);
} else {
write_data = g_new0(GuestFileWrite, 1);
write_data->count = write_count;
write_data->eof = feof(fh);
gfh->state = RW_STATE_WRITING;
}
g_free(buf);
clearerr(fh);
return write_data;
}
struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
GuestFileWhence *whence_code,
Error **errp)
{
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
GuestFileSeek *seek_data = NULL;
FILE *fh;
int ret;
int whence;
Error *err = NULL;
if (!gfh) {
return NULL;
}
/* We stupidly exposed 'whence':'int' in our qapi */
whence = ga_parse_whence(whence_code, &err);
if (err) {
error_propagate(errp, err);
return NULL;
}
fh = gfh->fh;
ret = fseek(fh, offset, whence);
if (ret == -1) {
error_setg_errno(errp, errno, "failed to seek file");
if (errno == ESPIPE) {
/* file is non-seekable, stdio shouldn't be buffering anyways */
gfh->state = RW_STATE_NEW;
}
} else {
seek_data = g_new0(GuestFileSeek, 1);
seek_data->position = ftell(fh);
seek_data->eof = feof(fh);
gfh->state = RW_STATE_NEW;
}
clearerr(fh);
return seek_data;
}
void qmp_guest_file_flush(int64_t handle, Error **errp)
{
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
FILE *fh;
int ret;
if (!gfh) {
return;
}
fh = gfh->fh;
ret = fflush(fh);
if (ret == EOF) {
error_setg_errno(errp, errno, "failed to flush file");
} else {
gfh->state = RW_STATE_NEW;
}
}
#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
void free_fs_mount_list(FsMountList *mounts)
{
FsMount *mount, *temp;
if (!mounts) {
return;
}
QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
QTAILQ_REMOVE(mounts, mount, next);
g_free(mount->dirname);
g_free(mount->devtype);
g_free(mount);
}
}
#endif
#if defined(CONFIG_FSFREEZE)
typedef enum {
FSFREEZE_HOOK_THAW = 0,
FSFREEZE_HOOK_FREEZE,
} FsfreezeHookArg;
static const char *fsfreeze_hook_arg_string[] = {
"thaw",
"freeze",
};
static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
{
const char *hook;
const char *arg_str = fsfreeze_hook_arg_string[arg];
Error *local_err = NULL;
hook = ga_fsfreeze_hook(ga_state);
if (!hook) {
return;
}
const char *argv[] = {hook, arg_str, NULL};
slog("executing fsfreeze hook with arg '%s'", arg_str);
ga_run_command(argv, NULL, "execute fsfreeze hook", &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
}
/*
* Return status of freeze/thaw
*/
GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
{
if (ga_is_frozen(ga_state)) {
return GUEST_FSFREEZE_STATUS_FROZEN;
}
return GUEST_FSFREEZE_STATUS_THAWED;
}
int64_t qmp_guest_fsfreeze_freeze(Error **errp)
{
return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
}
int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
strList *mountpoints,
Error **errp)
{
int ret;
FsMountList mounts;
Error *local_err = NULL;
slog("guest-fsfreeze called");
execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return -1;
}
QTAILQ_INIT(&mounts);
if (!build_fs_mount_list(&mounts, &local_err)) {
error_propagate(errp, local_err);
return -1;
}
/* cannot risk guest agent blocking itself on a write in this state */
ga_set_frozen(ga_state);
ret = qmp_guest_fsfreeze_do_freeze_list(has_mountpoints, mountpoints,
mounts, errp);
free_fs_mount_list(&mounts);
/* We may not issue any FIFREEZE here.
* Just unset ga_state here and ready for the next call.
*/
if (ret == 0) {
ga_unset_frozen(ga_state);
} else if (ret < 0) {
qmp_guest_fsfreeze_thaw(NULL);
}
return ret;
}
int64_t qmp_guest_fsfreeze_thaw(Error **errp)
{
int ret;
ret = qmp_guest_fsfreeze_do_thaw(errp);
if (ret >= 0) {
ga_unset_frozen(ga_state);
execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
} else {
ret = 0;
}
return ret;
}
static void guest_fsfreeze_cleanup(void)
{
Error *err = NULL;
if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
qmp_guest_fsfreeze_thaw(&err);
if (err) {
slog("failed to clean up frozen filesystems: %s",
error_get_pretty(err));
error_free(err);
}
}
}
#endif
#if defined(__linux__) || defined(__FreeBSD__)
qga: add guest-set-user-password command Add a new 'guest-set-user-password' command for changing the password of guest OS user accounts. This command is needed to enable OpenStack to support its API for changing the admin password of guests running on KVM/QEMU. It is not practical to provide a command at the QEMU level explicitly targetting administrator account password change only, since different guest OS have different names for the admin account. While UNIX systems use 'root', Windows systems typically use 'Administrator' and even that can be renamed. Higher level apps like OpenStack have the ability to figure out the correct admin account name since they have info that QEMU/libvirt do not. The command accepts either the clear text password string, encoded in base64 to make it 8-bit safe in JSON: $ echo -n "123456" | base64 MTIzNDU2 $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": false, "username": "root", "password": "MTIzNDU2" } }' {"return":{}} Or a password that has already been run though a crypt(3) like algorithm appropriate for the guest, again then base64 encoded: $ echo -n '$6$n01A2Tau$e...snip...DfMOP7of9AJ1I8q0' | base64 JDYkb...snip...YT2Ey $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": true, "username": "root", "password": "JDYkb...snip...YT2Ey" } }' NB windows support is desirable, but not implemented in this patch. Signed-off-by: Daniel P. Berrange <berrange@redhat.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2015-02-11 14:26:12 +03:00
void qmp_guest_set_user_password(const char *username,
const char *password,
bool crypted,
Error **errp)
{
Error *local_err = NULL;
g_autofree char *rawpasswddata = NULL;
qga: add guest-set-user-password command Add a new 'guest-set-user-password' command for changing the password of guest OS user accounts. This command is needed to enable OpenStack to support its API for changing the admin password of guests running on KVM/QEMU. It is not practical to provide a command at the QEMU level explicitly targetting administrator account password change only, since different guest OS have different names for the admin account. While UNIX systems use 'root', Windows systems typically use 'Administrator' and even that can be renamed. Higher level apps like OpenStack have the ability to figure out the correct admin account name since they have info that QEMU/libvirt do not. The command accepts either the clear text password string, encoded in base64 to make it 8-bit safe in JSON: $ echo -n "123456" | base64 MTIzNDU2 $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": false, "username": "root", "password": "MTIzNDU2" } }' {"return":{}} Or a password that has already been run though a crypt(3) like algorithm appropriate for the guest, again then base64 encoded: $ echo -n '$6$n01A2Tau$e...snip...DfMOP7of9AJ1I8q0' | base64 JDYkb...snip...YT2Ey $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": true, "username": "root", "password": "JDYkb...snip...YT2Ey" } }' NB windows support is desirable, but not implemented in this patch. Signed-off-by: Daniel P. Berrange <berrange@redhat.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2015-02-11 14:26:12 +03:00
size_t rawpasswdlen;
rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
if (!rawpasswddata) {
return;
}
qga: add guest-set-user-password command Add a new 'guest-set-user-password' command for changing the password of guest OS user accounts. This command is needed to enable OpenStack to support its API for changing the admin password of guests running on KVM/QEMU. It is not practical to provide a command at the QEMU level explicitly targetting administrator account password change only, since different guest OS have different names for the admin account. While UNIX systems use 'root', Windows systems typically use 'Administrator' and even that can be renamed. Higher level apps like OpenStack have the ability to figure out the correct admin account name since they have info that QEMU/libvirt do not. The command accepts either the clear text password string, encoded in base64 to make it 8-bit safe in JSON: $ echo -n "123456" | base64 MTIzNDU2 $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": false, "username": "root", "password": "MTIzNDU2" } }' {"return":{}} Or a password that has already been run though a crypt(3) like algorithm appropriate for the guest, again then base64 encoded: $ echo -n '$6$n01A2Tau$e...snip...DfMOP7of9AJ1I8q0' | base64 JDYkb...snip...YT2Ey $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": true, "username": "root", "password": "JDYkb...snip...YT2Ey" } }' NB windows support is desirable, but not implemented in this patch. Signed-off-by: Daniel P. Berrange <berrange@redhat.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2015-02-11 14:26:12 +03:00
rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
rawpasswddata[rawpasswdlen] = '\0';
if (strchr(rawpasswddata, '\n')) {
error_setg(errp, "forbidden characters in raw password");
return;
qga: add guest-set-user-password command Add a new 'guest-set-user-password' command for changing the password of guest OS user accounts. This command is needed to enable OpenStack to support its API for changing the admin password of guests running on KVM/QEMU. It is not practical to provide a command at the QEMU level explicitly targetting administrator account password change only, since different guest OS have different names for the admin account. While UNIX systems use 'root', Windows systems typically use 'Administrator' and even that can be renamed. Higher level apps like OpenStack have the ability to figure out the correct admin account name since they have info that QEMU/libvirt do not. The command accepts either the clear text password string, encoded in base64 to make it 8-bit safe in JSON: $ echo -n "123456" | base64 MTIzNDU2 $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": false, "username": "root", "password": "MTIzNDU2" } }' {"return":{}} Or a password that has already been run though a crypt(3) like algorithm appropriate for the guest, again then base64 encoded: $ echo -n '$6$n01A2Tau$e...snip...DfMOP7of9AJ1I8q0' | base64 JDYkb...snip...YT2Ey $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": true, "username": "root", "password": "JDYkb...snip...YT2Ey" } }' NB windows support is desirable, but not implemented in this patch. Signed-off-by: Daniel P. Berrange <berrange@redhat.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2015-02-11 14:26:12 +03:00
}
if (strchr(username, '\n') ||
strchr(username, ':')) {
error_setg(errp, "forbidden characters in username");
return;
qga: add guest-set-user-password command Add a new 'guest-set-user-password' command for changing the password of guest OS user accounts. This command is needed to enable OpenStack to support its API for changing the admin password of guests running on KVM/QEMU. It is not practical to provide a command at the QEMU level explicitly targetting administrator account password change only, since different guest OS have different names for the admin account. While UNIX systems use 'root', Windows systems typically use 'Administrator' and even that can be renamed. Higher level apps like OpenStack have the ability to figure out the correct admin account name since they have info that QEMU/libvirt do not. The command accepts either the clear text password string, encoded in base64 to make it 8-bit safe in JSON: $ echo -n "123456" | base64 MTIzNDU2 $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": false, "username": "root", "password": "MTIzNDU2" } }' {"return":{}} Or a password that has already been run though a crypt(3) like algorithm appropriate for the guest, again then base64 encoded: $ echo -n '$6$n01A2Tau$e...snip...DfMOP7of9AJ1I8q0' | base64 JDYkb...snip...YT2Ey $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": true, "username": "root", "password": "JDYkb...snip...YT2Ey" } }' NB windows support is desirable, but not implemented in this patch. Signed-off-by: Daniel P. Berrange <berrange@redhat.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2015-02-11 14:26:12 +03:00
}
#ifdef __FreeBSD__
g_autofree char *chpasswddata = g_strdup(rawpasswddata);
const char *crypt_flag = crypted ? "-H" : "-h";
const char *argv[] = {"pw", "usermod", "-n", username,
crypt_flag, "0", NULL};
#else
g_autofree char *chpasswddata = g_strdup_printf("%s:%s\n", username,
rawpasswddata);
const char *crypt_flag = crypted ? "-e" : NULL;
const char *argv[] = {"chpasswd", crypt_flag, NULL};
#endif
ga_run_command(argv, chpasswddata, "set user password", &local_err);
qga: add guest-set-user-password command Add a new 'guest-set-user-password' command for changing the password of guest OS user accounts. This command is needed to enable OpenStack to support its API for changing the admin password of guests running on KVM/QEMU. It is not practical to provide a command at the QEMU level explicitly targetting administrator account password change only, since different guest OS have different names for the admin account. While UNIX systems use 'root', Windows systems typically use 'Administrator' and even that can be renamed. Higher level apps like OpenStack have the ability to figure out the correct admin account name since they have info that QEMU/libvirt do not. The command accepts either the clear text password string, encoded in base64 to make it 8-bit safe in JSON: $ echo -n "123456" | base64 MTIzNDU2 $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": false, "username": "root", "password": "MTIzNDU2" } }' {"return":{}} Or a password that has already been run though a crypt(3) like algorithm appropriate for the guest, again then base64 encoded: $ echo -n '$6$n01A2Tau$e...snip...DfMOP7of9AJ1I8q0' | base64 JDYkb...snip...YT2Ey $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": true, "username": "root", "password": "JDYkb...snip...YT2Ey" } }' NB windows support is desirable, but not implemented in this patch. Signed-off-by: Daniel P. Berrange <berrange@redhat.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2015-02-11 14:26:12 +03:00
if (local_err) {
error_propagate(errp, local_err);
return;
qga: add guest-set-user-password command Add a new 'guest-set-user-password' command for changing the password of guest OS user accounts. This command is needed to enable OpenStack to support its API for changing the admin password of guests running on KVM/QEMU. It is not practical to provide a command at the QEMU level explicitly targetting administrator account password change only, since different guest OS have different names for the admin account. While UNIX systems use 'root', Windows systems typically use 'Administrator' and even that can be renamed. Higher level apps like OpenStack have the ability to figure out the correct admin account name since they have info that QEMU/libvirt do not. The command accepts either the clear text password string, encoded in base64 to make it 8-bit safe in JSON: $ echo -n "123456" | base64 MTIzNDU2 $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": false, "username": "root", "password": "MTIzNDU2" } }' {"return":{}} Or a password that has already been run though a crypt(3) like algorithm appropriate for the guest, again then base64 encoded: $ echo -n '$6$n01A2Tau$e...snip...DfMOP7of9AJ1I8q0' | base64 JDYkb...snip...YT2Ey $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": true, "username": "root", "password": "JDYkb...snip...YT2Ey" } }' NB windows support is desirable, but not implemented in this patch. Signed-off-by: Daniel P. Berrange <berrange@redhat.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2015-02-11 14:26:12 +03:00
}
}
#endif /* __linux__ || __FreeBSD__ */
qga: add guest-set-user-password command Add a new 'guest-set-user-password' command for changing the password of guest OS user accounts. This command is needed to enable OpenStack to support its API for changing the admin password of guests running on KVM/QEMU. It is not practical to provide a command at the QEMU level explicitly targetting administrator account password change only, since different guest OS have different names for the admin account. While UNIX systems use 'root', Windows systems typically use 'Administrator' and even that can be renamed. Higher level apps like OpenStack have the ability to figure out the correct admin account name since they have info that QEMU/libvirt do not. The command accepts either the clear text password string, encoded in base64 to make it 8-bit safe in JSON: $ echo -n "123456" | base64 MTIzNDU2 $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": false, "username": "root", "password": "MTIzNDU2" } }' {"return":{}} Or a password that has already been run though a crypt(3) like algorithm appropriate for the guest, again then base64 encoded: $ echo -n '$6$n01A2Tau$e...snip...DfMOP7of9AJ1I8q0' | base64 JDYkb...snip...YT2Ey $ virsh -c qemu:///system qemu-agent-command f21x86_64 \ '{ "execute": "guest-set-user-password", "arguments": { "crypted": true, "username": "root", "password": "JDYkb...snip...YT2Ey" } }' NB windows support is desirable, but not implemented in this patch. Signed-off-by: Daniel P. Berrange <berrange@redhat.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
2015-02-11 14:26:12 +03:00
#ifdef HAVE_GETIFADDRS
static GuestNetworkInterface *
guest_find_interface(GuestNetworkInterfaceList *head,
const char *name)
{
for (; head; head = head->next) {
if (strcmp(head->value->name, name) == 0) {
return head->value;
}
}
return NULL;
}
static int guest_get_network_stats(const char *name,
GuestNetworkInterfaceStat *stats)
{
#ifdef CONFIG_LINUX
int name_len;
char const *devinfo = "/proc/net/dev";
FILE *fp;
char *line = NULL, *colon;
size_t n = 0;
fp = fopen(devinfo, "r");
if (!fp) {
g_debug("failed to open network stats %s: %s", devinfo,
g_strerror(errno));
return -1;
}
name_len = strlen(name);
while (getline(&line, &n, fp) != -1) {
long long dummy;
long long rx_bytes;
long long rx_packets;
long long rx_errs;
long long rx_dropped;
long long tx_bytes;
long long tx_packets;
long long tx_errs;
long long tx_dropped;
char *trim_line;
trim_line = g_strchug(line);
if (trim_line[0] == '\0') {
continue;
}
colon = strchr(trim_line, ':');
if (!colon) {
continue;
}
if (colon - name_len == trim_line &&
strncmp(trim_line, name, name_len) == 0) {
if (sscanf(colon + 1,
"%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
&rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
&dummy, &dummy, &dummy, &dummy,
&tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
&dummy, &dummy, &dummy, &dummy) != 16) {
continue;
}
stats->rx_bytes = rx_bytes;
stats->rx_packets = rx_packets;
stats->rx_errs = rx_errs;
stats->rx_dropped = rx_dropped;
stats->tx_bytes = tx_bytes;
stats->tx_packets = tx_packets;
stats->tx_errs = tx_errs;
stats->tx_dropped = tx_dropped;
fclose(fp);
g_free(line);
return 0;
}
}
fclose(fp);
g_free(line);
g_debug("/proc/net/dev: Interface '%s' not found", name);
#else /* !CONFIG_LINUX */
g_debug("Network stats reporting available only for Linux");
#endif /* !CONFIG_LINUX */
return -1;
}
#ifndef CONFIG_BSD
/*
* Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
* buffer with ETHER_ADDR_LEN length at least.
*
* Returns false in case of an error, otherwise true. "obtained" argument
* is true if a MAC address was obtained successful, otherwise false.
*/
bool guest_get_hw_addr(struct ifaddrs *ifa, unsigned char *buf,
bool *obtained, Error **errp)
{
struct ifreq ifr;
int sock;
*obtained = false;
/* we haven't obtained HW address yet */
sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock == -1) {
error_setg_errno(errp, errno, "failed to create socket");
return false;
}
memset(&ifr, 0, sizeof(ifr));
pstrcpy(ifr.ifr_name, IF_NAMESIZE, ifa->ifa_name);
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
/*
* We can't get the hw addr of this interface, but that's not a
* fatal error.
*/
if (errno == EADDRNOTAVAIL) {
/* The interface doesn't have a hw addr (e.g. loopback). */
g_debug("failed to get MAC address of %s: %s",
ifa->ifa_name, strerror(errno));
} else{
g_warning("failed to get MAC address of %s: %s",
ifa->ifa_name, strerror(errno));
}
} else {
#ifdef CONFIG_SOLARIS
memcpy(buf, &ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
#else
memcpy(buf, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
#endif
*obtained = true;
}
close(sock);
return true;
}
#endif /* CONFIG_BSD */
/*
* Build information about guest interfaces
*/
GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
{
GuestNetworkInterfaceList *head = NULL, **tail = &head;
struct ifaddrs *ifap, *ifa;
if (getifaddrs(&ifap) < 0) {
error_setg_errno(errp, errno, "getifaddrs failed");
goto error;
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
GuestNetworkInterface *info;
GuestIpAddressList **address_tail;
GuestIpAddress *address_item = NULL;
GuestNetworkInterfaceStat *interface_stat = NULL;
char addr4[INET_ADDRSTRLEN];
char addr6[INET6_ADDRSTRLEN];
unsigned char mac_addr[ETHER_ADDR_LEN];
bool obtained;
void *p;
g_debug("Processing %s interface", ifa->ifa_name);
info = guest_find_interface(head, ifa->ifa_name);
if (!info) {
info = g_malloc0(sizeof(*info));
info->name = g_strdup(ifa->ifa_name);
QAPI_LIST_APPEND(tail, info);
}
if (!info->hardware_address) {
if (!guest_get_hw_addr(ifa, mac_addr, &obtained, errp)) {
goto error;
}
if (obtained) {
qga/commands-posix: Fix iface hw address detection Since its introduction in commit 3424fc9f16a1 ("qemu-ga: add guest-network-get-interfaces command"), guest-network-get-interfaces seems to check if a given interface has a hardware address by checking 'ifa->ifa_flags & SIOCGIFHWADDR'. But ifa_flags is a field for IFF_* flags (IFF_UP, IFF_LOOPBACK, etc), and comparing it to an ioctl like SIOCGIFHWADDR doesn't make sense. On Linux, this isn't a big deal, since SIOCGIFHWADDR has so many bits set (0x8927), 'ifa->ifa_flags & SIOCGIFHWADDR' will usually have a nonzero result for any 'normal'-looking interfaces: anything with IFF_UP (0x1) or IFF_BROADCAST (0x2) set, as well as several less-common flags. This means we'll try to get the hardware address for most/all interfaces, even those that don't really have one (like the loopback device). For those interfaces, Linux just returns a hardware address of all zeroes. On Solaris, however, trying to get the hardware address for a loopback device returns an EADDRNOTAVAIL error. This causes us to return an error and the entire guest-network-get-interfaces call fails. Change this logic to always try to get the hardware address for each interface, and don't return an error if we fail to get it. Instead, just don't include the 'hardware-address' field in the result if we can't get the hardware address. Signed-off-by: Andrew Deason <adeason@sinenomine.net> Reviewed-by: Michal Privoznik <mprivozn@redhat.com> Message-Id: <20220426195526.7699-3-adeason@sinenomine.net>
2022-04-26 22:55:23 +03:00
info->hardware_address =
g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
(int) mac_addr[0], (int) mac_addr[1],
(int) mac_addr[2], (int) mac_addr[3],
(int) mac_addr[4], (int) mac_addr[5]);
}
}
if (ifa->ifa_addr &&
ifa->ifa_addr->sa_family == AF_INET) {
/* interface with IPv4 address */
p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
error_setg_errno(errp, errno, "inet_ntop failed");
goto error;
}
address_item = g_malloc0(sizeof(*address_item));
address_item->ip_address = g_strdup(addr4);
address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
if (ifa->ifa_netmask) {
/* Count the number of set bits in netmask.
* This is safe as '1' and '0' cannot be shuffled in netmask. */
p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
address_item->prefix = ctpop32(((uint32_t *) p)[0]);
}
} else if (ifa->ifa_addr &&
ifa->ifa_addr->sa_family == AF_INET6) {
/* interface with IPv6 address */
p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
error_setg_errno(errp, errno, "inet_ntop failed");
goto error;
}
address_item = g_malloc0(sizeof(*address_item));
address_item->ip_address = g_strdup(addr6);
address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
if (ifa->ifa_netmask) {
/* Count the number of set bits in netmask.
* This is safe as '1' and '0' cannot be shuffled in netmask. */
p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
address_item->prefix =
ctpop32(((uint32_t *) p)[0]) +
ctpop32(((uint32_t *) p)[1]) +
ctpop32(((uint32_t *) p)[2]) +
ctpop32(((uint32_t *) p)[3]);
}
}
if (!address_item) {
continue;
}
address_tail = &info->ip_addresses;
while (*address_tail) {
address_tail = &(*address_tail)->next;
}
QAPI_LIST_APPEND(address_tail, address_item);
info->has_ip_addresses = true;
if (!info->statistics) {
interface_stat = g_malloc0(sizeof(*interface_stat));
if (guest_get_network_stats(info->name, interface_stat) == -1) {
g_free(interface_stat);
} else {
info->statistics = interface_stat;
}
}
}
freeifaddrs(ifap);
return head;
error:
freeifaddrs(ifap);
qapi_free_GuestNetworkInterfaceList(head);
return NULL;
}
#endif /* HAVE_GETIFADDRS */
/* register init/cleanup routines for stateful command groups */
void ga_command_state_init(GAState *s, GACommandState *cs)
{
#if defined(CONFIG_FSFREEZE)
ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
#endif
}
#ifdef HAVE_UTMPX
#define QGA_MICRO_SECOND_TO_SECOND 1000000
static double ga_get_login_time(struct utmpx *user_info)
{
double seconds = (double)user_info->ut_tv.tv_sec;
double useconds = (double)user_info->ut_tv.tv_usec;
useconds /= QGA_MICRO_SECOND_TO_SECOND;
return seconds + useconds;
}
GuestUserList *qmp_guest_get_users(Error **errp)
{
GHashTable *cache = NULL;
GuestUserList *head = NULL, **tail = &head;
struct utmpx *user_info = NULL;
gpointer value = NULL;
GuestUser *user = NULL;
double login_time = 0;
cache = g_hash_table_new(g_str_hash, g_str_equal);
setutxent();
for (;;) {
user_info = getutxent();
if (user_info == NULL) {
break;
} else if (user_info->ut_type != USER_PROCESS) {
continue;
} else if (g_hash_table_contains(cache, user_info->ut_user)) {
value = g_hash_table_lookup(cache, user_info->ut_user);
user = (GuestUser *)value;
login_time = ga_get_login_time(user_info);
/* We're ensuring the earliest login time to be sent */
if (login_time < user->login_time) {
user->login_time = login_time;
}
continue;
}
user = g_new0(GuestUser, 1);
user->user = g_strdup(user_info->ut_user);
user->login_time = ga_get_login_time(user_info);
g_hash_table_insert(cache, user->user, user);
QAPI_LIST_APPEND(tail, user);
}
endutxent();
g_hash_table_destroy(cache);
return head;
}
#endif /* HAVE_UTMPX */
/* Replace escaped special characters with their real values. The replacement
* is done in place -- returned value is in the original string.
*/
static void ga_osrelease_replace_special(gchar *value)
{
gchar *p, *p2, quote;
/* Trim the string at first space or semicolon if it is not enclosed in
* single or double quotes. */
if ((value[0] != '"') || (value[0] == '\'')) {
p = strchr(value, ' ');
if (p != NULL) {
*p = 0;
}
p = strchr(value, ';');
if (p != NULL) {
*p = 0;
}
return;
}
quote = value[0];
p2 = value;
p = value + 1;
while (*p != 0) {
if (*p == '\\') {
p++;
switch (*p) {
case '$':
case '\'':
case '"':
case '\\':
case '`':
break;
default:
/* Keep literal backslash followed by whatever is there */
p--;
break;
}
} else if (*p == quote) {
*p2 = 0;
break;
}
*(p2++) = *(p++);
}
}
static GKeyFile *ga_parse_osrelease(const char *fname)
{
gchar *content = NULL;
gchar *content2 = NULL;
GError *err = NULL;
GKeyFile *keys = g_key_file_new();
const char *group = "[os-release]\n";
if (!g_file_get_contents(fname, &content, NULL, &err)) {
slog("failed to read '%s', error: %s", fname, err->message);
goto fail;
}
if (!g_utf8_validate(content, -1, NULL)) {
slog("file is not utf-8 encoded: %s", fname);
goto fail;
}
content2 = g_strdup_printf("%s%s", group, content);
if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
&err)) {
slog("failed to parse file '%s', error: %s", fname, err->message);
goto fail;
}
g_free(content);
g_free(content2);
return keys;
fail:
g_error_free(err);
g_free(content);
g_free(content2);
g_key_file_free(keys);
return NULL;
}
GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
{
GuestOSInfo *info = NULL;
struct utsname kinfo;
GKeyFile *osrelease = NULL;
const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
info = g_new0(GuestOSInfo, 1);
if (uname(&kinfo) != 0) {
error_setg_errno(errp, errno, "uname failed");
} else {
info->kernel_version = g_strdup(kinfo.version);
info->kernel_release = g_strdup(kinfo.release);
info->machine = g_strdup(kinfo.machine);
}
if (qga_os_release != NULL) {
osrelease = ga_parse_osrelease(qga_os_release);
} else {
osrelease = ga_parse_osrelease("/etc/os-release");
if (osrelease == NULL) {
osrelease = ga_parse_osrelease("/usr/lib/os-release");
}
}
if (osrelease != NULL) {
char *value;
#define GET_FIELD(field, osfield) do { \
value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
if (value != NULL) { \
ga_osrelease_replace_special(value); \
info->field = value; \
} \
} while (0)
GET_FIELD(id, "ID");
GET_FIELD(name, "NAME");
GET_FIELD(pretty_name, "PRETTY_NAME");
GET_FIELD(version, "VERSION");
GET_FIELD(version_id, "VERSION_ID");
GET_FIELD(variant, "VARIANT");
GET_FIELD(variant_id, "VARIANT_ID");
#undef GET_FIELD
g_key_file_free(osrelease);
}
return info;
}
#ifndef HOST_NAME_MAX
# ifdef _POSIX_HOST_NAME_MAX
# define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
# else
# define HOST_NAME_MAX 255
# endif
#endif
char *qga_get_host_name(Error **errp)
{
long len = -1;
g_autofree char *hostname = NULL;
#ifdef _SC_HOST_NAME_MAX
len = sysconf(_SC_HOST_NAME_MAX);
#endif /* _SC_HOST_NAME_MAX */
if (len < 0) {
len = HOST_NAME_MAX;
}
/* Unfortunately, gethostname() below does not guarantee a
* NULL terminated string. Therefore, allocate one byte more
* to be sure. */
hostname = g_new0(char, len + 1);
if (gethostname(hostname, len) < 0) {
error_setg_errno(errp, errno,
"cannot get hostname");
return NULL;
}
return g_steal_pointer(&hostname);
}