main.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  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 "qemu/osdep.h"
  14. #include <getopt.h>
  15. #include <glib/gstdio.h>
  16. #ifndef _WIN32
  17. #include <syslog.h>
  18. #include <sys/wait.h>
  19. #endif
  20. #include "qemu/help-texts.h"
  21. #include "qapi/qmp/json-parser.h"
  22. #include "qapi/qmp/qdict.h"
  23. #include "qapi/qmp/qjson.h"
  24. #include "guest-agent-core.h"
  25. #include "qga-qapi-init-commands.h"
  26. #include "qapi/qmp/qerror.h"
  27. #include "qapi/error.h"
  28. #include "channel.h"
  29. #include "qemu/cutils.h"
  30. #include "qemu/help_option.h"
  31. #include "qemu/sockets.h"
  32. #include "qemu/systemd.h"
  33. #include "qemu-version.h"
  34. #ifdef _WIN32
  35. #include <dbt.h>
  36. #include "qga/service-win32.h"
  37. #include "qga/vss-win32.h"
  38. #endif
  39. #include "commands-common.h"
  40. #ifndef _WIN32
  41. #ifdef CONFIG_BSD
  42. #define QGA_VIRTIO_PATH_DEFAULT "/dev/vtcon/org.qemu.guest_agent.0"
  43. #else /* CONFIG_BSD */
  44. #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
  45. #endif /* CONFIG_BSD */
  46. #define QGA_SERIAL_PATH_DEFAULT "/dev/ttyS0"
  47. #define QGA_STATE_RELATIVE_DIR "run"
  48. #else
  49. #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
  50. #define QGA_STATE_RELATIVE_DIR "qemu-ga"
  51. #define QGA_SERIAL_PATH_DEFAULT "COM1"
  52. #endif
  53. #ifdef CONFIG_FSFREEZE
  54. #define QGA_FSFREEZE_HOOK_DEFAULT CONFIG_QEMU_CONFDIR "/fsfreeze-hook"
  55. #endif
  56. #define QGA_SENTINEL_BYTE 0xFF
  57. #define QGA_CONF_DEFAULT CONFIG_QEMU_CONFDIR G_DIR_SEPARATOR_S "qemu-ga.conf"
  58. #define QGA_RETRY_INTERVAL 5
  59. static struct {
  60. const char *state_dir;
  61. const char *pidfile;
  62. } dfl_pathnames;
  63. typedef struct GAPersistentState {
  64. #define QGA_PSTATE_DEFAULT_FD_COUNTER 1000
  65. int64_t fd_counter;
  66. } GAPersistentState;
  67. typedef struct GAConfig GAConfig;
  68. struct GAState {
  69. JSONMessageParser parser;
  70. GMainLoop *main_loop;
  71. GAChannel *channel;
  72. bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
  73. GACommandState *command_state;
  74. GLogLevelFlags log_level;
  75. FILE *log_file;
  76. bool logging_enabled;
  77. #ifdef _WIN32
  78. GAService service;
  79. HANDLE wakeup_event;
  80. HANDLE event_log;
  81. #endif
  82. bool delimit_response;
  83. bool frozen;
  84. GList *blockedrpcs;
  85. char *state_filepath_isfrozen;
  86. struct {
  87. const char *log_filepath;
  88. const char *pid_filepath;
  89. } deferred_options;
  90. #ifdef CONFIG_FSFREEZE
  91. const char *fsfreeze_hook;
  92. #endif
  93. gchar *pstate_filepath;
  94. GAPersistentState pstate;
  95. GAConfig *config;
  96. int socket_activation;
  97. bool force_exit;
  98. };
  99. struct GAState *ga_state;
  100. QmpCommandList ga_commands;
  101. /* commands that are safe to issue while filesystems are frozen */
  102. static const char *ga_freeze_allowlist[] = {
  103. "guest-ping",
  104. "guest-info",
  105. "guest-sync",
  106. "guest-sync-delimited",
  107. "guest-fsfreeze-status",
  108. "guest-fsfreeze-thaw",
  109. NULL
  110. };
  111. #ifdef _WIN32
  112. DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
  113. LPVOID ctx);
  114. DWORD WINAPI handle_serial_device_events(DWORD type, LPVOID data);
  115. VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
  116. #endif
  117. static int run_agent(GAState *s);
  118. static void stop_agent(GAState *s, bool requested);
  119. static void
  120. init_dfl_pathnames(void)
  121. {
  122. g_autofree char *state = qemu_get_local_state_dir();
  123. g_assert(dfl_pathnames.state_dir == NULL);
  124. g_assert(dfl_pathnames.pidfile == NULL);
  125. dfl_pathnames.state_dir = g_build_filename(state, QGA_STATE_RELATIVE_DIR, NULL);
  126. dfl_pathnames.pidfile = g_build_filename(state, QGA_STATE_RELATIVE_DIR, "qemu-ga.pid", NULL);
  127. }
  128. static void quit_handler(int sig)
  129. {
  130. /* if we're frozen, don't exit unless we're absolutely forced to,
  131. * because it's basically impossible for graceful exit to complete
  132. * unless all log/pid files are on unfreezable filesystems. there's
  133. * also a very likely chance killing the agent before unfreezing
  134. * the filesystems is a mistake (or will be viewed as one later).
  135. * On Windows the freeze interval is limited to 10 seconds, so
  136. * we should quit, but first we should wait for the timeout, thaw
  137. * the filesystem and quit.
  138. */
  139. if (ga_is_frozen(ga_state)) {
  140. #ifdef _WIN32
  141. int i = 0;
  142. Error *err = NULL;
  143. HANDLE hEventTimeout;
  144. g_debug("Thawing filesystems before exiting");
  145. hEventTimeout = OpenEvent(EVENT_ALL_ACCESS, FALSE, EVENT_NAME_TIMEOUT);
  146. if (hEventTimeout) {
  147. WaitForSingleObject(hEventTimeout, 0);
  148. CloseHandle(hEventTimeout);
  149. }
  150. qga_vss_fsfreeze(&i, false, NULL, &err);
  151. if (err) {
  152. g_debug("Error unfreezing filesystems prior to exiting: %s",
  153. error_get_pretty(err));
  154. error_free(err);
  155. }
  156. #else
  157. return;
  158. #endif
  159. }
  160. g_debug("received signal num %d, quitting", sig);
  161. stop_agent(ga_state, true);
  162. }
  163. #ifndef _WIN32
  164. static gboolean register_signal_handlers(void)
  165. {
  166. struct sigaction sigact;
  167. int ret;
  168. memset(&sigact, 0, sizeof(struct sigaction));
  169. sigact.sa_handler = quit_handler;
  170. ret = sigaction(SIGINT, &sigact, NULL);
  171. if (ret == -1) {
  172. g_error("error configuring signal handler: %s", strerror(errno));
  173. }
  174. ret = sigaction(SIGTERM, &sigact, NULL);
  175. if (ret == -1) {
  176. g_error("error configuring signal handler: %s", strerror(errno));
  177. }
  178. sigact.sa_handler = SIG_IGN;
  179. if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
  180. g_error("error configuring SIGPIPE signal handler: %s",
  181. strerror(errno));
  182. }
  183. return true;
  184. }
  185. /* TODO: use this in place of all post-fork() fclose(std*) callers */
  186. void reopen_fd_to_null(int fd)
  187. {
  188. int nullfd;
  189. nullfd = open("/dev/null", O_RDWR);
  190. if (nullfd < 0) {
  191. return;
  192. }
  193. dup2(nullfd, fd);
  194. if (nullfd != fd) {
  195. close(nullfd);
  196. }
  197. }
  198. #endif
  199. static void usage(const char *cmd)
  200. {
  201. #ifdef CONFIG_FSFREEZE
  202. g_autofree char *fsfreeze_hook = get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT);
  203. #endif
  204. printf(
  205. "Usage: %s [-m <method> -p <path>] [<options>]\n"
  206. "QEMU Guest Agent " QEMU_FULL_VERSION "\n"
  207. QEMU_COPYRIGHT "\n"
  208. "\n"
  209. " -m, --method transport method: one of unix-listen, virtio-serial,\n"
  210. " isa-serial, or vsock-listen (virtio-serial is the default)\n"
  211. " -p, --path device/socket path (the default for virtio-serial is:\n"
  212. " %s,\n"
  213. " the default for isa-serial is:\n"
  214. " %s).\n"
  215. " Socket addresses for vsock-listen are written as\n"
  216. " <cid>:<port>.\n"
  217. " -l, --logfile set logfile path, logs to stderr by default\n"
  218. " -f, --pidfile specify pidfile (default is %s)\n"
  219. #ifdef CONFIG_FSFREEZE
  220. " -F, --fsfreeze-hook\n"
  221. " enable fsfreeze hook. Accepts an optional argument that\n"
  222. " specifies script to run on freeze/thaw. Script will be\n"
  223. " called with 'freeze'/'thaw' arguments accordingly.\n"
  224. " (default is %s)\n"
  225. " If using -F with an argument, do not follow -F with a\n"
  226. " space.\n"
  227. " (for example: -F/var/run/fsfreezehook.sh)\n"
  228. #endif
  229. " -t, --statedir specify dir to store state information (absolute paths\n"
  230. " only, default is %s)\n"
  231. " -v, --verbose log extra debugging information\n"
  232. " -V, --version print version information and exit\n"
  233. " -d, --daemonize become a daemon\n"
  234. #ifdef _WIN32
  235. " -s, --service service commands: install, uninstall, vss-install, vss-uninstall\n"
  236. #endif
  237. " -b, --block-rpcs comma-separated list of RPCs to disable (no spaces,\n"
  238. " use \"help\" to list available RPCs)\n"
  239. " -D, --dump-conf dump a qemu-ga config file based on current config\n"
  240. " options / command-line parameters to stdout\n"
  241. " -r, --retry-path attempt re-opening path if it's unavailable or closed\n"
  242. " due to an error which may be recoverable in the future\n"
  243. " (virtio-serial driver re-install, serial device hot\n"
  244. " plug/unplug, etc.)\n"
  245. " -h, --help display this help and exit\n"
  246. "\n"
  247. QEMU_HELP_BOTTOM "\n"
  248. , cmd, QGA_VIRTIO_PATH_DEFAULT, QGA_SERIAL_PATH_DEFAULT,
  249. dfl_pathnames.pidfile,
  250. #ifdef CONFIG_FSFREEZE
  251. fsfreeze_hook,
  252. #endif
  253. dfl_pathnames.state_dir);
  254. }
  255. static const char *ga_log_level_str(GLogLevelFlags level)
  256. {
  257. switch (level & G_LOG_LEVEL_MASK) {
  258. case G_LOG_LEVEL_ERROR:
  259. return "error";
  260. case G_LOG_LEVEL_CRITICAL:
  261. return "critical";
  262. case G_LOG_LEVEL_WARNING:
  263. return "warning";
  264. case G_LOG_LEVEL_MESSAGE:
  265. return "message";
  266. case G_LOG_LEVEL_INFO:
  267. return "info";
  268. case G_LOG_LEVEL_DEBUG:
  269. return "debug";
  270. default:
  271. return "user";
  272. }
  273. }
  274. bool ga_logging_enabled(GAState *s)
  275. {
  276. return s->logging_enabled;
  277. }
  278. void ga_disable_logging(GAState *s)
  279. {
  280. s->logging_enabled = false;
  281. }
  282. void ga_enable_logging(GAState *s)
  283. {
  284. s->logging_enabled = true;
  285. }
  286. static void ga_log(const gchar *domain, GLogLevelFlags level,
  287. const gchar *msg, gpointer opaque)
  288. {
  289. GAState *s = opaque;
  290. const char *level_str = ga_log_level_str(level);
  291. if (!ga_logging_enabled(s)) {
  292. return;
  293. }
  294. level &= G_LOG_LEVEL_MASK;
  295. if (g_strcmp0(domain, "syslog") == 0) {
  296. #ifndef _WIN32
  297. syslog(LOG_INFO, "%s: %s", level_str, msg);
  298. #else
  299. ReportEvent(s->event_log, EVENTLOG_INFORMATION_TYPE,
  300. 0, 1, NULL, 1, 0, &msg, NULL);
  301. #endif
  302. } else if (level & s->log_level) {
  303. g_autoptr(GDateTime) now = g_date_time_new_now_utc();
  304. g_autofree char *nowstr = g_date_time_format(now, "%s.%f");
  305. fprintf(s->log_file, "%s: %s: %s\n", nowstr, level_str, msg);
  306. fflush(s->log_file);
  307. }
  308. }
  309. void ga_set_response_delimited(GAState *s)
  310. {
  311. s->delimit_response = true;
  312. }
  313. static FILE *ga_open_logfile(const char *logfile)
  314. {
  315. FILE *f;
  316. f = fopen(logfile, "a");
  317. if (!f) {
  318. return NULL;
  319. }
  320. qemu_set_cloexec(fileno(f));
  321. return f;
  322. }
  323. static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
  324. {
  325. return strcmp(str1, str2);
  326. }
  327. /* disable commands that aren't safe for fsfreeze */
  328. static void ga_disable_not_allowed(const QmpCommand *cmd, void *opaque)
  329. {
  330. bool allowed = false;
  331. int i = 0;
  332. const char *name = qmp_command_name(cmd);
  333. while (ga_freeze_allowlist[i] != NULL) {
  334. if (strcmp(name, ga_freeze_allowlist[i]) == 0) {
  335. allowed = true;
  336. }
  337. i++;
  338. }
  339. if (!allowed) {
  340. g_debug("disabling command: %s", name);
  341. qmp_disable_command(&ga_commands, name, "the agent is in frozen state");
  342. }
  343. }
  344. /* [re-]enable all commands, except those explicitly blocked by user */
  345. static void ga_enable_non_blocked(const QmpCommand *cmd, void *opaque)
  346. {
  347. GList *blockedrpcs = opaque;
  348. const char *name = qmp_command_name(cmd);
  349. if (g_list_find_custom(blockedrpcs, name, ga_strcmp) == NULL &&
  350. !qmp_command_is_enabled(cmd)) {
  351. g_debug("enabling command: %s", name);
  352. qmp_enable_command(&ga_commands, name);
  353. }
  354. }
  355. static bool ga_create_file(const char *path)
  356. {
  357. int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
  358. if (fd == -1) {
  359. g_warning("unable to open/create file %s: %s", path, strerror(errno));
  360. return false;
  361. }
  362. close(fd);
  363. return true;
  364. }
  365. static bool ga_delete_file(const char *path)
  366. {
  367. int ret = unlink(path);
  368. if (ret == -1) {
  369. g_warning("unable to delete file: %s: %s", path, strerror(errno));
  370. return false;
  371. }
  372. return true;
  373. }
  374. bool ga_is_frozen(GAState *s)
  375. {
  376. return s->frozen;
  377. }
  378. void ga_set_frozen(GAState *s)
  379. {
  380. if (ga_is_frozen(s)) {
  381. return;
  382. }
  383. /* disable all forbidden (for frozen state) commands */
  384. qmp_for_each_command(&ga_commands, ga_disable_not_allowed, NULL);
  385. g_warning("disabling logging due to filesystem freeze");
  386. ga_disable_logging(s);
  387. s->frozen = true;
  388. if (!ga_create_file(s->state_filepath_isfrozen)) {
  389. g_warning("unable to create %s, fsfreeze may not function properly",
  390. s->state_filepath_isfrozen);
  391. }
  392. }
  393. void ga_unset_frozen(GAState *s)
  394. {
  395. if (!ga_is_frozen(s)) {
  396. return;
  397. }
  398. /* if we delayed creation/opening of pid/log files due to being
  399. * in a frozen state at start up, do it now
  400. */
  401. if (s->deferred_options.log_filepath) {
  402. s->log_file = ga_open_logfile(s->deferred_options.log_filepath);
  403. if (!s->log_file) {
  404. s->log_file = stderr;
  405. }
  406. s->deferred_options.log_filepath = NULL;
  407. }
  408. ga_enable_logging(s);
  409. g_warning("logging re-enabled due to filesystem unfreeze");
  410. if (s->deferred_options.pid_filepath) {
  411. Error *err = NULL;
  412. if (!qemu_write_pidfile(s->deferred_options.pid_filepath, &err)) {
  413. g_warning("%s", error_get_pretty(err));
  414. error_free(err);
  415. }
  416. s->deferred_options.pid_filepath = NULL;
  417. }
  418. /* enable all disabled, non-blocked commands */
  419. qmp_for_each_command(&ga_commands, ga_enable_non_blocked, s->blockedrpcs);
  420. s->frozen = false;
  421. if (!ga_delete_file(s->state_filepath_isfrozen)) {
  422. g_warning("unable to delete %s, fsfreeze may not function properly",
  423. s->state_filepath_isfrozen);
  424. }
  425. }
  426. #ifdef CONFIG_FSFREEZE
  427. const char *ga_fsfreeze_hook(GAState *s)
  428. {
  429. return s->fsfreeze_hook;
  430. }
  431. #endif
  432. static void become_daemon(const char *pidfile)
  433. {
  434. #ifndef _WIN32
  435. pid_t pid, sid;
  436. pid = fork();
  437. if (pid < 0) {
  438. exit(EXIT_FAILURE);
  439. }
  440. if (pid > 0) {
  441. exit(EXIT_SUCCESS);
  442. }
  443. if (pidfile) {
  444. Error *err = NULL;
  445. if (!qemu_write_pidfile(pidfile, &err)) {
  446. g_critical("%s", error_get_pretty(err));
  447. error_free(err);
  448. exit(EXIT_FAILURE);
  449. }
  450. }
  451. umask(S_IRWXG | S_IRWXO);
  452. sid = setsid();
  453. if (sid < 0) {
  454. goto fail;
  455. }
  456. if ((chdir("/")) < 0) {
  457. goto fail;
  458. }
  459. reopen_fd_to_null(STDIN_FILENO);
  460. reopen_fd_to_null(STDOUT_FILENO);
  461. reopen_fd_to_null(STDERR_FILENO);
  462. return;
  463. fail:
  464. if (pidfile) {
  465. unlink(pidfile);
  466. }
  467. g_critical("failed to daemonize");
  468. exit(EXIT_FAILURE);
  469. #endif
  470. }
  471. static int send_response(GAState *s, const QDict *rsp)
  472. {
  473. GString *response;
  474. GIOStatus status;
  475. g_assert(s->channel);
  476. if (!rsp) {
  477. return 0;
  478. }
  479. response = qobject_to_json(QOBJECT(rsp));
  480. if (!response) {
  481. return -EINVAL;
  482. }
  483. if (s->delimit_response) {
  484. s->delimit_response = false;
  485. g_string_prepend_c(response, QGA_SENTINEL_BYTE);
  486. }
  487. g_string_append_c(response, '\n');
  488. status = ga_channel_write_all(s->channel, response->str, response->len);
  489. g_string_free(response, true);
  490. if (status != G_IO_STATUS_NORMAL) {
  491. return -EIO;
  492. }
  493. return 0;
  494. }
  495. /* handle requests/control events coming in over the channel */
  496. static void process_event(void *opaque, QObject *obj, Error *err)
  497. {
  498. GAState *s = opaque;
  499. QDict *rsp;
  500. int ret;
  501. g_debug("process_event: called");
  502. assert(!obj != !err);
  503. if (err) {
  504. rsp = qmp_error_response(err);
  505. goto end;
  506. }
  507. g_debug("processing command");
  508. rsp = qmp_dispatch(&ga_commands, obj, false, NULL);
  509. end:
  510. ret = send_response(s, rsp);
  511. if (ret < 0) {
  512. g_warning("error sending error response: %s", strerror(-ret));
  513. }
  514. qobject_unref(rsp);
  515. qobject_unref(obj);
  516. }
  517. /* false return signals GAChannel to close the current client connection */
  518. static gboolean channel_event_cb(GIOCondition condition, gpointer data)
  519. {
  520. GAState *s = data;
  521. gchar buf[QGA_READ_COUNT_DEFAULT + 1];
  522. gsize count;
  523. GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
  524. switch (status) {
  525. case G_IO_STATUS_ERROR:
  526. g_warning("error reading channel");
  527. stop_agent(s, false);
  528. return false;
  529. case G_IO_STATUS_NORMAL:
  530. buf[count] = 0;
  531. g_debug("read data, count: %d, data: %s", (int)count, buf);
  532. json_message_parser_feed(&s->parser, (char *)buf, (int)count);
  533. break;
  534. case G_IO_STATUS_EOF:
  535. g_debug("received EOF");
  536. if (!s->virtio) {
  537. return false;
  538. }
  539. /* fall through */
  540. case G_IO_STATUS_AGAIN:
  541. /* virtio causes us to spin here when no process is attached to
  542. * host-side chardev. sleep a bit to mitigate this
  543. */
  544. if (s->virtio) {
  545. g_usleep(G_USEC_PER_SEC / 10);
  546. }
  547. return true;
  548. default:
  549. g_warning("unknown channel read status, closing");
  550. return false;
  551. }
  552. return true;
  553. }
  554. static gboolean channel_init(GAState *s, const gchar *method, const gchar *path,
  555. int listen_fd)
  556. {
  557. GAChannelMethod channel_method;
  558. if (strcmp(method, "virtio-serial") == 0) {
  559. s->virtio = true; /* virtio requires special handling in some cases */
  560. channel_method = GA_CHANNEL_VIRTIO_SERIAL;
  561. } else if (strcmp(method, "isa-serial") == 0) {
  562. channel_method = GA_CHANNEL_ISA_SERIAL;
  563. } else if (strcmp(method, "unix-listen") == 0) {
  564. channel_method = GA_CHANNEL_UNIX_LISTEN;
  565. } else if (strcmp(method, "vsock-listen") == 0) {
  566. channel_method = GA_CHANNEL_VSOCK_LISTEN;
  567. } else {
  568. g_critical("unsupported channel method/type: %s", method);
  569. return false;
  570. }
  571. s->channel = ga_channel_new(channel_method, path, listen_fd,
  572. channel_event_cb, s);
  573. if (!s->channel) {
  574. g_critical("failed to create guest agent channel");
  575. return false;
  576. }
  577. return true;
  578. }
  579. #ifdef _WIN32
  580. DWORD WINAPI handle_serial_device_events(DWORD type, LPVOID data)
  581. {
  582. DWORD ret = NO_ERROR;
  583. PDEV_BROADCAST_HDR broadcast_header = (PDEV_BROADCAST_HDR)data;
  584. if (broadcast_header->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
  585. switch (type) {
  586. /* Device inserted */
  587. case DBT_DEVICEARRIVAL:
  588. /* Start QEMU-ga's service */
  589. if (!SetEvent(ga_state->wakeup_event)) {
  590. ret = GetLastError();
  591. }
  592. break;
  593. /* Device removed */
  594. case DBT_DEVICEQUERYREMOVE:
  595. case DBT_DEVICEREMOVEPENDING:
  596. case DBT_DEVICEREMOVECOMPLETE:
  597. /* Stop QEMU-ga's service */
  598. if (!ResetEvent(ga_state->wakeup_event)) {
  599. ret = GetLastError();
  600. }
  601. break;
  602. default:
  603. ret = ERROR_CALL_NOT_IMPLEMENTED;
  604. }
  605. }
  606. return ret;
  607. }
  608. DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
  609. LPVOID ctx)
  610. {
  611. DWORD ret = NO_ERROR;
  612. GAService *service = &ga_state->service;
  613. switch (ctrl) {
  614. case SERVICE_CONTROL_STOP:
  615. case SERVICE_CONTROL_SHUTDOWN:
  616. quit_handler(SIGTERM);
  617. SetEvent(ga_state->wakeup_event);
  618. service->status.dwCurrentState = SERVICE_STOP_PENDING;
  619. SetServiceStatus(service->status_handle, &service->status);
  620. break;
  621. case SERVICE_CONTROL_DEVICEEVENT:
  622. handle_serial_device_events(type, data);
  623. break;
  624. default:
  625. ret = ERROR_CALL_NOT_IMPLEMENTED;
  626. }
  627. return ret;
  628. }
  629. VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
  630. {
  631. GAService *service = &ga_state->service;
  632. service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
  633. service_ctrl_handler, NULL);
  634. if (service->status_handle == 0) {
  635. g_critical("Failed to register extended requests function!\n");
  636. return;
  637. }
  638. service->status.dwServiceType = SERVICE_WIN32;
  639. service->status.dwCurrentState = SERVICE_RUNNING;
  640. service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  641. service->status.dwWin32ExitCode = NO_ERROR;
  642. service->status.dwServiceSpecificExitCode = NO_ERROR;
  643. service->status.dwCheckPoint = 0;
  644. service->status.dwWaitHint = 0;
  645. DEV_BROADCAST_DEVICEINTERFACE notification_filter;
  646. ZeroMemory(&notification_filter, sizeof(notification_filter));
  647. notification_filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
  648. notification_filter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
  649. notification_filter.dbcc_classguid = GUID_VIOSERIAL_PORT;
  650. service->device_notification_handle =
  651. RegisterDeviceNotification(service->status_handle,
  652. &notification_filter, DEVICE_NOTIFY_SERVICE_HANDLE);
  653. if (!service->device_notification_handle) {
  654. g_critical("Failed to register device notification handle!\n");
  655. return;
  656. }
  657. SetServiceStatus(service->status_handle, &service->status);
  658. run_agent(ga_state);
  659. UnregisterDeviceNotification(service->device_notification_handle);
  660. service->status.dwCurrentState = SERVICE_STOPPED;
  661. SetServiceStatus(service->status_handle, &service->status);
  662. }
  663. #endif
  664. static void set_persistent_state_defaults(GAPersistentState *pstate)
  665. {
  666. g_assert(pstate);
  667. pstate->fd_counter = QGA_PSTATE_DEFAULT_FD_COUNTER;
  668. }
  669. static void persistent_state_from_keyfile(GAPersistentState *pstate,
  670. GKeyFile *keyfile)
  671. {
  672. g_assert(pstate);
  673. g_assert(keyfile);
  674. /* if any fields are missing, either because the file was tampered with
  675. * by agents of chaos, or because the field wasn't present at the time the
  676. * file was created, the best we can ever do is start over with the default
  677. * values. so load them now, and ignore any errors in accessing key-value
  678. * pairs
  679. */
  680. set_persistent_state_defaults(pstate);
  681. if (g_key_file_has_key(keyfile, "global", "fd_counter", NULL)) {
  682. pstate->fd_counter =
  683. g_key_file_get_integer(keyfile, "global", "fd_counter", NULL);
  684. }
  685. }
  686. static void persistent_state_to_keyfile(const GAPersistentState *pstate,
  687. GKeyFile *keyfile)
  688. {
  689. g_assert(pstate);
  690. g_assert(keyfile);
  691. g_key_file_set_integer(keyfile, "global", "fd_counter", pstate->fd_counter);
  692. }
  693. static gboolean write_persistent_state(const GAPersistentState *pstate,
  694. const gchar *path)
  695. {
  696. GKeyFile *keyfile = g_key_file_new();
  697. GError *gerr = NULL;
  698. gboolean ret = true;
  699. gchar *data = NULL;
  700. gsize data_len;
  701. g_assert(pstate);
  702. persistent_state_to_keyfile(pstate, keyfile);
  703. data = g_key_file_to_data(keyfile, &data_len, &gerr);
  704. if (gerr) {
  705. g_critical("failed to convert persistent state to string: %s",
  706. gerr->message);
  707. ret = false;
  708. goto out;
  709. }
  710. g_file_set_contents(path, data, data_len, &gerr);
  711. if (gerr) {
  712. g_critical("failed to write persistent state to %s: %s",
  713. path, gerr->message);
  714. ret = false;
  715. goto out;
  716. }
  717. out:
  718. if (gerr) {
  719. g_error_free(gerr);
  720. }
  721. if (keyfile) {
  722. g_key_file_free(keyfile);
  723. }
  724. g_free(data);
  725. return ret;
  726. }
  727. static gboolean read_persistent_state(GAPersistentState *pstate,
  728. const gchar *path, gboolean frozen)
  729. {
  730. GKeyFile *keyfile = NULL;
  731. GError *gerr = NULL;
  732. struct stat st;
  733. gboolean ret = true;
  734. g_assert(pstate);
  735. if (stat(path, &st) == -1) {
  736. /* it's okay if state file doesn't exist, but any other error
  737. * indicates a permissions issue or some other misconfiguration
  738. * that we likely won't be able to recover from.
  739. */
  740. if (errno != ENOENT) {
  741. g_critical("unable to access state file at path %s: %s",
  742. path, strerror(errno));
  743. ret = false;
  744. goto out;
  745. }
  746. /* file doesn't exist. initialize state to default values and
  747. * attempt to save now. (we could wait till later when we have
  748. * modified state we need to commit, but if there's a problem,
  749. * such as a missing parent directory, we want to catch it now)
  750. *
  751. * there is a potential scenario where someone either managed to
  752. * update the agent from a version that didn't use a key store
  753. * while qemu-ga thought the filesystem was frozen, or
  754. * deleted the key store prior to issuing a fsfreeze, prior
  755. * to restarting the agent. in this case we go ahead and defer
  756. * initial creation till we actually have modified state to
  757. * write, otherwise fail to recover from freeze.
  758. */
  759. set_persistent_state_defaults(pstate);
  760. if (!frozen) {
  761. ret = write_persistent_state(pstate, path);
  762. if (!ret) {
  763. g_critical("unable to create state file at path %s", path);
  764. ret = false;
  765. goto out;
  766. }
  767. }
  768. ret = true;
  769. goto out;
  770. }
  771. keyfile = g_key_file_new();
  772. g_key_file_load_from_file(keyfile, path, 0, &gerr);
  773. if (gerr) {
  774. g_critical("error loading persistent state from path: %s, %s",
  775. path, gerr->message);
  776. ret = false;
  777. goto out;
  778. }
  779. persistent_state_from_keyfile(pstate, keyfile);
  780. out:
  781. if (keyfile) {
  782. g_key_file_free(keyfile);
  783. }
  784. if (gerr) {
  785. g_error_free(gerr);
  786. }
  787. return ret;
  788. }
  789. int64_t ga_get_fd_handle(GAState *s, Error **errp)
  790. {
  791. int64_t handle;
  792. g_assert(s->pstate_filepath);
  793. /*
  794. * We block commands and avoid operations that potentially require
  795. * writing to disk when we're in a frozen state. this includes opening
  796. * new files, so we should never get here in that situation
  797. */
  798. g_assert(!ga_is_frozen(s));
  799. handle = s->pstate.fd_counter++;
  800. /* This should never happen on a reasonable timeframe, as guest-file-open
  801. * would have to be issued 2^63 times */
  802. if (s->pstate.fd_counter == INT64_MAX) {
  803. abort();
  804. }
  805. if (!write_persistent_state(&s->pstate, s->pstate_filepath)) {
  806. error_setg(errp, "failed to commit persistent state to disk");
  807. return -1;
  808. }
  809. return handle;
  810. }
  811. static void ga_print_cmd(const QmpCommand *cmd, void *opaque)
  812. {
  813. printf("%s\n", qmp_command_name(cmd));
  814. }
  815. static GList *split_list(const gchar *str, const gchar *delim)
  816. {
  817. GList *list = NULL;
  818. int i;
  819. gchar **strv;
  820. strv = g_strsplit(str, delim, -1);
  821. for (i = 0; strv[i]; i++) {
  822. list = g_list_prepend(list, strv[i]);
  823. }
  824. g_free(strv);
  825. return list;
  826. }
  827. struct GAConfig {
  828. char *channel_path;
  829. char *method;
  830. char *log_filepath;
  831. char *pid_filepath;
  832. #ifdef CONFIG_FSFREEZE
  833. char *fsfreeze_hook;
  834. #endif
  835. char *state_dir;
  836. #ifdef _WIN32
  837. const char *service;
  838. #endif
  839. gchar *bliststr; /* blockedrpcs may point to this string */
  840. GList *blockedrpcs;
  841. int daemonize;
  842. GLogLevelFlags log_level;
  843. int dumpconf;
  844. bool retry_path;
  845. };
  846. static void config_load(GAConfig *config)
  847. {
  848. GError *gerr = NULL;
  849. GKeyFile *keyfile;
  850. g_autofree char *conf = g_strdup(g_getenv("QGA_CONF")) ?: get_relocated_path(QGA_CONF_DEFAULT);
  851. const gchar *blockrpcs_key = "block-rpcs";
  852. /* read system config */
  853. keyfile = g_key_file_new();
  854. if (!g_key_file_load_from_file(keyfile, conf, 0, &gerr)) {
  855. goto end;
  856. }
  857. if (g_key_file_has_key(keyfile, "general", "daemon", NULL)) {
  858. config->daemonize =
  859. g_key_file_get_boolean(keyfile, "general", "daemon", &gerr);
  860. }
  861. if (g_key_file_has_key(keyfile, "general", "method", NULL)) {
  862. config->method =
  863. g_key_file_get_string(keyfile, "general", "method", &gerr);
  864. }
  865. if (g_key_file_has_key(keyfile, "general", "path", NULL)) {
  866. config->channel_path =
  867. g_key_file_get_string(keyfile, "general", "path", &gerr);
  868. }
  869. if (g_key_file_has_key(keyfile, "general", "logfile", NULL)) {
  870. config->log_filepath =
  871. g_key_file_get_string(keyfile, "general", "logfile", &gerr);
  872. }
  873. if (g_key_file_has_key(keyfile, "general", "pidfile", NULL)) {
  874. config->pid_filepath =
  875. g_key_file_get_string(keyfile, "general", "pidfile", &gerr);
  876. }
  877. #ifdef CONFIG_FSFREEZE
  878. if (g_key_file_has_key(keyfile, "general", "fsfreeze-hook", NULL)) {
  879. config->fsfreeze_hook =
  880. g_key_file_get_string(keyfile,
  881. "general", "fsfreeze-hook", &gerr);
  882. }
  883. #endif
  884. if (g_key_file_has_key(keyfile, "general", "statedir", NULL)) {
  885. config->state_dir =
  886. g_key_file_get_string(keyfile, "general", "statedir", &gerr);
  887. }
  888. if (g_key_file_has_key(keyfile, "general", "verbose", NULL) &&
  889. g_key_file_get_boolean(keyfile, "general", "verbose", &gerr)) {
  890. /* enable all log levels */
  891. config->log_level = G_LOG_LEVEL_MASK;
  892. }
  893. if (g_key_file_has_key(keyfile, "general", "retry-path", NULL)) {
  894. config->retry_path =
  895. g_key_file_get_boolean(keyfile, "general", "retry-path", &gerr);
  896. }
  897. if (g_key_file_has_key(keyfile, "general", "blacklist", NULL)) {
  898. g_warning("config using deprecated 'blacklist' key, should be replaced"
  899. " with the 'block-rpcs' key.");
  900. blockrpcs_key = "blacklist";
  901. }
  902. if (g_key_file_has_key(keyfile, "general", blockrpcs_key, NULL)) {
  903. config->bliststr =
  904. g_key_file_get_string(keyfile, "general", blockrpcs_key, &gerr);
  905. config->blockedrpcs = g_list_concat(config->blockedrpcs,
  906. split_list(config->bliststr, ","));
  907. }
  908. end:
  909. g_key_file_free(keyfile);
  910. if (gerr &&
  911. !(gerr->domain == G_FILE_ERROR && gerr->code == G_FILE_ERROR_NOENT)) {
  912. g_critical("error loading configuration from path: %s, %s",
  913. conf, gerr->message);
  914. exit(EXIT_FAILURE);
  915. }
  916. g_clear_error(&gerr);
  917. }
  918. static gchar *list_join(GList *list, const gchar separator)
  919. {
  920. GString *str = g_string_new("");
  921. while (list) {
  922. str = g_string_append(str, (gchar *)list->data);
  923. list = g_list_next(list);
  924. if (list) {
  925. str = g_string_append_c(str, separator);
  926. }
  927. }
  928. return g_string_free(str, FALSE);
  929. }
  930. static void config_dump(GAConfig *config)
  931. {
  932. GError *error = NULL;
  933. GKeyFile *keyfile;
  934. gchar *tmp;
  935. keyfile = g_key_file_new();
  936. g_assert(keyfile);
  937. g_key_file_set_boolean(keyfile, "general", "daemon", config->daemonize);
  938. g_key_file_set_string(keyfile, "general", "method", config->method);
  939. if (config->channel_path) {
  940. g_key_file_set_string(keyfile, "general", "path", config->channel_path);
  941. }
  942. if (config->log_filepath) {
  943. g_key_file_set_string(keyfile, "general", "logfile",
  944. config->log_filepath);
  945. }
  946. g_key_file_set_string(keyfile, "general", "pidfile", config->pid_filepath);
  947. #ifdef CONFIG_FSFREEZE
  948. if (config->fsfreeze_hook) {
  949. g_key_file_set_string(keyfile, "general", "fsfreeze-hook",
  950. config->fsfreeze_hook);
  951. }
  952. #endif
  953. g_key_file_set_string(keyfile, "general", "statedir", config->state_dir);
  954. g_key_file_set_boolean(keyfile, "general", "verbose",
  955. config->log_level == G_LOG_LEVEL_MASK);
  956. g_key_file_set_boolean(keyfile, "general", "retry-path",
  957. config->retry_path);
  958. tmp = list_join(config->blockedrpcs, ',');
  959. g_key_file_set_string(keyfile, "general", "block-rpcs", tmp);
  960. g_free(tmp);
  961. tmp = g_key_file_to_data(keyfile, NULL, &error);
  962. if (error) {
  963. g_critical("Failed to dump keyfile: %s", error->message);
  964. g_clear_error(&error);
  965. } else {
  966. printf("%s", tmp);
  967. }
  968. g_free(tmp);
  969. g_key_file_free(keyfile);
  970. }
  971. static void config_parse(GAConfig *config, int argc, char **argv)
  972. {
  973. const char *sopt = "hVvdm:p:l:f:F::b:s:t:Dr";
  974. int opt_ind = 0, ch;
  975. const struct option lopt[] = {
  976. { "help", 0, NULL, 'h' },
  977. { "version", 0, NULL, 'V' },
  978. { "dump-conf", 0, NULL, 'D' },
  979. { "logfile", 1, NULL, 'l' },
  980. { "pidfile", 1, NULL, 'f' },
  981. #ifdef CONFIG_FSFREEZE
  982. { "fsfreeze-hook", 2, NULL, 'F' },
  983. #endif
  984. { "verbose", 0, NULL, 'v' },
  985. { "method", 1, NULL, 'm' },
  986. { "path", 1, NULL, 'p' },
  987. { "daemonize", 0, NULL, 'd' },
  988. { "block-rpcs", 1, NULL, 'b' },
  989. { "blacklist", 1, NULL, 'b' }, /* deprecated alias for 'block-rpcs' */
  990. #ifdef _WIN32
  991. { "service", 1, NULL, 's' },
  992. #endif
  993. { "statedir", 1, NULL, 't' },
  994. { "retry-path", 0, NULL, 'r' },
  995. { NULL, 0, NULL, 0 }
  996. };
  997. while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
  998. switch (ch) {
  999. case 'm':
  1000. g_free(config->method);
  1001. config->method = g_strdup(optarg);
  1002. break;
  1003. case 'p':
  1004. g_free(config->channel_path);
  1005. config->channel_path = g_strdup(optarg);
  1006. break;
  1007. case 'l':
  1008. g_free(config->log_filepath);
  1009. config->log_filepath = g_strdup(optarg);
  1010. break;
  1011. case 'f':
  1012. g_free(config->pid_filepath);
  1013. config->pid_filepath = g_strdup(optarg);
  1014. break;
  1015. #ifdef CONFIG_FSFREEZE
  1016. case 'F':
  1017. g_free(config->fsfreeze_hook);
  1018. config->fsfreeze_hook = optarg ? g_strdup(optarg) : get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT);
  1019. break;
  1020. #endif
  1021. case 't':
  1022. g_free(config->state_dir);
  1023. config->state_dir = g_strdup(optarg);
  1024. break;
  1025. case 'v':
  1026. /* enable all log levels */
  1027. config->log_level = G_LOG_LEVEL_MASK;
  1028. break;
  1029. case 'V':
  1030. printf("QEMU Guest Agent %s\n", QEMU_VERSION);
  1031. exit(EXIT_SUCCESS);
  1032. case 'd':
  1033. config->daemonize = 1;
  1034. break;
  1035. case 'D':
  1036. config->dumpconf = 1;
  1037. break;
  1038. case 'r':
  1039. config->retry_path = true;
  1040. break;
  1041. case 'b': {
  1042. if (is_help_option(optarg)) {
  1043. qmp_for_each_command(&ga_commands, ga_print_cmd, NULL);
  1044. exit(EXIT_SUCCESS);
  1045. }
  1046. config->blockedrpcs = g_list_concat(config->blockedrpcs,
  1047. split_list(optarg, ","));
  1048. break;
  1049. }
  1050. #ifdef _WIN32
  1051. case 's':
  1052. config->service = optarg;
  1053. if (strcmp(config->service, "install") == 0) {
  1054. if (ga_install_vss_provider()) {
  1055. exit(EXIT_FAILURE);
  1056. }
  1057. if (ga_install_service(config->channel_path,
  1058. config->log_filepath, config->state_dir)) {
  1059. exit(EXIT_FAILURE);
  1060. }
  1061. exit(EXIT_SUCCESS);
  1062. } else if (strcmp(config->service, "uninstall") == 0) {
  1063. ga_uninstall_vss_provider();
  1064. exit(ga_uninstall_service());
  1065. } else if (strcmp(config->service, "vss-install") == 0) {
  1066. if (ga_install_vss_provider()) {
  1067. exit(EXIT_FAILURE);
  1068. }
  1069. exit(EXIT_SUCCESS);
  1070. } else if (strcmp(config->service, "vss-uninstall") == 0) {
  1071. ga_uninstall_vss_provider();
  1072. exit(EXIT_SUCCESS);
  1073. } else {
  1074. printf("Unknown service command.\n");
  1075. exit(EXIT_FAILURE);
  1076. }
  1077. break;
  1078. #endif
  1079. case 'h':
  1080. usage(argv[0]);
  1081. exit(EXIT_SUCCESS);
  1082. case '?':
  1083. g_print("Unknown option, try '%s --help' for more information.\n",
  1084. argv[0]);
  1085. exit(EXIT_FAILURE);
  1086. }
  1087. }
  1088. }
  1089. static void config_free(GAConfig *config)
  1090. {
  1091. g_free(config->method);
  1092. g_free(config->log_filepath);
  1093. g_free(config->pid_filepath);
  1094. g_free(config->state_dir);
  1095. g_free(config->channel_path);
  1096. g_free(config->bliststr);
  1097. #ifdef CONFIG_FSFREEZE
  1098. g_free(config->fsfreeze_hook);
  1099. #endif
  1100. g_list_free_full(config->blockedrpcs, g_free);
  1101. g_free(config);
  1102. }
  1103. static bool check_is_frozen(GAState *s)
  1104. {
  1105. #ifndef _WIN32
  1106. /* check if a previous instance of qemu-ga exited with filesystems' state
  1107. * marked as frozen. this could be a stale value (a non-qemu-ga process
  1108. * or reboot may have since unfrozen them), but better to require an
  1109. * uneeded unfreeze than to risk hanging on start-up
  1110. */
  1111. struct stat st;
  1112. if (stat(s->state_filepath_isfrozen, &st) == -1) {
  1113. /* it's okay if the file doesn't exist, but if we can't access for
  1114. * some other reason, such as permissions, there's a configuration
  1115. * that needs to be addressed. so just bail now before we get into
  1116. * more trouble later
  1117. */
  1118. if (errno != ENOENT) {
  1119. g_critical("unable to access state file at path %s: %s",
  1120. s->state_filepath_isfrozen, strerror(errno));
  1121. return EXIT_FAILURE;
  1122. }
  1123. } else {
  1124. g_warning("previous instance appears to have exited with frozen"
  1125. " filesystems. deferring logging/pidfile creation and"
  1126. " disabling non-fsfreeze-safe commands until"
  1127. " guest-fsfreeze-thaw is issued, or filesystems are"
  1128. " manually unfrozen and the file %s is removed",
  1129. s->state_filepath_isfrozen);
  1130. return true;
  1131. }
  1132. #endif
  1133. return false;
  1134. }
  1135. static GAState *initialize_agent(GAConfig *config, int socket_activation)
  1136. {
  1137. GAState *s = g_new0(GAState, 1);
  1138. g_assert(ga_state == NULL);
  1139. s->log_level = config->log_level;
  1140. s->log_file = stderr;
  1141. #ifdef CONFIG_FSFREEZE
  1142. s->fsfreeze_hook = config->fsfreeze_hook;
  1143. #endif
  1144. s->pstate_filepath = g_strdup_printf("%s/qga.state", config->state_dir);
  1145. s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
  1146. config->state_dir);
  1147. s->frozen = check_is_frozen(s);
  1148. g_log_set_default_handler(ga_log, s);
  1149. g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
  1150. ga_enable_logging(s);
  1151. g_debug("Guest agent version %s started", QEMU_FULL_VERSION);
  1152. #ifdef _WIN32
  1153. s->event_log = RegisterEventSource(NULL, "qemu-ga");
  1154. if (!s->event_log) {
  1155. g_autofree gchar *errmsg = g_win32_error_message(GetLastError());
  1156. g_critical("unable to register event source: %s", errmsg);
  1157. return NULL;
  1158. }
  1159. /* On win32 the state directory is application specific (be it the default
  1160. * or a user override). We got past the command line parsing; let's create
  1161. * the directory (with any intermediate directories). If we run into an
  1162. * error later on, we won't try to clean up the directory, it is considered
  1163. * persistent.
  1164. */
  1165. if (g_mkdir_with_parents(config->state_dir, S_IRWXU) == -1) {
  1166. g_critical("unable to create (an ancestor of) the state directory"
  1167. " '%s': %s", config->state_dir, strerror(errno));
  1168. return NULL;
  1169. }
  1170. #endif
  1171. if (ga_is_frozen(s)) {
  1172. if (config->daemonize) {
  1173. /* delay opening/locking of pidfile till filesystems are unfrozen */
  1174. s->deferred_options.pid_filepath = config->pid_filepath;
  1175. become_daemon(NULL);
  1176. }
  1177. if (config->log_filepath) {
  1178. /* delay opening the log file till filesystems are unfrozen */
  1179. s->deferred_options.log_filepath = config->log_filepath;
  1180. }
  1181. ga_disable_logging(s);
  1182. qmp_for_each_command(&ga_commands, ga_disable_not_allowed, NULL);
  1183. } else {
  1184. if (config->daemonize) {
  1185. become_daemon(config->pid_filepath);
  1186. }
  1187. if (config->log_filepath) {
  1188. FILE *log_file = ga_open_logfile(config->log_filepath);
  1189. if (!log_file) {
  1190. g_critical("unable to open specified log file: %s",
  1191. strerror(errno));
  1192. return NULL;
  1193. }
  1194. s->log_file = log_file;
  1195. }
  1196. }
  1197. /* load persistent state from disk */
  1198. if (!read_persistent_state(&s->pstate,
  1199. s->pstate_filepath,
  1200. ga_is_frozen(s))) {
  1201. g_critical("failed to load persistent state");
  1202. return NULL;
  1203. }
  1204. config->blockedrpcs = ga_command_init_blockedrpcs(config->blockedrpcs);
  1205. if (config->blockedrpcs) {
  1206. GList *l = config->blockedrpcs;
  1207. s->blockedrpcs = config->blockedrpcs;
  1208. do {
  1209. g_debug("disabling command: %s", (char *)l->data);
  1210. qmp_disable_command(&ga_commands, l->data, NULL);
  1211. l = g_list_next(l);
  1212. } while (l);
  1213. }
  1214. s->command_state = ga_command_state_new();
  1215. ga_command_state_init(s, s->command_state);
  1216. ga_command_state_init_all(s->command_state);
  1217. json_message_parser_init(&s->parser, process_event, s, NULL);
  1218. #ifndef _WIN32
  1219. if (!register_signal_handlers()) {
  1220. g_critical("failed to register signal handlers");
  1221. return NULL;
  1222. }
  1223. #endif
  1224. s->main_loop = g_main_loop_new(NULL, false);
  1225. s->config = config;
  1226. s->socket_activation = socket_activation;
  1227. #ifdef _WIN32
  1228. s->wakeup_event = CreateEvent(NULL, TRUE, FALSE, TEXT("WakeUp"));
  1229. if (s->wakeup_event == NULL) {
  1230. g_critical("CreateEvent failed");
  1231. return NULL;
  1232. }
  1233. #endif
  1234. ga_state = s;
  1235. return s;
  1236. }
  1237. static void cleanup_agent(GAState *s)
  1238. {
  1239. #ifdef _WIN32
  1240. CloseHandle(s->wakeup_event);
  1241. CloseHandle(s->event_log);
  1242. #endif
  1243. if (s->command_state) {
  1244. ga_command_state_cleanup_all(s->command_state);
  1245. ga_command_state_free(s->command_state);
  1246. json_message_parser_destroy(&s->parser);
  1247. }
  1248. g_free(s->pstate_filepath);
  1249. g_free(s->state_filepath_isfrozen);
  1250. if (s->main_loop) {
  1251. g_main_loop_unref(s->main_loop);
  1252. }
  1253. g_free(s);
  1254. ga_state = NULL;
  1255. }
  1256. static int run_agent_once(GAState *s)
  1257. {
  1258. if (!channel_init(s, s->config->method, s->config->channel_path,
  1259. s->socket_activation ? FIRST_SOCKET_ACTIVATION_FD : -1)) {
  1260. g_critical("failed to initialize guest agent channel");
  1261. return EXIT_FAILURE;
  1262. }
  1263. g_main_loop_run(ga_state->main_loop);
  1264. if (s->channel) {
  1265. ga_channel_free(s->channel);
  1266. }
  1267. return EXIT_SUCCESS;
  1268. }
  1269. static void wait_for_channel_availability(GAState *s)
  1270. {
  1271. g_warning("waiting for channel path...");
  1272. #ifndef _WIN32
  1273. sleep(QGA_RETRY_INTERVAL);
  1274. #else
  1275. DWORD dwWaitResult;
  1276. dwWaitResult = WaitForSingleObject(s->wakeup_event, INFINITE);
  1277. switch (dwWaitResult) {
  1278. case WAIT_OBJECT_0:
  1279. break;
  1280. case WAIT_TIMEOUT:
  1281. break;
  1282. default:
  1283. g_critical("WaitForSingleObject failed");
  1284. }
  1285. #endif
  1286. }
  1287. static int run_agent(GAState *s)
  1288. {
  1289. int ret = EXIT_SUCCESS;
  1290. s->force_exit = false;
  1291. do {
  1292. ret = run_agent_once(s);
  1293. if (s->config->retry_path && !s->force_exit) {
  1294. g_warning("agent stopped unexpectedly, restarting...");
  1295. wait_for_channel_availability(s);
  1296. }
  1297. } while (s->config->retry_path && !s->force_exit);
  1298. return ret;
  1299. }
  1300. static void stop_agent(GAState *s, bool requested)
  1301. {
  1302. if (!s->force_exit) {
  1303. s->force_exit = requested;
  1304. }
  1305. if (g_main_loop_is_running(s->main_loop)) {
  1306. g_main_loop_quit(s->main_loop);
  1307. }
  1308. }
  1309. int main(int argc, char **argv)
  1310. {
  1311. int ret = EXIT_SUCCESS;
  1312. GAState *s;
  1313. GAConfig *config = g_new0(GAConfig, 1);
  1314. int socket_activation;
  1315. config->log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
  1316. qemu_init_exec_dir(argv[0]);
  1317. qga_qmp_init_marshal(&ga_commands);
  1318. init_dfl_pathnames();
  1319. config_load(config);
  1320. config_parse(config, argc, argv);
  1321. if (config->pid_filepath == NULL) {
  1322. config->pid_filepath = g_strdup(dfl_pathnames.pidfile);
  1323. }
  1324. if (config->state_dir == NULL) {
  1325. config->state_dir = g_strdup(dfl_pathnames.state_dir);
  1326. }
  1327. if (config->method == NULL) {
  1328. config->method = g_strdup("virtio-serial");
  1329. }
  1330. socket_activation = check_socket_activation();
  1331. if (socket_activation > 1) {
  1332. g_critical("qemu-ga only supports listening on one socket");
  1333. ret = EXIT_FAILURE;
  1334. goto end;
  1335. }
  1336. if (socket_activation) {
  1337. SocketAddress *addr;
  1338. g_free(config->method);
  1339. g_free(config->channel_path);
  1340. config->method = NULL;
  1341. config->channel_path = NULL;
  1342. addr = socket_local_address(FIRST_SOCKET_ACTIVATION_FD, NULL);
  1343. if (addr) {
  1344. if (addr->type == SOCKET_ADDRESS_TYPE_UNIX) {
  1345. config->method = g_strdup("unix-listen");
  1346. } else if (addr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
  1347. config->method = g_strdup("vsock-listen");
  1348. }
  1349. qapi_free_SocketAddress(addr);
  1350. }
  1351. if (!config->method) {
  1352. g_critical("unsupported listen fd type");
  1353. ret = EXIT_FAILURE;
  1354. goto end;
  1355. }
  1356. } else if (config->channel_path == NULL) {
  1357. if (strcmp(config->method, "virtio-serial") == 0) {
  1358. /* try the default path for the virtio-serial port */
  1359. config->channel_path = g_strdup(QGA_VIRTIO_PATH_DEFAULT);
  1360. } else if (strcmp(config->method, "isa-serial") == 0) {
  1361. /* try the default path for the serial port - COM1 */
  1362. config->channel_path = g_strdup(QGA_SERIAL_PATH_DEFAULT);
  1363. } else {
  1364. g_critical("must specify a path for this channel");
  1365. ret = EXIT_FAILURE;
  1366. goto end;
  1367. }
  1368. }
  1369. if (config->dumpconf) {
  1370. config_dump(config);
  1371. goto end;
  1372. }
  1373. s = initialize_agent(config, socket_activation);
  1374. if (!s) {
  1375. g_critical("error initializing guest agent");
  1376. goto end;
  1377. }
  1378. #ifdef _WIN32
  1379. if (config->daemonize) {
  1380. SERVICE_TABLE_ENTRY service_table[] = {
  1381. { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
  1382. StartServiceCtrlDispatcher(service_table);
  1383. } else {
  1384. ret = run_agent(s);
  1385. }
  1386. #else
  1387. ret = run_agent(s);
  1388. #endif
  1389. cleanup_agent(s);
  1390. end:
  1391. if (config->daemonize) {
  1392. unlink(config->pid_filepath);
  1393. }
  1394. config_free(config);
  1395. return ret;
  1396. }