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.

2029 lines
55KB

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