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