]> Git Repo - qemu.git/blob - qga/commands.c
qga: Extract qmp_guest_file_read() to common commands.c
[qemu.git] / qga / commands.c
1 /*
2  * QEMU Guest Agent common/cross-platform command implementations
3  *
4  * Copyright IBM Corp. 2012
5  *
6  * Authors:
7  *  Michael Roth      <[email protected]>
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 #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 /* Note: in some situations, like with the fsfreeze, logging may be
29  * temporarilly disabled. if it is necessary that a command be able
30  * to log for accounting purposes, check ga_logging_enabled() beforehand,
31  * and use the QERR_QGA_LOGGING_DISABLED to generate an error
32  */
33 void slog(const gchar *fmt, ...)
34 {
35     va_list ap;
36
37     va_start(ap, fmt);
38     g_logv("syslog", G_LOG_LEVEL_INFO, fmt, ap);
39     va_end(ap);
40 }
41
42 int64_t qmp_guest_sync_delimited(int64_t id, Error **errp)
43 {
44     ga_set_response_delimited(ga_state);
45     return id;
46 }
47
48 int64_t qmp_guest_sync(int64_t id, Error **errp)
49 {
50     return id;
51 }
52
53 void qmp_guest_ping(Error **errp)
54 {
55     slog("guest-ping called");
56 }
57
58 static void qmp_command_info(const QmpCommand *cmd, void *opaque)
59 {
60     GuestAgentInfo *info = opaque;
61     GuestAgentCommandInfo *cmd_info;
62     GuestAgentCommandInfoList *cmd_info_list;
63
64     cmd_info = g_new0(GuestAgentCommandInfo, 1);
65     cmd_info->name = g_strdup(qmp_command_name(cmd));
66     cmd_info->enabled = qmp_command_is_enabled(cmd);
67     cmd_info->success_response = qmp_has_success_response(cmd);
68
69     cmd_info_list = g_new0(GuestAgentCommandInfoList, 1);
70     cmd_info_list->value = cmd_info;
71     cmd_info_list->next = info->supported_commands;
72     info->supported_commands = cmd_info_list;
73 }
74
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
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
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
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
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, QERR_INVALID_PARAMETER, "pid");
157         return NULL;
158     }
159
160     ges = g_new0(GuestExecStatus, 1);
161
162     bool finished = atomic_mb_read(&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 = finished && atomic_mb_read(&gei->out.closed);
168         finished = finished && atomic_mb_read(&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->has_out_data = true;
209             ges->out_data = g_base64_encode(gei->out.data, gei->out.length);
210             g_free(gei->out.data);
211             ges->has_out_truncated = gei->out.truncated;
212         }
213
214         if (gei->err.length > 0) {
215             ges->has_err_data = true;
216             ges->err_data = g_base64_encode(gei->err.data, gei->err.length);
217             g_free(gei->err.data);
218             ges->has_err_truncated = gei->err.truncated;
219         }
220
221         QTAILQ_REMOVE(&guest_exec_state.processes, gei, next);
222         g_free(gei);
223     }
224
225     return ges;
226 }
227
228 /* Get environment variables or arguments array for execve(). */
229 static char **guest_exec_get_args(const strList *entry, bool log)
230 {
231     const strList *it;
232     int count = 1, i = 0;  /* reserve for NULL terminator */
233     char **args;
234     char *str; /* for logging array of arguments */
235     size_t str_size = 1;
236
237     for (it = entry; it != NULL; it = it->next) {
238         count++;
239         str_size += 1 + strlen(it->value);
240     }
241
242     str = g_malloc(str_size);
243     *str = 0;
244     args = g_malloc(count * sizeof(char *));
245     for (it = entry; it != NULL; it = it->next) {
246         args[i++] = it->value;
247         pstrcat(str, str_size, it->value);
248         if (it->next) {
249             pstrcat(str, str_size, " ");
250         }
251     }
252     args[i] = NULL;
253
254     if (log) {
255         slog("guest-exec called: \"%s\"", str);
256     }
257     g_free(str);
258
259     return args;
260 }
261
262 static void guest_exec_child_watch(GPid pid, gint status, gpointer data)
263 {
264     GuestExecInfo *gei = (GuestExecInfo *)data;
265
266     g_debug("guest_exec_child_watch called, pid: %d, status: %u",
267             (int32_t)gpid_to_int64(pid), (uint32_t)status);
268
269     gei->status = status;
270     atomic_mb_set(&gei->finished, true);
271
272     g_spawn_close_pid(pid);
273 }
274
275 /** Reset ignored signals back to default. */
276 static void guest_exec_task_setup(gpointer data)
277 {
278 #if !defined(G_OS_WIN32)
279     struct sigaction sigact;
280
281     memset(&sigact, 0, sizeof(struct sigaction));
282     sigact.sa_handler = SIG_DFL;
283
284     if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
285         slog("sigaction() failed to reset child process's SIGPIPE: %s",
286              strerror(errno));
287     }
288 #endif
289 }
290
291 static gboolean guest_exec_input_watch(GIOChannel *ch,
292         GIOCondition cond, gpointer p_)
293 {
294     GuestExecIOData *p = (GuestExecIOData *)p_;
295     gsize bytes_written = 0;
296     GIOStatus status;
297     GError *gerr = NULL;
298
299     /* nothing left to write */
300     if (p->size == p->length) {
301         goto done;
302     }
303
304     status = g_io_channel_write_chars(ch, (gchar *)p->data + p->length,
305             p->size - p->length, &bytes_written, &gerr);
306
307     /* can be not 0 even if not G_IO_STATUS_NORMAL */
308     if (bytes_written != 0) {
309         p->length += bytes_written;
310     }
311
312     /* continue write, our callback will be called again */
313     if (status == G_IO_STATUS_NORMAL || status == G_IO_STATUS_AGAIN) {
314         return true;
315     }
316
317     if (gerr) {
318         g_warning("qga: i/o error writing to input_data channel: %s",
319                 gerr->message);
320         g_error_free(gerr);
321     }
322
323 done:
324     g_io_channel_shutdown(ch, true, NULL);
325     g_io_channel_unref(ch);
326     atomic_mb_set(&p->closed, true);
327     g_free(p->data);
328
329     return false;
330 }
331
332 static gboolean guest_exec_output_watch(GIOChannel *ch,
333         GIOCondition cond, gpointer p_)
334 {
335     GuestExecIOData *p = (GuestExecIOData *)p_;
336     gsize bytes_read;
337     GIOStatus gstatus;
338
339     if (cond == G_IO_HUP || cond == G_IO_ERR) {
340         goto close;
341     }
342
343     if (p->size == p->length) {
344         gpointer t = NULL;
345         if (!p->truncated && p->size < GUEST_EXEC_MAX_OUTPUT) {
346             t = g_try_realloc(p->data, p->size + GUEST_EXEC_IO_SIZE);
347         }
348         if (t == NULL) {
349             /* ignore truncated output */
350             gchar buf[GUEST_EXEC_IO_SIZE];
351
352             p->truncated = true;
353             gstatus = g_io_channel_read_chars(ch, buf, sizeof(buf),
354                                               &bytes_read, NULL);
355             if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
356                 goto close;
357             }
358
359             return true;
360         }
361         p->size += GUEST_EXEC_IO_SIZE;
362         p->data = t;
363     }
364
365     /* Calling read API once.
366      * On next available data our callback will be called again */
367     gstatus = g_io_channel_read_chars(ch, (gchar *)p->data + p->length,
368             p->size - p->length, &bytes_read, NULL);
369     if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
370         goto close;
371     }
372
373     p->length += bytes_read;
374
375     return true;
376
377 close:
378     g_io_channel_shutdown(ch, true, NULL);
379     g_io_channel_unref(ch);
380     atomic_mb_set(&p->closed, true);
381     return false;
382 }
383
384 GuestExec *qmp_guest_exec(const char *path,
385                        bool has_arg, strList *arg,
386                        bool has_env, strList *env,
387                        bool has_input_data, const char *input_data,
388                        bool has_capture_output, bool capture_output,
389                        Error **errp)
390 {
391     GPid pid;
392     GuestExec *ge = NULL;
393     GuestExecInfo *gei;
394     char **argv, **envp;
395     strList arglist;
396     gboolean ret;
397     GError *gerr = NULL;
398     gint in_fd, out_fd, err_fd;
399     GIOChannel *in_ch, *out_ch, *err_ch;
400     GSpawnFlags flags;
401     bool has_output = (has_capture_output && capture_output);
402     uint8_t *input = NULL;
403     size_t ninput = 0;
404
405     arglist.value = (char *)path;
406     arglist.next = has_arg ? arg : NULL;
407
408     if (has_input_data) {
409         input = qbase64_decode(input_data, -1, &ninput, errp);
410         if (!input) {
411             return NULL;
412         }
413     }
414
415     argv = guest_exec_get_args(&arglist, true);
416     envp = has_env ? guest_exec_get_args(env, false) : NULL;
417
418     flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD |
419         G_SPAWN_SEARCH_PATH_FROM_ENVP;
420     if (!has_output) {
421         flags |= G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL;
422     }
423
424     ret = g_spawn_async_with_pipes(NULL, argv, envp, flags,
425             guest_exec_task_setup, NULL, &pid, has_input_data ? &in_fd : NULL,
426             has_output ? &out_fd : NULL, has_output ? &err_fd : NULL, &gerr);
427     if (!ret) {
428         error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
429         g_error_free(gerr);
430         goto done;
431     }
432
433     ge = g_new0(GuestExec, 1);
434     ge->pid = gpid_to_int64(pid);
435
436     gei = guest_exec_info_add(pid);
437     gei->has_output = has_output;
438     g_child_watch_add(pid, guest_exec_child_watch, gei);
439
440     if (has_input_data) {
441         gei->in.data = input;
442         gei->in.size = ninput;
443 #ifdef G_OS_WIN32
444         in_ch = g_io_channel_win32_new_fd(in_fd);
445 #else
446         in_ch = g_io_channel_unix_new(in_fd);
447 #endif
448         g_io_channel_set_encoding(in_ch, NULL, NULL);
449         g_io_channel_set_buffered(in_ch, false);
450         g_io_channel_set_flags(in_ch, G_IO_FLAG_NONBLOCK, NULL);
451         g_io_channel_set_close_on_unref(in_ch, true);
452         g_io_add_watch(in_ch, G_IO_OUT, guest_exec_input_watch, &gei->in);
453     }
454
455     if (has_output) {
456 #ifdef G_OS_WIN32
457         out_ch = g_io_channel_win32_new_fd(out_fd);
458         err_ch = g_io_channel_win32_new_fd(err_fd);
459 #else
460         out_ch = g_io_channel_unix_new(out_fd);
461         err_ch = g_io_channel_unix_new(err_fd);
462 #endif
463         g_io_channel_set_encoding(out_ch, NULL, NULL);
464         g_io_channel_set_encoding(err_ch, NULL, NULL);
465         g_io_channel_set_buffered(out_ch, false);
466         g_io_channel_set_buffered(err_ch, false);
467         g_io_channel_set_close_on_unref(out_ch, true);
468         g_io_channel_set_close_on_unref(err_ch, true);
469         g_io_add_watch(out_ch, G_IO_IN | G_IO_HUP,
470                 guest_exec_output_watch, &gei->out);
471         g_io_add_watch(err_ch, G_IO_IN | G_IO_HUP,
472                 guest_exec_output_watch, &gei->err);
473     }
474
475 done:
476     g_free(argv);
477     g_free(envp);
478
479     return ge;
480 }
481
482 /* Convert GuestFileWhence (either a raw integer or an enum value) into
483  * the guest's SEEK_ constants.  */
484 int ga_parse_whence(GuestFileWhence *whence, Error **errp)
485 {
486     /*
487      * Exploit the fact that we picked values to match QGA_SEEK_*;
488      * however, we have to use a temporary variable since the union
489      * members may have different size.
490      */
491     if (whence->type == QTYPE_QSTRING) {
492         int value = whence->u.name;
493         whence->type = QTYPE_QNUM;
494         whence->u.value = value;
495     }
496     switch (whence->u.value) {
497     case QGA_SEEK_SET:
498         return SEEK_SET;
499     case QGA_SEEK_CUR:
500         return SEEK_CUR;
501     case QGA_SEEK_END:
502         return SEEK_END;
503     }
504     error_setg(errp, "invalid whence code %"PRId64, whence->u.value);
505     return -1;
506 }
507
508 GuestHostName *qmp_guest_get_host_name(Error **errp)
509 {
510     GuestHostName *result = NULL;
511     gchar const *hostname = g_get_host_name();
512     if (hostname != NULL) {
513         result = g_new0(GuestHostName, 1);
514         result->host_name = g_strdup(hostname);
515     }
516     return result;
517 }
518
519 GuestTimezone *qmp_guest_get_timezone(Error **errp)
520 {
521     GuestTimezone *info = NULL;
522     GTimeZone *tz = NULL;
523     gint64 now = 0;
524     gint32 intv = 0;
525     gchar const *name = NULL;
526
527     info = g_new0(GuestTimezone, 1);
528     tz = g_time_zone_new_local();
529     if (tz == NULL) {
530         error_setg(errp, QERR_QGA_COMMAND_FAILED,
531                    "Couldn't retrieve local timezone");
532         goto error;
533     }
534
535     now = g_get_real_time() / G_USEC_PER_SEC;
536     intv = g_time_zone_find_interval(tz, G_TIME_TYPE_UNIVERSAL, now);
537     info->offset = g_time_zone_get_offset(tz, intv);
538     name = g_time_zone_get_abbreviation(tz, intv);
539     if (name != NULL) {
540         info->has_zone = true;
541         info->zone = g_strdup(name);
542     }
543     g_time_zone_unref(tz);
544
545     return info;
546
547 error:
548     g_free(info);
549     return NULL;
550 }
551
552 GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
553                                    int64_t count, Error **errp)
554 {
555     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
556     GuestFileRead *read_data;
557
558     if (!gfh) {
559         return NULL;
560     }
561     if (!has_count) {
562         count = QGA_READ_COUNT_DEFAULT;
563     } else if (count < 0 || count >= UINT32_MAX) {
564         error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
565                    count);
566         return NULL;
567     }
568
569     read_data = guest_file_read_unsafe(gfh, count, errp);
570     if (!read_data) {
571         slog("guest-file-write failed, handle: %" PRId64, handle);
572     }
573
574     return read_data;
575 }
This page took 0.055147 seconds and 4 git commands to generate.