xref: /openbmc/qemu/qga/commands.c (revision d38ea87a)
1 /*
2  * QEMU Guest Agent common/cross-platform command implementations
3  *
4  * Copyright IBM Corp. 2012
5  *
6  * Authors:
7  *  Michael Roth      <mdroth@linux.vnet.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  */
12 
13 #include "qemu/osdep.h"
14 #include <glib.h>
15 #include "qga/guest-agent-core.h"
16 #include "qga-qmp-commands.h"
17 #include "qapi/qmp/qerror.h"
18 #include "qemu/base64.h"
19 
20 /* Maximum captured guest-exec out_data/err_data - 16MB */
21 #define GUEST_EXEC_MAX_OUTPUT (16*1024*1024)
22 /* Allocation and I/O buffer for reading guest-exec out_data/err_data - 4KB */
23 #define GUEST_EXEC_IO_SIZE (4*1024)
24 
25 /* Note: in some situations, like with the fsfreeze, logging may be
26  * temporarilly disabled. if it is necessary that a command be able
27  * to log for accounting purposes, check ga_logging_enabled() beforehand,
28  * and use the QERR_QGA_LOGGING_DISABLED to generate an error
29  */
30 void slog(const gchar *fmt, ...)
31 {
32     va_list ap;
33 
34     va_start(ap, fmt);
35     g_logv("syslog", G_LOG_LEVEL_INFO, fmt, ap);
36     va_end(ap);
37 }
38 
39 int64_t qmp_guest_sync_delimited(int64_t id, Error **errp)
40 {
41     ga_set_response_delimited(ga_state);
42     return id;
43 }
44 
45 int64_t qmp_guest_sync(int64_t id, Error **errp)
46 {
47     return id;
48 }
49 
50 void qmp_guest_ping(Error **errp)
51 {
52     slog("guest-ping called");
53 }
54 
55 static void qmp_command_info(QmpCommand *cmd, void *opaque)
56 {
57     GuestAgentInfo *info = opaque;
58     GuestAgentCommandInfo *cmd_info;
59     GuestAgentCommandInfoList *cmd_info_list;
60 
61     cmd_info = g_new0(GuestAgentCommandInfo, 1);
62     cmd_info->name = g_strdup(qmp_command_name(cmd));
63     cmd_info->enabled = qmp_command_is_enabled(cmd);
64     cmd_info->success_response = qmp_has_success_response(cmd);
65 
66     cmd_info_list = g_new0(GuestAgentCommandInfoList, 1);
67     cmd_info_list->value = cmd_info;
68     cmd_info_list->next = info->supported_commands;
69     info->supported_commands = cmd_info_list;
70 }
71 
72 struct GuestAgentInfo *qmp_guest_info(Error **errp)
73 {
74     GuestAgentInfo *info = g_new0(GuestAgentInfo, 1);
75 
76     info->version = g_strdup(QEMU_VERSION);
77     qmp_for_each_command(qmp_command_info, info);
78     return info;
79 }
80 
81 struct GuestExecIOData {
82     guchar *data;
83     gsize size;
84     gsize length;
85     gint closed;
86     bool truncated;
87     const char *name;
88 };
89 typedef struct GuestExecIOData GuestExecIOData;
90 
91 struct GuestExecInfo {
92     GPid pid;
93     int64_t pid_numeric;
94     gint status;
95     bool has_output;
96     gint finished;
97     GuestExecIOData in;
98     GuestExecIOData out;
99     GuestExecIOData err;
100     QTAILQ_ENTRY(GuestExecInfo) next;
101 };
102 typedef struct GuestExecInfo GuestExecInfo;
103 
104 static struct {
105     QTAILQ_HEAD(, GuestExecInfo) processes;
106 } guest_exec_state = {
107     .processes = QTAILQ_HEAD_INITIALIZER(guest_exec_state.processes),
108 };
109 
110 static int64_t gpid_to_int64(GPid pid)
111 {
112 #ifdef G_OS_WIN32
113     return GetProcessId(pid);
114 #else
115     return (int64_t)pid;
116 #endif
117 }
118 
119 static GuestExecInfo *guest_exec_info_add(GPid pid)
120 {
121     GuestExecInfo *gei;
122 
123     gei = g_new0(GuestExecInfo, 1);
124     gei->pid = pid;
125     gei->pid_numeric = gpid_to_int64(pid);
126     QTAILQ_INSERT_TAIL(&guest_exec_state.processes, gei, next);
127 
128     return gei;
129 }
130 
131 static GuestExecInfo *guest_exec_info_find(int64_t pid_numeric)
132 {
133     GuestExecInfo *gei;
134 
135     QTAILQ_FOREACH(gei, &guest_exec_state.processes, next) {
136         if (gei->pid_numeric == pid_numeric) {
137             return gei;
138         }
139     }
140 
141     return NULL;
142 }
143 
144 GuestExecStatus *qmp_guest_exec_status(int64_t pid, Error **err)
145 {
146     GuestExecInfo *gei;
147     GuestExecStatus *ges;
148 
149     slog("guest-exec-status called, pid: %u", (uint32_t)pid);
150 
151     gei = guest_exec_info_find(pid);
152     if (gei == NULL) {
153         error_setg(err, QERR_INVALID_PARAMETER, "pid");
154         return NULL;
155     }
156 
157     ges = g_new0(GuestExecStatus, 1);
158 
159     bool finished = g_atomic_int_get(&gei->finished);
160 
161     /* need to wait till output channels are closed
162      * to be sure we captured all output at this point */
163     if (gei->has_output) {
164         finished = finished && g_atomic_int_get(&gei->out.closed);
165         finished = finished && g_atomic_int_get(&gei->err.closed);
166     }
167 
168     ges->exited = finished;
169     if (finished) {
170         /* Glib has no portable way to parse exit status.
171          * On UNIX, we can get either exit code from normal termination
172          * or signal number.
173          * On Windows, it is either the same exit code or the exception
174          * value for an unhandled exception that caused the process
175          * to terminate.
176          * See MSDN for GetExitCodeProcess() and ntstatus.h for possible
177          * well-known codes, e.g. C0000005 ACCESS_DENIED - analog of SIGSEGV
178          * References:
179          *   https://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx
180          *   https://msdn.microsoft.com/en-us/library/aa260331(v=vs.60).aspx
181          */
182 #ifdef G_OS_WIN32
183         /* Additionally WIN32 does not provide any additional information
184          * on whetherthe child exited or terminated via signal.
185          * We use this simple range check to distingish application exit code
186          * (usually value less then 256) and unhandled exception code with
187          * ntstatus (always value greater then 0xC0000005). */
188         if ((uint32_t)gei->status < 0xC0000000U) {
189             ges->has_exitcode = true;
190             ges->exitcode = gei->status;
191         } else {
192             ges->has_signal = true;
193             ges->signal = gei->status;
194         }
195 #else
196         if (WIFEXITED(gei->status)) {
197             ges->has_exitcode = true;
198             ges->exitcode = WEXITSTATUS(gei->status);
199         } else if (WIFSIGNALED(gei->status)) {
200             ges->has_signal = true;
201             ges->signal = WTERMSIG(gei->status);
202         }
203 #endif
204         if (gei->out.length > 0) {
205             ges->has_out_data = true;
206             ges->out_data = g_base64_encode(gei->out.data, gei->out.length);
207             g_free(gei->out.data);
208             ges->has_out_truncated = gei->out.truncated;
209         }
210 
211         if (gei->err.length > 0) {
212             ges->has_err_data = true;
213             ges->err_data = g_base64_encode(gei->err.data, gei->err.length);
214             g_free(gei->err.data);
215             ges->has_err_truncated = gei->err.truncated;
216         }
217 
218         QTAILQ_REMOVE(&guest_exec_state.processes, gei, next);
219         g_free(gei);
220     }
221 
222     return ges;
223 }
224 
225 /* Get environment variables or arguments array for execve(). */
226 static char **guest_exec_get_args(const strList *entry, bool log)
227 {
228     const strList *it;
229     int count = 1, i = 0;  /* reserve for NULL terminator */
230     char **args;
231     char *str; /* for logging array of arguments */
232     size_t str_size = 1;
233 
234     for (it = entry; it != NULL; it = it->next) {
235         count++;
236         str_size += 1 + strlen(it->value);
237     }
238 
239     str = g_malloc(str_size);
240     *str = 0;
241     args = g_malloc(count * sizeof(char *));
242     for (it = entry; it != NULL; it = it->next) {
243         args[i++] = it->value;
244         pstrcat(str, str_size, it->value);
245         if (it->next) {
246             pstrcat(str, str_size, " ");
247         }
248     }
249     args[i] = NULL;
250 
251     if (log) {
252         slog("guest-exec called: \"%s\"", str);
253     }
254     g_free(str);
255 
256     return args;
257 }
258 
259 static void guest_exec_child_watch(GPid pid, gint status, gpointer data)
260 {
261     GuestExecInfo *gei = (GuestExecInfo *)data;
262 
263     g_debug("guest_exec_child_watch called, pid: %d, status: %u",
264             (int32_t)gpid_to_int64(pid), (uint32_t)status);
265 
266     gei->status = status;
267     gei->finished = true;
268 
269     g_spawn_close_pid(pid);
270 }
271 
272 /** Reset ignored signals back to default. */
273 static void guest_exec_task_setup(gpointer data)
274 {
275 #if !defined(G_OS_WIN32)
276     struct sigaction sigact;
277 
278     memset(&sigact, 0, sizeof(struct sigaction));
279     sigact.sa_handler = SIG_DFL;
280 
281     if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
282         slog("sigaction() failed to reset child process's SIGPIPE: %s",
283              strerror(errno));
284     }
285 #endif
286 }
287 
288 static gboolean guest_exec_input_watch(GIOChannel *ch,
289         GIOCondition cond, gpointer p_)
290 {
291     GuestExecIOData *p = (GuestExecIOData *)p_;
292     gsize bytes_written = 0;
293     GIOStatus status;
294     GError *gerr = NULL;
295 
296     /* nothing left to write */
297     if (p->size == p->length) {
298         goto done;
299     }
300 
301     status = g_io_channel_write_chars(ch, (gchar *)p->data + p->length,
302             p->size - p->length, &bytes_written, &gerr);
303 
304     /* can be not 0 even if not G_IO_STATUS_NORMAL */
305     if (bytes_written != 0) {
306         p->length += bytes_written;
307     }
308 
309     /* continue write, our callback will be called again */
310     if (status == G_IO_STATUS_NORMAL || status == G_IO_STATUS_AGAIN) {
311         return true;
312     }
313 
314     if (gerr) {
315         g_warning("qga: i/o error writing to input_data channel: %s",
316                 gerr->message);
317         g_error_free(gerr);
318     }
319 
320 done:
321     g_io_channel_shutdown(ch, true, NULL);
322     g_io_channel_unref(ch);
323     g_atomic_int_set(&p->closed, 1);
324     g_free(p->data);
325 
326     return false;
327 }
328 
329 static gboolean guest_exec_output_watch(GIOChannel *ch,
330         GIOCondition cond, gpointer p_)
331 {
332     GuestExecIOData *p = (GuestExecIOData *)p_;
333     gsize bytes_read;
334     GIOStatus gstatus;
335 
336     if (cond == G_IO_HUP || cond == G_IO_ERR) {
337         goto close;
338     }
339 
340     if (p->size == p->length) {
341         gpointer t = NULL;
342         if (!p->truncated && p->size < GUEST_EXEC_MAX_OUTPUT) {
343             t = g_try_realloc(p->data, p->size + GUEST_EXEC_IO_SIZE);
344         }
345         if (t == NULL) {
346             /* ignore truncated output */
347             gchar buf[GUEST_EXEC_IO_SIZE];
348 
349             p->truncated = true;
350             gstatus = g_io_channel_read_chars(ch, buf, sizeof(buf),
351                                               &bytes_read, NULL);
352             if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
353                 goto close;
354             }
355 
356             return true;
357         }
358         p->size += GUEST_EXEC_IO_SIZE;
359         p->data = t;
360     }
361 
362     /* Calling read API once.
363      * On next available data our callback will be called again */
364     gstatus = g_io_channel_read_chars(ch, (gchar *)p->data + p->length,
365             p->size - p->length, &bytes_read, NULL);
366     if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
367         goto close;
368     }
369 
370     p->length += bytes_read;
371 
372     return true;
373 
374 close:
375     g_io_channel_unref(ch);
376     g_atomic_int_set(&p->closed, 1);
377     return false;
378 }
379 
380 GuestExec *qmp_guest_exec(const char *path,
381                        bool has_arg, strList *arg,
382                        bool has_env, strList *env,
383                        bool has_input_data, const char *input_data,
384                        bool has_capture_output, bool capture_output,
385                        Error **err)
386 {
387     GPid pid;
388     GuestExec *ge = NULL;
389     GuestExecInfo *gei;
390     char **argv, **envp;
391     strList arglist;
392     gboolean ret;
393     GError *gerr = NULL;
394     gint in_fd, out_fd, err_fd;
395     GIOChannel *in_ch, *out_ch, *err_ch;
396     GSpawnFlags flags;
397     bool has_output = (has_capture_output && capture_output);
398     uint8_t *input = NULL;
399     size_t ninput = 0;
400 
401     arglist.value = (char *)path;
402     arglist.next = has_arg ? arg : NULL;
403 
404     if (has_input_data) {
405         input = qbase64_decode(input_data, -1, &ninput, err);
406         if (!input) {
407             return NULL;
408         }
409     }
410 
411     argv = guest_exec_get_args(&arglist, true);
412     envp = has_env ? guest_exec_get_args(env, false) : NULL;
413 
414     flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD;
415 #if GLIB_CHECK_VERSION(2, 33, 2)
416     flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
417 #endif
418     if (!has_output) {
419         flags |= G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL;
420     }
421 
422     ret = g_spawn_async_with_pipes(NULL, argv, envp, flags,
423             guest_exec_task_setup, NULL, &pid, has_input_data ? &in_fd : NULL,
424             has_output ? &out_fd : NULL, has_output ? &err_fd : NULL, &gerr);
425     if (!ret) {
426         error_setg(err, QERR_QGA_COMMAND_FAILED, gerr->message);
427         g_error_free(gerr);
428         goto done;
429     }
430 
431     ge = g_new0(GuestExec, 1);
432     ge->pid = gpid_to_int64(pid);
433 
434     gei = guest_exec_info_add(pid);
435     gei->has_output = has_output;
436     g_child_watch_add(pid, guest_exec_child_watch, gei);
437 
438     if (has_input_data) {
439         gei->in.data = input;
440         gei->in.size = ninput;
441 #ifdef G_OS_WIN32
442         in_ch = g_io_channel_win32_new_fd(in_fd);
443 #else
444         in_ch = g_io_channel_unix_new(in_fd);
445 #endif
446         g_io_channel_set_encoding(in_ch, NULL, NULL);
447         g_io_channel_set_buffered(in_ch, false);
448         g_io_channel_set_flags(in_ch, G_IO_FLAG_NONBLOCK, NULL);
449         g_io_add_watch(in_ch, G_IO_OUT, guest_exec_input_watch, &gei->in);
450     }
451 
452     if (has_output) {
453 #ifdef G_OS_WIN32
454         out_ch = g_io_channel_win32_new_fd(out_fd);
455         err_ch = g_io_channel_win32_new_fd(err_fd);
456 #else
457         out_ch = g_io_channel_unix_new(out_fd);
458         err_ch = g_io_channel_unix_new(err_fd);
459 #endif
460         g_io_channel_set_encoding(out_ch, NULL, NULL);
461         g_io_channel_set_encoding(err_ch, NULL, NULL);
462         g_io_channel_set_buffered(out_ch, false);
463         g_io_channel_set_buffered(err_ch, false);
464         g_io_add_watch(out_ch, G_IO_IN | G_IO_HUP,
465                 guest_exec_output_watch, &gei->out);
466         g_io_add_watch(err_ch, G_IO_IN | G_IO_HUP,
467                 guest_exec_output_watch, &gei->err);
468     }
469 
470 done:
471     g_free(argv);
472     g_free(envp);
473 
474     return ge;
475 }
476