commands.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 "guest-agent-core.h"
  14. #include "qga-qapi-commands.h"
  15. #include "qapi/error.h"
  16. #include "qapi/qmp/qerror.h"
  17. #include "qemu/base64.h"
  18. #include "qemu/cutils.h"
  19. #include "qemu/atomic.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. /* Note: in some situations, like with the fsfreeze, logging may be
  25. * temporarilly disabled. if it is necessary that a command be able
  26. * to log for accounting purposes, check ga_logging_enabled() beforehand,
  27. * and use the QERR_QGA_LOGGING_DISABLED to generate an error
  28. */
  29. void slog(const gchar *fmt, ...)
  30. {
  31. va_list ap;
  32. va_start(ap, fmt);
  33. g_logv("syslog", G_LOG_LEVEL_INFO, fmt, ap);
  34. va_end(ap);
  35. }
  36. int64_t qmp_guest_sync_delimited(int64_t id, Error **errp)
  37. {
  38. ga_set_response_delimited(ga_state);
  39. return id;
  40. }
  41. int64_t qmp_guest_sync(int64_t id, Error **errp)
  42. {
  43. return id;
  44. }
  45. void qmp_guest_ping(Error **errp)
  46. {
  47. slog("guest-ping called");
  48. }
  49. static void qmp_command_info(QmpCommand *cmd, void *opaque)
  50. {
  51. GuestAgentInfo *info = opaque;
  52. GuestAgentCommandInfo *cmd_info;
  53. GuestAgentCommandInfoList *cmd_info_list;
  54. cmd_info = g_new0(GuestAgentCommandInfo, 1);
  55. cmd_info->name = g_strdup(qmp_command_name(cmd));
  56. cmd_info->enabled = qmp_command_is_enabled(cmd);
  57. cmd_info->success_response = qmp_has_success_response(cmd);
  58. cmd_info_list = g_new0(GuestAgentCommandInfoList, 1);
  59. cmd_info_list->value = cmd_info;
  60. cmd_info_list->next = info->supported_commands;
  61. info->supported_commands = cmd_info_list;
  62. }
  63. struct GuestAgentInfo *qmp_guest_info(Error **errp)
  64. {
  65. GuestAgentInfo *info = g_new0(GuestAgentInfo, 1);
  66. info->version = g_strdup(QEMU_VERSION);
  67. qmp_for_each_command(&ga_commands, qmp_command_info, info);
  68. return info;
  69. }
  70. struct GuestExecIOData {
  71. guchar *data;
  72. gsize size;
  73. gsize length;
  74. bool closed;
  75. bool truncated;
  76. const char *name;
  77. };
  78. typedef struct GuestExecIOData GuestExecIOData;
  79. struct GuestExecInfo {
  80. GPid pid;
  81. int64_t pid_numeric;
  82. gint status;
  83. bool has_output;
  84. bool finished;
  85. GuestExecIOData in;
  86. GuestExecIOData out;
  87. GuestExecIOData err;
  88. QTAILQ_ENTRY(GuestExecInfo) next;
  89. };
  90. typedef struct GuestExecInfo GuestExecInfo;
  91. static struct {
  92. QTAILQ_HEAD(, GuestExecInfo) processes;
  93. } guest_exec_state = {
  94. .processes = QTAILQ_HEAD_INITIALIZER(guest_exec_state.processes),
  95. };
  96. static int64_t gpid_to_int64(GPid pid)
  97. {
  98. #ifdef G_OS_WIN32
  99. return GetProcessId(pid);
  100. #else
  101. return (int64_t)pid;
  102. #endif
  103. }
  104. static GuestExecInfo *guest_exec_info_add(GPid pid)
  105. {
  106. GuestExecInfo *gei;
  107. gei = g_new0(GuestExecInfo, 1);
  108. gei->pid = pid;
  109. gei->pid_numeric = gpid_to_int64(pid);
  110. QTAILQ_INSERT_TAIL(&guest_exec_state.processes, gei, next);
  111. return gei;
  112. }
  113. static GuestExecInfo *guest_exec_info_find(int64_t pid_numeric)
  114. {
  115. GuestExecInfo *gei;
  116. QTAILQ_FOREACH(gei, &guest_exec_state.processes, next) {
  117. if (gei->pid_numeric == pid_numeric) {
  118. return gei;
  119. }
  120. }
  121. return NULL;
  122. }
  123. GuestExecStatus *qmp_guest_exec_status(int64_t pid, Error **err)
  124. {
  125. GuestExecInfo *gei;
  126. GuestExecStatus *ges;
  127. slog("guest-exec-status called, pid: %u", (uint32_t)pid);
  128. gei = guest_exec_info_find(pid);
  129. if (gei == NULL) {
  130. error_setg(err, QERR_INVALID_PARAMETER, "pid");
  131. return NULL;
  132. }
  133. ges = g_new0(GuestExecStatus, 1);
  134. bool finished = atomic_mb_read(&gei->finished);
  135. /* need to wait till output channels are closed
  136. * to be sure we captured all output at this point */
  137. if (gei->has_output) {
  138. finished = finished && atomic_mb_read(&gei->out.closed);
  139. finished = finished && atomic_mb_read(&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->has_out_data = true;
  179. ges->out_data = g_base64_encode(gei->out.data, gei->out.length);
  180. g_free(gei->out.data);
  181. ges->has_out_truncated = gei->out.truncated;
  182. }
  183. if (gei->err.length > 0) {
  184. ges->has_err_data = true;
  185. ges->err_data = g_base64_encode(gei->err.data, gei->err.length);
  186. g_free(gei->err.data);
  187. ges->has_err_truncated = gei->err.truncated;
  188. }
  189. QTAILQ_REMOVE(&guest_exec_state.processes, gei, next);
  190. g_free(gei);
  191. }
  192. return ges;
  193. }
  194. /* Get environment variables or arguments array for execve(). */
  195. static char **guest_exec_get_args(const strList *entry, bool log)
  196. {
  197. const strList *it;
  198. int count = 1, i = 0; /* reserve for NULL terminator */
  199. char **args;
  200. char *str; /* for logging array of arguments */
  201. size_t str_size = 1;
  202. for (it = entry; it != NULL; it = it->next) {
  203. count++;
  204. str_size += 1 + strlen(it->value);
  205. }
  206. str = g_malloc(str_size);
  207. *str = 0;
  208. args = g_malloc(count * sizeof(char *));
  209. for (it = entry; it != NULL; it = it->next) {
  210. args[i++] = it->value;
  211. pstrcat(str, str_size, it->value);
  212. if (it->next) {
  213. pstrcat(str, str_size, " ");
  214. }
  215. }
  216. args[i] = NULL;
  217. if (log) {
  218. slog("guest-exec called: \"%s\"", str);
  219. }
  220. g_free(str);
  221. return args;
  222. }
  223. static void guest_exec_child_watch(GPid pid, gint status, gpointer data)
  224. {
  225. GuestExecInfo *gei = (GuestExecInfo *)data;
  226. g_debug("guest_exec_child_watch called, pid: %d, status: %u",
  227. (int32_t)gpid_to_int64(pid), (uint32_t)status);
  228. gei->status = status;
  229. atomic_mb_set(&gei->finished, true);
  230. g_spawn_close_pid(pid);
  231. }
  232. /** Reset ignored signals back to default. */
  233. static void guest_exec_task_setup(gpointer data)
  234. {
  235. #if !defined(G_OS_WIN32)
  236. struct sigaction sigact;
  237. memset(&sigact, 0, sizeof(struct sigaction));
  238. sigact.sa_handler = SIG_DFL;
  239. if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
  240. slog("sigaction() failed to reset child process's SIGPIPE: %s",
  241. strerror(errno));
  242. }
  243. #endif
  244. }
  245. static gboolean guest_exec_input_watch(GIOChannel *ch,
  246. GIOCondition cond, gpointer p_)
  247. {
  248. GuestExecIOData *p = (GuestExecIOData *)p_;
  249. gsize bytes_written = 0;
  250. GIOStatus status;
  251. GError *gerr = NULL;
  252. /* nothing left to write */
  253. if (p->size == p->length) {
  254. goto done;
  255. }
  256. status = g_io_channel_write_chars(ch, (gchar *)p->data + p->length,
  257. p->size - p->length, &bytes_written, &gerr);
  258. /* can be not 0 even if not G_IO_STATUS_NORMAL */
  259. if (bytes_written != 0) {
  260. p->length += bytes_written;
  261. }
  262. /* continue write, our callback will be called again */
  263. if (status == G_IO_STATUS_NORMAL || status == G_IO_STATUS_AGAIN) {
  264. return true;
  265. }
  266. if (gerr) {
  267. g_warning("qga: i/o error writing to input_data channel: %s",
  268. gerr->message);
  269. g_error_free(gerr);
  270. }
  271. done:
  272. g_io_channel_shutdown(ch, true, NULL);
  273. g_io_channel_unref(ch);
  274. atomic_mb_set(&p->closed, true);
  275. g_free(p->data);
  276. return false;
  277. }
  278. static gboolean guest_exec_output_watch(GIOChannel *ch,
  279. GIOCondition cond, gpointer p_)
  280. {
  281. GuestExecIOData *p = (GuestExecIOData *)p_;
  282. gsize bytes_read;
  283. GIOStatus gstatus;
  284. if (cond == G_IO_HUP || cond == G_IO_ERR) {
  285. goto close;
  286. }
  287. if (p->size == p->length) {
  288. gpointer t = NULL;
  289. if (!p->truncated && p->size < GUEST_EXEC_MAX_OUTPUT) {
  290. t = g_try_realloc(p->data, p->size + GUEST_EXEC_IO_SIZE);
  291. }
  292. if (t == NULL) {
  293. /* ignore truncated output */
  294. gchar buf[GUEST_EXEC_IO_SIZE];
  295. p->truncated = true;
  296. gstatus = g_io_channel_read_chars(ch, buf, sizeof(buf),
  297. &bytes_read, NULL);
  298. if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
  299. goto close;
  300. }
  301. return true;
  302. }
  303. p->size += GUEST_EXEC_IO_SIZE;
  304. p->data = t;
  305. }
  306. /* Calling read API once.
  307. * On next available data our callback will be called again */
  308. gstatus = g_io_channel_read_chars(ch, (gchar *)p->data + p->length,
  309. p->size - p->length, &bytes_read, NULL);
  310. if (gstatus == G_IO_STATUS_EOF || gstatus == G_IO_STATUS_ERROR) {
  311. goto close;
  312. }
  313. p->length += bytes_read;
  314. return true;
  315. close:
  316. g_io_channel_shutdown(ch, true, NULL);
  317. g_io_channel_unref(ch);
  318. atomic_mb_set(&p->closed, true);
  319. return false;
  320. }
  321. GuestExec *qmp_guest_exec(const char *path,
  322. bool has_arg, strList *arg,
  323. bool has_env, strList *env,
  324. bool has_input_data, const char *input_data,
  325. bool has_capture_output, bool capture_output,
  326. Error **err)
  327. {
  328. GPid pid;
  329. GuestExec *ge = NULL;
  330. GuestExecInfo *gei;
  331. char **argv, **envp;
  332. strList arglist;
  333. gboolean ret;
  334. GError *gerr = NULL;
  335. gint in_fd, out_fd, err_fd;
  336. GIOChannel *in_ch, *out_ch, *err_ch;
  337. GSpawnFlags flags;
  338. bool has_output = (has_capture_output && capture_output);
  339. uint8_t *input = NULL;
  340. size_t ninput = 0;
  341. arglist.value = (char *)path;
  342. arglist.next = has_arg ? arg : NULL;
  343. if (has_input_data) {
  344. input = qbase64_decode(input_data, -1, &ninput, err);
  345. if (!input) {
  346. return NULL;
  347. }
  348. }
  349. argv = guest_exec_get_args(&arglist, true);
  350. envp = has_env ? guest_exec_get_args(env, false) : NULL;
  351. flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD;
  352. #if GLIB_CHECK_VERSION(2, 33, 2)
  353. flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
  354. #endif
  355. if (!has_output) {
  356. flags |= G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL;
  357. }
  358. ret = g_spawn_async_with_pipes(NULL, argv, envp, flags,
  359. guest_exec_task_setup, NULL, &pid, has_input_data ? &in_fd : NULL,
  360. has_output ? &out_fd : NULL, has_output ? &err_fd : NULL, &gerr);
  361. if (!ret) {
  362. error_setg(err, QERR_QGA_COMMAND_FAILED, gerr->message);
  363. g_error_free(gerr);
  364. goto done;
  365. }
  366. ge = g_new0(GuestExec, 1);
  367. ge->pid = gpid_to_int64(pid);
  368. gei = guest_exec_info_add(pid);
  369. gei->has_output = has_output;
  370. g_child_watch_add(pid, guest_exec_child_watch, gei);
  371. if (has_input_data) {
  372. gei->in.data = input;
  373. gei->in.size = ninput;
  374. #ifdef G_OS_WIN32
  375. in_ch = g_io_channel_win32_new_fd(in_fd);
  376. #else
  377. in_ch = g_io_channel_unix_new(in_fd);
  378. #endif
  379. g_io_channel_set_encoding(in_ch, NULL, NULL);
  380. g_io_channel_set_buffered(in_ch, false);
  381. g_io_channel_set_flags(in_ch, G_IO_FLAG_NONBLOCK, NULL);
  382. g_io_channel_set_close_on_unref(in_ch, true);
  383. g_io_add_watch(in_ch, G_IO_OUT, guest_exec_input_watch, &gei->in);
  384. }
  385. if (has_output) {
  386. #ifdef G_OS_WIN32
  387. out_ch = g_io_channel_win32_new_fd(out_fd);
  388. err_ch = g_io_channel_win32_new_fd(err_fd);
  389. #else
  390. out_ch = g_io_channel_unix_new(out_fd);
  391. err_ch = g_io_channel_unix_new(err_fd);
  392. #endif
  393. g_io_channel_set_encoding(out_ch, NULL, NULL);
  394. g_io_channel_set_encoding(err_ch, NULL, NULL);
  395. g_io_channel_set_buffered(out_ch, false);
  396. g_io_channel_set_buffered(err_ch, false);
  397. g_io_channel_set_close_on_unref(out_ch, true);
  398. g_io_channel_set_close_on_unref(err_ch, true);
  399. g_io_add_watch(out_ch, G_IO_IN | G_IO_HUP,
  400. guest_exec_output_watch, &gei->out);
  401. g_io_add_watch(err_ch, G_IO_IN | G_IO_HUP,
  402. guest_exec_output_watch, &gei->err);
  403. }
  404. done:
  405. g_free(argv);
  406. g_free(envp);
  407. return ge;
  408. }
  409. /* Convert GuestFileWhence (either a raw integer or an enum value) into
  410. * the guest's SEEK_ constants. */
  411. int ga_parse_whence(GuestFileWhence *whence, Error **errp)
  412. {
  413. /* Exploit the fact that we picked values to match QGA_SEEK_*. */
  414. if (whence->type == QTYPE_QSTRING) {
  415. whence->type = QTYPE_QNUM;
  416. whence->u.value = whence->u.name;
  417. }
  418. switch (whence->u.value) {
  419. case QGA_SEEK_SET:
  420. return SEEK_SET;
  421. case QGA_SEEK_CUR:
  422. return SEEK_CUR;
  423. case QGA_SEEK_END:
  424. return SEEK_END;
  425. }
  426. error_setg(errp, "invalid whence code %"PRId64, whence->u.value);
  427. return -1;
  428. }
  429. GuestHostName *qmp_guest_get_host_name(Error **err)
  430. {
  431. GuestHostName *result = NULL;
  432. gchar const *hostname = g_get_host_name();
  433. if (hostname != NULL) {
  434. result = g_new0(GuestHostName, 1);
  435. result->host_name = g_strdup(hostname);
  436. }
  437. return result;
  438. }
  439. GuestTimezone *qmp_guest_get_timezone(Error **errp)
  440. {
  441. #if GLIB_CHECK_VERSION(2, 28, 0)
  442. GuestTimezone *info = NULL;
  443. GTimeZone *tz = NULL;
  444. gint64 now = 0;
  445. gint32 intv = 0;
  446. gchar const *name = NULL;
  447. info = g_new0(GuestTimezone, 1);
  448. tz = g_time_zone_new_local();
  449. if (tz == NULL) {
  450. error_setg(errp, QERR_QGA_COMMAND_FAILED,
  451. "Couldn't retrieve local timezone");
  452. goto error;
  453. }
  454. now = g_get_real_time() / G_USEC_PER_SEC;
  455. intv = g_time_zone_find_interval(tz, G_TIME_TYPE_UNIVERSAL, now);
  456. info->offset = g_time_zone_get_offset(tz, intv);
  457. name = g_time_zone_get_abbreviation(tz, intv);
  458. if (name != NULL) {
  459. info->has_zone = true;
  460. info->zone = g_strdup(name);
  461. }
  462. g_time_zone_unref(tz);
  463. return info;
  464. error:
  465. g_free(info);
  466. return NULL;
  467. #else
  468. error_setg(errp, QERR_UNSUPPORTED);
  469. return NULL;
  470. #endif
  471. }