main.c 49 KB

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