qemu-ga.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. /*
  2. * QEMU Guest Agent
  3. *
  4. * Copyright IBM Corp. 2011
  5. *
  6. * Authors:
  7. * Adam Litke <aglitke@linux.vnet.ibm.com>
  8. * Michael Roth <mdroth@linux.vnet.ibm.com>
  9. *
  10. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  11. * See the COPYING file in the top-level directory.
  12. */
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #include <stdbool.h>
  16. #include <glib.h>
  17. #include <getopt.h>
  18. #include <termios.h>
  19. #include <syslog.h>
  20. #include "qemu_socket.h"
  21. #include "json-streamer.h"
  22. #include "json-parser.h"
  23. #include "qint.h"
  24. #include "qjson.h"
  25. #include "qga/guest-agent-core.h"
  26. #include "module.h"
  27. #include "signal.h"
  28. #include "qerror.h"
  29. #include "error_int.h"
  30. #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
  31. #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
  32. #define QGA_BAUDRATE_DEFAULT B38400 /* for isa-serial channels */
  33. #define QGA_TIMEOUT_DEFAULT 30*1000 /* ms */
  34. struct GAState {
  35. JSONMessageParser parser;
  36. GMainLoop *main_loop;
  37. GIOChannel *conn_channel;
  38. GIOChannel *listen_channel;
  39. const char *path;
  40. const char *method;
  41. bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
  42. GACommandState *command_state;
  43. GLogLevelFlags log_level;
  44. FILE *log_file;
  45. bool logging_enabled;
  46. };
  47. static struct GAState *ga_state;
  48. static void quit_handler(int sig)
  49. {
  50. g_debug("recieved signal num %d, quitting", sig);
  51. if (g_main_loop_is_running(ga_state->main_loop)) {
  52. g_main_loop_quit(ga_state->main_loop);
  53. }
  54. }
  55. static void register_signal_handlers(void)
  56. {
  57. struct sigaction sigact;
  58. int ret;
  59. memset(&sigact, 0, sizeof(struct sigaction));
  60. sigact.sa_handler = quit_handler;
  61. ret = sigaction(SIGINT, &sigact, NULL);
  62. if (ret == -1) {
  63. g_error("error configuring signal handler: %s", strerror(errno));
  64. exit(EXIT_FAILURE);
  65. }
  66. ret = sigaction(SIGTERM, &sigact, NULL);
  67. if (ret == -1) {
  68. g_error("error configuring signal handler: %s", strerror(errno));
  69. }
  70. }
  71. static void usage(const char *cmd)
  72. {
  73. printf(
  74. "Usage: %s -c <channel_opts>\n"
  75. "QEMU Guest Agent %s\n"
  76. "\n"
  77. " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
  78. " isa-serial (virtio-serial is the default)\n"
  79. " -p, --path device/socket path (%s is the default for virtio-serial)\n"
  80. " -l, --logfile set logfile path, logs to stderr by default\n"
  81. " -f, --pidfile specify pidfile (default is %s)\n"
  82. " -v, --verbose log extra debugging information\n"
  83. " -V, --version print version information and exit\n"
  84. " -d, --daemonize become a daemon\n"
  85. " -h, --help display this help and exit\n"
  86. "\n"
  87. "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
  88. , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
  89. }
  90. static void conn_channel_close(GAState *s);
  91. static const char *ga_log_level_str(GLogLevelFlags level)
  92. {
  93. switch (level & G_LOG_LEVEL_MASK) {
  94. case G_LOG_LEVEL_ERROR:
  95. return "error";
  96. case G_LOG_LEVEL_CRITICAL:
  97. return "critical";
  98. case G_LOG_LEVEL_WARNING:
  99. return "warning";
  100. case G_LOG_LEVEL_MESSAGE:
  101. return "message";
  102. case G_LOG_LEVEL_INFO:
  103. return "info";
  104. case G_LOG_LEVEL_DEBUG:
  105. return "debug";
  106. default:
  107. return "user";
  108. }
  109. }
  110. bool ga_logging_enabled(GAState *s)
  111. {
  112. return s->logging_enabled;
  113. }
  114. void ga_disable_logging(GAState *s)
  115. {
  116. s->logging_enabled = false;
  117. }
  118. void ga_enable_logging(GAState *s)
  119. {
  120. s->logging_enabled = true;
  121. }
  122. static void ga_log(const gchar *domain, GLogLevelFlags level,
  123. const gchar *msg, gpointer opaque)
  124. {
  125. GAState *s = opaque;
  126. GTimeVal time;
  127. const char *level_str = ga_log_level_str(level);
  128. if (!ga_logging_enabled(s)) {
  129. return;
  130. }
  131. level &= G_LOG_LEVEL_MASK;
  132. if (g_strcmp0(domain, "syslog") == 0) {
  133. syslog(LOG_INFO, "%s: %s", level_str, msg);
  134. } else if (level & s->log_level) {
  135. g_get_current_time(&time);
  136. fprintf(s->log_file,
  137. "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
  138. fflush(s->log_file);
  139. }
  140. }
  141. static void become_daemon(const char *pidfile)
  142. {
  143. pid_t pid, sid;
  144. int pidfd;
  145. char *pidstr = NULL;
  146. pid = fork();
  147. if (pid < 0) {
  148. exit(EXIT_FAILURE);
  149. }
  150. if (pid > 0) {
  151. exit(EXIT_SUCCESS);
  152. }
  153. pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
  154. if (pidfd == -1) {
  155. g_critical("Cannot create pid file, %s", strerror(errno));
  156. exit(EXIT_FAILURE);
  157. }
  158. if (asprintf(&pidstr, "%d", getpid()) == -1) {
  159. g_critical("Cannot allocate memory");
  160. goto fail;
  161. }
  162. if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
  163. free(pidstr);
  164. g_critical("Failed to write pid file");
  165. goto fail;
  166. }
  167. umask(0);
  168. sid = setsid();
  169. if (sid < 0) {
  170. goto fail;
  171. }
  172. if ((chdir("/")) < 0) {
  173. goto fail;
  174. }
  175. close(STDIN_FILENO);
  176. close(STDOUT_FILENO);
  177. close(STDERR_FILENO);
  178. free(pidstr);
  179. return;
  180. fail:
  181. unlink(pidfile);
  182. g_critical("failed to daemonize");
  183. exit(EXIT_FAILURE);
  184. }
  185. static int conn_channel_send_buf(GIOChannel *channel, const char *buf,
  186. gsize count)
  187. {
  188. GError *err = NULL;
  189. gsize written = 0;
  190. GIOStatus status;
  191. while (count) {
  192. status = g_io_channel_write_chars(channel, buf, count, &written, &err);
  193. g_debug("sending data, count: %d", (int)count);
  194. if (err != NULL) {
  195. g_warning("error sending newline: %s", err->message);
  196. return err->code;
  197. }
  198. if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF) {
  199. return -EPIPE;
  200. }
  201. if (status == G_IO_STATUS_NORMAL) {
  202. count -= written;
  203. }
  204. }
  205. return 0;
  206. }
  207. static int conn_channel_send_payload(GIOChannel *channel, QObject *payload)
  208. {
  209. int ret = 0;
  210. const char *buf;
  211. QString *payload_qstr;
  212. GError *err = NULL;
  213. g_assert(payload && channel);
  214. payload_qstr = qobject_to_json(payload);
  215. if (!payload_qstr) {
  216. return -EINVAL;
  217. }
  218. qstring_append_chr(payload_qstr, '\n');
  219. buf = qstring_get_str(payload_qstr);
  220. ret = conn_channel_send_buf(channel, buf, strlen(buf));
  221. if (ret) {
  222. goto out_free;
  223. }
  224. g_io_channel_flush(channel, &err);
  225. if (err != NULL) {
  226. g_warning("error flushing payload: %s", err->message);
  227. ret = err->code;
  228. goto out_free;
  229. }
  230. out_free:
  231. QDECREF(payload_qstr);
  232. if (err) {
  233. g_error_free(err);
  234. }
  235. return ret;
  236. }
  237. static void process_command(GAState *s, QDict *req)
  238. {
  239. QObject *rsp = NULL;
  240. int ret;
  241. g_assert(req);
  242. g_debug("processing command");
  243. rsp = qmp_dispatch(QOBJECT(req));
  244. if (rsp) {
  245. ret = conn_channel_send_payload(s->conn_channel, rsp);
  246. if (ret) {
  247. g_warning("error sending payload: %s", strerror(ret));
  248. }
  249. qobject_decref(rsp);
  250. } else {
  251. g_warning("error getting response");
  252. }
  253. }
  254. /* handle requests/control events coming in over the channel */
  255. static void process_event(JSONMessageParser *parser, QList *tokens)
  256. {
  257. GAState *s = container_of(parser, GAState, parser);
  258. QObject *obj;
  259. QDict *qdict;
  260. Error *err = NULL;
  261. int ret;
  262. g_assert(s && parser);
  263. g_debug("process_event: called");
  264. obj = json_parser_parse_err(tokens, NULL, &err);
  265. if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
  266. qobject_decref(obj);
  267. qdict = qdict_new();
  268. if (!err) {
  269. g_warning("failed to parse event: unknown error");
  270. error_set(&err, QERR_JSON_PARSING);
  271. } else {
  272. g_warning("failed to parse event: %s", error_get_pretty(err));
  273. }
  274. qdict_put_obj(qdict, "error", error_get_qobject(err));
  275. error_free(err);
  276. } else {
  277. qdict = qobject_to_qdict(obj);
  278. }
  279. g_assert(qdict);
  280. /* handle host->guest commands */
  281. if (qdict_haskey(qdict, "execute")) {
  282. process_command(s, qdict);
  283. } else {
  284. if (!qdict_haskey(qdict, "error")) {
  285. QDECREF(qdict);
  286. qdict = qdict_new();
  287. g_warning("unrecognized payload format");
  288. error_set(&err, QERR_UNSUPPORTED);
  289. qdict_put_obj(qdict, "error", error_get_qobject(err));
  290. error_free(err);
  291. }
  292. ret = conn_channel_send_payload(s->conn_channel, QOBJECT(qdict));
  293. if (ret) {
  294. g_warning("error sending payload: %s", strerror(ret));
  295. }
  296. }
  297. QDECREF(qdict);
  298. }
  299. static gboolean conn_channel_read(GIOChannel *channel, GIOCondition condition,
  300. gpointer data)
  301. {
  302. GAState *s = data;
  303. gchar buf[1024];
  304. gsize count;
  305. GError *err = NULL;
  306. memset(buf, 0, 1024);
  307. GIOStatus status = g_io_channel_read_chars(channel, buf, 1024,
  308. &count, &err);
  309. if (err != NULL) {
  310. g_warning("error reading channel: %s", err->message);
  311. conn_channel_close(s);
  312. g_error_free(err);
  313. return false;
  314. }
  315. switch (status) {
  316. case G_IO_STATUS_ERROR:
  317. g_warning("problem");
  318. return false;
  319. case G_IO_STATUS_NORMAL:
  320. g_debug("read data, count: %d, data: %s", (int)count, buf);
  321. json_message_parser_feed(&s->parser, (char *)buf, (int)count);
  322. case G_IO_STATUS_AGAIN:
  323. /* virtio causes us to spin here when no process is attached to
  324. * host-side chardev. sleep a bit to mitigate this
  325. */
  326. if (s->virtio) {
  327. usleep(100*1000);
  328. }
  329. return true;
  330. case G_IO_STATUS_EOF:
  331. g_debug("received EOF");
  332. conn_channel_close(s);
  333. if (s->virtio) {
  334. return true;
  335. }
  336. return false;
  337. default:
  338. g_warning("unknown channel read status, closing");
  339. conn_channel_close(s);
  340. return false;
  341. }
  342. return true;
  343. }
  344. static int conn_channel_add(GAState *s, int fd)
  345. {
  346. GIOChannel *conn_channel;
  347. GError *err = NULL;
  348. g_assert(s && !s->conn_channel);
  349. conn_channel = g_io_channel_unix_new(fd);
  350. g_assert(conn_channel);
  351. g_io_channel_set_encoding(conn_channel, NULL, &err);
  352. if (err != NULL) {
  353. g_warning("error setting channel encoding to binary");
  354. g_error_free(err);
  355. return -1;
  356. }
  357. g_io_add_watch(conn_channel, G_IO_IN | G_IO_HUP,
  358. conn_channel_read, s);
  359. s->conn_channel = conn_channel;
  360. return 0;
  361. }
  362. static gboolean listen_channel_accept(GIOChannel *channel,
  363. GIOCondition condition, gpointer data)
  364. {
  365. GAState *s = data;
  366. g_assert(channel != NULL);
  367. int ret, conn_fd;
  368. bool accepted = false;
  369. struct sockaddr_un addr;
  370. socklen_t addrlen = sizeof(addr);
  371. conn_fd = qemu_accept(g_io_channel_unix_get_fd(s->listen_channel),
  372. (struct sockaddr *)&addr, &addrlen);
  373. if (conn_fd == -1) {
  374. g_warning("error converting fd to gsocket: %s", strerror(errno));
  375. goto out;
  376. }
  377. fcntl(conn_fd, F_SETFL, O_NONBLOCK);
  378. ret = conn_channel_add(s, conn_fd);
  379. if (ret) {
  380. g_warning("error setting up connection");
  381. goto out;
  382. }
  383. accepted = true;
  384. out:
  385. /* only accept 1 connection at a time */
  386. return !accepted;
  387. }
  388. /* start polling for readable events on listen fd, new==true
  389. * indicates we should use the existing s->listen_channel
  390. */
  391. static int listen_channel_add(GAState *s, int listen_fd, bool new)
  392. {
  393. if (new) {
  394. s->listen_channel = g_io_channel_unix_new(listen_fd);
  395. }
  396. g_io_add_watch(s->listen_channel, G_IO_IN,
  397. listen_channel_accept, s);
  398. return 0;
  399. }
  400. /* cleanup state for closed connection/session, start accepting new
  401. * connections if we're in listening mode
  402. */
  403. static void conn_channel_close(GAState *s)
  404. {
  405. if (strcmp(s->method, "unix-listen") == 0) {
  406. g_io_channel_shutdown(s->conn_channel, true, NULL);
  407. listen_channel_add(s, 0, false);
  408. } else if (strcmp(s->method, "virtio-serial") == 0) {
  409. /* we spin on EOF for virtio-serial, so back off a bit. also,
  410. * dont close the connection in this case, it'll resume normal
  411. * operation when another process connects to host chardev
  412. */
  413. usleep(100*1000);
  414. goto out_noclose;
  415. }
  416. g_io_channel_unref(s->conn_channel);
  417. s->conn_channel = NULL;
  418. out_noclose:
  419. return;
  420. }
  421. static void init_guest_agent(GAState *s)
  422. {
  423. struct termios tio;
  424. int ret, fd;
  425. if (s->method == NULL) {
  426. /* try virtio-serial as our default */
  427. s->method = "virtio-serial";
  428. }
  429. if (s->path == NULL) {
  430. if (strcmp(s->method, "virtio-serial") != 0) {
  431. g_critical("must specify a path for this channel");
  432. exit(EXIT_FAILURE);
  433. }
  434. /* try the default path for the virtio-serial port */
  435. s->path = QGA_VIRTIO_PATH_DEFAULT;
  436. }
  437. if (strcmp(s->method, "virtio-serial") == 0) {
  438. s->virtio = true;
  439. fd = qemu_open(s->path, O_RDWR | O_NONBLOCK | O_ASYNC);
  440. if (fd == -1) {
  441. g_critical("error opening channel: %s", strerror(errno));
  442. exit(EXIT_FAILURE);
  443. }
  444. ret = conn_channel_add(s, fd);
  445. if (ret) {
  446. g_critical("error adding channel to main loop");
  447. exit(EXIT_FAILURE);
  448. }
  449. } else if (strcmp(s->method, "isa-serial") == 0) {
  450. fd = qemu_open(s->path, O_RDWR | O_NOCTTY);
  451. if (fd == -1) {
  452. g_critical("error opening channel: %s", strerror(errno));
  453. exit(EXIT_FAILURE);
  454. }
  455. tcgetattr(fd, &tio);
  456. /* set up serial port for non-canonical, dumb byte streaming */
  457. tio.c_iflag &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP |
  458. INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY |
  459. IMAXBEL);
  460. tio.c_oflag = 0;
  461. tio.c_lflag = 0;
  462. tio.c_cflag |= QGA_BAUDRATE_DEFAULT;
  463. /* 1 available byte min or reads will block (we'll set non-blocking
  464. * elsewhere, else we have to deal with read()=0 instead)
  465. */
  466. tio.c_cc[VMIN] = 1;
  467. tio.c_cc[VTIME] = 0;
  468. /* flush everything waiting for read/xmit, it's garbage at this point */
  469. tcflush(fd, TCIFLUSH);
  470. tcsetattr(fd, TCSANOW, &tio);
  471. ret = conn_channel_add(s, fd);
  472. if (ret) {
  473. g_error("error adding channel to main loop");
  474. }
  475. } else if (strcmp(s->method, "unix-listen") == 0) {
  476. fd = unix_listen(s->path, NULL, strlen(s->path));
  477. if (fd == -1) {
  478. g_critical("error opening path: %s", strerror(errno));
  479. exit(EXIT_FAILURE);
  480. }
  481. ret = listen_channel_add(s, fd, true);
  482. if (ret) {
  483. g_critical("error binding/listening to specified socket");
  484. exit(EXIT_FAILURE);
  485. }
  486. } else {
  487. g_critical("unsupported channel method/type: %s", s->method);
  488. exit(EXIT_FAILURE);
  489. }
  490. json_message_parser_init(&s->parser, process_event);
  491. s->main_loop = g_main_loop_new(NULL, false);
  492. }
  493. int main(int argc, char **argv)
  494. {
  495. const char *sopt = "hVvdm:p:l:f:";
  496. const char *method = NULL, *path = NULL, *pidfile = QGA_PIDFILE_DEFAULT;
  497. const struct option lopt[] = {
  498. { "help", 0, NULL, 'h' },
  499. { "version", 0, NULL, 'V' },
  500. { "logfile", 0, NULL, 'l' },
  501. { "pidfile", 0, NULL, 'f' },
  502. { "verbose", 0, NULL, 'v' },
  503. { "method", 0, NULL, 'm' },
  504. { "path", 0, NULL, 'p' },
  505. { "daemonize", 0, NULL, 'd' },
  506. { NULL, 0, NULL, 0 }
  507. };
  508. int opt_ind = 0, ch, daemonize = 0;
  509. GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
  510. FILE *log_file = stderr;
  511. GAState *s;
  512. while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
  513. switch (ch) {
  514. case 'm':
  515. method = optarg;
  516. break;
  517. case 'p':
  518. path = optarg;
  519. break;
  520. case 'l':
  521. log_file = fopen(optarg, "a");
  522. if (!log_file) {
  523. g_critical("unable to open specified log file: %s",
  524. strerror(errno));
  525. return EXIT_FAILURE;
  526. }
  527. break;
  528. case 'f':
  529. pidfile = optarg;
  530. break;
  531. case 'v':
  532. /* enable all log levels */
  533. log_level = G_LOG_LEVEL_MASK;
  534. break;
  535. case 'V':
  536. printf("QEMU Guest Agent %s\n", QGA_VERSION);
  537. return 0;
  538. case 'd':
  539. daemonize = 1;
  540. break;
  541. case 'h':
  542. usage(argv[0]);
  543. return 0;
  544. case '?':
  545. g_print("Unknown option, try '%s --help' for more information.\n",
  546. argv[0]);
  547. return EXIT_FAILURE;
  548. }
  549. }
  550. if (daemonize) {
  551. g_debug("starting daemon");
  552. become_daemon(pidfile);
  553. }
  554. s = qemu_mallocz(sizeof(GAState));
  555. s->conn_channel = NULL;
  556. s->path = path;
  557. s->method = method;
  558. s->log_file = log_file;
  559. s->log_level = log_level;
  560. g_log_set_default_handler(ga_log, s);
  561. g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
  562. s->logging_enabled = true;
  563. s->command_state = ga_command_state_new();
  564. ga_command_state_init(s, s->command_state);
  565. ga_command_state_init_all(s->command_state);
  566. ga_state = s;
  567. module_call_init(MODULE_INIT_QAPI);
  568. init_guest_agent(ga_state);
  569. register_signal_handlers();
  570. g_main_loop_run(ga_state->main_loop);
  571. ga_command_state_cleanup_all(ga_state->command_state);
  572. unlink(pidfile);
  573. return 0;
  574. }