2 * QEMU Guest Agent common/cross-platform command implementations
4 * Copyright IBM Corp. 2012
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
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.
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"
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)
28 * Maximum file size to read - 48MB
30 * (48MB + Base64 3:4 overhead = JSON parser 64 MB limit)
32 #define GUEST_FILE_READ_COUNT_MAX (48 * MiB)
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.
38 void slog(const gchar
*fmt
, ...)
43 g_logv("syslog", G_LOG_LEVEL_INFO
, fmt
, ap
);
47 int64_t qmp_guest_sync_delimited(int64_t id
, Error
**errp
)
49 ga_set_response_delimited(ga_state
);
53 int64_t qmp_guest_sync(int64_t id
, Error
**errp
)
58 void qmp_guest_ping(Error
**errp
)
60 slog("guest-ping called");
63 static void qmp_command_info(const QmpCommand
*cmd
, void *opaque
)
65 GuestAgentInfo
*info
= opaque
;
66 GuestAgentCommandInfo
*cmd_info
;
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
);
73 QAPI_LIST_PREPEND(info
->supported_commands
, cmd_info
);
76 struct GuestAgentInfo
*qmp_guest_info(Error
**errp
)
78 GuestAgentInfo
*info
= g_new0(GuestAgentInfo
, 1);
80 info
->version
= g_strdup(QEMU_VERSION
);
81 qmp_for_each_command(&ga_commands
, qmp_command_info
, info
);
85 struct GuestExecIOData
{
93 typedef struct GuestExecIOData GuestExecIOData
;
95 struct GuestExecInfo
{
104 QTAILQ_ENTRY(GuestExecInfo
) next
;
106 typedef struct GuestExecInfo GuestExecInfo
;
109 QTAILQ_HEAD(, GuestExecInfo
) processes
;
110 } guest_exec_state
= {
111 .processes
= QTAILQ_HEAD_INITIALIZER(guest_exec_state
.processes
),
114 static int64_t gpid_to_int64(GPid pid
)
117 return GetProcessId(pid
);
123 static GuestExecInfo
*guest_exec_info_add(GPid pid
)
127 gei
= g_new0(GuestExecInfo
, 1);
129 gei
->pid_numeric
= gpid_to_int64(pid
);
130 QTAILQ_INSERT_TAIL(&guest_exec_state
.processes
, gei
, next
);
135 static GuestExecInfo
*guest_exec_info_find(int64_t pid_numeric
)
139 QTAILQ_FOREACH(gei
, &guest_exec_state
.processes
, next
) {
140 if (gei
->pid_numeric
== pid_numeric
) {
148 GuestExecStatus
*qmp_guest_exec_status(int64_t pid
, Error
**errp
)
151 GuestExecStatus
*ges
;
153 slog("guest-exec-status called, pid: %u", (uint32_t)pid
);
155 gei
= guest_exec_info_find(pid
);
157 error_setg(errp
, "PID " PRId64
" does not exist");
161 ges
= g_new0(GuestExecStatus
, 1);
163 bool finished
= gei
->finished
;
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
;
171 ges
->exited
= finished
;
173 /* Glib has no portable way to parse exit status.
174 * On UNIX, we can get either exit code from normal termination
176 * On Windows, it is either the same exit code or the exception
177 * value for an unhandled exception that caused the process
179 * See MSDN for GetExitCodeProcess() and ntstatus.h for possible
180 * well-known codes, e.g. C0000005 ACCESS_DENIED - analog of SIGSEGV
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
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
;
195 ges
->has_signal
= true;
196 ges
->signal
= gei
->status
;
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
);
207 if (gei
->out
.length
> 0) {
208 ges
->out_data
= g_base64_encode(gei
->out
.data
, gei
->out
.length
);
209 ges
->has_out_truncated
= gei
->out
.truncated
;
211 g_free(gei
->out
.data
);
213 if (gei
->err
.length
> 0) {
214 ges
->err_data
= g_base64_encode(gei
->err
.data
, gei
->err
.length
);
215 ges
->has_err_truncated
= gei
->err
.truncated
;
217 g_free(gei
->err
.data
);
219 QTAILQ_REMOVE(&guest_exec_state
.processes
, gei
, next
);
226 /* Get environment variables or arguments array for execve(). */
227 static char **guest_exec_get_args(const strList
*entry
, bool log
)
230 int count
= 1, i
= 0; /* reserve for NULL terminator */
232 char *str
; /* for logging array of arguments */
235 for (it
= entry
; it
!= NULL
; it
= it
->next
) {
237 str_size
+= 1 + strlen(it
->value
);
240 str
= g_malloc(str_size
);
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
);
247 pstrcat(str
, str_size
, " ");
253 slog("guest-exec called: \"%s\"", str
);
260 static void guest_exec_child_watch(GPid pid
, gint status
, gpointer data
)
262 GuestExecInfo
*gei
= (GuestExecInfo
*)data
;
264 g_debug("guest_exec_child_watch called, pid: %d, status: %u",
265 (int32_t)gpid_to_int64(pid
), (uint32_t)status
);
267 gei
->status
= status
;
268 gei
->finished
= true;
270 g_spawn_close_pid(pid
);
273 static void guest_exec_task_setup(gpointer data
)
275 #if !defined(G_OS_WIN32)
276 bool has_merge
= *(bool *)data
;
277 struct sigaction sigact
;
281 * FIXME: When `GLIB_VERSION_MIN_REQUIRED` is bumped to 2.58+, use
282 * g_spawn_async_with_fds() to be portable on windows. The current
283 * logic does not work on windows b/c `GSpawnChildSetupFunc` is run
284 * inside the parent, not the child.
286 if (dup2(STDOUT_FILENO
, STDERR_FILENO
) != 0) {
287 slog("dup2() failed to merge stderr into stdout: %s",
292 /* Reset ignored signals back to default. */
293 memset(&sigact
, 0, sizeof(struct sigaction
));
294 sigact
.sa_handler
= SIG_DFL
;
296 if (sigaction(SIGPIPE
, &sigact
, NULL
) != 0) {
297 slog("sigaction() failed to reset child process's SIGPIPE: %s",
303 static gboolean
guest_exec_input_watch(GIOChannel
*ch
,
304 GIOCondition cond
, gpointer p_
)
306 GuestExecIOData
*p
= (GuestExecIOData
*)p_
;
307 gsize bytes_written
= 0;
311 /* nothing left to write */
312 if (p
->size
== p
->length
) {
316 status
= g_io_channel_write_chars(ch
, (gchar
*)p
->data
+ p
->length
,
317 p
->size
- p
->length
, &bytes_written
, &gerr
);
319 /* can be not 0 even if not G_IO_STATUS_NORMAL */
320 if (bytes_written
!= 0) {
321 p
->length
+= bytes_written
;
324 /* continue write, our callback will be called again */
325 if (status
== G_IO_STATUS_NORMAL
|| status
== G_IO_STATUS_AGAIN
) {
330 g_warning("qga: i/o error writing to input_data channel: %s",
336 g_io_channel_shutdown(ch
, true, NULL
);
337 g_io_channel_unref(ch
);
344 static gboolean
guest_exec_output_watch(GIOChannel
*ch
,
345 GIOCondition cond
, gpointer p_
)
347 GuestExecIOData
*p
= (GuestExecIOData
*)p_
;
351 if (cond
== G_IO_HUP
|| cond
== G_IO_ERR
) {
355 if (p
->size
== p
->length
) {
357 if (!p
->truncated
&& p
->size
< GUEST_EXEC_MAX_OUTPUT
) {
358 t
= g_try_realloc(p
->data
, p
->size
+ GUEST_EXEC_IO_SIZE
);
361 /* ignore truncated output */
362 gchar buf
[GUEST_EXEC_IO_SIZE
];
365 gstatus
= g_io_channel_read_chars(ch
, buf
, sizeof(buf
),
367 if (gstatus
== G_IO_STATUS_EOF
|| gstatus
== G_IO_STATUS_ERROR
) {
373 p
->size
+= GUEST_EXEC_IO_SIZE
;
377 /* Calling read API once.
378 * On next available data our callback will be called again */
379 gstatus
= g_io_channel_read_chars(ch
, (gchar
*)p
->data
+ p
->length
,
380 p
->size
- p
->length
, &bytes_read
, NULL
);
381 if (gstatus
== G_IO_STATUS_EOF
|| gstatus
== G_IO_STATUS_ERROR
) {
385 p
->length
+= bytes_read
;
390 g_io_channel_shutdown(ch
, true, NULL
);
391 g_io_channel_unref(ch
);
396 static GuestExecCaptureOutputMode
ga_parse_capture_output(
397 GuestExecCaptureOutput
*capture_output
)
400 return GUEST_EXEC_CAPTURE_OUTPUT_MODE_NONE
;
401 else if (capture_output
->type
== QTYPE_QBOOL
)
402 return capture_output
->u
.flag
? GUEST_EXEC_CAPTURE_OUTPUT_MODE_SEPARATED
403 : GUEST_EXEC_CAPTURE_OUTPUT_MODE_NONE
;
405 return capture_output
->u
.mode
;
408 GuestExec
*qmp_guest_exec(const char *path
,
409 bool has_arg
, strList
*arg
,
410 bool has_env
, strList
*env
,
411 const char *input_data
,
412 GuestExecCaptureOutput
*capture_output
,
416 GuestExec
*ge
= NULL
;
422 gint in_fd
, out_fd
, err_fd
;
423 GIOChannel
*in_ch
, *out_ch
, *err_ch
;
425 bool has_output
= false;
426 bool has_merge
= false;
427 GuestExecCaptureOutputMode output_mode
;
428 g_autofree
uint8_t *input
= NULL
;
431 arglist
.value
= (char *)path
;
432 arglist
.next
= has_arg
? arg
: NULL
;
435 input
= qbase64_decode(input_data
, -1, &ninput
, errp
);
441 argv
= guest_exec_get_args(&arglist
, true);
442 envp
= has_env
? guest_exec_get_args(env
, false) : NULL
;
444 flags
= G_SPAWN_SEARCH_PATH
| G_SPAWN_DO_NOT_REAP_CHILD
|
445 G_SPAWN_SEARCH_PATH_FROM_ENVP
;
447 output_mode
= ga_parse_capture_output(capture_output
);
448 switch (output_mode
) {
449 case GUEST_EXEC_CAPTURE_OUTPUT_MODE_NONE
:
450 flags
|= G_SPAWN_STDOUT_TO_DEV_NULL
| G_SPAWN_STDERR_TO_DEV_NULL
;
452 case GUEST_EXEC_CAPTURE_OUTPUT_MODE_STDOUT
:
454 flags
|= G_SPAWN_STDERR_TO_DEV_NULL
;
456 case GUEST_EXEC_CAPTURE_OUTPUT_MODE_STDERR
:
458 flags
|= G_SPAWN_STDOUT_TO_DEV_NULL
;
460 case GUEST_EXEC_CAPTURE_OUTPUT_MODE_SEPARATED
:
463 #if !defined(G_OS_WIN32)
464 case GUEST_EXEC_CAPTURE_OUTPUT_MODE_MERGED
:
469 case GUEST_EXEC_CAPTURE_OUTPUT_MODE__MAX
:
470 /* Silence warning; impossible branch */
474 ret
= g_spawn_async_with_pipes(NULL
, argv
, envp
, flags
,
475 guest_exec_task_setup
, &has_merge
, &pid
, input_data
? &in_fd
: NULL
,
476 has_output
? &out_fd
: NULL
, has_output
? &err_fd
: NULL
, &gerr
);
478 error_setg(errp
, QERR_QGA_COMMAND_FAILED
, gerr
->message
);
483 ge
= g_new0(GuestExec
, 1);
484 ge
->pid
= gpid_to_int64(pid
);
486 gei
= guest_exec_info_add(pid
);
487 gei
->has_output
= has_output
;
488 g_child_watch_add(pid
, guest_exec_child_watch
, gei
);
491 gei
->in
.data
= g_steal_pointer(&input
);
492 gei
->in
.size
= ninput
;
494 in_ch
= g_io_channel_win32_new_fd(in_fd
);
496 in_ch
= g_io_channel_unix_new(in_fd
);
498 g_io_channel_set_encoding(in_ch
, NULL
, NULL
);
499 g_io_channel_set_buffered(in_ch
, false);
500 g_io_channel_set_flags(in_ch
, G_IO_FLAG_NONBLOCK
, NULL
);
501 g_io_channel_set_close_on_unref(in_ch
, true);
502 g_io_add_watch(in_ch
, G_IO_OUT
, guest_exec_input_watch
, &gei
->in
);
507 out_ch
= g_io_channel_win32_new_fd(out_fd
);
508 err_ch
= g_io_channel_win32_new_fd(err_fd
);
510 out_ch
= g_io_channel_unix_new(out_fd
);
511 err_ch
= g_io_channel_unix_new(err_fd
);
513 g_io_channel_set_encoding(out_ch
, NULL
, NULL
);
514 g_io_channel_set_encoding(err_ch
, NULL
, NULL
);
515 g_io_channel_set_buffered(out_ch
, false);
516 g_io_channel_set_buffered(err_ch
, false);
517 g_io_channel_set_close_on_unref(out_ch
, true);
518 g_io_channel_set_close_on_unref(err_ch
, true);
519 g_io_add_watch(out_ch
, G_IO_IN
| G_IO_HUP
,
520 guest_exec_output_watch
, &gei
->out
);
521 g_io_add_watch(err_ch
, G_IO_IN
| G_IO_HUP
,
522 guest_exec_output_watch
, &gei
->err
);
532 /* Convert GuestFileWhence (either a raw integer or an enum value) into
533 * the guest's SEEK_ constants. */
534 int ga_parse_whence(GuestFileWhence
*whence
, Error
**errp
)
537 * Exploit the fact that we picked values to match QGA_SEEK_*;
538 * however, we have to use a temporary variable since the union
539 * members may have different size.
541 if (whence
->type
== QTYPE_QSTRING
) {
542 int value
= whence
->u
.name
;
543 whence
->type
= QTYPE_QNUM
;
544 whence
->u
.value
= value
;
546 switch (whence
->u
.value
) {
554 error_setg(errp
, "invalid whence code %"PRId64
, whence
->u
.value
);
558 GuestHostName
*qmp_guest_get_host_name(Error
**errp
)
560 GuestHostName
*result
= NULL
;
561 g_autofree
char *hostname
= qga_get_host_name(errp
);
564 * We want to avoid using g_get_host_name() because that
565 * caches the result and we wouldn't reflect changes in the
570 hostname
= g_strdup("localhost");
573 result
= g_new0(GuestHostName
, 1);
574 result
->host_name
= g_steal_pointer(&hostname
);
578 GuestTimezone
*qmp_guest_get_timezone(Error
**errp
)
580 GuestTimezone
*info
= NULL
;
581 GTimeZone
*tz
= NULL
;
584 gchar
const *name
= NULL
;
586 info
= g_new0(GuestTimezone
, 1);
587 tz
= g_time_zone_new_local();
589 error_setg(errp
, QERR_QGA_COMMAND_FAILED
,
590 "Couldn't retrieve local timezone");
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
);
599 info
->zone
= g_strdup(name
);
601 g_time_zone_unref(tz
);
610 GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
611 int64_t count
, Error
**errp
)
613 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
614 GuestFileRead
*read_data
;
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",
627 read_data
= guest_file_read_unsafe(gfh
, count
, errp
);
629 slog("guest-file-write failed, handle: %" PRId64
, handle
);
635 int64_t qmp_guest_get_time(Error
**errp
)
637 return g_get_real_time() * 1000;