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.
 
 
 
 
 
 

2252 lines
61 KiB

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