commands.c 18 KB

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