Experimental IRC client, daemon and bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2046 lines
56KB

  1. /*
  2. * zyklonb.c: the experimental IRC bot
  3. *
  4. * Copyright (c) 2014 - 2016, Přemysl Janouch <p.janouch@gmail.com>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  13. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  15. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  16. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. *
  18. */
  19. #include "config.h"
  20. #define PROGRAM_NAME "ZyklonB"
  21. #define PLUGIN_DIR ZYKLONB_PLUGIN_DIR
  22. #include "common.c"
  23. // --- Configuration (application-specific) ------------------------------------
  24. static struct simple_config_item g_config_table[] =
  25. {
  26. { "nickname", "ZyklonB", "IRC nickname" },
  27. { "username", "bot", "IRC user name" },
  28. { "realname", "ZyklonB IRC bot", "IRC real name/e-mail" },
  29. { "irc_host", NULL, "Address of the IRC server" },
  30. { "irc_port", "6667", "Port of the IRC server" },
  31. { "tls", "off", "Whether to use TLS" },
  32. { "tls_cert", NULL, "Client TLS certificate (PEM)" },
  33. { "tls_verify", "on", "Whether to verify certificates" },
  34. { "tls_ca_file", NULL, "OpenSSL CA bundle file" },
  35. { "tls_ca_path", NULL, "OpenSSL CA bundle path" },
  36. { "autojoin", NULL, "Channels to join on start" },
  37. { "reconnect", "on", "Whether to reconnect on error" },
  38. { "reconnect_delay", "5", "Time between reconnecting" },
  39. { "socks_host", NULL, "Address of a SOCKS 4a/5 proxy" },
  40. { "socks_port", "1080", "SOCKS port number" },
  41. { "socks_username", NULL, "SOCKS auth. username" },
  42. { "socks_password", NULL, "SOCKS auth. password" },
  43. { "prefix", ":", "The prefix for bot commands" },
  44. { "admin", NULL, "Host mask for administrators" },
  45. { "plugins", NULL, "The plugins to load on startup" },
  46. { "plugin_dir", PLUGIN_DIR, "Where to search for plugins" },
  47. { "recover", "on", "Whether to re-launch on crash" },
  48. { NULL, NULL, NULL }
  49. };
  50. // --- Application data --------------------------------------------------------
  51. struct plugin
  52. {
  53. LIST_HEADER (struct plugin)
  54. struct bot_context *ctx; ///< Parent context
  55. char *name; ///< Plugin identifier
  56. pid_t pid; ///< PID of the plugin process
  57. bool is_zombie; ///< Whether the child is a zombie
  58. bool initialized; ///< Ready to exchange IRC messages
  59. struct str queued_output; ///< Output queued up until initialized
  60. // Since we're doing non-blocking I/O, we need to queue up data so that
  61. // we don't stall on plugins unnecessarily.
  62. int read_fd; ///< The read end of the comm. pipe
  63. int write_fd; ///< The write end of the comm. pipe
  64. struct poller_fd read_event; ///< Read FD event
  65. struct poller_fd write_event; ///< Write FD event
  66. struct str read_buffer; ///< Unprocessed input
  67. struct str write_buffer; ///< Output yet to be sent out
  68. };
  69. static struct plugin *
  70. plugin_new (void)
  71. {
  72. struct plugin *self = xcalloc (1, sizeof *self);
  73. self->pid = -1;
  74. self->queued_output = str_make ();
  75. self->read_fd = -1;
  76. self->read_buffer = str_make ();
  77. self->write_fd = -1;
  78. self->write_buffer = str_make ();
  79. return self;
  80. }
  81. static void
  82. plugin_destroy (struct plugin *self)
  83. {
  84. soft_assert (self->pid == -1);
  85. free (self->name);
  86. str_free (&self->read_buffer);
  87. if (!soft_assert (self->read_fd == -1))
  88. xclose (self->read_fd);
  89. str_free (&self->write_buffer);
  90. if (!soft_assert (self->write_fd == -1))
  91. xclose (self->write_fd);
  92. if (!self->initialized)
  93. str_free (&self->queued_output);
  94. free (self);
  95. }
  96. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  97. struct bot_context
  98. {
  99. struct str_map config; ///< User configuration
  100. regex_t *admin_re; ///< Regex to match our administrator
  101. bool reconnect; ///< Whether to reconnect on conn. fail.
  102. unsigned long reconnect_delay; ///< Reconnect delay in seconds
  103. int irc_fd; ///< Socket FD of the server
  104. struct str read_buffer; ///< Input yet to be processed
  105. struct poller_fd irc_event; ///< IRC FD event
  106. bool irc_registered; ///< Whether we may send messages now
  107. struct poller_fd signal_event; ///< Signal FD event
  108. struct poller_timer ping_tmr; ///< We should send a ping
  109. struct poller_timer timeout_tmr; ///< Connection seems to be dead
  110. struct poller_timer reconnect_tmr; ///< We should reconnect now
  111. SSL_CTX *ssl_ctx; ///< SSL context
  112. SSL *ssl; ///< SSL connection
  113. struct plugin *plugins; ///< Linked list of plugins
  114. struct str_map plugins_by_name; ///< Indexes @em plugins by their name
  115. struct poller poller; ///< Manages polled descriptors
  116. bool quitting; ///< User requested quitting
  117. bool polling; ///< The event loop is running
  118. };
  119. static void on_irc_ping_timeout (void *user_data);
  120. static void on_irc_timeout (void *user_data);
  121. static void on_irc_reconnect_timeout (void *user_data);
  122. static void
  123. bot_context_init (struct bot_context *self)
  124. {
  125. self->config = str_map_make (free);
  126. simple_config_load_defaults (&self->config, g_config_table);
  127. self->admin_re = NULL;
  128. self->irc_fd = -1;
  129. self->read_buffer = str_make ();
  130. self->irc_registered = false;
  131. self->ssl = NULL;
  132. self->ssl_ctx = NULL;
  133. self->plugins = NULL;
  134. self->plugins_by_name = str_map_make (NULL);
  135. poller_init (&self->poller);
  136. self->quitting = false;
  137. self->polling = false;
  138. self->timeout_tmr = poller_timer_make (&self->poller);
  139. self->timeout_tmr.dispatcher = on_irc_timeout;
  140. self->timeout_tmr.user_data = self;
  141. self->ping_tmr = poller_timer_make (&self->poller);
  142. self->ping_tmr.dispatcher = on_irc_ping_timeout;
  143. self->ping_tmr.user_data = self;
  144. self->reconnect_tmr = poller_timer_make (&self->poller);
  145. self->reconnect_tmr.dispatcher = on_irc_reconnect_timeout;
  146. self->reconnect_tmr.user_data = self;
  147. }
  148. static void
  149. bot_context_free (struct bot_context *self)
  150. {
  151. str_map_free (&self->config);
  152. if (self->admin_re)
  153. regex_free (self->admin_re);
  154. str_free (&self->read_buffer);
  155. // TODO: terminate the plugins properly before this is called
  156. LIST_FOR_EACH (struct plugin, link, self->plugins)
  157. plugin_destroy (link);
  158. if (self->irc_fd != -1)
  159. {
  160. poller_fd_reset (&self->irc_event);
  161. xclose (self->irc_fd);
  162. }
  163. if (self->ssl)
  164. SSL_free (self->ssl);
  165. if (self->ssl_ctx)
  166. SSL_CTX_free (self->ssl_ctx);
  167. str_map_free (&self->plugins_by_name);
  168. poller_free (&self->poller);
  169. }
  170. static void
  171. irc_shutdown (struct bot_context *ctx)
  172. {
  173. // TODO: set a timer after which we cut the connection?
  174. // Generally non-critical
  175. if (ctx->ssl)
  176. soft_assert (SSL_shutdown (ctx->ssl) != -1);
  177. else
  178. soft_assert (shutdown (ctx->irc_fd, SHUT_WR) == 0);
  179. }
  180. static void
  181. try_finish_quit (struct bot_context *ctx)
  182. {
  183. if (ctx->quitting && ctx->irc_fd == -1 && !ctx->plugins)
  184. ctx->polling = false;
  185. }
  186. static bool plugin_zombify (struct plugin *);
  187. static void
  188. initiate_quit (struct bot_context *ctx)
  189. {
  190. // Initiate bringing down of the two things that block our shutdown:
  191. // a/ the IRC socket, b/ our child processes:
  192. for (struct plugin *plugin = ctx->plugins;
  193. plugin; plugin = plugin->next)
  194. plugin_zombify (plugin);
  195. if (ctx->irc_fd != -1)
  196. irc_shutdown (ctx);
  197. ctx->quitting = true;
  198. try_finish_quit (ctx);
  199. }
  200. static bool irc_send (struct bot_context *ctx,
  201. const char *format, ...) ATTRIBUTE_PRINTF (2, 3);
  202. static bool
  203. irc_send (struct bot_context *ctx, const char *format, ...)
  204. {
  205. va_list ap;
  206. if (g_debug_mode)
  207. {
  208. fputs ("[IRC] <== \"", stderr);
  209. va_start (ap, format);
  210. vfprintf (stderr, format, ap);
  211. va_end (ap);
  212. fputs ("\"\n", stderr);
  213. }
  214. if (!soft_assert (ctx->irc_fd != -1))
  215. return false;
  216. va_start (ap, format);
  217. struct str str = str_make ();
  218. str_append_vprintf (&str, format, ap);
  219. str_append (&str, "\r\n");
  220. va_end (ap);
  221. bool result = true;
  222. if (ctx->ssl)
  223. {
  224. // TODO: call SSL_get_error() to detect if a clean shutdown has occured
  225. ERR_clear_error ();
  226. if (SSL_write (ctx->ssl, str.str, str.len) != (int) str.len)
  227. {
  228. print_debug ("%s: %s: %s", __func__, "SSL_write",
  229. ERR_error_string (ERR_get_error (), NULL));
  230. result = false;
  231. }
  232. }
  233. else if (write (ctx->irc_fd, str.str, str.len) != (ssize_t) str.len)
  234. {
  235. print_debug ("%s: %s: %s", __func__, "write", strerror (errno));
  236. result = false;
  237. }
  238. str_free (&str);
  239. return result;
  240. }
  241. static bool
  242. irc_get_boolean_from_config
  243. (struct bot_context *ctx, const char *name, bool *value, struct error **e)
  244. {
  245. const char *str = str_map_find (&ctx->config, name);
  246. hard_assert (str != NULL);
  247. if (set_boolean_if_valid (value, str))
  248. return true;
  249. return error_set (e, "invalid configuration value for `%s'", name);
  250. }
  251. static bool
  252. irc_initialize_ca_set (SSL_CTX *ssl_ctx, const char *file, const char *path,
  253. struct error **e)
  254. {
  255. ERR_clear_error ();
  256. if (file || path)
  257. {
  258. if (SSL_CTX_load_verify_locations (ssl_ctx, file, path))
  259. return true;
  260. return error_set (e, "%s: %s",
  261. "failed to set locations for the CA certificate bundle",
  262. ERR_reason_error_string (ERR_get_error ()));
  263. }
  264. if (!SSL_CTX_set_default_verify_paths (ssl_ctx))
  265. return error_set (e, "%s: %s",
  266. "couldn't load the default CA certificate bundle",
  267. ERR_reason_error_string (ERR_get_error ()));
  268. return true;
  269. }
  270. static bool
  271. irc_initialize_ca (struct bot_context *ctx, struct error **e)
  272. {
  273. const char *ca_file = str_map_find (&ctx->config, "tls_ca_file");
  274. const char *ca_path = str_map_find (&ctx->config, "tls_ca_path");
  275. char *full_file = ca_file
  276. ? resolve_filename (ca_file, resolve_relative_config_filename) : NULL;
  277. char *full_path = ca_path
  278. ? resolve_filename (ca_path, resolve_relative_config_filename) : NULL;
  279. bool ok = false;
  280. if (ca_file && !full_file)
  281. error_set (e, "couldn't find the CA bundle file");
  282. else if (ca_path && !full_path)
  283. error_set (e, "couldn't find the CA bundle path");
  284. else
  285. ok = irc_initialize_ca_set (ctx->ssl_ctx, full_file, full_path, e);
  286. free (full_file);
  287. free (full_path);
  288. return ok;
  289. }
  290. static bool
  291. irc_initialize_ssl_ctx (struct bot_context *ctx, struct error **e)
  292. {
  293. // Disable deprecated protocols (see RFC 7568)
  294. SSL_CTX_set_options (ctx->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
  295. bool verify;
  296. if (!irc_get_boolean_from_config (ctx, "tls_verify", &verify, e))
  297. return false;
  298. SSL_CTX_set_verify (ctx->ssl_ctx,
  299. verify ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
  300. struct error *error = NULL;
  301. if (!irc_initialize_ca (ctx, &error))
  302. {
  303. if (verify)
  304. {
  305. error_propagate (e, error);
  306. return false;
  307. }
  308. // Only inform the user if we're not actually verifying
  309. print_warning ("%s", error->message);
  310. error_free (error);
  311. }
  312. return true;
  313. }
  314. static bool
  315. irc_initialize_tls (struct bot_context *ctx, struct error **e)
  316. {
  317. const char *error_info = NULL;
  318. ctx->ssl_ctx = SSL_CTX_new (SSLv23_client_method ());
  319. if (!ctx->ssl_ctx)
  320. goto error_ssl_1;
  321. if (!irc_initialize_ssl_ctx (ctx, e))
  322. goto error_ssl_2;
  323. ctx->ssl = SSL_new (ctx->ssl_ctx);
  324. if (!ctx->ssl)
  325. goto error_ssl_2;
  326. const char *tls_cert = str_map_find (&ctx->config, "tls_cert");
  327. if (tls_cert)
  328. {
  329. char *path = resolve_filename
  330. (tls_cert, resolve_relative_config_filename);
  331. if (!path)
  332. print_error ("%s: %s", "cannot open file", tls_cert);
  333. // XXX: perhaps we should read the file ourselves for better messages
  334. else if (!SSL_use_certificate_file (ctx->ssl, path, SSL_FILETYPE_PEM)
  335. || !SSL_use_PrivateKey_file (ctx->ssl, path, SSL_FILETYPE_PEM))
  336. print_error ("%s: %s", "setting the TLS client certificate failed",
  337. ERR_error_string (ERR_get_error (), NULL));
  338. free (path);
  339. }
  340. SSL_set_connect_state (ctx->ssl);
  341. if (!SSL_set_fd (ctx->ssl, ctx->irc_fd))
  342. goto error_ssl_3;
  343. // Avoid SSL_write() returning SSL_ERROR_WANT_READ
  344. SSL_set_mode (ctx->ssl, SSL_MODE_AUTO_RETRY);
  345. switch (xssl_get_error (ctx->ssl, SSL_connect (ctx->ssl), &error_info))
  346. {
  347. case SSL_ERROR_NONE:
  348. return true;
  349. case SSL_ERROR_ZERO_RETURN:
  350. error_info = "server closed the connection";
  351. default:
  352. break;
  353. }
  354. error_ssl_3:
  355. SSL_free (ctx->ssl);
  356. ctx->ssl = NULL;
  357. error_ssl_2:
  358. SSL_CTX_free (ctx->ssl_ctx);
  359. ctx->ssl_ctx = NULL;
  360. error_ssl_1:
  361. // XXX: these error strings are really nasty; also there could be
  362. // multiple errors on the OpenSSL stack.
  363. if (!error_info)
  364. error_info = ERR_error_string (ERR_get_error (), NULL);
  365. return error_set (e, "%s: %s", "could not initialize TLS", error_info);
  366. }
  367. static bool
  368. irc_establish_connection (struct bot_context *ctx,
  369. const char *host, const char *port, struct error **e)
  370. {
  371. struct addrinfo gai_hints, *gai_result, *gai_iter;
  372. memset (&gai_hints, 0, sizeof gai_hints);
  373. gai_hints.ai_socktype = SOCK_STREAM;
  374. int err = getaddrinfo (host, port, &gai_hints, &gai_result);
  375. if (err)
  376. return error_set (e, "%s: %s: %s", "connection failed",
  377. "getaddrinfo", gai_strerror (err));
  378. int sockfd;
  379. for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next)
  380. {
  381. sockfd = socket (gai_iter->ai_family,
  382. gai_iter->ai_socktype, gai_iter->ai_protocol);
  383. if (sockfd == -1)
  384. continue;
  385. set_cloexec (sockfd);
  386. int yes = 1;
  387. soft_assert (setsockopt (sockfd, SOL_SOCKET, SO_KEEPALIVE,
  388. &yes, sizeof yes) != -1);
  389. const char *real_host = host;
  390. // Let's try to resolve the address back into a real hostname;
  391. // we don't really need this, so we can let it quietly fail
  392. char buf[NI_MAXHOST];
  393. err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
  394. buf, sizeof buf, NULL, 0, 0);
  395. if (err)
  396. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  397. else
  398. real_host = buf;
  399. // XXX: we shouldn't mix these statuses with `struct error'; choose 1!
  400. char *address = format_host_port_pair (real_host, port);
  401. print_status ("connecting to %s...", address);
  402. free (address);
  403. if (!connect (sockfd, gai_iter->ai_addr, gai_iter->ai_addrlen))
  404. break;
  405. xclose (sockfd);
  406. }
  407. freeaddrinfo (gai_result);
  408. if (!gai_iter)
  409. return error_set (e, "connection failed");
  410. ctx->irc_fd = sockfd;
  411. return true;
  412. }
  413. // --- Signals -----------------------------------------------------------------
  414. static int g_signal_pipe[2]; ///< A pipe used to signal... signals
  415. static struct strv
  416. g_original_argv, ///< Original program arguments
  417. g_recovery_env; ///< Environment for re-exec recovery
  418. /// Program termination has been requested by a signal
  419. static volatile sig_atomic_t g_termination_requested;
  420. /// Points to startup reason location within `g_recovery_environment'
  421. static char **g_startup_reason_location;
  422. /// The environment variable used to pass the startup reason when re-executing
  423. static const char g_startup_reason_str[] = "STARTUP_REASON";
  424. static void
  425. sigchld_handler (int signum)
  426. {
  427. (void) signum;
  428. int original_errno = errno;
  429. // Just so that the read end of the pipe wakes up the poller.
  430. // NOTE: Linux has signalfd() and eventfd(), and the BSD's have kqueue.
  431. // All of them are better than this approach, although platform-specific.
  432. if (write (g_signal_pipe[1], "c", 1) == -1)
  433. soft_assert (errno == EAGAIN);
  434. errno = original_errno;
  435. }
  436. static void
  437. sigterm_handler (int signum)
  438. {
  439. (void) signum;
  440. g_termination_requested = true;
  441. int original_errno = errno;
  442. if (write (g_signal_pipe[1], "t", 1) == -1)
  443. soft_assert (errno == EAGAIN);
  444. errno = original_errno;
  445. }
  446. static void
  447. setup_signal_handlers (void)
  448. {
  449. if (pipe (g_signal_pipe) == -1)
  450. exit_fatal ("%s: %s", "pipe", strerror (errno));
  451. set_cloexec (g_signal_pipe[0]);
  452. set_cloexec (g_signal_pipe[1]);
  453. // So that the pipe cannot overflow; it would make write() block within
  454. // the signal handler, which is something we really don't want to happen.
  455. // The same holds true for read().
  456. set_blocking (g_signal_pipe[0], false);
  457. set_blocking (g_signal_pipe[1], false);
  458. struct sigaction sa;
  459. sa.sa_flags = SA_RESTART;
  460. sa.sa_handler = sigchld_handler;
  461. sigemptyset (&sa.sa_mask);
  462. if (sigaction (SIGCHLD, &sa, NULL) == -1)
  463. exit_fatal ("sigaction: %s", strerror (errno));
  464. signal (SIGPIPE, SIG_IGN);
  465. sa.sa_handler = sigterm_handler;
  466. if (sigaction (SIGINT, &sa, NULL) == -1
  467. || sigaction (SIGTERM, &sa, NULL) == -1)
  468. exit_fatal ("sigaction: %s", strerror (errno));
  469. }
  470. static void
  471. translate_signal_info (int no, const char **name, int code, const char **reason)
  472. {
  473. if (code == SI_USER) *reason = "signal sent by kill()";
  474. if (code == SI_QUEUE) *reason = "signal sent by sigqueue()";
  475. switch (no)
  476. {
  477. case SIGILL:
  478. *name = "SIGILL";
  479. if (code == ILL_ILLOPC) *reason = "illegal opcode";
  480. if (code == ILL_ILLOPN) *reason = "illegal operand";
  481. if (code == ILL_ILLADR) *reason = "illegal addressing mode";
  482. if (code == ILL_ILLTRP) *reason = "illegal trap";
  483. if (code == ILL_PRVOPC) *reason = "privileged opcode";
  484. if (code == ILL_PRVREG) *reason = "privileged register";
  485. if (code == ILL_COPROC) *reason = "coprocessor error";
  486. if (code == ILL_BADSTK) *reason = "internal stack error";
  487. break;
  488. case SIGFPE:
  489. *name = "SIGFPE";
  490. if (code == FPE_INTDIV) *reason = "integer divide by zero";
  491. if (code == FPE_INTOVF) *reason = "integer overflow";
  492. if (code == FPE_FLTDIV) *reason = "floating-point divide by zero";
  493. if (code == FPE_FLTOVF) *reason = "floating-point overflow";
  494. if (code == FPE_FLTUND) *reason = "floating-point underflow";
  495. if (code == FPE_FLTRES) *reason = "floating-point inexact result";
  496. if (code == FPE_FLTINV) *reason = "invalid floating-point operation";
  497. if (code == FPE_FLTSUB) *reason = "subscript out of range";
  498. break;
  499. case SIGSEGV:
  500. *name = "SIGSEGV";
  501. if (code == SEGV_MAPERR)
  502. *reason = "address not mapped to object";
  503. if (code == SEGV_ACCERR)
  504. *reason = "invalid permissions for mapped object";
  505. break;
  506. case SIGBUS:
  507. *name = "SIGBUS";
  508. if (code == BUS_ADRALN) *reason = "invalid address alignment";
  509. if (code == BUS_ADRERR) *reason = "nonexistent physical address";
  510. if (code == BUS_OBJERR) *reason = "object-specific hardware error";
  511. break;
  512. default:
  513. *name = NULL;
  514. }
  515. }
  516. static void
  517. recovery_handler (int signum, siginfo_t *info, void *context)
  518. {
  519. (void) context;
  520. // TODO: maybe try to force a core dump like this: if (fork() == 0) return;
  521. // TODO: maybe we could even send "\r\nQUIT :reason\r\n" to the server. >_>
  522. // As long as we're not connected via TLS, that is.
  523. const char *signal_name = NULL, *reason = NULL;
  524. translate_signal_info (signum, &signal_name, info->si_code, &reason);
  525. char buf[128], numbuf[8];
  526. if (!signal_name)
  527. {
  528. snprintf (numbuf, sizeof numbuf, "%d", signum);
  529. signal_name = numbuf;
  530. }
  531. if (reason)
  532. snprintf (buf, sizeof buf, "%s=%s: %s: %s", g_startup_reason_str,
  533. "signal received", signal_name, reason);
  534. else
  535. snprintf (buf, sizeof buf, "%s=%s: %s", g_startup_reason_str,
  536. "signal received", signal_name);
  537. *g_startup_reason_location = buf;
  538. // Avoid annoying resource intensive infinite loops by sleeping for a bit
  539. (void) sleep (1);
  540. // TODO: maybe pregenerate the path, see the following for some other ways
  541. // that would be illegal to do from within a signal handler:
  542. // http://stackoverflow.com/a/1024937
  543. // http://stackoverflow.com/q/799679
  544. // Especially if we change the current working directory in the program.
  545. //
  546. // Note that I can just overwrite g_orig_argv[0].
  547. // NOTE: our children will read EOF on the read ends of their pipes as a
  548. // a result of O_CLOEXEC. That should be enough to make them terminate.
  549. char **argv = g_original_argv.vector, **argp = g_recovery_env.vector;
  550. execve ("/proc/self/exe", argv, argp); // Linux
  551. execve ("/proc/curproc/file", argv, argp); // BSD
  552. execve ("/proc/curproc/exe", argv, argp); // BSD
  553. execve ("/proc/self/path/a.out", argv, argp); // Solaris
  554. execve (argv[0], argv, argp); // unreliable fallback
  555. // Let's just crash
  556. perror ("execve");
  557. signal (signum, SIG_DFL);
  558. raise (signum);
  559. }
  560. static void
  561. prepare_recovery_environment (void)
  562. {
  563. g_recovery_env = strv_make ();
  564. strv_append_vector (&g_recovery_env, environ);
  565. // Prepare a location within the environment where we will put the startup
  566. // (or maybe rather restart) reason in case of an irrecoverable error.
  567. char **iter;
  568. for (iter = g_recovery_env.vector; *iter; iter++)
  569. {
  570. const size_t len = sizeof g_startup_reason_str - 1;
  571. if (!strncmp (*iter, g_startup_reason_str, len) && (*iter)[len] == '=')
  572. break;
  573. }
  574. if (*iter)
  575. g_startup_reason_location = iter;
  576. else
  577. {
  578. g_startup_reason_location = g_recovery_env.vector + g_recovery_env.len;
  579. strv_append (&g_recovery_env, "");
  580. }
  581. }
  582. static bool
  583. setup_recovery_handler (struct bot_context *ctx, struct error **e)
  584. {
  585. bool recover;
  586. if (!irc_get_boolean_from_config (ctx, "recover", &recover, e))
  587. return false;
  588. if (!recover)
  589. return true;
  590. // Make sure these signals aren't blocked, otherwise we would be unable
  591. // to handle them, making the critical conditions fatal.
  592. sigset_t mask;
  593. sigemptyset (&mask);
  594. sigaddset (&mask, SIGSEGV);
  595. sigaddset (&mask, SIGBUS);
  596. sigaddset (&mask, SIGFPE);
  597. sigaddset (&mask, SIGILL);
  598. sigprocmask (SIG_UNBLOCK, &mask, NULL);
  599. struct sigaction sa;
  600. sa.sa_flags = SA_SIGINFO;
  601. sa.sa_sigaction = recovery_handler;
  602. sigemptyset (&sa.sa_mask);
  603. prepare_recovery_environment ();
  604. // TODO: also handle SIGABRT... or avoid doing abort() in the first place?
  605. if (sigaction (SIGSEGV, &sa, NULL) == -1
  606. || sigaction (SIGBUS, &sa, NULL) == -1
  607. || sigaction (SIGFPE, &sa, NULL) == -1
  608. || sigaction (SIGILL, &sa, NULL) == -1)
  609. print_error ("sigaction: %s", strerror (errno));
  610. return true;
  611. }
  612. // --- Plugins -----------------------------------------------------------------
  613. /// The name of the special IRC command for interprocess communication
  614. static const char *plugin_ipc_command = "ZYKLONB";
  615. static struct plugin *
  616. plugin_find_by_pid (struct bot_context *ctx, pid_t pid)
  617. {
  618. struct plugin *iter;
  619. for (iter = ctx->plugins; iter; iter = iter->next)
  620. if (iter->pid == pid)
  621. return iter;
  622. return NULL;
  623. }
  624. static bool
  625. plugin_zombify (struct plugin *plugin)
  626. {
  627. if (plugin->is_zombie)
  628. return false;
  629. // FIXME: make sure that we don't remove entries from the poller while we
  630. // still may have stuff to read; maybe just check that the read pipe is
  631. // empty before closing it... and then on EOF check if `pid == -1' and
  632. // only then dispose of it (it'd be best to simulate that both of these
  633. // cases may happen).
  634. poller_fd_reset (&plugin->write_event);
  635. // TODO: try to flush the write buffer (non-blocking)?
  636. // The plugin should terminate itself after it receives EOF.
  637. xclose (plugin->write_fd);
  638. plugin->write_fd = -1;
  639. // Make it a pseudo-anonymous zombie. In this state we process any
  640. // remaining commands it attempts to send to us before it finally dies.
  641. str_map_set (&plugin->ctx->plugins_by_name, plugin->name, NULL);
  642. plugin->is_zombie = true;
  643. // TODO: wait a few seconds and then send SIGKILL to the plugin
  644. return true;
  645. }
  646. static void
  647. on_plugin_writable (const struct pollfd *fd, struct plugin *plugin)
  648. {
  649. struct str *buf = &plugin->write_buffer;
  650. size_t written_total = 0;
  651. if (fd->revents & ~(POLLOUT | POLLHUP | POLLERR))
  652. print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);
  653. while (written_total != buf->len)
  654. {
  655. ssize_t n_written = write (fd->fd, buf->str + written_total,
  656. buf->len - written_total);
  657. if (n_written < 0)
  658. {
  659. if (errno == EAGAIN)
  660. break;
  661. if (errno == EINTR)
  662. continue;
  663. soft_assert (errno == EPIPE);
  664. // Zombies shouldn't get dispatched for writability
  665. hard_assert (!plugin->is_zombie);
  666. print_debug ("%s: %s", "write", strerror (errno));
  667. print_error ("failure on writing to plugin `%s',"
  668. " therefore I'm unloading it", plugin->name);
  669. plugin_zombify (plugin);
  670. break;
  671. }
  672. // This may be equivalent to EAGAIN on some implementations
  673. if (n_written == 0)
  674. break;
  675. written_total += n_written;
  676. }
  677. if (written_total != 0)
  678. str_remove_slice (buf, 0, written_total);
  679. if (buf->len == 0)
  680. // Everything has been written, there's no need to end up in here again
  681. poller_fd_reset (&plugin->write_event);
  682. }
  683. static void
  684. plugin_queue_write (struct plugin *plugin)
  685. {
  686. if (plugin->is_zombie)
  687. return;
  688. // Don't let the write buffer grow indefinitely. If there's a ton of data
  689. // waiting to be processed by the plugin, it usually means there's something
  690. // wrong with it (such as someone stopping the process).
  691. if (plugin->write_buffer.len >= (1 << 20))
  692. {
  693. print_warning ("plugin `%s' does not seem to process messages fast"
  694. " enough, I'm unloading it", plugin->name);
  695. plugin_zombify (plugin);
  696. return;
  697. }
  698. poller_fd_set (&plugin->write_event, POLLOUT);
  699. }
  700. static void
  701. plugin_send (struct plugin *plugin, const char *format, ...)
  702. ATTRIBUTE_PRINTF (2, 3);
  703. static void
  704. plugin_send (struct plugin *plugin, const char *format, ...)
  705. {
  706. va_list ap;
  707. if (g_debug_mode)
  708. {
  709. fprintf (stderr, "[%s] <-- \"", plugin->name);
  710. va_start (ap, format);
  711. vfprintf (stderr, format, ap);
  712. va_end (ap);
  713. fputs ("\"\n", stderr);
  714. }
  715. va_start (ap, format);
  716. str_append_vprintf (&plugin->write_buffer, format, ap);
  717. va_end (ap);
  718. str_append (&plugin->write_buffer, "\r\n");
  719. plugin_queue_write (plugin);
  720. }
  721. static void
  722. plugin_process_ipc (struct plugin *plugin, const struct irc_message *msg)
  723. {
  724. // Replies are sent in the order in which they came in, so there's
  725. // no need to attach a special identifier to them. It might be
  726. // desirable in some cases, though.
  727. if (msg->params.len < 1)
  728. return;
  729. const char *command = msg->params.vector[0];
  730. if (!plugin->initialized && !strcasecmp (command, "register"))
  731. {
  732. // Register for relaying of IRC traffic
  733. plugin->initialized = true;
  734. // Flush any queued up traffic here. The point of queuing it in
  735. // the first place is so that we don't have to wait for plugin
  736. // initialization during startup.
  737. //
  738. // Note that if we start filtering data coming to the plugins e.g.
  739. // based on what it tells us upon registration, we might need to
  740. // filter `queued_output' as well.
  741. str_append_str (&plugin->write_buffer, &plugin->queued_output);
  742. str_free (&plugin->queued_output);
  743. // NOTE: this may trigger the buffer length check
  744. plugin_queue_write (plugin);
  745. }
  746. else if (!strcasecmp (command, "get_config"))
  747. {
  748. if (msg->params.len < 2)
  749. return;
  750. const char *value =
  751. str_map_find (&plugin->ctx->config, msg->params.vector[1]);
  752. // TODO: escape the value (although there's no need to ATM)
  753. plugin_send (plugin, "%s :%s",
  754. plugin_ipc_command, value ? value : "");
  755. }
  756. else if (!strcasecmp (command, "print"))
  757. {
  758. if (msg->params.len < 2)
  759. return;
  760. printf ("%s\n", msg->params.vector[1]);
  761. }
  762. }
  763. static void
  764. plugin_process_message (const struct irc_message *msg,
  765. const char *raw, void *user_data)
  766. {
  767. struct plugin *plugin = user_data;
  768. struct bot_context *ctx = plugin->ctx;
  769. if (g_debug_mode)
  770. fprintf (stderr, "[%s] --> \"%s\"\n", plugin->name, raw);
  771. if (!strcasecmp (msg->command, plugin_ipc_command))
  772. plugin_process_ipc (plugin, msg);
  773. else if (plugin->initialized && ctx->irc_registered)
  774. {
  775. // Pass everything else through to the IRC server
  776. // XXX: when the server isn't ready yet, these messages get silently
  777. // discarded, which shouldn't pose a problem most of the time.
  778. // Perhaps we could send a "connected" notification on `register'
  779. // if `irc_ready' is true, or after it becomes true later, so that
  780. // plugins know when to start sending unprovoked IRC messages.
  781. // XXX: another case is when the connection gets interrupted and the
  782. // plugin tries to send something back while we're reconnecting.
  783. // For that we might set up a global buffer that gets flushed out
  784. // after `irc_ready' becomes true. Note that there is always some
  785. // chance of messages getting lost without us even noticing it.
  786. irc_send (ctx, "%s", raw);
  787. }
  788. }
  789. static void
  790. on_plugin_readable (const struct pollfd *fd, struct plugin *plugin)
  791. {
  792. if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
  793. print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);
  794. // TODO: see if I can reuse irc_fill_read_buffer()
  795. struct str *buf = &plugin->read_buffer;
  796. while (true)
  797. {
  798. str_reserve (buf, 512 + 1);
  799. ssize_t n_read = read (fd->fd, buf->str + buf->len,
  800. buf->alloc - buf->len - 1);
  801. if (n_read < 0)
  802. {
  803. if (errno == EAGAIN)
  804. break;
  805. if (soft_assert (errno == EINTR))
  806. continue;
  807. if (!plugin->is_zombie)
  808. {
  809. print_error ("failure on reading from plugin `%s',"
  810. " therefore I'm unloading it", plugin->name);
  811. plugin_zombify (plugin);
  812. }
  813. return;
  814. }
  815. // EOF; hopefully it will die soon (maybe it already has)
  816. if (n_read == 0)
  817. break;
  818. buf->str[buf->len += n_read] = '\0';
  819. if (buf->len >= (1 << 20))
  820. {
  821. // XXX: this isn't really the best flood prevention mechanism,
  822. // but it wasn't even supposed to be one.
  823. if (plugin->is_zombie)
  824. {
  825. print_error ("a zombie of plugin `%s' is trying to flood us,"
  826. " therefore I'm killing it", plugin->name);
  827. kill (plugin->pid, SIGKILL);
  828. }
  829. else
  830. {
  831. print_error ("plugin `%s' seems to spew out data frantically,"
  832. " therefore I'm unloading it", plugin->name);
  833. plugin_zombify (plugin);
  834. }
  835. return;
  836. }
  837. }
  838. irc_process_buffer (buf, plugin_process_message, plugin);
  839. }
  840. static bool
  841. is_valid_plugin_name (const char *name)
  842. {
  843. if (!*name)
  844. return false;
  845. for (const char *p = name; *p; p++)
  846. if (!isgraph (*p) || *p == '/')
  847. return false;
  848. return true;
  849. }
  850. static struct plugin *
  851. plugin_launch (struct bot_context *ctx, const char *name, struct error **e)
  852. {
  853. const char *plugin_dir = str_map_find (&ctx->config, "plugin_dir");
  854. if (!plugin_dir)
  855. {
  856. error_set (e, "plugin directory not set");
  857. return NULL;
  858. }
  859. int stdin_pipe[2];
  860. if (pipe (stdin_pipe) == -1)
  861. {
  862. error_set (e, "%s: %s", "pipe", strerror (errno));
  863. return NULL;
  864. }
  865. int stdout_pipe[2];
  866. if (pipe (stdout_pipe) == -1)
  867. {
  868. error_set (e, "%s: %s", "pipe", strerror (errno));
  869. goto fail_1;
  870. }
  871. struct str work_dir = str_make ();
  872. get_xdg_home_dir (&work_dir, "XDG_DATA_HOME", ".local/share");
  873. str_append_printf (&work_dir, "/%s", PROGRAM_NAME);
  874. if (!mkdir_with_parents (work_dir.str, e))
  875. goto fail_2;
  876. set_cloexec (stdin_pipe[1]);
  877. set_cloexec (stdout_pipe[0]);
  878. pid_t pid = fork ();
  879. if (pid == -1)
  880. {
  881. error_set (e, "%s: %s", "fork", strerror (errno));
  882. goto fail_2;
  883. }
  884. if (pid == 0)
  885. {
  886. // Redirect the child's stdin and stdout to the pipes
  887. if (dup2 (stdin_pipe[0], STDIN_FILENO) == -1
  888. || dup2 (stdout_pipe[1], STDOUT_FILENO) == -1)
  889. {
  890. print_error ("%s: %s: %s", "failed to load the plugin",
  891. "dup2", strerror (errno));
  892. _exit (EXIT_FAILURE);
  893. }
  894. if (chdir (work_dir.str))
  895. {
  896. print_error ("%s: %s: %s", "failed to load the plugin",
  897. "chdir", strerror (errno));
  898. _exit (EXIT_FAILURE);
  899. }
  900. xclose (stdin_pipe[0]);
  901. xclose (stdout_pipe[1]);
  902. // Restore some of the signal handling
  903. signal (SIGPIPE, SIG_DFL);
  904. char *argv[] = { xstrdup_printf ("%s/%s", plugin_dir, name), NULL };
  905. execve (argv[0], argv, environ);
  906. // We will collect the failure later via SIGCHLD
  907. print_error ("%s: %s: %s", "failed to load the plugin",
  908. "exec", strerror (errno));
  909. _exit (EXIT_FAILURE);
  910. }
  911. str_free (&work_dir);
  912. xclose (stdin_pipe[0]);
  913. xclose (stdout_pipe[1]);
  914. struct plugin *plugin = plugin_new ();
  915. plugin->ctx = ctx;
  916. plugin->pid = pid;
  917. plugin->name = xstrdup (name);
  918. plugin->read_fd = stdout_pipe[0];
  919. plugin->write_fd = stdin_pipe[1];
  920. return plugin;
  921. fail_2:
  922. str_free (&work_dir);
  923. xclose (stdout_pipe[0]);
  924. xclose (stdout_pipe[1]);
  925. fail_1:
  926. xclose (stdin_pipe[0]);
  927. xclose (stdin_pipe[1]);
  928. return NULL;
  929. }
  930. static bool
  931. plugin_load (struct bot_context *ctx, const char *name, struct error **e)
  932. {
  933. if (!is_valid_plugin_name (name))
  934. return error_set (e, "invalid plugin name");
  935. if (str_map_find (&ctx->plugins_by_name, name))
  936. return error_set (e, "the plugin has already been loaded");
  937. struct plugin *plugin;
  938. if (!(plugin = plugin_launch (ctx, name, e)))
  939. return false;
  940. set_blocking (plugin->read_fd, false);
  941. set_blocking (plugin->write_fd, false);
  942. plugin->read_event = poller_fd_make (&ctx->poller, plugin->read_fd);
  943. plugin->read_event.dispatcher = (poller_fd_fn) on_plugin_readable;
  944. plugin->read_event.user_data = plugin;
  945. plugin->write_event = poller_fd_make (&ctx->poller, plugin->write_fd);
  946. plugin->write_event.dispatcher = (poller_fd_fn) on_plugin_writable;
  947. plugin->write_event.user_data = plugin;
  948. LIST_PREPEND (ctx->plugins, plugin);
  949. str_map_set (&ctx->plugins_by_name, name, plugin);
  950. poller_fd_set (&plugin->read_event, POLLIN);
  951. return true;
  952. }
  953. static bool
  954. plugin_unload (struct bot_context *ctx, const char *name, struct error **e)
  955. {
  956. struct plugin *plugin = str_map_find (&ctx->plugins_by_name, name);
  957. if (!plugin)
  958. return error_set (e, "no such plugin is loaded");
  959. plugin_zombify (plugin);
  960. // TODO: add a `kill zombies' command to forcefully get rid of processes
  961. // that do not understand the request.
  962. return true;
  963. }
  964. static void
  965. plugin_load_all_from_config (struct bot_context *ctx)
  966. {
  967. const char *plugin_list = str_map_find (&ctx->config, "plugins");
  968. if (!plugin_list)
  969. return;
  970. struct strv plugins = strv_make ();
  971. cstr_split (plugin_list, ",", true, &plugins);
  972. for (size_t i = 0; i < plugins.len; i++)
  973. {
  974. char *name = cstr_strip_in_place (plugins.vector[i], " ");
  975. struct error *e = NULL;
  976. if (!plugin_load (ctx, name, &e))
  977. {
  978. print_error ("plugin `%s' failed to load: %s", name, e->message);
  979. error_free (e);
  980. }
  981. }
  982. strv_free (&plugins);
  983. }
  984. // --- Main program ------------------------------------------------------------
  985. static bool
  986. parse_bot_command (const char *s, const char *command, const char **following)
  987. {
  988. size_t command_len = strlen (command);
  989. if (strncasecmp (s, command, command_len))
  990. return false;
  991. s += command_len;
  992. // Expect a word boundary, so that we don't respond to invalid things
  993. if (isalnum (*s))
  994. return false;
  995. // Ignore any initial spaces; the rest is the command's argument
  996. while (isblank (*s))
  997. s++;
  998. *following = s;
  999. return true;
  1000. }
  1001. static void
  1002. split_bot_command_argument_list (const char *arguments, struct strv *out)
  1003. {
  1004. cstr_split (arguments, ",", true, out);
  1005. for (size_t i = 0; i < out->len; )
  1006. {
  1007. if (!*cstr_strip_in_place (out->vector[i], " \t"))
  1008. strv_remove (out, i);
  1009. else
  1010. i++;
  1011. }
  1012. }
  1013. static bool
  1014. is_private_message (const struct irc_message *msg)
  1015. {
  1016. hard_assert (msg->params.len);
  1017. return !strchr ("#&+!", *msg->params.vector[0]);
  1018. }
  1019. static bool
  1020. is_sent_by_admin (struct bot_context *ctx, const struct irc_message *msg)
  1021. {
  1022. // No administrator set -> everyone is an administrator
  1023. if (!ctx->admin_re)
  1024. return true;
  1025. return regexec (ctx->admin_re, msg->prefix, 0, NULL, 0) != REG_NOMATCH;
  1026. }
  1027. static void respond_to_user (struct bot_context *ctx, const struct
  1028. irc_message *msg, const char *format, ...) ATTRIBUTE_PRINTF (3, 4);
  1029. static void
  1030. respond_to_user (struct bot_context *ctx, const struct irc_message *msg,
  1031. const char *format, ...)
  1032. {
  1033. if (!soft_assert (msg->prefix && msg->params.len))
  1034. return;
  1035. char nick[strcspn (msg->prefix, "!") + 1];
  1036. strncpy (nick, msg->prefix, sizeof nick - 1);
  1037. nick[sizeof nick - 1] = '\0';
  1038. va_list ap;
  1039. struct str text = str_make ();
  1040. va_start (ap, format);
  1041. str_append_vprintf (&text, format, ap);
  1042. va_end (ap);
  1043. if (is_private_message (msg))
  1044. irc_send (ctx, "PRIVMSG %s :%s", nick, text.str);
  1045. else
  1046. irc_send (ctx, "PRIVMSG %s :%s: %s",
  1047. msg->params.vector[0], nick, text.str);
  1048. str_free (&text);
  1049. }
  1050. static void
  1051. process_plugin_load (struct bot_context *ctx,
  1052. const struct irc_message *msg, const char *name)
  1053. {
  1054. struct error *e = NULL;
  1055. if (plugin_load (ctx, name, &e))
  1056. respond_to_user (ctx, msg, "plugin `%s' queued for loading", name);
  1057. else
  1058. {
  1059. respond_to_user (ctx, msg, "plugin `%s' could not be loaded: %s",
  1060. name, e->message);
  1061. error_free (e);
  1062. }
  1063. }
  1064. static void
  1065. process_plugin_unload (struct bot_context *ctx,
  1066. const struct irc_message *msg, const char *name)
  1067. {
  1068. struct error *e = NULL;
  1069. if (plugin_unload (ctx, name, &e))
  1070. respond_to_user (ctx, msg, "plugin `%s' unloaded", name);
  1071. else
  1072. {
  1073. respond_to_user (ctx, msg, "plugin `%s' could not be unloaded: %s",
  1074. name, e->message);
  1075. error_free (e);
  1076. }
  1077. }
  1078. static void
  1079. process_plugin_reload (struct bot_context *ctx,
  1080. const struct irc_message *msg, const char *name)
  1081. {
  1082. // XXX: we might want to wait until the plugin terminates before we try
  1083. // to reload it (so that it can save its configuration or whatever)
  1084. // So far the only error that can occur is that the plugin hasn't been
  1085. // loaded, which in this case doesn't really matter.
  1086. plugin_unload (ctx, name, NULL);
  1087. process_plugin_load (ctx, msg, name);
  1088. }
  1089. static char *
  1090. make_status_report (struct bot_context *ctx)
  1091. {
  1092. struct str report = str_make ();
  1093. const char *reason = getenv (g_startup_reason_str);
  1094. if (!reason)
  1095. reason = "launched normally";
  1096. str_append_printf (&report, "\x02startup reason:\x0f %s", reason);
  1097. size_t zombies = 0;
  1098. const char *prepend = "; \x02plugins:\x0f ";
  1099. for (struct plugin *plugin = ctx->plugins; plugin; plugin = plugin->next)
  1100. {
  1101. if (plugin->is_zombie)
  1102. zombies++;
  1103. else
  1104. {
  1105. str_append_printf (&report, "%s%s", prepend, plugin->name);
  1106. prepend = ", ";
  1107. }
  1108. }
  1109. if (!ctx->plugins)
  1110. str_append_printf (&report, "%s\x02none\x0f", prepend);
  1111. str_append_printf (&report, "; \x02zombies:\x0f %zu", zombies);
  1112. return str_steal (&report);
  1113. }
  1114. static void
  1115. process_privmsg (struct bot_context *ctx, const struct irc_message *msg)
  1116. {
  1117. if (!is_sent_by_admin (ctx, msg))
  1118. return;
  1119. if (msg->params.len < 2)
  1120. return;
  1121. const char *prefix = str_map_find (&ctx->config, "prefix");
  1122. hard_assert (prefix != NULL); // We have a default value for this
  1123. // For us to recognize the command, it has to start with the prefix,
  1124. // with the exception of PM's sent directly to us.
  1125. const char *text = msg->params.vector[1];
  1126. if (!strncmp (text, prefix, strlen (prefix)))
  1127. text += strlen (prefix);
  1128. else if (!is_private_message (msg))
  1129. return;
  1130. const char *following;
  1131. struct strv list = strv_make ();
  1132. if (parse_bot_command (text, "quote", &following))
  1133. // This seems to replace tons of random stupid commands
  1134. irc_send (ctx, "%s", following);
  1135. else if (parse_bot_command (text, "quit", &following))
  1136. {
  1137. // We actually need this command (instead of just `quote') because we
  1138. // could try to reconnect to the server automatically otherwise.
  1139. if (*following)
  1140. irc_send (ctx, "QUIT :%s", following);
  1141. else
  1142. irc_send (ctx, "QUIT");
  1143. initiate_quit (ctx);
  1144. }
  1145. else if (parse_bot_command (text, "status", &following))
  1146. {
  1147. char *report = make_status_report (ctx);
  1148. respond_to_user (ctx, msg, "%s", report);
  1149. free (report);
  1150. }
  1151. else if (parse_bot_command (text, "load", &following))
  1152. {
  1153. split_bot_command_argument_list (following, &list);
  1154. for (size_t i = 0; i < list.len; i++)
  1155. process_plugin_load (ctx, msg, list.vector[i]);
  1156. }
  1157. else if (parse_bot_command (text, "reload", &following))
  1158. {
  1159. split_bot_command_argument_list (following, &list);
  1160. for (size_t i = 0; i < list.len; i++)
  1161. process_plugin_reload (ctx, msg, list.vector[i]);
  1162. }
  1163. else if (parse_bot_command (text, "unload", &following))
  1164. {
  1165. split_bot_command_argument_list (following, &list);
  1166. for (size_t i = 0; i < list.len; i++)
  1167. process_plugin_unload (ctx, msg, list.vector[i]);
  1168. }
  1169. strv_free (&list);
  1170. }
  1171. static void
  1172. irc_forward_message_to_plugins (struct bot_context *ctx, const char *raw)
  1173. {
  1174. // For consistency with plugin_process_message()
  1175. if (!ctx->irc_registered)
  1176. return;
  1177. for (struct plugin *plugin = ctx->plugins;
  1178. plugin; plugin = plugin->next)
  1179. {
  1180. if (plugin->is_zombie)
  1181. continue;
  1182. if (plugin->initialized)
  1183. plugin_send (plugin, "%s", raw);
  1184. else
  1185. // TODO: make sure that this buffer doesn't get too large either
  1186. str_append_printf (&plugin->queued_output, "%s\r\n", raw);
  1187. }
  1188. }
  1189. static void
  1190. irc_process_message (const struct irc_message *msg,
  1191. const char *raw, void *user_data)
  1192. {
  1193. struct bot_context *ctx = user_data;
  1194. if (g_debug_mode)
  1195. fprintf (stderr, "[%s] ==> \"%s\"\n", "IRC", raw);
  1196. // This should be as minimal as possible, I don't want to have the whole bot
  1197. // written in C, especially when I have this overengineered plugin system.
  1198. // Therefore the very basic functionality only.
  1199. //
  1200. // I should probably even rip out the autojoin...
  1201. irc_forward_message_to_plugins (ctx, raw);
  1202. if (!strcasecmp (msg->command, "PING"))
  1203. {
  1204. if (msg->params.len)
  1205. irc_send (ctx, "PONG :%s", msg->params.vector[0]);
  1206. else
  1207. irc_send (ctx, "PONG");
  1208. }
  1209. else if (!ctx->irc_registered && !strcasecmp (msg->command, "001"))
  1210. {
  1211. print_status ("successfully connected");
  1212. ctx->irc_registered = true;
  1213. const char *autojoin = str_map_find (&ctx->config, "autojoin");
  1214. if (autojoin)
  1215. irc_send (ctx, "JOIN :%s", autojoin);
  1216. }
  1217. else if (!strcasecmp (msg->command, "PRIVMSG"))
  1218. process_privmsg (ctx, msg);
  1219. }
  1220. enum irc_read_result
  1221. {
  1222. IRC_READ_OK, ///< Some data were read successfully
  1223. IRC_READ_EOF, ///< The server has closed connection
  1224. IRC_READ_AGAIN, ///< No more data at the moment
  1225. IRC_READ_ERROR ///< General connection failure
  1226. };
  1227. static enum irc_read_result
  1228. irc_fill_read_buffer_tls (struct bot_context *ctx, struct str *buf)
  1229. {
  1230. int n_read;
  1231. start:
  1232. ERR_clear_error ();
  1233. n_read = SSL_read (ctx->ssl, buf->str + buf->len,
  1234. buf->alloc - buf->len - 1 /* null byte */);
  1235. const char *error_info = NULL;
  1236. switch (xssl_get_error (ctx->ssl, n_read, &error_info))
  1237. {
  1238. case SSL_ERROR_NONE:
  1239. buf->str[buf->len += n_read] = '\0';
  1240. return IRC_READ_OK;
  1241. case SSL_ERROR_ZERO_RETURN:
  1242. return IRC_READ_EOF;
  1243. case SSL_ERROR_WANT_READ:
  1244. return IRC_READ_AGAIN;
  1245. case SSL_ERROR_WANT_WRITE:
  1246. {
  1247. // Let it finish the handshake as we don't poll for writability;
  1248. // any errors are to be collected by SSL_read() in the next iteration
  1249. struct pollfd pfd = { .fd = ctx->irc_fd, .events = POLLOUT };
  1250. soft_assert (poll (&pfd, 1, 0) > 0);
  1251. goto start;
  1252. }
  1253. case XSSL_ERROR_TRY_AGAIN:
  1254. goto start;
  1255. default:
  1256. print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
  1257. return IRC_READ_ERROR;
  1258. }
  1259. }
  1260. static enum irc_read_result
  1261. irc_fill_read_buffer (struct bot_context *ctx, struct str *buf)
  1262. {
  1263. ssize_t n_read;
  1264. start:
  1265. n_read = recv (ctx->irc_fd, buf->str + buf->len,
  1266. buf->alloc - buf->len - 1 /* null byte */, 0);
  1267. if (n_read > 0)
  1268. {
  1269. buf->str[buf->len += n_read] = '\0';
  1270. return IRC_READ_OK;
  1271. }
  1272. if (n_read == 0)
  1273. return IRC_READ_EOF;
  1274. if (errno == EAGAIN)
  1275. return IRC_READ_AGAIN;
  1276. if (errno == EINTR)
  1277. goto start;
  1278. print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
  1279. return IRC_READ_ERROR;
  1280. }
  1281. static bool irc_connect (struct bot_context *, struct error **);
  1282. static void irc_queue_reconnect (struct bot_context *);
  1283. static void
  1284. irc_cancel_timers (struct bot_context *ctx)
  1285. {
  1286. poller_timer_reset (&ctx->timeout_tmr);
  1287. poller_timer_reset (&ctx->ping_tmr);
  1288. poller_timer_reset (&ctx->reconnect_tmr);
  1289. }
  1290. static void
  1291. on_irc_reconnect_timeout (void *user_data)
  1292. {
  1293. struct bot_context *ctx = user_data;
  1294. struct error *e = NULL;
  1295. if (irc_connect (ctx, &e))
  1296. {
  1297. // TODO: inform plugins about the new connection
  1298. return;
  1299. }
  1300. print_error ("%s", e->message);
  1301. error_free (e);
  1302. irc_queue_reconnect (ctx);
  1303. }
  1304. static void
  1305. irc_queue_reconnect (struct bot_context *ctx)
  1306. {
  1307. hard_assert (ctx->irc_fd == -1);
  1308. print_status ("trying to reconnect in %ld seconds...",
  1309. ctx->reconnect_delay);
  1310. poller_timer_set (&ctx->reconnect_tmr, ctx->reconnect_delay * 1000);
  1311. }
  1312. static void
  1313. on_irc_disconnected (struct bot_context *ctx)
  1314. {
  1315. // Get rid of the dead socket and related things
  1316. if (ctx->ssl)
  1317. {
  1318. SSL_free (ctx->ssl);
  1319. ctx->ssl = NULL;
  1320. SSL_CTX_free (ctx->ssl_ctx);
  1321. ctx->ssl_ctx = NULL;
  1322. }
  1323. poller_fd_reset (&ctx->irc_event);
  1324. xclose (ctx->irc_fd);
  1325. ctx->irc_fd = -1;
  1326. ctx->irc_registered = false;
  1327. // TODO: inform plugins about the disconnect event
  1328. // All of our timers have lost their meaning now
  1329. irc_cancel_timers (ctx);
  1330. if (ctx->quitting)
  1331. try_finish_quit (ctx);
  1332. else if (!ctx->reconnect)
  1333. initiate_quit (ctx);
  1334. else
  1335. irc_queue_reconnect (ctx);
  1336. }
  1337. static void
  1338. on_irc_ping_timeout (void *user_data)
  1339. {
  1340. struct bot_context *ctx = user_data;
  1341. print_error ("connection timeout");
  1342. on_irc_disconnected (ctx);
  1343. }
  1344. static void
  1345. on_irc_timeout (void *user_data)
  1346. {
  1347. // Provoke a response from the server
  1348. struct bot_context *ctx = user_data;
  1349. irc_send (ctx, "PING :%s",
  1350. (char *) str_map_find (&ctx->config, "nickname"));
  1351. }
  1352. static void
  1353. irc_reset_connection_timeouts (struct bot_context *ctx)
  1354. {
  1355. irc_cancel_timers (ctx);
  1356. poller_timer_set (&ctx->timeout_tmr, 3 * 60 * 1000);
  1357. poller_timer_set (&ctx->ping_tmr, (3 * 60 + 30) * 1000);
  1358. }
  1359. static void
  1360. on_irc_readable (const struct pollfd *fd, struct bot_context *ctx)
  1361. {
  1362. if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
  1363. print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);
  1364. (void) set_blocking (ctx->irc_fd, false);
  1365. struct str *buf = &ctx->read_buffer;
  1366. enum irc_read_result (*fill_buffer)(struct bot_context *, struct str *)
  1367. = ctx->ssl
  1368. ? irc_fill_read_buffer_tls
  1369. : irc_fill_read_buffer;
  1370. bool disconnected = false;
  1371. while (true)
  1372. {
  1373. str_reserve (buf, 512);
  1374. switch (fill_buffer (ctx, buf))
  1375. {
  1376. case IRC_READ_AGAIN:
  1377. goto end;
  1378. case IRC_READ_ERROR:
  1379. print_error ("reading from the IRC server failed");
  1380. disconnected = true;
  1381. goto end;
  1382. case IRC_READ_EOF:
  1383. print_status ("the IRC server closed the connection");
  1384. disconnected = true;
  1385. goto end;
  1386. case IRC_READ_OK:
  1387. break;
  1388. }
  1389. if (buf->len >= (1 << 20))
  1390. {
  1391. print_error ("the IRC server seems to spew out data frantically");
  1392. irc_shutdown (ctx);
  1393. goto end;
  1394. }
  1395. }
  1396. end:
  1397. (void) set_blocking (ctx->irc_fd, true);
  1398. irc_process_buffer (buf, irc_process_message, ctx);
  1399. if (disconnected)
  1400. on_irc_disconnected (ctx);
  1401. else
  1402. irc_reset_connection_timeouts (ctx);
  1403. }
  1404. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1405. // The bot is currently mostly synchronous (which also makes it shorter),
  1406. // however our current SOCKS code is not, hence we must wrap it.
  1407. struct irc_socks_data
  1408. {
  1409. struct bot_context *ctx; ///< Bot context
  1410. struct poller inner_poller; ///< Special inner poller
  1411. bool polling; ///< Inner poller is no longer needed
  1412. struct socks_connector connector; ///< SOCKS connector
  1413. bool succeeded; ///< Were we successful in connecting?
  1414. };
  1415. static void
  1416. irc_on_socks_connected (void *user_data, int socket, const char *hostname)
  1417. {
  1418. (void) hostname;
  1419. struct irc_socks_data *data = user_data;
  1420. data->ctx->irc_fd = socket;
  1421. data->succeeded = true;
  1422. data->polling = false;
  1423. }
  1424. static void
  1425. irc_on_socks_failure (void *user_data)
  1426. {
  1427. struct irc_socks_data *data = user_data;
  1428. data->succeeded = false;
  1429. data->polling = false;
  1430. }
  1431. static void
  1432. irc_on_socks_connecting (void *user_data,
  1433. const char *address, const char *via, const char *version)
  1434. {
  1435. (void) user_data;
  1436. print_status ("connecting to %s via %s (%s)...", address, via, version);
  1437. }
  1438. static void
  1439. irc_on_socks_error (void *user_data, const char *error)
  1440. {
  1441. (void) user_data;
  1442. print_error ("%s: %s", "SOCKS connection failed", error);
  1443. }
  1444. static bool
  1445. irc_establish_connection_socks (struct bot_context *ctx,
  1446. const char *socks_host, const char *socks_port,
  1447. const char *host, const char *service, struct error **e)
  1448. {
  1449. struct irc_socks_data data;
  1450. struct poller *poller = &data.inner_poller;
  1451. struct socks_connector *connector = &data.connector;
  1452. data.ctx = ctx;
  1453. poller_init (poller);
  1454. data.polling = true;
  1455. socks_connector_init (connector, poller);
  1456. data.succeeded = false;
  1457. connector->on_connected = irc_on_socks_connected;
  1458. connector->on_connecting = irc_on_socks_connecting;
  1459. connector->on_error = irc_on_socks_error;
  1460. connector->on_failure = irc_on_socks_failure;
  1461. connector->user_data = &data;
  1462. if (socks_connector_add_target (connector, host, service, e))
  1463. {
  1464. socks_connector_run (connector, socks_host, socks_port,
  1465. str_map_find (&ctx->config, "socks_username"),
  1466. str_map_find (&ctx->config, "socks_password"));
  1467. while (data.polling)
  1468. poller_run (poller);
  1469. if (!data.succeeded)
  1470. error_set (e, "connection failed");
  1471. }
  1472. socks_connector_free (connector);
  1473. poller_free (poller);
  1474. return data.succeeded;
  1475. }
  1476. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1477. static bool
  1478. irc_connect (struct bot_context *ctx, struct error **e)
  1479. {
  1480. const char *irc_host = str_map_find (&ctx->config, "irc_host");
  1481. const char *irc_port = str_map_find (&ctx->config, "irc_port");
  1482. const char *socks_host = str_map_find (&ctx->config, "socks_host");
  1483. const char *socks_port = str_map_find (&ctx->config, "socks_port");
  1484. const char *nickname = str_map_find (&ctx->config, "nickname");
  1485. const char *username = str_map_find (&ctx->config, "username");
  1486. const char *realname = str_map_find (&ctx->config, "realname");
  1487. // We have a default value for these
  1488. hard_assert (irc_port && socks_port);
  1489. hard_assert (nickname && username && realname);
  1490. // TODO: again, get rid of `struct error' in here. The question is: how
  1491. // do we tell our caller that he should not try to reconnect?
  1492. if (!irc_host)
  1493. return error_set (e, "no hostname specified in configuration");
  1494. bool use_tls;
  1495. if (!irc_get_boolean_from_config (ctx, "tls", &use_tls, e))
  1496. return false;
  1497. bool connected = socks_host
  1498. ? irc_establish_connection_socks (ctx,
  1499. socks_host, socks_port, irc_host, irc_port, e)
  1500. : irc_establish_connection (ctx, irc_host, irc_port, e);
  1501. if (!connected)
  1502. return false;
  1503. if (use_tls && !irc_initialize_tls (ctx, e))
  1504. {
  1505. xclose (ctx->irc_fd);
  1506. ctx->irc_fd = -1;
  1507. return false;
  1508. }
  1509. print_status ("connection established");
  1510. ctx->irc_event = poller_fd_make (&ctx->poller, ctx->irc_fd);
  1511. ctx->irc_event.dispatcher = (poller_fd_fn) on_irc_readable;
  1512. ctx->irc_event.user_data = ctx;
  1513. // TODO: in exec try: 1/ set blocking, 2/ setsockopt() SO_LINGER,
  1514. // (struct linger) { .l_onoff = true; .l_linger = 1 /* 1s should do */; }
  1515. // 3/ /* O_CLOEXEC */ But only if the QUIT message proves unreliable.
  1516. poller_fd_set (&ctx->irc_event, POLLIN);
  1517. irc_reset_connection_timeouts (ctx);
  1518. irc_send (ctx, "NICK %s", nickname);
  1519. irc_send (ctx, "USER %s 8 * :%s", username, realname);
  1520. return true;
  1521. }
  1522. static bool
  1523. parse_config (struct bot_context *ctx, struct error **e)
  1524. {
  1525. if (!irc_get_boolean_from_config (ctx, "reconnect", &ctx->reconnect, e))
  1526. return false;
  1527. const char *delay_str = str_map_find (&ctx->config, "reconnect_delay");
  1528. hard_assert (delay_str != NULL); // We have a default value for this
  1529. if (!xstrtoul (&ctx->reconnect_delay, delay_str, 10))
  1530. {
  1531. return error_set (e,
  1532. "invalid configuration value for `%s'", "reconnect_delay");
  1533. }
  1534. hard_assert (!ctx->admin_re);
  1535. const char *admin = str_map_find (&ctx->config, "admin");
  1536. if (!admin)
  1537. return true;
  1538. struct error *error = NULL;
  1539. ctx->admin_re = regex_compile (admin, REG_EXTENDED | REG_NOSUB, &error);
  1540. if (!error)
  1541. return true;
  1542. error_set (e, "invalid configuration value for `%s': %s",
  1543. "admin", error->message);
  1544. error_free (error);
  1545. return false;
  1546. }
  1547. static void
  1548. on_plugin_death (struct plugin *plugin, int status)
  1549. {
  1550. struct bot_context *ctx = plugin->ctx;
  1551. // TODO: callbacks on children death, so that we may tell the user
  1552. // "plugin `name' died like a dirty jewish pig"; use `status'
  1553. if (!plugin->is_zombie && WIFSIGNALED (status))
  1554. {
  1555. const char *notes = "";
  1556. #ifdef WCOREDUMP
  1557. if (WCOREDUMP (status))
  1558. notes = " (core dumped)";
  1559. #endif
  1560. print_warning ("Plugin `%s' died from signal %d%s",
  1561. plugin->name, WTERMSIG (status), notes);
  1562. }
  1563. // Let's go through the zombie state to simplify things a bit
  1564. // TODO: might not be a completely bad idea to restart the plugin
  1565. plugin_zombify (plugin);
  1566. plugin->pid = -1;
  1567. // In theory we could close `read_fd', set `read_event->closed' to true
  1568. // and expect epoll to no longer return events for the descriptor, as
  1569. // all the pipe ends should be closed by then (the child is dead, so its
  1570. // pipe FDs have been closed [assuming it hasn't forked without closing
  1571. // the descriptors, which would be evil], and we would have closed all
  1572. // of our FDs for this pipe as well). In practice that doesn't work.
  1573. poller_fd_reset (&plugin->read_event);
  1574. xclose (plugin->read_fd);
  1575. plugin->read_fd = -1;
  1576. LIST_UNLINK (ctx->plugins, plugin);
  1577. plugin_destroy (plugin);
  1578. // Living child processes block us from quitting
  1579. try_finish_quit (ctx);
  1580. }
  1581. static bool
  1582. try_reap_plugin (struct bot_context *ctx)
  1583. {
  1584. int status;
  1585. pid_t zombie = waitpid (-1, &status, WNOHANG);
  1586. if (zombie == -1)
  1587. {
  1588. // No children to wait on
  1589. if (errno == ECHILD)
  1590. return false;
  1591. hard_assert (errno == EINTR);
  1592. return true;
  1593. }
  1594. if (zombie == 0)
  1595. return false;
  1596. struct plugin *plugin = plugin_find_by_pid (ctx, zombie);
  1597. // XXX: re-exec if something has died that we don't recognize?
  1598. if (soft_assert (plugin != NULL))
  1599. on_plugin_death (plugin, status);
  1600. return true;
  1601. }
  1602. static void
  1603. kill_all_zombies (struct bot_context *ctx)
  1604. {
  1605. for (struct plugin *plugin = ctx->plugins; plugin; plugin = plugin->next)
  1606. {
  1607. if (!plugin->is_zombie)
  1608. continue;
  1609. print_status ("forcefully killing a zombie of `%s' (PID %d)",
  1610. plugin->name, (int) plugin->pid);
  1611. kill (plugin->pid, SIGKILL);
  1612. }
  1613. }
  1614. static void
  1615. on_signal_pipe_readable (const struct pollfd *fd, struct bot_context *ctx)
  1616. {
  1617. char dummy;
  1618. (void) read (fd->fd, &dummy, 1);
  1619. if (g_termination_requested)
  1620. {
  1621. g_termination_requested = false;
  1622. if (!ctx->quitting)
  1623. {
  1624. // There may be a timer set to reconnect to the server
  1625. irc_cancel_timers (ctx);
  1626. if (ctx->irc_fd != -1)
  1627. irc_send (ctx, "QUIT :Terminated by signal");
  1628. initiate_quit (ctx);
  1629. }
  1630. else
  1631. // Disregard proper termination, just kill all the children
  1632. kill_all_zombies (ctx);
  1633. }
  1634. // Reap all dead children (since the signal pipe may overflow etc. we run
  1635. // waitpid() in a loop to return all the zombies it knows about).
  1636. while (try_reap_plugin (ctx))
  1637. ;
  1638. }
  1639. int
  1640. main (int argc, char *argv[])
  1641. {
  1642. g_original_argv = strv_make ();
  1643. strv_append_vector (&g_original_argv, argv);
  1644. static const struct opt opts[] =
  1645. {
  1646. { 'd', "debug", NULL, 0, "run in debug mode" },
  1647. { 'h', "help", NULL, 0, "display this help and exit" },
  1648. { 'V', "version", NULL, 0, "output version information and exit" },
  1649. { 'w', "write-default-cfg", "FILENAME",
  1650. OPT_OPTIONAL_ARG | OPT_LONG_ONLY,
  1651. "write a default configuration file and exit" },
  1652. { 0, NULL, NULL, 0, NULL }
  1653. };
  1654. struct opt_handler oh =
  1655. opt_handler_make (argc, argv, opts, NULL, "Experimental IRC bot.");
  1656. int c;
  1657. while ((c = opt_handler_get (&oh)) != -1)
  1658. switch (c)
  1659. {
  1660. case 'd':
  1661. g_debug_mode = true;
  1662. break;
  1663. case 'h':
  1664. opt_handler_usage (&oh, stdout);
  1665. exit (EXIT_SUCCESS);
  1666. case 'V':
  1667. printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
  1668. exit (EXIT_SUCCESS);
  1669. case 'w':
  1670. call_simple_config_write_default (optarg, g_config_table);
  1671. exit (EXIT_SUCCESS);
  1672. default:
  1673. print_error ("wrong options");
  1674. opt_handler_usage (&oh, stderr);
  1675. exit (EXIT_FAILURE);
  1676. }
  1677. opt_handler_free (&oh);
  1678. print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting");
  1679. setup_signal_handlers ();
  1680. init_openssl ();
  1681. struct bot_context ctx;
  1682. bot_context_init (&ctx);
  1683. struct error *e = NULL;
  1684. if (!simple_config_update_from_file (&ctx.config, &e)
  1685. || !setup_recovery_handler (&ctx, &e))
  1686. {
  1687. print_error ("%s", e->message);
  1688. error_free (e);
  1689. exit (EXIT_FAILURE);
  1690. }
  1691. ctx.signal_event = poller_fd_make (&ctx.poller, g_signal_pipe[0]);
  1692. ctx.signal_event.dispatcher = (poller_fd_fn) on_signal_pipe_readable;
  1693. ctx.signal_event.user_data = &ctx;
  1694. poller_fd_set (&ctx.signal_event, POLLIN);
  1695. #if OpenBSD >= 201605
  1696. // cpath is for creating the plugin home directory
  1697. if (pledge ("stdio rpath cpath inet proc exec", NULL))
  1698. exit_fatal ("%s: %s", "pledge", strerror (errno));
  1699. #endif
  1700. plugin_load_all_from_config (&ctx);
  1701. if (!parse_config (&ctx, &e)
  1702. || !irc_connect (&ctx, &e))
  1703. {
  1704. print_error ("%s", e->message);
  1705. error_free (e);
  1706. exit (EXIT_FAILURE);
  1707. }
  1708. // TODO: clean re-exec support; to save the state I can either use argv,
  1709. // argp, or I can create a temporary file, unlink it and use the FD
  1710. // (mkstemp() on a `struct str' constructed from XDG_RUNTIME_DIR, TMPDIR
  1711. // or /tmp as a last resort + PROGRAM_NAME + ".XXXXXX" -> unlink();
  1712. // remember to use O_CREAT | O_EXCL). The state needs to be versioned.
  1713. // Unfortunately I cannot de/serialize SSL state.
  1714. ctx.polling = true;
  1715. while (ctx.polling)
  1716. poller_run (&ctx.poller);
  1717. bot_context_free (&ctx);
  1718. strv_free (&g_original_argv);
  1719. return EXIT_SUCCESS;
  1720. }