xref: /qemu/qga/commands.c (revision 27a4a30e)
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 "guest-agent-core.h"
15 #include "qga-qapi-commands.h"
16 #include "qapi/error.h"
17 #include "qapi/qmp/qerror.h"
18 #include "qemu/base64.h"
19 #include "qemu/cutils.h"
20 #include "qemu/atomic.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 /* Note: in some situations, like with the fsfreeze, logging may be
28  * temporarilly disabled. if it is necessary that a command be able
29  * to log for accounting purposes, check ga_logging_enabled() beforehand,
30  * and use the QERR_QGA_LOGGING_DISABLED to generate an error
31  */
32 void slog(const gchar *fmt, ...)
33 {
34     va_list ap;
35 
36     va_start(ap, fmt);
37     g_logv("syslog", G_LOG_LEVEL_INFO, fmt, ap);
38     va_end(ap);
39 }
40 
41 int64_t qmp_guest_sync_delimited(int64_t id, Error **errp)
42 {
43     ga_set_response_delimited(ga_state);
44     return id;
45 }
46 
47 int64_t qmp_guest_sync(int64_t id, Error **errp)
48 {
49     return id;
50 }
51 
52 void qmp_guest_ping(Error **errp)
53 {
54     slog("guest-ping called");
55 }
56 
57 static void qmp_command_info(const QmpCommand *cmd, void *opaque)
58 {
59     GuestAgentInfo *info = opaque;
60     GuestAgentCommandInfo *cmd_info;
61     GuestAgentCommandInfoList *cmd_info_list;
62 
63     cmd_info = g_new0(GuestAgentCommandInfo, 1);
64     cmd_info->name = g_strdup(qmp_command_name(cmd));
65     cmd_info->enabled = qmp_command_is_enabled(cmd);
66     cmd_info->success_response = qmp_has_success_response(cmd);
67 
68     cmd_info_list = g_new0(GuestAgentCommandInfoList, 1);
69     cmd_info_list->value = cmd_info;
70     cmd_info_list->next = info->supported_commands;
71     info->supported_commands = cmd_info_list;
72 }
73 
74 struct GuestAgentInfo *qmp_guest_info(Error **errp)
75 {
76     GuestAgentInfo *info = g_new0(GuestAgentInfo, 1);
77 
78     info->version = g_strdup(QEMU_VERSION);
79     qmp_for_each_command(&ga_commands, qmp_command_info, info);
80     return info;
81 }
82 
83 struct GuestExecIOData {
84     guchar *data;
85     gsize size;
86     gsize length;
87     bool closed;
88     bool truncated;
89     const char *name;
90 };
91 typedef struct GuestExecIOData GuestExecIOData;
92 
93 struct GuestExecInfo {
94     GPid pid;
95     int64_t pid_numeric;
96     gint status;
97     bool has_output;
98     bool finished;
99     GuestExecIOData in;
100     GuestExecIOData out;
101     GuestExecIOData err;
102     QTAILQ_ENTRY(GuestExecInfo) next;
103 };
104 typedef struct GuestExecInfo GuestExecInfo;
105 
106 static struct {
107     QTAILQ_HEAD(, GuestExecInfo) processes;
108 } guest_exec_state = {
109     .processes = QTAILQ_HEAD_INITIALIZER(guest_exec_state.processes),
110 };
111 
112 static int64_t gpid_to_int64(GPid pid)
113 {
114 #ifdef G_OS_WIN32
115     return GetProcessId(pid);
116 #else
117     return (int64_t)pid;
118 #endif
119 }
120 
121 static GuestExecInfo *guest_exec_info_add(GPid pid)
122 {
123     GuestExecInfo *gei;
124 
125     gei = g_new0(GuestExecInfo, 1);
126     gei->pid = pid;
127     gei->pid_numeric = gpid_to_int64(pid);
128     QTAILQ_INSERT_TAIL(&guest_exec_state.processes, gei, next);
129 
130     return gei;
131 }
132 
133 static GuestExecInfo *guest_exec_info_find(int64_t pid_numeric)
134 {
135     GuestExecInfo *gei;
136 
137     QTAILQ_FOREACH(gei, &guest_exec_state.processes, next) {
138         if (gei->pid_numeric == pid_numeric) {
139             return gei;
140         }
141     }
142 
143     return NULL;
144 }
145 
146 GuestExecStatus *qmp_guest_exec_status(int64_t pid, Error **errp)
147 {
148     GuestExecInfo *gei;
149     GuestExecStatus *ges;
150 
151     slog("guest-exec-status called, pid: %u", (uint32_t)pid);
152 
153     gei = guest_exec_info_find(pid);
154     if (gei == NULL) {
155         error_setg(errp, QERR_INVALID_PARAMETER, "pid");
156         return NULL;
157     }
158 
159     ges = g_new0(GuestExecStatus, 1);
160 
161     bool finished = atomic_mb_read(&gei->finished);
162 
163     /* need to wait till output channels are closed
164      * to be sure we captured all output at this point */
165     if (gei->has_output) {
166         finished = finished && atomic_mb_read(&gei->out.closed);
167         finished = finished && atomic_mb_read(&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->has_out_data = true;
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->has_err_data = true;
215             ges->err_data = g_base64_encode(gei->err.data, gei->err.length);
216             g_free(gei->err.data);
217             ges->has_err_truncated = gei->err.truncated;
218         }
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(). */
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_malloc(count * sizeof(char *));
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 
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     atomic_mb_set(&gei->finished, true);
270 
271     g_spawn_close_pid(pid);
272 }
273 
274 /** Reset ignored signals back to default. */
275 static void guest_exec_task_setup(gpointer data)
276 {
277 #if !defined(G_OS_WIN32)
278     struct sigaction sigact;
279 
280     memset(&sigact, 0, sizeof(struct sigaction));
281     sigact.sa_handler = SIG_DFL;
282 
283     if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
284         slog("sigaction() failed to reset child process's SIGPIPE: %s",
285              strerror(errno));
286     }
287 #endif
288 }
289 
290 static gboolean guest_exec_input_watch(GIOChannel *ch,
291         GIOCondition cond, gpointer p_)
292 {
293     GuestExecIOData *p = (GuestExecIOData *)p_;
294     gsize bytes_written = 0;
295     GIOStatus status;
296     GError *gerr = NULL;
297 
298     /* nothing left to write */
299     if (p->size == p->length) {
300         goto done;
301     }
302 
303     status = g_io_channel_write_chars(ch, (gchar *)p->data + p->length,
304             p->size - p->length, &bytes_written, &gerr);
305 
306     /* can be not 0 even if not G_IO_STATUS_NORMAL */
307     if (bytes_written != 0) {
308         p->length += bytes_written;
309     }
310 
311     /* continue write, our callback will be called again */
312     if (status == G_IO_STATUS_NORMAL || status == G_IO_STATUS_AGAIN) {
313         return true;
314     }
315 
316     if (gerr) {
317         g_warning("qga: i/o error writing to input_data channel: %s",
318                 gerr->message);
319         g_error_free(gerr);
320     }
321 
322 done:
323     g_io_channel_shutdown(ch, true, NULL);
324     g_io_channel_unref(ch);
325     atomic_mb_set(&p->closed, true);
326     g_free(p->data);
327 
328     return false;
329 }
330 
331 static gboolean guest_exec_output_watch(GIOChannel *ch,
332         GIOCondition cond, gpointer p_)
333 {
334     GuestExecIOData *p = (GuestExecIOData *)p_;
335     gsize bytes_read;
336     GIOStatus gstatus;
337 
338     if (cond == G_IO_HUP || cond == G_IO_ERR) {
339         goto close;
340     }
341 
342     if (p->size == p->length) {
343         gpointer t = NULL;
344         if (!p->truncated && p->size < GUEST_EXEC_MAX_OUTPUT) {
345             t = g_try_realloc(p->data, p->size + GUEST_EXEC_IO_SIZE);
346         }
347         if (t == NULL) {
348             /* ignore truncated output */
349             gchar buf[GUEST_EXEC_IO_SIZE];
350 
351             p->truncated = true;
352             gstatus = g_io_channel_read_chars(ch, buf, sizeof(buf),
353                                               &bytes_read, NULL);
354             if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
355                 goto close;
356             }
357 
358             return true;
359         }
360         p->size += GUEST_EXEC_IO_SIZE;
361         p->data = t;
362     }
363 
364     /* Calling read API once.
365      * On next available data our callback will be called again */
366     gstatus = g_io_channel_read_chars(ch, (gchar *)p->data + p->length,
367             p->size - p->length, &bytes_read, NULL);
368     if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
369         goto close;
370     }
371 
372     p->length += bytes_read;
373 
374     return true;
375 
376 close:
377     g_io_channel_shutdown(ch, true, NULL);
378     g_io_channel_unref(ch);
379     atomic_mb_set(&p->closed, true);
380     return false;
381 }
382 
383 GuestExec *qmp_guest_exec(const char *path,
384                        bool has_arg, strList *arg,
385                        bool has_env, strList *env,
386                        bool has_input_data, const char *input_data,
387                        bool has_capture_output, bool capture_output,
388                        Error **errp)
389 {
390     GPid pid;
391     GuestExec *ge = NULL;
392     GuestExecInfo *gei;
393     char **argv, **envp;
394     strList arglist;
395     gboolean ret;
396     GError *gerr = NULL;
397     gint in_fd, out_fd, err_fd;
398     GIOChannel *in_ch, *out_ch, *err_ch;
399     GSpawnFlags flags;
400     bool has_output = (has_capture_output && capture_output);
401     uint8_t *input = NULL;
402     size_t ninput = 0;
403 
404     arglist.value = (char *)path;
405     arglist.next = has_arg ? arg : NULL;
406 
407     if (has_input_data) {
408         input = qbase64_decode(input_data, -1, &ninput, errp);
409         if (!input) {
410             return NULL;
411         }
412     }
413 
414     argv = guest_exec_get_args(&arglist, true);
415     envp = has_env ? guest_exec_get_args(env, false) : NULL;
416 
417     flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD |
418         G_SPAWN_SEARCH_PATH_FROM_ENVP;
419     if (!has_output) {
420         flags |= G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL;
421     }
422 
423     ret = g_spawn_async_with_pipes(NULL, argv, envp, flags,
424             guest_exec_task_setup, NULL, &pid, has_input_data ? &in_fd : NULL,
425             has_output ? &out_fd : NULL, has_output ? &err_fd : NULL, &gerr);
426     if (!ret) {
427         error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
428         g_error_free(gerr);
429         goto done;
430     }
431 
432     ge = g_new0(GuestExec, 1);
433     ge->pid = gpid_to_int64(pid);
434 
435     gei = guest_exec_info_add(pid);
436     gei->has_output = has_output;
437     g_child_watch_add(pid, guest_exec_child_watch, gei);
438 
439     if (has_input_data) {
440         gei->in.data = input;
441         gei->in.size = ninput;
442 #ifdef G_OS_WIN32
443         in_ch = g_io_channel_win32_new_fd(in_fd);
444 #else
445         in_ch = g_io_channel_unix_new(in_fd);
446 #endif
447         g_io_channel_set_encoding(in_ch, NULL, NULL);
448         g_io_channel_set_buffered(in_ch, false);
449         g_io_channel_set_flags(in_ch, G_IO_FLAG_NONBLOCK, NULL);
450         g_io_channel_set_close_on_unref(in_ch, true);
451         g_io_add_watch(in_ch, G_IO_OUT, guest_exec_input_watch, &gei->in);
452     }
453 
454     if (has_output) {
455 #ifdef G_OS_WIN32
456         out_ch = g_io_channel_win32_new_fd(out_fd);
457         err_ch = g_io_channel_win32_new_fd(err_fd);
458 #else
459         out_ch = g_io_channel_unix_new(out_fd);
460         err_ch = g_io_channel_unix_new(err_fd);
461 #endif
462         g_io_channel_set_encoding(out_ch, NULL, NULL);
463         g_io_channel_set_encoding(err_ch, NULL, NULL);
464         g_io_channel_set_buffered(out_ch, false);
465         g_io_channel_set_buffered(err_ch, false);
466         g_io_channel_set_close_on_unref(out_ch, true);
467         g_io_channel_set_close_on_unref(err_ch, true);
468         g_io_add_watch(out_ch, G_IO_IN | G_IO_HUP,
469                 guest_exec_output_watch, &gei->out);
470         g_io_add_watch(err_ch, G_IO_IN | G_IO_HUP,
471                 guest_exec_output_watch, &gei->err);
472     }
473 
474 done:
475     g_free(argv);
476     g_free(envp);
477 
478     return ge;
479 }
480 
481 /* Convert GuestFileWhence (either a raw integer or an enum value) into
482  * the guest's SEEK_ constants.  */
483 int ga_parse_whence(GuestFileWhence *whence, Error **errp)
484 {
485     /* Exploit the fact that we picked values to match QGA_SEEK_*. */
486     if (whence->type == QTYPE_QSTRING) {
487         whence->type = QTYPE_QNUM;
488         whence->u.value = whence->u.name;
489     }
490     switch (whence->u.value) {
491     case QGA_SEEK_SET:
492         return SEEK_SET;
493     case QGA_SEEK_CUR:
494         return SEEK_CUR;
495     case QGA_SEEK_END:
496         return SEEK_END;
497     }
498     error_setg(errp, "invalid whence code %"PRId64, whence->u.value);
499     return -1;
500 }
501 
502 GuestHostName *qmp_guest_get_host_name(Error **errp)
503 {
504     GuestHostName *result = NULL;
505     gchar const *hostname = g_get_host_name();
506     if (hostname != NULL) {
507         result = g_new0(GuestHostName, 1);
508         result->host_name = g_strdup(hostname);
509     }
510     return result;
511 }
512 
513 GuestTimezone *qmp_guest_get_timezone(Error **errp)
514 {
515     GuestTimezone *info = NULL;
516     GTimeZone *tz = NULL;
517     gint64 now = 0;
518     gint32 intv = 0;
519     gchar const *name = NULL;
520 
521     info = g_new0(GuestTimezone, 1);
522     tz = g_time_zone_new_local();
523     if (tz == NULL) {
524         error_setg(errp, QERR_QGA_COMMAND_FAILED,
525                    "Couldn't retrieve local timezone");
526         goto error;
527     }
528 
529     now = g_get_real_time() / G_USEC_PER_SEC;
530     intv = g_time_zone_find_interval(tz, G_TIME_TYPE_UNIVERSAL, now);
531     info->offset = g_time_zone_get_offset(tz, intv);
532     name = g_time_zone_get_abbreviation(tz, intv);
533     if (name != NULL) {
534         info->has_zone = true;
535         info->zone = g_strdup(name);
536     }
537     g_time_zone_unref(tz);
538 
539     return info;
540 
541 error:
542     g_free(info);
543     return NULL;
544 }
545