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