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.

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