xref: /openbmc/qemu/qga/commands.c (revision 6d2d454a)
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 "qemu/units.h"
15 #include "guest-agent-core.h"
16 #include "qga-qapi-commands.h"
17 #include "qapi/error.h"
18 #include "qapi/qmp/qerror.h"
19 #include "qemu/base64.h"
20 #include "qemu/cutils.h"
21 #include "commands-common.h"
22 
23 /* Maximum captured guest-exec out_data/err_data - 16MB */
24 #define GUEST_EXEC_MAX_OUTPUT (16 * 1024 * 1024)
25 /* Allocation and I/O buffer for reading guest-exec out_data/err_data - 4KB */
26 #define GUEST_EXEC_IO_SIZE (4 * 1024)
27 /*
28  * Maximum file size to read - 48MB
29  *
30  * (48MB + Base64 3:4 overhead = JSON parser 64 MB limit)
31  */
32 #define GUEST_FILE_READ_COUNT_MAX (48 * MiB)
33 
34 /* Note: in some situations, like with the fsfreeze, logging may be
35  * temporarily disabled. if it is necessary that a command be able
36  * to log for accounting purposes, check ga_logging_enabled() beforehand.
37  */
38 void slog(const gchar *fmt, ...)
39 {
40     va_list ap;
41 
42     va_start(ap, fmt);
43     g_logv("syslog", G_LOG_LEVEL_INFO, fmt, ap);
44     va_end(ap);
45 }
46 
47 int64_t qmp_guest_sync_delimited(int64_t id, Error **errp)
48 {
49     ga_set_response_delimited(ga_state);
50     return id;
51 }
52 
53 int64_t qmp_guest_sync(int64_t id, Error **errp)
54 {
55     return id;
56 }
57 
58 void qmp_guest_ping(Error **errp)
59 {
60     slog("guest-ping called");
61 }
62 
63 static void qmp_command_info(const QmpCommand *cmd, void *opaque)
64 {
65     GuestAgentInfo *info = opaque;
66     GuestAgentCommandInfo *cmd_info;
67 
68     cmd_info = g_new0(GuestAgentCommandInfo, 1);
69     cmd_info->name = g_strdup(qmp_command_name(cmd));
70     cmd_info->enabled = qmp_command_is_enabled(cmd);
71     cmd_info->success_response = qmp_has_success_response(cmd);
72 
73     QAPI_LIST_PREPEND(info->supported_commands, cmd_info);
74 }
75 
76 struct GuestAgentInfo *qmp_guest_info(Error **errp)
77 {
78     GuestAgentInfo *info = g_new0(GuestAgentInfo, 1);
79 
80     info->version = g_strdup(QEMU_VERSION);
81     qmp_for_each_command(&ga_commands, qmp_command_info, info);
82     return info;
83 }
84 
85 struct GuestExecIOData {
86     guchar *data;
87     gsize size;
88     gsize length;
89     bool closed;
90     bool truncated;
91     const char *name;
92 };
93 typedef struct GuestExecIOData GuestExecIOData;
94 
95 struct GuestExecInfo {
96     GPid pid;
97     int64_t pid_numeric;
98     gint status;
99     bool has_output;
100     bool finished;
101     GuestExecIOData in;
102     GuestExecIOData out;
103     GuestExecIOData err;
104     QTAILQ_ENTRY(GuestExecInfo) next;
105 };
106 typedef struct GuestExecInfo GuestExecInfo;
107 
108 static struct {
109     QTAILQ_HEAD(, GuestExecInfo) processes;
110 } guest_exec_state = {
111     .processes = QTAILQ_HEAD_INITIALIZER(guest_exec_state.processes),
112 };
113 
114 static int64_t gpid_to_int64(GPid pid)
115 {
116 #ifdef G_OS_WIN32
117     return GetProcessId(pid);
118 #else
119     return (int64_t)pid;
120 #endif
121 }
122 
123 static GuestExecInfo *guest_exec_info_add(GPid pid)
124 {
125     GuestExecInfo *gei;
126 
127     gei = g_new0(GuestExecInfo, 1);
128     gei->pid = pid;
129     gei->pid_numeric = gpid_to_int64(pid);
130     QTAILQ_INSERT_TAIL(&guest_exec_state.processes, gei, next);
131 
132     return gei;
133 }
134 
135 static GuestExecInfo *guest_exec_info_find(int64_t pid_numeric)
136 {
137     GuestExecInfo *gei;
138 
139     QTAILQ_FOREACH(gei, &guest_exec_state.processes, next) {
140         if (gei->pid_numeric == pid_numeric) {
141             return gei;
142         }
143     }
144 
145     return NULL;
146 }
147 
148 GuestExecStatus *qmp_guest_exec_status(int64_t pid, Error **errp)
149 {
150     GuestExecInfo *gei;
151     GuestExecStatus *ges;
152 
153     slog("guest-exec-status called, pid: %u", (uint32_t)pid);
154 
155     gei = guest_exec_info_find(pid);
156     if (gei == NULL) {
157         error_setg(errp, QERR_INVALID_PARAMETER, "pid");
158         return NULL;
159     }
160 
161     ges = g_new0(GuestExecStatus, 1);
162 
163     bool finished = gei->finished;
164 
165     /* need to wait till output channels are closed
166      * to be sure we captured all output at this point */
167     if (gei->has_output) {
168         finished &= gei->out.closed && gei->err.closed;
169     }
170 
171     ges->exited = finished;
172     if (finished) {
173         /* Glib has no portable way to parse exit status.
174          * On UNIX, we can get either exit code from normal termination
175          * or signal number.
176          * On Windows, it is either the same exit code or the exception
177          * value for an unhandled exception that caused the process
178          * to terminate.
179          * See MSDN for GetExitCodeProcess() and ntstatus.h for possible
180          * well-known codes, e.g. C0000005 ACCESS_DENIED - analog of SIGSEGV
181          * References:
182          *   https://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx
183          *   https://msdn.microsoft.com/en-us/library/aa260331(v=vs.60).aspx
184          */
185 #ifdef G_OS_WIN32
186         /* Additionally WIN32 does not provide any additional information
187          * on whether the child exited or terminated via signal.
188          * We use this simple range check to distinguish application exit code
189          * (usually value less then 256) and unhandled exception code with
190          * ntstatus (always value greater then 0xC0000005). */
191         if ((uint32_t)gei->status < 0xC0000000U) {
192             ges->has_exitcode = true;
193             ges->exitcode = gei->status;
194         } else {
195             ges->has_signal = true;
196             ges->signal = gei->status;
197         }
198 #else
199         if (WIFEXITED(gei->status)) {
200             ges->has_exitcode = true;
201             ges->exitcode = WEXITSTATUS(gei->status);
202         } else if (WIFSIGNALED(gei->status)) {
203             ges->has_signal = true;
204             ges->signal = WTERMSIG(gei->status);
205         }
206 #endif
207         if (gei->out.length > 0) {
208             ges->out_data = g_base64_encode(gei->out.data, gei->out.length);
209             g_free(gei->out.data);
210             ges->has_out_truncated = gei->out.truncated;
211         }
212 
213         if (gei->err.length > 0) {
214             ges->err_data = g_base64_encode(gei->err.data, gei->err.length);
215             g_free(gei->err.data);
216             ges->has_err_truncated = gei->err.truncated;
217         }
218 
219         QTAILQ_REMOVE(&guest_exec_state.processes, gei, next);
220         g_free(gei);
221     }
222 
223     return ges;
224 }
225 
226 /* Get environment variables or arguments array for execve(). */
227 static char **guest_exec_get_args(const strList *entry, bool log)
228 {
229     const strList *it;
230     int count = 1, i = 0;  /* reserve for NULL terminator */
231     char **args;
232     char *str; /* for logging array of arguments */
233     size_t str_size = 1;
234 
235     for (it = entry; it != NULL; it = it->next) {
236         count++;
237         str_size += 1 + strlen(it->value);
238     }
239 
240     str = g_malloc(str_size);
241     *str = 0;
242     args = g_new(char *, count);
243     for (it = entry; it != NULL; it = it->next) {
244         args[i++] = it->value;
245         pstrcat(str, str_size, it->value);
246         if (it->next) {
247             pstrcat(str, str_size, " ");
248         }
249     }
250     args[i] = NULL;
251 
252     if (log) {
253         slog("guest-exec called: \"%s\"", str);
254     }
255     g_free(str);
256 
257     return args;
258 }
259 
260 static void guest_exec_child_watch(GPid pid, gint status, gpointer data)
261 {
262     GuestExecInfo *gei = (GuestExecInfo *)data;
263 
264     g_debug("guest_exec_child_watch called, pid: %d, status: %u",
265             (int32_t)gpid_to_int64(pid), (uint32_t)status);
266 
267     gei->status = status;
268     gei->finished = true;
269 
270     g_spawn_close_pid(pid);
271 }
272 
273 /** Reset ignored signals back to default. */
274 static void guest_exec_task_setup(gpointer data)
275 {
276 #if !defined(G_OS_WIN32)
277     struct sigaction sigact;
278 
279     memset(&sigact, 0, sizeof(struct sigaction));
280     sigact.sa_handler = SIG_DFL;
281 
282     if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
283         slog("sigaction() failed to reset child process's SIGPIPE: %s",
284              strerror(errno));
285     }
286 #endif
287 }
288 
289 static gboolean guest_exec_input_watch(GIOChannel *ch,
290         GIOCondition cond, gpointer p_)
291 {
292     GuestExecIOData *p = (GuestExecIOData *)p_;
293     gsize bytes_written = 0;
294     GIOStatus status;
295     GError *gerr = NULL;
296 
297     /* nothing left to write */
298     if (p->size == p->length) {
299         goto done;
300     }
301 
302     status = g_io_channel_write_chars(ch, (gchar *)p->data + p->length,
303             p->size - p->length, &bytes_written, &gerr);
304 
305     /* can be not 0 even if not G_IO_STATUS_NORMAL */
306     if (bytes_written != 0) {
307         p->length += bytes_written;
308     }
309 
310     /* continue write, our callback will be called again */
311     if (status == G_IO_STATUS_NORMAL || status == G_IO_STATUS_AGAIN) {
312         return true;
313     }
314 
315     if (gerr) {
316         g_warning("qga: i/o error writing to input_data channel: %s",
317                 gerr->message);
318         g_error_free(gerr);
319     }
320 
321 done:
322     g_io_channel_shutdown(ch, true, NULL);
323     g_io_channel_unref(ch);
324     p->closed = true;
325     g_free(p->data);
326 
327     return false;
328 }
329 
330 static gboolean guest_exec_output_watch(GIOChannel *ch,
331         GIOCondition cond, gpointer p_)
332 {
333     GuestExecIOData *p = (GuestExecIOData *)p_;
334     gsize bytes_read;
335     GIOStatus gstatus;
336 
337     if (cond == G_IO_HUP || cond == G_IO_ERR) {
338         goto close;
339     }
340 
341     if (p->size == p->length) {
342         gpointer t = NULL;
343         if (!p->truncated && p->size < GUEST_EXEC_MAX_OUTPUT) {
344             t = g_try_realloc(p->data, p->size + GUEST_EXEC_IO_SIZE);
345         }
346         if (t == NULL) {
347             /* ignore truncated output */
348             gchar buf[GUEST_EXEC_IO_SIZE];
349 
350             p->truncated = true;
351             gstatus = g_io_channel_read_chars(ch, buf, sizeof(buf),
352                                               &bytes_read, NULL);
353             if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
354                 goto close;
355             }
356 
357             return true;
358         }
359         p->size += GUEST_EXEC_IO_SIZE;
360         p->data = t;
361     }
362 
363     /* Calling read API once.
364      * On next available data our callback will be called again */
365     gstatus = g_io_channel_read_chars(ch, (gchar *)p->data + p->length,
366             p->size - p->length, &bytes_read, NULL);
367     if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
368         goto close;
369     }
370 
371     p->length += bytes_read;
372 
373     return true;
374 
375 close:
376     g_io_channel_shutdown(ch, true, NULL);
377     g_io_channel_unref(ch);
378     p->closed = true;
379     return false;
380 }
381 
382 GuestExec *qmp_guest_exec(const char *path,
383                        bool has_arg, strList *arg,
384                        bool has_env, strList *env,
385                        const char *input_data,
386                        bool has_capture_output, bool capture_output,
387                        Error **errp)
388 {
389     GPid pid;
390     GuestExec *ge = NULL;
391     GuestExecInfo *gei;
392     char **argv, **envp;
393     strList arglist;
394     gboolean ret;
395     GError *gerr = NULL;
396     gint in_fd, out_fd, err_fd;
397     GIOChannel *in_ch, *out_ch, *err_ch;
398     GSpawnFlags flags;
399     bool has_output = (has_capture_output && capture_output);
400     g_autofree uint8_t *input = NULL;
401     size_t ninput = 0;
402 
403     arglist.value = (char *)path;
404     arglist.next = has_arg ? arg : NULL;
405 
406     if (input_data) {
407         input = qbase64_decode(input_data, -1, &ninput, errp);
408         if (!input) {
409             return NULL;
410         }
411     }
412 
413     argv = guest_exec_get_args(&arglist, true);
414     envp = has_env ? guest_exec_get_args(env, false) : NULL;
415 
416     flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD |
417         G_SPAWN_SEARCH_PATH_FROM_ENVP;
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, input_data ? &in_fd : NULL,
424             has_output ? &out_fd : NULL, has_output ? &err_fd : NULL, &gerr);
425     if (!ret) {
426         error_setg(errp, 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 (input_data) {
439         gei->in.data = g_steal_pointer(&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_channel_set_close_on_unref(in_ch, true);
450         g_io_add_watch(in_ch, G_IO_OUT, guest_exec_input_watch, &gei->in);
451     }
452 
453     if (has_output) {
454 #ifdef G_OS_WIN32
455         out_ch = g_io_channel_win32_new_fd(out_fd);
456         err_ch = g_io_channel_win32_new_fd(err_fd);
457 #else
458         out_ch = g_io_channel_unix_new(out_fd);
459         err_ch = g_io_channel_unix_new(err_fd);
460 #endif
461         g_io_channel_set_encoding(out_ch, NULL, NULL);
462         g_io_channel_set_encoding(err_ch, NULL, NULL);
463         g_io_channel_set_buffered(out_ch, false);
464         g_io_channel_set_buffered(err_ch, false);
465         g_io_channel_set_close_on_unref(out_ch, true);
466         g_io_channel_set_close_on_unref(err_ch, true);
467         g_io_add_watch(out_ch, G_IO_IN | G_IO_HUP,
468                 guest_exec_output_watch, &gei->out);
469         g_io_add_watch(err_ch, G_IO_IN | G_IO_HUP,
470                 guest_exec_output_watch, &gei->err);
471     }
472 
473 done:
474     g_free(argv);
475     g_free(envp);
476 
477     return ge;
478 }
479 
480 /* Convert GuestFileWhence (either a raw integer or an enum value) into
481  * the guest's SEEK_ constants.  */
482 int ga_parse_whence(GuestFileWhence *whence, Error **errp)
483 {
484     /*
485      * Exploit the fact that we picked values to match QGA_SEEK_*;
486      * however, we have to use a temporary variable since the union
487      * members may have different size.
488      */
489     if (whence->type == QTYPE_QSTRING) {
490         int value = whence->u.name;
491         whence->type = QTYPE_QNUM;
492         whence->u.value = value;
493     }
494     switch (whence->u.value) {
495     case QGA_SEEK_SET:
496         return SEEK_SET;
497     case QGA_SEEK_CUR:
498         return SEEK_CUR;
499     case QGA_SEEK_END:
500         return SEEK_END;
501     }
502     error_setg(errp, "invalid whence code %"PRId64, whence->u.value);
503     return -1;
504 }
505 
506 GuestHostName *qmp_guest_get_host_name(Error **errp)
507 {
508     GuestHostName *result = NULL;
509     g_autofree char *hostname = qga_get_host_name(errp);
510 
511     /*
512      * We want to avoid using g_get_host_name() because that
513      * caches the result and we wouldn't reflect changes in the
514      * host name.
515      */
516 
517     if (!hostname) {
518         hostname = g_strdup("localhost");
519     }
520 
521     result = g_new0(GuestHostName, 1);
522     result->host_name = g_steal_pointer(&hostname);
523     return result;
524 }
525 
526 GuestTimezone *qmp_guest_get_timezone(Error **errp)
527 {
528     GuestTimezone *info = NULL;
529     GTimeZone *tz = NULL;
530     gint64 now = 0;
531     gint32 intv = 0;
532     gchar const *name = NULL;
533 
534     info = g_new0(GuestTimezone, 1);
535     tz = g_time_zone_new_local();
536     if (tz == NULL) {
537         error_setg(errp, QERR_QGA_COMMAND_FAILED,
538                    "Couldn't retrieve local timezone");
539         goto error;
540     }
541 
542     now = g_get_real_time() / G_USEC_PER_SEC;
543     intv = g_time_zone_find_interval(tz, G_TIME_TYPE_UNIVERSAL, now);
544     info->offset = g_time_zone_get_offset(tz, intv);
545     name = g_time_zone_get_abbreviation(tz, intv);
546     if (name != NULL) {
547         info->zone = g_strdup(name);
548     }
549     g_time_zone_unref(tz);
550 
551     return info;
552 
553 error:
554     g_free(info);
555     return NULL;
556 }
557 
558 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
559                                    int64_t count, Error **errp)
560 {
561     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
562     GuestFileRead *read_data;
563 
564     if (!gfh) {
565         return NULL;
566     }
567     if (!has_count) {
568         count = QGA_READ_COUNT_DEFAULT;
569     } else if (count < 0 || count > GUEST_FILE_READ_COUNT_MAX) {
570         error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
571                    count);
572         return NULL;
573     }
574 
575     read_data = guest_file_read_unsafe(gfh, count, errp);
576     if (!read_data) {
577         slog("guest-file-write failed, handle: %" PRId64, handle);
578     }
579 
580     return read_data;
581 }
582 
583 int64_t qmp_guest_get_time(Error **errp)
584 {
585     return g_get_real_time() * 1000;
586 }
587