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.

1961 lines
53KB

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