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.
 
 
 
 
 
 

3321 lines
83 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 _POSIX_C_SOURCE 199309L
  21. #define _XOPEN_SOURCE 500
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <errno.h>
  25. #include <string.h>
  26. #include <stdarg.h>
  27. #include <stdint.h>
  28. #include <stdbool.h>
  29. #include <ctype.h>
  30. #include <unistd.h>
  31. #include <sys/wait.h>
  32. #include <sys/stat.h>
  33. #include <fcntl.h>
  34. #include <poll.h>
  35. #include <signal.h>
  36. #include <strings.h>
  37. #include <regex.h>
  38. #include <libgen.h>
  39. #include <sys/socket.h>
  40. #include <netinet/in.h>
  41. #include <netdb.h>
  42. #ifndef NI_MAXHOST
  43. #define NI_MAXHOST 1025
  44. #endif // ! NI_MAXHOST
  45. #include <getopt.h>
  46. #include <openssl/ssl.h>
  47. #include <openssl/err.h>
  48. #include "siphash.h"
  49. #define PROGRAM_NAME "ZyklonB"
  50. #define PROGRAM_VERSION "alpha"
  51. extern char **environ;
  52. #if defined __GNUC__
  53. #define ATTRIBUTE_PRINTF(x, y) __attribute__ ((format (printf, x, y)))
  54. #else // ! __GNUC__
  55. #define ATTRIBUTE_PRINTF(x, y)
  56. #endif // ! __GNUC__
  57. #if defined __GNUC__ && __GNUC__ >= 4
  58. #define ATTRIBUTE_SENTINEL __attribute__ ((sentinel))
  59. #else // ! __GNUC__ || __GNUC__ < 4
  60. #define ATTRIBUTE_SENTINEL
  61. #endif // ! __GNUC__ || __GNUC__ < 4
  62. #define N_ELEMENTS(a) (sizeof (a) / sizeof ((a)[0]))
  63. #define BLOCK_START do {
  64. #define BLOCK_END } while (0)
  65. // --- Utilities ---------------------------------------------------------------
  66. static void
  67. print_message (FILE *stream, const char *type, const char *fmt, ...)
  68. ATTRIBUTE_PRINTF (3, 4);
  69. static void
  70. print_message (FILE *stream, const char *type, const char *fmt, ...)
  71. {
  72. va_list ap;
  73. va_start (ap, fmt);
  74. fprintf (stream, "%s ", type);
  75. vfprintf (stream, fmt, ap);
  76. fputs ("\n", stream);
  77. va_end (ap);
  78. }
  79. #define print_fatal(...) print_message (stderr, "fatal:", __VA_ARGS__)
  80. #define print_error(...) print_message (stderr, "error:", __VA_ARGS__)
  81. #define print_warning(...) print_message (stderr, "warning:", __VA_ARGS__)
  82. #define print_status(...) print_message (stdout, "--", __VA_ARGS__)
  83. // --- Debugging and assertions ------------------------------------------------
  84. // We should check everything that may possibly fail with at least a soft
  85. // assertion, so that any causes for problems don't slip us by silently.
  86. //
  87. // `g_soft_asserts_are_deadly' may be useful while running inside a debugger.
  88. static bool g_debug_mode; ///< Debug messages are printed
  89. static bool g_soft_asserts_are_deadly; ///< soft_assert() aborts as well
  90. #define print_debug(...) \
  91. BLOCK_START \
  92. if (g_debug_mode) \
  93. print_message (stderr, "debug:", __VA_ARGS__); \
  94. BLOCK_END
  95. static void
  96. assertion_failure_handler (bool is_fatal, const char *file, int line,
  97. const char *function, const char *condition)
  98. {
  99. if (is_fatal)
  100. {
  101. print_fatal ("assertion failed [%s:%d in function %s]: %s",
  102. file, line, function, condition);
  103. abort ();
  104. }
  105. else
  106. print_debug ("assertion failed [%s:%d in function %s]: %s",
  107. file, line, function, condition);
  108. }
  109. #define soft_assert(condition) \
  110. ((condition) ? true : \
  111. (assertion_failure_handler (g_soft_asserts_are_deadly, \
  112. __FILE__, __LINE__, __func__, #condition), false))
  113. #define hard_assert(condition) \
  114. ((condition) ? (void) 0 : \
  115. assertion_failure_handler (true, \
  116. __FILE__, __LINE__, __func__, #condition))
  117. // --- Safe memory management --------------------------------------------------
  118. // When a memory allocation fails and we need the memory, we're usually pretty
  119. // much fucked. Use the non-prefixed versions when there's a legitimate
  120. // worry that an unrealistic amount of memory may be requested for allocation.
  121. // XXX: it's not a good idea to use print_message() as it may want to allocate
  122. // further memory for printf() and the output streams. That may fail.
  123. static void *
  124. xmalloc (size_t n)
  125. {
  126. void *p = malloc (n);
  127. if (!p)
  128. {
  129. print_fatal ("malloc: %s", strerror (errno));
  130. exit (EXIT_FAILURE);
  131. }
  132. return p;
  133. }
  134. static void *
  135. xcalloc (size_t n, size_t m)
  136. {
  137. void *p = calloc (n, m);
  138. if (!p && n && m)
  139. {
  140. print_fatal ("calloc: %s", strerror (errno));
  141. exit (EXIT_FAILURE);
  142. }
  143. return p;
  144. }
  145. static void *
  146. xrealloc (void *o, size_t n)
  147. {
  148. void *p = realloc (o, n);
  149. if (!p && n)
  150. {
  151. print_fatal ("realloc: %s", strerror (errno));
  152. exit (EXIT_FAILURE);
  153. }
  154. return p;
  155. }
  156. static void *
  157. xreallocarray (void *o, size_t n, size_t m)
  158. {
  159. if (m && n > SIZE_MAX / m)
  160. {
  161. errno = ENOMEM;
  162. print_fatal ("reallocarray: %s", strerror (errno));
  163. exit (EXIT_FAILURE);
  164. }
  165. return xrealloc (o, n * m);
  166. }
  167. static char *
  168. xstrdup (const char *s)
  169. {
  170. return strcpy (xmalloc (strlen (s) + 1), s);
  171. }
  172. static char *
  173. xstrndup (const char *s, size_t n)
  174. {
  175. size_t size = strlen (s);
  176. if (n > size)
  177. n = size;
  178. char *copy = xmalloc (n + 1);
  179. memcpy (copy, s, n);
  180. copy[n] = '\0';
  181. return copy;
  182. }
  183. // --- Double-linked list helpers ----------------------------------------------
  184. // The links of the list need to have the members `prev' and `next'.
  185. #define LIST_PREPEND(head, link) \
  186. BLOCK_START \
  187. (link)->prev = NULL; \
  188. (link)->next = (head); \
  189. if ((link)->next) \
  190. (link)->next->prev = (link); \
  191. (head) = (link); \
  192. BLOCK_END
  193. #define LIST_UNLINK(head, link) \
  194. BLOCK_START \
  195. if ((link)->prev) \
  196. (link)->prev->next = (link)->next; \
  197. else \
  198. (head) = (link)->next; \
  199. if ((link)->next) \
  200. (link)->next->prev = (link)->prev; \
  201. BLOCK_END
  202. // --- Dynamically allocated string array --------------------------------------
  203. struct str_vector
  204. {
  205. char **vector;
  206. size_t len;
  207. size_t alloc;
  208. };
  209. static void
  210. str_vector_init (struct str_vector *self)
  211. {
  212. self->alloc = 4;
  213. self->len = 0;
  214. self->vector = xcalloc (sizeof *self->vector, self->alloc);
  215. }
  216. static void
  217. str_vector_free (struct str_vector *self)
  218. {
  219. unsigned i;
  220. for (i = 0; i < self->len; i++)
  221. free (self->vector[i]);
  222. free (self->vector);
  223. self->vector = NULL;
  224. }
  225. static void
  226. str_vector_add_owned (struct str_vector *self, char *s)
  227. {
  228. self->vector[self->len] = s;
  229. if (++self->len >= self->alloc)
  230. self->vector = xreallocarray (self->vector,
  231. sizeof *self->vector, (self->alloc <<= 1));
  232. self->vector[self->len] = NULL;
  233. }
  234. static void
  235. str_vector_add (struct str_vector *self, const char *s)
  236. {
  237. str_vector_add_owned (self, xstrdup (s));
  238. }
  239. static void
  240. str_vector_add_args (struct str_vector *self, const char *s, ...)
  241. ATTRIBUTE_SENTINEL;
  242. static void
  243. str_vector_add_args (struct str_vector *self, const char *s, ...)
  244. {
  245. va_list ap;
  246. va_start (ap, s);
  247. while (s)
  248. {
  249. str_vector_add (self, s);
  250. s = va_arg (ap, const char *);
  251. }
  252. va_end (ap);
  253. }
  254. static void
  255. str_vector_add_vector (struct str_vector *self, char **vector)
  256. {
  257. while (*vector)
  258. str_vector_add (self, *vector++);
  259. }
  260. static void
  261. str_vector_remove (struct str_vector *self, size_t i)
  262. {
  263. hard_assert (i < self->len);
  264. free (self->vector[i]);
  265. memmove (self->vector + i, self->vector + i + 1,
  266. (self->len-- - i) * sizeof *self->vector);
  267. }
  268. // --- Dynamically allocated strings -------------------------------------------
  269. // Basically a string builder to abstract away manual memory management.
  270. struct str
  271. {
  272. char *str; ///< String data, null terminated
  273. size_t alloc; ///< How many bytes are allocated
  274. size_t len; ///< How long the string actually is
  275. };
  276. /// We don't care about allocations that are way too large for the content, as
  277. /// long as the allocation is below the given threshold. (Trivial heuristics.)
  278. #define STR_SHRINK_THRESHOLD (1 << 20)
  279. static void
  280. str_init (struct str *self)
  281. {
  282. self->alloc = 16;
  283. self->len = 0;
  284. self->str = strcpy (xmalloc (self->alloc), "");
  285. }
  286. static void
  287. str_free (struct str *self)
  288. {
  289. free (self->str);
  290. self->str = NULL;
  291. self->alloc = 0;
  292. self->len = 0;
  293. }
  294. static void
  295. str_reset (struct str *self)
  296. {
  297. str_free (self);
  298. str_init (self);
  299. }
  300. static char *
  301. str_steal (struct str *self)
  302. {
  303. char *str = self->str;
  304. self->str = NULL;
  305. str_free (self);
  306. return str;
  307. }
  308. static void
  309. str_ensure_space (struct str *self, size_t n)
  310. {
  311. // We allocate at least one more byte for the terminating null character
  312. size_t new_alloc = self->alloc;
  313. while (new_alloc <= self->len + n)
  314. new_alloc <<= 1;
  315. if (new_alloc != self->alloc)
  316. self->str = xrealloc (self->str, (self->alloc = new_alloc));
  317. }
  318. static void
  319. str_append_data (struct str *self, const char *data, size_t n)
  320. {
  321. str_ensure_space (self, n);
  322. memcpy (self->str + self->len, data, n);
  323. self->len += n;
  324. self->str[self->len] = '\0';
  325. }
  326. static void
  327. str_append_c (struct str *self, char c)
  328. {
  329. str_append_data (self, &c, 1);
  330. }
  331. static void
  332. str_append (struct str *self, const char *s)
  333. {
  334. str_append_data (self, s, strlen (s));
  335. }
  336. static void
  337. str_append_str (struct str *self, const struct str *another)
  338. {
  339. str_append_data (self, another->str, another->len);
  340. }
  341. static int
  342. str_append_vprintf (struct str *self, const char *fmt, va_list va)
  343. {
  344. va_list ap;
  345. int size;
  346. va_copy (ap, va);
  347. size = vsnprintf (NULL, 0, fmt, ap);
  348. va_end (ap);
  349. if (size < 0)
  350. return -1;
  351. va_copy (ap, va);
  352. str_ensure_space (self, size);
  353. size = vsnprintf (self->str + self->len, self->alloc - self->len, fmt, ap);
  354. va_end (ap);
  355. if (size > 0)
  356. self->len += size;
  357. return size;
  358. }
  359. static int
  360. str_append_printf (struct str *self, const char *fmt, ...)
  361. ATTRIBUTE_PRINTF (2, 3);
  362. static int
  363. str_append_printf (struct str *self, const char *fmt, ...)
  364. {
  365. va_list ap;
  366. va_start (ap, fmt);
  367. int size = str_append_vprintf (self, fmt, ap);
  368. va_end (ap);
  369. return size;
  370. }
  371. static void
  372. str_remove_slice (struct str *self, size_t start, size_t length)
  373. {
  374. size_t end = start + length;
  375. hard_assert (end <= self->len);
  376. memmove (self->str + start, self->str + end, self->len - end);
  377. self->str[self->len -= length] = '\0';
  378. // Shrink the string if the allocation becomes way too large
  379. if (self->alloc >= STR_SHRINK_THRESHOLD && self->len < (self->alloc >> 2))
  380. self->str = xrealloc (self->str, self->alloc >>= 2);
  381. }
  382. // --- Errors ------------------------------------------------------------------
  383. // Error reporting utilities. Inspired by GError, only much simpler.
  384. struct error
  385. {
  386. size_t domain; ///< The domain of the error
  387. int id; ///< The concrete error ID
  388. char *message; ///< Textual description of the event
  389. };
  390. static size_t
  391. error_resolve_domain (size_t *tag)
  392. {
  393. // This method is fairly sensitive to the order in which resolution
  394. // requests come in, does not provide a good way of decoding the number
  395. // back to a meaningful identifier, and may not play all too well with
  396. // dynamic libraries when a module is e.g. statically linked into multiple
  397. // libraries, but it's fast, simple, and more than enough for our purposes.
  398. static size_t domain_counter;
  399. if (!*tag)
  400. *tag = ++domain_counter;
  401. return *tag;
  402. }
  403. static void
  404. error_set (struct error **e, size_t domain, int id,
  405. const char *message, ...) ATTRIBUTE_PRINTF (4, 5);
  406. static void
  407. error_set (struct error **e, size_t domain, int id,
  408. const char *message, ...)
  409. {
  410. if (!e)
  411. return;
  412. va_list ap;
  413. va_start (ap, message);
  414. int size = snprintf (NULL, 0, message, ap);
  415. va_end (ap);
  416. hard_assert (size >= 0);
  417. struct error *tmp = xmalloc (sizeof *tmp);
  418. tmp->domain = domain;
  419. tmp->id = id;
  420. tmp->message = xmalloc (size + 1);
  421. va_start (ap, message);
  422. size = snprintf (tmp->message, size + 1, message, ap);
  423. va_end (ap);
  424. hard_assert (size >= 0);
  425. soft_assert (*e == NULL);
  426. *e = tmp;
  427. }
  428. static void
  429. error_free (struct error *e)
  430. {
  431. free (e->message);
  432. free (e);
  433. }
  434. static void
  435. error_propagate (struct error **destination, struct error *source)
  436. {
  437. if (!destination)
  438. {
  439. error_free (source);
  440. return;
  441. }
  442. soft_assert (*destination == NULL);
  443. *destination = source;
  444. }
  445. // --- String hash map ---------------------------------------------------------
  446. // The most basic <string, managed pointer> map (or associative array).
  447. struct str_map_link
  448. {
  449. struct str_map_link *next; ///< The next link in a chain
  450. struct str_map_link *prev; ///< The previous link in a chain
  451. void *data; ///< Payload
  452. size_t key_length; ///< Length of the key without '\0'
  453. char key[]; ///< The key for this link
  454. };
  455. struct str_map
  456. {
  457. struct str_map_link **map; ///< The hash table data itself
  458. size_t alloc; ///< Number of allocated entries
  459. size_t len; ///< Number of entries in the table
  460. void (*free) (void *); ///< Callback to destruct the payload
  461. };
  462. #define STR_MAP_MIN_ALLOC 16
  463. typedef void (*str_map_free_func) (void *);
  464. static void
  465. str_map_init (struct str_map *self)
  466. {
  467. self->alloc = STR_MAP_MIN_ALLOC;
  468. self->len = 0;
  469. self->free = NULL;
  470. self->map = xcalloc (self->alloc, sizeof *self->map);
  471. }
  472. static void
  473. str_map_free (struct str_map *self)
  474. {
  475. struct str_map_link **iter, **end = self->map + self->alloc;
  476. struct str_map_link *link, *tmp;
  477. for (iter = self->map; iter < end; iter++)
  478. for (link = *iter; link; link = tmp)
  479. {
  480. tmp = link->next;
  481. if (self->free)
  482. self->free (link->data);
  483. free (link);
  484. }
  485. free (self->map);
  486. self->map = NULL;
  487. }
  488. static uint64_t
  489. str_map_hash (const char *s, size_t len)
  490. {
  491. static unsigned char key[16] = "SipHash 2-4 key!";
  492. return siphash (key, (const void *) s, len);
  493. }
  494. static uint64_t
  495. str_map_pos (struct str_map *self, const char *s)
  496. {
  497. size_t mask = self->alloc - 1;
  498. return str_map_hash (s, strlen (s)) & mask;
  499. }
  500. static uint64_t
  501. str_map_link_hash (struct str_map_link *self)
  502. {
  503. return str_map_hash (self->key, self->key_length);
  504. }
  505. static void
  506. str_map_resize (struct str_map *self, size_t new_size)
  507. {
  508. struct str_map_link **old_map = self->map;
  509. size_t i, old_size = self->alloc;
  510. // Only powers of two, so that we don't need to compute the modulo
  511. hard_assert ((new_size & (new_size - 1)) == 0);
  512. size_t mask = new_size - 1;
  513. self->alloc = new_size;
  514. self->map = xcalloc (self->alloc, sizeof *self->map);
  515. for (i = 0; i < old_size; i++)
  516. {
  517. struct str_map_link *iter = old_map[i], *next_iter;
  518. while (iter)
  519. {
  520. next_iter = iter->next;
  521. uint64_t pos = str_map_link_hash (iter) & mask;
  522. LIST_PREPEND (self->map[pos], iter);
  523. iter = next_iter;
  524. }
  525. }
  526. free (old_map);
  527. }
  528. static void
  529. str_map_set (struct str_map *self, const char *key, void *value)
  530. {
  531. uint64_t pos = str_map_pos (self, key);
  532. struct str_map_link *iter = self->map[pos];
  533. for (; iter; iter = iter->next)
  534. {
  535. if (strcmp (key, iter->key))
  536. continue;
  537. // Storing the same data doesn't destroy it
  538. if (self->free && value != iter->data)
  539. self->free (iter->data);
  540. if (value)
  541. {
  542. iter->data = value;
  543. return;
  544. }
  545. LIST_UNLINK (self->map[pos], iter);
  546. free (iter);
  547. self->len--;
  548. // The array should be at least 1/4 full
  549. if (self->alloc >= (STR_MAP_MIN_ALLOC << 2)
  550. && self->len < (self->alloc >> 2))
  551. str_map_resize (self, self->alloc >> 2);
  552. return;
  553. }
  554. if (!value)
  555. return;
  556. if (self->len >= self->alloc)
  557. {
  558. str_map_resize (self, self->alloc << 1);
  559. pos = str_map_pos (self, key);
  560. }
  561. // Link in a new element for the given <key, value> pair
  562. size_t key_length = strlen (key);
  563. struct str_map_link *link = xmalloc (sizeof *link + key_length + 1);
  564. link->data = value;
  565. link->key_length = key_length;
  566. memcpy (link->key, key, key_length + 1);
  567. LIST_PREPEND (self->map[pos], link);
  568. self->len++;
  569. }
  570. static void *
  571. str_map_find (struct str_map *self, const char *key)
  572. {
  573. struct str_map_link *iter = self->map[str_map_pos (self, key)];
  574. for (; iter; iter = iter->next)
  575. if (!strcmp (key, (char *) iter + sizeof *iter))
  576. return iter->data;
  577. return NULL;
  578. }
  579. // --- File descriptor utilities -----------------------------------------------
  580. static void
  581. set_cloexec (int fd)
  582. {
  583. soft_assert (fcntl (fd, F_SETFD, fcntl (fd, F_GETFD) | FD_CLOEXEC) != -1);
  584. }
  585. static bool
  586. set_blocking (int fd, bool blocking)
  587. {
  588. int flags = fcntl (fd, F_GETFL);
  589. hard_assert (flags != -1);
  590. bool prev = !(flags & O_NONBLOCK);
  591. if (blocking)
  592. flags &= ~O_NONBLOCK;
  593. else
  594. flags |= O_NONBLOCK;
  595. hard_assert (fcntl (fd, F_SETFL, flags) != -1);
  596. return prev;
  597. }
  598. static void
  599. xclose (int fd)
  600. {
  601. while (close (fd) == -1)
  602. if (!soft_assert (errno == EINTR))
  603. break;
  604. }
  605. // --- Polling -----------------------------------------------------------------
  606. // Basically the poor man's GMainLoop/libev/libuv. It might make some sense
  607. // to instead use those tested and proven libraries but we don't need much
  608. // and it's interesting to implement.
  609. // At the moment the FD's are stored in an unsorted array. This is not ideal
  610. // complexity-wise but I don't think I have much of a choice with poll(),
  611. // and neither with epoll for that matter.
  612. //
  613. // unsorted array sorted array
  614. // search O(n) O(log n) [O(log log n)]
  615. // insert by fd O(n) O(n)
  616. // delete by fd O(n) O(n)
  617. //
  618. // Insertion in the unsorted array can be reduced to O(1) if I maintain a
  619. // bitmap of present FD's but that's still not a huge win.
  620. //
  621. // I don't expect this to be much of an issue, as there are typically not going
  622. // to be that many FD's to watch, and the linear approach is cache-friendly.
  623. typedef void (*poller_dispatcher_func) (const struct pollfd *, void *);
  624. #define POLLER_MIN_ALLOC 16
  625. #ifdef __linux__
  626. // I don't really need this, I've basically implemented this just because I can.
  627. #include <sys/epoll.h>
  628. struct poller_info
  629. {
  630. int fd; ///< Our file descriptor
  631. uint32_t events; ///< The events we registered
  632. poller_dispatcher_func dispatcher; ///< Event dispatcher
  633. void *user_data; ///< User data
  634. };
  635. struct poller
  636. {
  637. int epoll_fd; ///< The epoll FD
  638. struct poller_info **info; ///< Information associated with each FD
  639. struct epoll_event *revents; ///< Output array for epoll_wait()
  640. size_t len; ///< Number of polled descriptors
  641. size_t alloc; ///< Number of entries allocated
  642. /// Index of the element in `revents' that's currently being dispatched,
  643. /// or -1 if we're not dispatching at the moment.
  644. int dispatch_iterator;
  645. /// The total number of entries stored in `revents' by epoll_wait().
  646. int dispatch_total;
  647. };
  648. static void
  649. poller_init (struct poller *self)
  650. {
  651. self->epoll_fd = epoll_create (POLLER_MIN_ALLOC);
  652. hard_assert (self->epoll_fd != -1);
  653. set_cloexec (self->epoll_fd);
  654. self->len = 0;
  655. self->alloc = POLLER_MIN_ALLOC;
  656. self->info = xcalloc (self->alloc, sizeof *self->info);
  657. self->revents = xcalloc (self->alloc, sizeof *self->revents);
  658. self->dispatch_iterator = -1;
  659. self->dispatch_total = 0;
  660. }
  661. static void
  662. poller_free (struct poller *self)
  663. {
  664. for (size_t i = 0; i < self->len; i++)
  665. {
  666. struct poller_info *info = self->info[i];
  667. hard_assert (epoll_ctl (self->epoll_fd,
  668. EPOLL_CTL_DEL, info->fd, (void *) "") != -1);
  669. free (info);
  670. }
  671. xclose (self->epoll_fd);
  672. free (self->info);
  673. free (self->revents);
  674. }
  675. static ssize_t
  676. poller_find_by_fd (struct poller *self, int fd)
  677. {
  678. for (size_t i = 0; i < self->len; i++)
  679. if (self->info[i]->fd == fd)
  680. return i;
  681. return -1;
  682. }
  683. static void
  684. poller_ensure_space (struct poller *self)
  685. {
  686. if (self->len < self->alloc)
  687. return;
  688. self->alloc <<= 1;
  689. self->revents = xreallocarray
  690. (self->revents, sizeof *self->revents, self->alloc);
  691. self->info = xreallocarray
  692. (self->info, sizeof *self->info, self->alloc);
  693. }
  694. static int
  695. poller_epoll_to_poll_events (int events)
  696. {
  697. int result = 0;
  698. if (events & EPOLLIN) result |= POLLIN;
  699. if (events & EPOLLOUT) result |= POLLOUT;
  700. if (events & EPOLLERR) result |= POLLERR;
  701. if (events & EPOLLHUP) result |= POLLHUP;
  702. if (events & EPOLLPRI) result |= POLLPRI;
  703. return result;
  704. }
  705. static uint32_t
  706. poller_poll_to_epoll_events (uint32_t events)
  707. {
  708. uint32_t result = 0;
  709. if (events & POLLIN) result |= EPOLLIN;
  710. if (events & POLLOUT) result |= EPOLLOUT;
  711. if (events & POLLERR) result |= EPOLLERR;
  712. if (events & POLLHUP) result |= EPOLLHUP;
  713. if (events & POLLPRI) result |= EPOLLPRI;
  714. return result;
  715. }
  716. static void
  717. poller_set (struct poller *self, int fd, short int events,
  718. poller_dispatcher_func dispatcher, void *data)
  719. {
  720. ssize_t index = poller_find_by_fd (self, fd);
  721. bool modifying = true;
  722. if (index == -1)
  723. {
  724. poller_ensure_space (self);
  725. self->info[index = self->len++] = xcalloc (1, sizeof **self->info);
  726. modifying = false;
  727. }
  728. struct poller_info *info = self->info[index];
  729. info->fd = fd;
  730. info->dispatcher = dispatcher;
  731. info->user_data = data;
  732. struct epoll_event event;
  733. event.events = poller_poll_to_epoll_events (events);
  734. event.data.ptr = info;
  735. hard_assert (epoll_ctl (self->epoll_fd,
  736. modifying ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, fd, &event) != -1);
  737. }
  738. static void
  739. poller_remove_from_dispatch (struct poller *self,
  740. const struct poller_info *info)
  741. {
  742. if (self->dispatch_iterator == -1)
  743. return;
  744. int i;
  745. for (i = self->dispatch_iterator; i < self->dispatch_total; i++)
  746. if (self->revents[i].data.ptr == info)
  747. break;
  748. if (i == self->dispatch_total)
  749. return;
  750. if (i != --self->dispatch_total)
  751. self->revents[i] = self->revents[self->dispatch_total];
  752. // We've removed the element we're currently processing; go back one entry
  753. // so that we don't skip the one we might have replaced it with.
  754. if (i == self->dispatch_iterator)
  755. self->dispatch_iterator--;
  756. }
  757. static void
  758. poller_remove_at_index (struct poller *self, size_t index)
  759. {
  760. hard_assert (index < self->len);
  761. struct poller_info *info = self->info[index];
  762. poller_remove_from_dispatch (self, info);
  763. hard_assert (epoll_ctl (self->epoll_fd,
  764. EPOLL_CTL_DEL, info->fd, (void *) "") != -1);
  765. free (info);
  766. if (index != --self->len)
  767. self->info[index] = self->info[self->len];
  768. }
  769. static void
  770. poller_run (struct poller *self)
  771. {
  772. // Not reentrant
  773. hard_assert (self->dispatch_iterator == -1);
  774. int n_fds;
  775. do
  776. n_fds = epoll_wait (self->epoll_fd, self->revents, self->len, -1);
  777. while (n_fds == -1 && errno == EINTR);
  778. if (n_fds == -1)
  779. {
  780. print_fatal ("%s: %s", "epoll", strerror (errno));
  781. exit (EXIT_FAILURE);
  782. }
  783. for (int i = 0; i < n_fds; i++)
  784. {
  785. struct epoll_event *revents = self->revents + i;
  786. struct poller_info *info = revents->data.ptr;
  787. struct pollfd pfd;
  788. pfd.fd = info->fd;
  789. pfd.revents = poller_epoll_to_poll_events (revents->events);
  790. pfd.events = poller_epoll_to_poll_events (info->events);
  791. self->dispatch_iterator = i;
  792. self->dispatch_total = n_fds;
  793. info->dispatcher (&pfd, info->user_data);
  794. i = self->dispatch_iterator;
  795. n_fds = self->dispatch_total;
  796. }
  797. self->dispatch_iterator = -1;
  798. self->dispatch_total = 0;
  799. }
  800. #else // !__linux__
  801. struct poller_info
  802. {
  803. poller_dispatcher_func dispatcher; ///< Event dispatcher
  804. void *user_data; ///< User data
  805. };
  806. struct poller
  807. {
  808. struct pollfd *fds; ///< Polled descriptors
  809. struct poller_info *fds_info; ///< Additional information for each FD
  810. size_t len; ///< Number of polled descriptors
  811. size_t alloc; ///< Number of entries allocated
  812. int dispatch_index; ///< The currently dispatched FD or -1
  813. };
  814. static void
  815. poller_init (struct poller *self)
  816. {
  817. self->alloc = POLLER_MIN_ALLOC;
  818. self->len = 0;
  819. self->fds = xcalloc (self->alloc, sizeof *self->fds);
  820. self->fds_info = xcalloc (self->alloc, sizeof *self->fds_info);
  821. self->dispatch_index = -1;
  822. }
  823. static void
  824. poller_free (struct poller *self)
  825. {
  826. free (self->fds);
  827. free (self->fds_info);
  828. }
  829. static ssize_t
  830. poller_find_by_fd (struct poller *self, int fd)
  831. {
  832. for (size_t i = 0; i < self->len; i++)
  833. if (self->fds[i].fd == fd)
  834. return i;
  835. return -1;
  836. }
  837. static void
  838. poller_ensure_space (struct poller *self)
  839. {
  840. if (self->len < self->alloc)
  841. return;
  842. self->alloc <<= 1;
  843. self->fds = xreallocarray (self->fds, sizeof *self->fds, self->alloc);
  844. self->fds_info = xreallocarray
  845. (self->fds_info, sizeof *self->fds_info, self->alloc);
  846. }
  847. static void
  848. poller_set (struct poller *self, int fd, short int events,
  849. poller_dispatcher_func dispatcher, void *data)
  850. {
  851. ssize_t index = poller_find_by_fd (self, fd);
  852. if (index == -1)
  853. {
  854. poller_ensure_space (self);
  855. index = self->len++;
  856. }
  857. struct pollfd *new_entry = self->fds + index;
  858. memset (new_entry, 0, sizeof *new_entry);
  859. new_entry->fd = fd;
  860. new_entry->events = events;
  861. self->fds_info[self->len] = (struct poller_info) { dispatcher, data };
  862. }
  863. static void
  864. poller_remove_at_index (struct poller *self, size_t index)
  865. {
  866. hard_assert (index < self->len);
  867. if (index == --self->len)
  868. return;
  869. // Make sure that we don't disrupt the dispatch loop; kind of crude
  870. if ((int) index < self->dispatch_index)
  871. {
  872. memmove (self->fds + index, self->fds + index + 1,
  873. (self->len - index) * sizeof *self->fds);
  874. memmove (self->fds_info + index, self->fds_info + index + 1,
  875. (self->len - index) * sizeof *self->fds_info);
  876. }
  877. else
  878. {
  879. self->fds[index] = self->fds[self->len];
  880. self->fds_info[index] = self->fds_info[self->len];
  881. }
  882. if ((int) index <= self->dispatch_index)
  883. self->dispatch_index--;
  884. }
  885. static void
  886. poller_run (struct poller *self)
  887. {
  888. // Not reentrant
  889. hard_assert (self->dispatch_index == -1);
  890. int result;
  891. do
  892. result = poll (self->fds, self->len, -1);
  893. while (result == -1 && errno == EINTR);
  894. if (result == -1)
  895. {
  896. print_fatal ("%s: %s", "poll", strerror (errno));
  897. exit (EXIT_FAILURE);
  898. }
  899. for (int i = 0; i < (int) self->len; i++)
  900. {
  901. struct pollfd pfd = self->fds[i];
  902. if (!pfd.revents)
  903. continue;
  904. struct poller_info *info = self->fds_info + i;
  905. self->dispatch_index = i;
  906. info->dispatcher (&pfd, info->user_data);
  907. i = self->dispatch_index;
  908. }
  909. self->dispatch_index = -1;
  910. }
  911. #endif // !__linux__
  912. // --- Utilities ---------------------------------------------------------------
  913. static void
  914. split_str_ignore_empty (const char *s, char delimiter, struct str_vector *out)
  915. {
  916. const char *begin = s, *end;
  917. while ((end = strchr (begin, delimiter)))
  918. {
  919. if (begin != end)
  920. str_vector_add_owned (out, xstrndup (begin, end - begin));
  921. begin = ++end;
  922. }
  923. if (*begin)
  924. str_vector_add (out, begin);
  925. }
  926. static char *
  927. strip_str_in_place (char *s, const char *stripped_chars)
  928. {
  929. char *end = s + strlen (s);
  930. while (end > s && strchr (stripped_chars, end[-1]))
  931. *--end = '\0';
  932. char *start = s + strspn (s, stripped_chars);
  933. if (start > s)
  934. memmove (s, start, end - start + 1);
  935. return s;
  936. }
  937. static bool
  938. str_append_env_path (struct str *output, const char *var, bool only_absolute)
  939. {
  940. const char *value = getenv (var);
  941. if (!value || (only_absolute && *value != '/'))
  942. return false;
  943. str_append (output, value);
  944. return true;
  945. }
  946. static void
  947. get_xdg_home_dir (struct str *output, const char *var, const char *def)
  948. {
  949. str_reset (output);
  950. if (!str_append_env_path (output, var, true))
  951. {
  952. str_append_env_path (output, "HOME", false);
  953. str_append_c (output, '/');
  954. str_append (output, def);
  955. }
  956. }
  957. static size_t io_error_domain_tag;
  958. #define IO_ERROR (error_resolve_domain (&io_error_domain_tag))
  959. enum
  960. {
  961. IO_ERROR_FAILED
  962. };
  963. static bool
  964. ensure_directory_existence (const char *path, struct error **e)
  965. {
  966. struct stat st;
  967. if (stat (path, &st))
  968. {
  969. if (mkdir (path, S_IRWXU | S_IRWXG | S_IRWXO))
  970. {
  971. error_set (e, IO_ERROR, IO_ERROR_FAILED,
  972. "cannot create directory `%s': %s",
  973. path, strerror (errno));
  974. return false;
  975. }
  976. }
  977. else if (!S_ISDIR (st.st_mode))
  978. {
  979. error_set (e, IO_ERROR, IO_ERROR_FAILED,
  980. "cannot create directory `%s': %s",
  981. path, "file exists but is not a directory");
  982. return false;
  983. }
  984. return true;
  985. }
  986. static bool
  987. mkdir_with_parents (char *path, struct error **e)
  988. {
  989. char *p = path;
  990. // XXX: This is prone to the TOCTTOU problem. The solution would be to
  991. // rewrite the function using the {mkdir,fstat}at() functions from
  992. // POSIX.1-2008, ideally returning a file descriptor to the open
  993. // directory, with the current code as a fallback. Or to use chdir().
  994. while ((p = strchr (p + 1, '/')))
  995. {
  996. *p = '\0';
  997. bool success = ensure_directory_existence (path, e);
  998. *p = '/';
  999. if (!success)
  1000. return false;
  1001. }
  1002. return ensure_directory_existence (path, e);
  1003. }
  1004. static bool
  1005. set_boolean_if_valid (bool *out, const char *s)
  1006. {
  1007. if (!strcasecmp (s, "yes")) *out = true;
  1008. else if (!strcasecmp (s, "no")) *out = false;
  1009. else if (!strcasecmp (s, "on")) *out = true;
  1010. else if (!strcasecmp (s, "off")) *out = false;
  1011. else if (!strcasecmp (s, "true")) *out = true;
  1012. else if (!strcasecmp (s, "false")) *out = false;
  1013. else return false;
  1014. return true;
  1015. }
  1016. static void
  1017. regerror_to_str (int code, const regex_t *preg, struct str *out)
  1018. {
  1019. size_t required = regerror (code, preg, NULL, 0);
  1020. str_ensure_space (out, required);
  1021. out->len += regerror (code, preg,
  1022. out->str + out->len, out->alloc - out->len) - 1;
  1023. }
  1024. static size_t regex_error_domain_tag;
  1025. #define REGEX_ERROR (error_resolve_domain (&regex_error_domain_tag))
  1026. enum
  1027. {
  1028. REGEX_ERROR_COMPILATION_FAILED
  1029. };
  1030. static bool
  1031. regex_match (const char *regex, const char *s, struct error **e)
  1032. {
  1033. regex_t re;
  1034. int err = regcomp (&re, regex, REG_EXTENDED | REG_NOSUB);
  1035. if (err)
  1036. {
  1037. struct str desc;
  1038. str_init (&desc);
  1039. regerror_to_str (err, &re, &desc);
  1040. error_set (e, REGEX_ERROR, REGEX_ERROR_COMPILATION_FAILED,
  1041. "failed to compile regular expression: %s", desc.str);
  1042. str_free (&desc);
  1043. return false;
  1044. }
  1045. bool result = regexec (&re, s, 0, NULL, 0) != REG_NOMATCH;
  1046. regfree (&re);
  1047. return result;
  1048. }
  1049. static bool
  1050. read_line (FILE *fp, struct str *s)
  1051. {
  1052. int c;
  1053. bool at_end = true;
  1054. str_reset (s);
  1055. while ((c = fgetc (fp)) != EOF)
  1056. {
  1057. at_end = false;
  1058. if (c == '\r')
  1059. continue;
  1060. if (c == '\n')
  1061. break;
  1062. str_append_c (s, c);
  1063. }
  1064. return !at_end;
  1065. }
  1066. // --- IRC utilities -----------------------------------------------------------
  1067. struct irc_message
  1068. {
  1069. char *prefix;
  1070. char *command;
  1071. struct str_vector params;
  1072. };
  1073. static void
  1074. irc_parse_message (struct irc_message *msg, const char *line)
  1075. {
  1076. msg->prefix = NULL;
  1077. msg->command = NULL;
  1078. str_vector_init (&msg->params);
  1079. // Prefix
  1080. if (*line == ':')
  1081. {
  1082. size_t prefix_len = strcspn (++line, " ");
  1083. msg->prefix = xstrndup (line, prefix_len);
  1084. line += prefix_len;
  1085. }
  1086. // Command name
  1087. {
  1088. while (*line == ' ')
  1089. line++;
  1090. size_t cmd_len = strcspn (line, " ");
  1091. msg->command = xstrndup (line, cmd_len);
  1092. line += cmd_len;
  1093. }
  1094. // Arguments
  1095. while (true)
  1096. {
  1097. while (*line == ' ')
  1098. line++;
  1099. if (*line == ':')
  1100. {
  1101. str_vector_add (&msg->params, ++line);
  1102. break;
  1103. }
  1104. size_t param_len = strcspn (line, " ");
  1105. if (!param_len)
  1106. break;
  1107. str_vector_add_owned (&msg->params, xstrndup (line, param_len));
  1108. line += param_len;
  1109. }
  1110. }
  1111. static void
  1112. irc_free_message (struct irc_message *msg)
  1113. {
  1114. free (msg->prefix);
  1115. free (msg->command);
  1116. str_vector_free (&msg->params);
  1117. }
  1118. static void
  1119. irc_process_buffer (struct str *buf,
  1120. void (*callback)(const struct irc_message *, const char *, void *),
  1121. void *user_data)
  1122. {
  1123. char *start = buf->str;
  1124. char *end = start + buf->len;
  1125. for (char *p = start; p + 1 < end; p++)
  1126. {
  1127. // Split the input on newlines
  1128. if (p[0] != '\r' || p[1] != '\n')
  1129. continue;
  1130. *p = 0;
  1131. struct irc_message msg;
  1132. irc_parse_message (&msg, start);
  1133. callback (&msg, start, user_data);
  1134. irc_free_message (&msg);
  1135. start = p + 2;
  1136. }
  1137. str_remove_slice (buf, 0, start - buf->str);
  1138. }
  1139. // --- Configuration -----------------------------------------------------------
  1140. // The keys are stripped of surrounding whitespace, the values are not.
  1141. static size_t config_error_domain_tag;
  1142. #define CONFIG_ERROR (error_resolve_domain (&config_error_domain_tag))
  1143. enum
  1144. {
  1145. CONFIG_ERROR_MALFORMED
  1146. };
  1147. struct config_item
  1148. {
  1149. const char *key;
  1150. const char *default_value;
  1151. const char *description;
  1152. };
  1153. static FILE *
  1154. get_config_file (void)
  1155. {
  1156. struct str_vector paths;
  1157. struct str config_home, file;
  1158. const char *xdg_config_dirs;
  1159. unsigned i;
  1160. FILE *fp = NULL;
  1161. str_vector_init (&paths);
  1162. str_init (&config_home);
  1163. get_xdg_home_dir (&config_home, "XDG_CONFIG_HOME", ".config");
  1164. str_vector_add (&paths, config_home.str);
  1165. str_free (&config_home);
  1166. if ((xdg_config_dirs = getenv ("XDG_CONFIG_DIRS")))
  1167. split_str_ignore_empty (xdg_config_dirs, ':', &paths);
  1168. str_init (&file);
  1169. for (i = 0; i < paths.len; i++)
  1170. {
  1171. // As per spec, relative paths are ignored
  1172. if (*paths.vector[i] != '/')
  1173. continue;
  1174. str_reset (&file);
  1175. str_append (&file, paths.vector[i]);
  1176. str_append (&file, "/" PROGRAM_NAME "/" PROGRAM_NAME ".conf");
  1177. if ((fp = fopen (file.str, "r")))
  1178. break;
  1179. }
  1180. str_free (&file);
  1181. str_vector_free (&paths);
  1182. return fp;
  1183. }
  1184. static bool
  1185. read_config_file (struct str_map *config, struct error **e)
  1186. {
  1187. struct str line;
  1188. FILE *fp = get_config_file ();
  1189. unsigned line_no = 0;
  1190. bool errors = false;
  1191. if (!fp)
  1192. return true;
  1193. str_init (&line);
  1194. for (line_no = 1; read_line (fp, &line); line_no++)
  1195. {
  1196. char *start = line.str;
  1197. if (*start == '#')
  1198. continue;
  1199. while (isspace (*start))
  1200. start++;
  1201. char *end = strchr (start, '=');
  1202. if (!end)
  1203. {
  1204. if (*start)
  1205. {
  1206. error_set (e, CONFIG_ERROR, CONFIG_ERROR_MALFORMED,
  1207. "line %u in config: %s", line_no, "malformed input");
  1208. errors = true;
  1209. break;
  1210. }
  1211. }
  1212. else
  1213. {
  1214. char *value = end + 1;
  1215. do
  1216. *end = '\0';
  1217. while (isspace (*--end));
  1218. str_map_set (config, start, xstrdup (value));
  1219. }
  1220. }
  1221. str_free (&line);
  1222. fclose (fp);
  1223. return !errors;
  1224. }
  1225. // --- Configuration (application-specific) ------------------------------------
  1226. static struct config_item g_config_table[] =
  1227. {
  1228. { "nickname", "ZyklonB", "IRC nickname" },
  1229. { "username", "bot", "IRC user name" },
  1230. { "fullname", "ZyklonB IRC bot", "IRC full name/e-mail" },
  1231. { "irc_host", NULL, "Address of the IRC server" },
  1232. { "irc_port", "6667", "Port of the IRC server" },
  1233. { "ssl_use", "off", "Whether to use SSL" },
  1234. { "ssl_cert", NULL, "Client SSL certificate (PEM)" },
  1235. { "autojoin", NULL, "Channels to join on start" },
  1236. { "reconnect", "on", "Whether to reconnect on error" },
  1237. { "reconnect_delay", "5", "Time between reconnecting" },
  1238. { "prefix", ":", "The prefix for bot commands" },
  1239. { "admin", NULL, "Host mask for administrators" },
  1240. { "plugins", NULL, "The plugins to load on startup" },
  1241. { "plugin_dir", NULL, "Where to search for plugins" },
  1242. { "recover", "on", "Whether to re-launch on crash" },
  1243. };
  1244. static void
  1245. load_config_defaults (struct str_map *config)
  1246. {
  1247. for (size_t i = 0; i < N_ELEMENTS (g_config_table); i++)
  1248. {
  1249. const struct config_item *item = g_config_table + i;
  1250. if (item->default_value)
  1251. str_map_set (config, item->key, xstrdup (item->default_value));
  1252. }
  1253. }
  1254. // --- Application data --------------------------------------------------------
  1255. struct plugin_data
  1256. {
  1257. struct plugin_data *next; ///< The next link in a chain
  1258. struct plugin_data *prev; ///< The previous link in a chain
  1259. struct bot_context *ctx; ///< Parent context
  1260. pid_t pid; ///< PID of the plugin process
  1261. char *name; ///< Plugin identifier
  1262. bool is_zombie; ///< Whether the child is a zombie
  1263. bool initialized; ///< Ready to exchange IRC messages
  1264. struct str queued_output; ///< Output queued up until initialized
  1265. // Since we're doing non-blocking I/O, we need to queue up data so that
  1266. // we don't stall on plugins unnecessarily.
  1267. int read_fd; ///< The read end of the comm. pipe
  1268. struct str read_buffer; ///< Unprocessed input
  1269. int write_fd; ///< The write end of the comm. pipe
  1270. struct str write_buffer; ///< Output yet to be sent out
  1271. };
  1272. static void
  1273. plugin_data_init (struct plugin_data *self)
  1274. {
  1275. memset (self, 0, sizeof *self);
  1276. self->pid = -1;
  1277. str_init (&self->queued_output);
  1278. self->read_fd = -1;
  1279. str_init (&self->read_buffer);
  1280. self->write_fd = -1;
  1281. str_init (&self->write_buffer);
  1282. }
  1283. static void
  1284. plugin_data_free (struct plugin_data *self)
  1285. {
  1286. soft_assert (self->pid == -1);
  1287. free (self->name);
  1288. str_free (&self->read_buffer);
  1289. if (!soft_assert (self->read_fd == -1))
  1290. xclose (self->read_fd);
  1291. str_free (&self->write_buffer);
  1292. if (!soft_assert (self->write_fd == -1))
  1293. xclose (self->write_fd);
  1294. if (!self->initialized)
  1295. str_free (&self->queued_output);
  1296. }
  1297. static size_t connect_error_domain_tag;
  1298. #define CONNECT_ERROR (error_resolve_domain (&connect_error_domain_tag))
  1299. enum
  1300. {
  1301. CONNECT_ERROR_INVALID_CONFIGURATION,
  1302. CONNECT_ERROR_FAILED
  1303. };
  1304. struct bot_context
  1305. {
  1306. struct str_map config; ///< User configuration
  1307. int irc_fd; ///< Socket FD of the server
  1308. struct str read_buffer; ///< Input yet to be processed
  1309. bool irc_ready; ///< Whether we may send messages now
  1310. SSL_CTX *ssl_ctx; ///< SSL context
  1311. SSL *ssl; ///< SSL connection
  1312. struct plugin_data *plugins; ///< Linked list of plugins
  1313. struct str_map plugins_by_name; ///< Indexes @em plugins by their name
  1314. struct poller poller; ///< Manages polled descriptors
  1315. bool quitting; ///< User requested quitting
  1316. bool polling; ///< The event loop is running
  1317. };
  1318. static void
  1319. bot_context_init (struct bot_context *ctx)
  1320. {
  1321. str_map_init (&ctx->config);
  1322. ctx->config.free = free;
  1323. load_config_defaults (&ctx->config);
  1324. ctx->irc_fd = -1;
  1325. str_init (&ctx->read_buffer);
  1326. ctx->irc_ready = false;
  1327. ctx->ssl = NULL;
  1328. ctx->ssl_ctx = NULL;
  1329. ctx->plugins = NULL;
  1330. str_map_init (&ctx->plugins_by_name);
  1331. poller_init (&ctx->poller);
  1332. ctx->quitting = false;
  1333. ctx->polling = false;
  1334. }
  1335. static void
  1336. bot_context_free (struct bot_context *ctx)
  1337. {
  1338. str_map_free (&ctx->config);
  1339. str_free (&ctx->read_buffer);
  1340. // TODO: terminate the plugins properly before this is called
  1341. struct plugin_data *link, *tmp;
  1342. for (link = ctx->plugins; link; link = tmp)
  1343. {
  1344. tmp = link->next;
  1345. plugin_data_free (link);
  1346. free (link);
  1347. }
  1348. if (ctx->irc_fd != -1)
  1349. xclose (ctx->irc_fd);
  1350. if (ctx->ssl)
  1351. SSL_free (ctx->ssl);
  1352. if (ctx->ssl_ctx)
  1353. SSL_CTX_free (ctx->ssl_ctx);
  1354. str_map_free (&ctx->plugins_by_name);
  1355. poller_free (&ctx->poller);
  1356. }
  1357. static void
  1358. irc_shutdown (struct bot_context *ctx)
  1359. {
  1360. // Generally non-critical
  1361. if (ctx->ssl)
  1362. soft_assert (SSL_shutdown (ctx->ssl) != -1);
  1363. else
  1364. soft_assert (shutdown (ctx->irc_fd, SHUT_WR) == 0);
  1365. }
  1366. static void
  1367. initiate_quit (struct bot_context *ctx)
  1368. {
  1369. irc_shutdown (ctx);
  1370. ctx->quitting = true;
  1371. }
  1372. static void
  1373. try_finish_quit (struct bot_context *ctx)
  1374. {
  1375. if (!ctx->quitting)
  1376. return;
  1377. if (ctx->irc_fd == -1 && !ctx->plugins)
  1378. ctx->polling = false;
  1379. }
  1380. static bool irc_send (struct bot_context *ctx,
  1381. const char *format, ...) ATTRIBUTE_PRINTF (2, 3);
  1382. // XXX: is it okay to just ignore the return value and wait until we receive
  1383. // it in on_irc_readable()?
  1384. static bool
  1385. irc_send (struct bot_context *ctx, const char *format, ...)
  1386. {
  1387. va_list ap;
  1388. if (g_debug_mode)
  1389. {
  1390. fputs ("[IRC] <== \"", stderr);
  1391. va_start (ap, format);
  1392. vfprintf (stderr, format, ap);
  1393. va_end (ap);
  1394. fputs ("\"\n", stderr);
  1395. }
  1396. soft_assert (ctx->irc_fd != -1);
  1397. va_start (ap, format);
  1398. struct str str;
  1399. str_init (&str);
  1400. str_append_vprintf (&str, format, ap);
  1401. str_append (&str, "\r\n");
  1402. va_end (ap);
  1403. bool result = true;
  1404. if (ctx->ssl)
  1405. {
  1406. // TODO: call SSL_get_error() to detect if a clean shutdown has occured
  1407. if (SSL_write (ctx->ssl, str.str, str.len) != (int) str.len)
  1408. {
  1409. print_debug ("%s: %s: %s", __func__, "SSL_write",
  1410. ERR_error_string (ERR_get_error (), NULL));
  1411. result = false;
  1412. }
  1413. }
  1414. else if (write (ctx->irc_fd, str.str, str.len) != (ssize_t) str.len)
  1415. {
  1416. print_debug ("%s: %s: %s", __func__, "write", strerror (errno));
  1417. result = false;
  1418. }
  1419. str_free (&str);
  1420. return result;
  1421. }
  1422. static bool
  1423. irc_initialize_ssl (struct bot_context *ctx, struct error **e)
  1424. {
  1425. ctx->ssl_ctx = SSL_CTX_new (SSLv23_client_method ());
  1426. if (!ctx->ssl_ctx)
  1427. goto error_ssl_1;
  1428. // We don't care; some encryption is always better than no encryption
  1429. SSL_CTX_set_verify (ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  1430. // XXX: maybe we should call SSL_CTX_set_options() for some workarounds
  1431. ctx->ssl = SSL_new (ctx->ssl_ctx);
  1432. if (!ctx->ssl)
  1433. goto error_ssl_2;
  1434. const char *ssl_cert = str_map_find (&ctx->config, "ssl_cert");
  1435. if (ssl_cert
  1436. && !SSL_use_certificate_file (ctx->ssl, ssl_cert, SSL_FILETYPE_PEM))
  1437. {
  1438. // XXX: perhaps we should read the file ourselves for better messages
  1439. print_error ("%s: %s", "setting the SSL client certificate failed",
  1440. ERR_error_string (ERR_get_error (), NULL));
  1441. }
  1442. SSL_set_connect_state (ctx->ssl);
  1443. if (!SSL_set_fd (ctx->ssl, ctx->irc_fd))
  1444. goto error_ssl_3;
  1445. // Avoid SSL_write() returning SSL_ERROR_WANT_READ
  1446. SSL_set_mode (ctx->ssl, SSL_MODE_AUTO_RETRY);
  1447. if (SSL_connect (ctx->ssl) > 0)
  1448. return true;
  1449. error_ssl_3:
  1450. SSL_free (ctx->ssl);
  1451. ctx->ssl = NULL;
  1452. error_ssl_2:
  1453. SSL_CTX_free (ctx->ssl_ctx);
  1454. ctx->ssl_ctx = NULL;
  1455. error_ssl_1:
  1456. // XXX: these error strings are really nasty; also there could be
  1457. // multiple errors on the OpenSSL stack.
  1458. error_set (e, CONNECT_ERROR, CONNECT_ERROR_FAILED,
  1459. "%s: %s", "could not initialize SSL",
  1460. ERR_error_string (ERR_get_error (), NULL));
  1461. return false;
  1462. }
  1463. static bool
  1464. irc_establish_connection (struct bot_context *ctx,
  1465. const char *host, const char *port, bool use_ssl, struct error **e)
  1466. {
  1467. struct addrinfo gai_hints, *gai_result, *gai_iter;
  1468. memset (&gai_hints, 0, sizeof gai_hints);
  1469. // We definitely want TCP.
  1470. gai_hints.ai_socktype = SOCK_STREAM;
  1471. int err = getaddrinfo (host, port, &gai_hints, &gai_result);
  1472. if (err)
  1473. {
  1474. error_set (e, CONNECT_ERROR, CONNECT_ERROR_FAILED, "%s: %s: %s",
  1475. "connection failed", "getaddrinfo", gai_strerror (err));
  1476. return false;
  1477. }
  1478. int sockfd;
  1479. for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next)
  1480. {
  1481. sockfd = socket (gai_iter->ai_family,
  1482. gai_iter->ai_socktype, gai_iter->ai_protocol);
  1483. if (sockfd == -1)
  1484. continue;
  1485. set_cloexec (sockfd);
  1486. int yes = 1;
  1487. soft_assert (setsockopt (sockfd, SOL_SOCKET, SO_KEEPALIVE,
  1488. &yes, sizeof yes) != -1);
  1489. const char *real_host = host;
  1490. // Let's try to resolve the address back into a real hostname;
  1491. // we don't really need this, so we can let it quietly fail
  1492. char buf[NI_MAXHOST];
  1493. err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
  1494. buf, sizeof buf, NULL, 0, 0);
  1495. if (err)
  1496. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  1497. else
  1498. real_host = buf;
  1499. // XXX: we shouldn't mix these statuses with `struct error'; choose 1!
  1500. print_status ("connecting to `%s:%s'...", real_host, port);
  1501. if (!connect (sockfd, gai_iter->ai_addr, gai_iter->ai_addrlen))
  1502. break;
  1503. xclose (sockfd);
  1504. }
  1505. freeaddrinfo (gai_result);
  1506. if (!gai_iter)
  1507. {
  1508. error_set (e, CONNECT_ERROR, CONNECT_ERROR_FAILED, "connection failed");
  1509. return false;
  1510. }
  1511. ctx->irc_fd = sockfd;
  1512. if (use_ssl && !irc_initialize_ssl (ctx, e))
  1513. {
  1514. xclose (ctx->irc_fd);
  1515. ctx->irc_fd = -1;
  1516. return false;
  1517. }
  1518. print_status ("connection established");
  1519. return true;
  1520. }
  1521. // --- Signals -----------------------------------------------------------------
  1522. static int g_signal_pipe[2]; ///< A pipe used to signal... signals
  1523. static struct str_vector
  1524. g_original_argv, ///< Original program arguments
  1525. g_recovery_env; ///< Environment for re-exec recovery
  1526. /// Program termination has been requested by a signal
  1527. static volatile sig_atomic_t g_termination_requested;
  1528. /// Points to startup reason location within `g_recovery_environment'
  1529. static char **g_startup_reason_location;
  1530. /// The environment variable used to pass the startup reason when re-executing
  1531. static const char g_startup_reason_str[] = "STARTUP_REASON";
  1532. static void
  1533. sigchld_handler (int signum)
  1534. {
  1535. (void) signum;
  1536. int original_errno = errno;
  1537. // Just so that the read end of the pipe wakes up the poller.
  1538. // NOTE: Linux has signalfd() and eventfd(), and the BSD's have kqueue.
  1539. // All of them are better than this approach, although platform-specific.
  1540. if (write (g_signal_pipe[1], "c", 1) == -1)
  1541. soft_assert (errno == EAGAIN);
  1542. errno = original_errno;
  1543. }
  1544. static void
  1545. sigterm_handler (int signum)
  1546. {
  1547. (void) signum;
  1548. g_termination_requested = true;
  1549. int original_errno = errno;
  1550. if (write (g_signal_pipe[1], "t", 1) == -1)
  1551. soft_assert (errno == EAGAIN);
  1552. errno = original_errno;
  1553. }
  1554. static void
  1555. setup_signal_handlers (void)
  1556. {
  1557. if (pipe (g_signal_pipe) == -1)
  1558. {
  1559. print_fatal ("pipe: %s", strerror (errno));
  1560. exit (EXIT_FAILURE);
  1561. }
  1562. set_cloexec (g_signal_pipe[0]);
  1563. set_cloexec (g_signal_pipe[1]);
  1564. // So that the pipe cannot overflow; it would make write() block within
  1565. // the signal handler, which is something we really don't want to happen.
  1566. // The same holds true for read().
  1567. set_blocking (g_signal_pipe[0], false);
  1568. set_blocking (g_signal_pipe[1], false);
  1569. struct sigaction sa;
  1570. sa.sa_flags = SA_RESTART;
  1571. sa.sa_handler = sigchld_handler;
  1572. sigemptyset (&sa.sa_mask);
  1573. if (sigaction (SIGCHLD, &sa, NULL) == -1)
  1574. {
  1575. print_fatal ("sigaction: %s", strerror (errno));
  1576. exit (EXIT_FAILURE);
  1577. }
  1578. signal (SIGPIPE, SIG_IGN);
  1579. sa.sa_handler = sigterm_handler;
  1580. if (sigaction (SIGINT, &sa, NULL) == -1
  1581. || sigaction (SIGTERM, &sa, NULL) == -1)
  1582. print_error ("sigaction: %s", strerror (errno));
  1583. }
  1584. static void
  1585. translate_signal_info (int no, const char **name, int code, const char **reason)
  1586. {
  1587. if (code == SI_USER) *reason = "signal sent by kill()";
  1588. if (code == SI_QUEUE) *reason = "signal sent by sigqueue()";
  1589. switch (no)
  1590. {
  1591. case SIGILL:
  1592. *name = "SIGILL";
  1593. if (code == ILL_ILLOPC) *reason = "illegal opcode";
  1594. if (code == ILL_ILLOPN) *reason = "illegal operand";
  1595. if (code == ILL_ILLADR) *reason = "illegal addressing mode";
  1596. if (code == ILL_ILLTRP) *reason = "illegal trap";
  1597. if (code == ILL_PRVOPC) *reason = "privileged opcode";
  1598. if (code == ILL_PRVREG) *reason = "privileged register";
  1599. if (code == ILL_COPROC) *reason = "coprocessor error";
  1600. if (code == ILL_BADSTK) *reason = "internal stack error";
  1601. break;
  1602. case SIGFPE:
  1603. *name = "SIGFPE";
  1604. if (code == FPE_INTDIV) *reason = "integer divide by zero";
  1605. if (code == FPE_INTOVF) *reason = "integer overflow";
  1606. if (code == FPE_FLTDIV) *reason = "floating-point divide by zero";
  1607. if (code == FPE_FLTOVF) *reason = "floating-point overflow";
  1608. if (code == FPE_FLTUND) *reason = "floating-point underflow";
  1609. if (code == FPE_FLTRES) *reason = "floating-point inexact result";
  1610. if (code == FPE_FLTINV) *reason = "invalid floating-point operation";
  1611. if (code == FPE_FLTSUB) *reason = "subscript out of range";
  1612. break;
  1613. case SIGSEGV:
  1614. *name = "SIGSEGV";
  1615. if (code == SEGV_MAPERR)
  1616. *reason = "address not mapped to object";
  1617. if (code == SEGV_ACCERR)
  1618. *reason = "invalid permissions for mapped object";
  1619. break;
  1620. case SIGBUS:
  1621. *name = "SIGBUS";
  1622. if (code == BUS_ADRALN) *reason = "invalid address alignment";
  1623. if (code == BUS_ADRERR) *reason = "nonexistent physical address";
  1624. if (code == BUS_OBJERR) *reason = "object-specific hardware error";
  1625. break;
  1626. default:
  1627. *name = NULL;
  1628. }
  1629. }
  1630. static void
  1631. recovery_handler (int signum, siginfo_t *info, void *context)
  1632. {
  1633. (void) context;
  1634. // TODO: maybe try to force a core dump like this: if (fork() == 0) return;
  1635. // TODO: maybe we could even send "\r\nQUIT :reason\r\n" to the server. >_>
  1636. // As long as we're not connected via TLS, that is.
  1637. const char *signal_name = NULL, *reason = NULL;
  1638. translate_signal_info (signum, &signal_name, info->si_code, &reason);
  1639. char buf[128], numbuf[8];
  1640. if (!signal_name)
  1641. {
  1642. snprintf (numbuf, sizeof numbuf, "%d", signum);
  1643. signal_name = numbuf;
  1644. }
  1645. if (reason)
  1646. snprintf (buf, sizeof buf, "%s=%s: %s: %s", g_startup_reason_str,
  1647. "signal received", signal_name, reason);
  1648. else
  1649. snprintf (buf, sizeof buf, "%s=%s: %s", g_startup_reason_str,
  1650. "signal received", signal_name);
  1651. *g_startup_reason_location = buf;
  1652. // TODO: maybe pregenerate the path, see the following for some other ways
  1653. // that would be illegal to do from within a signal handler:
  1654. // http://stackoverflow.com/a/1024937
  1655. // http://stackoverflow.com/q/799679
  1656. // Especially if we change the current working directory in the program.
  1657. //
  1658. // Note that I can just overwrite g_orig_argv[0].
  1659. // NOTE: our children will read EOF on the read ends of their pipes as a
  1660. // a result of O_CLOEXEC. That should be enough to make them terminate.
  1661. char **argv = g_original_argv.vector, **argp = g_recovery_env.vector;
  1662. execve ("/proc/self/exe", argv, argp); // Linux
  1663. execve ("/proc/curproc/file", argv, argp); // BSD
  1664. execve ("/proc/curproc/exe", argv, argp); // BSD
  1665. execve ("/proc/self/path/a.out", argv, argp); // Solaris
  1666. execve (argv[0], argv, argp); // unreliable fallback
  1667. // Let's just crash
  1668. perror ("execve");
  1669. signal (signum, SIG_DFL);
  1670. raise (signum);
  1671. }
  1672. static void
  1673. prepare_recovery_environment (void)
  1674. {
  1675. str_vector_init (&g_recovery_env);
  1676. str_vector_add_vector (&g_recovery_env, environ);
  1677. // Prepare a location within the environment where we will put the startup
  1678. // (or maybe rather restart) reason in case of an irrecoverable error.
  1679. char **iter;
  1680. for (iter = g_recovery_env.vector; *iter; iter++)
  1681. {
  1682. const size_t len = sizeof g_startup_reason_str - 1;
  1683. if (!strncmp (*iter, g_startup_reason_str, len) && (*iter)[len] == '=')
  1684. break;
  1685. }
  1686. if (iter)
  1687. g_startup_reason_location = iter;
  1688. else
  1689. {
  1690. str_vector_add (&g_recovery_env, "");
  1691. g_startup_reason_location =
  1692. g_recovery_env.vector + g_recovery_env.len - 1;
  1693. }
  1694. }
  1695. static void
  1696. setup_recovery_handler (struct bot_context *ctx)
  1697. {
  1698. const char *recover_str = str_map_find (&ctx->config, "recover");
  1699. hard_assert (recover_str != NULL); // We have a default value for this
  1700. bool recover;
  1701. if (!set_boolean_if_valid (&recover, recover_str))
  1702. {
  1703. print_fatal ("invalid configuration value for `%s'", "recover");
  1704. exit (EXIT_FAILURE);
  1705. }
  1706. if (!recover)
  1707. return;
  1708. // Make sure these signals aren't blocked, otherwise we would be unable
  1709. // to handle them, making the critical conditions fatal.
  1710. sigset_t mask;
  1711. sigemptyset (&mask);
  1712. sigaddset (&mask, SIGSEGV);
  1713. sigaddset (&mask, SIGBUS);
  1714. sigaddset (&mask, SIGFPE);
  1715. sigaddset (&mask, SIGILL);
  1716. sigprocmask (SIG_UNBLOCK, &mask, NULL);
  1717. struct sigaction sa;
  1718. sa.sa_flags = SA_SIGINFO;
  1719. sa.sa_sigaction = recovery_handler;
  1720. sigemptyset (&sa.sa_mask);
  1721. prepare_recovery_environment ();
  1722. // TODO: also handle SIGABRT... or avoid doing abort() in the first place?
  1723. if (sigaction (SIGSEGV, &sa, NULL) == -1
  1724. || sigaction (SIGBUS, &sa, NULL) == -1
  1725. || sigaction (SIGFPE, &sa, NULL) == -1
  1726. || sigaction (SIGILL, &sa, NULL) == -1)
  1727. print_error ("sigaction: %s", strerror (errno));
  1728. }
  1729. // --- Plugins -----------------------------------------------------------------
  1730. /// The name of the special IRC command for interprocess communication
  1731. static const char *plugin_ipc_command = "ZYKLONB";
  1732. static size_t plugin_error_domain_tag;
  1733. #define PLUGIN_ERROR (error_resolve_domain (&plugin_error_domain_tag))
  1734. enum
  1735. {
  1736. PLUGIN_ERROR_ALREADY_LOADED,
  1737. PLUGIN_ERROR_NOT_LOADED,
  1738. PLUGIN_ERROR_LOADING_FAILED
  1739. };
  1740. static struct plugin_data *
  1741. plugin_find_by_pid (struct bot_context *ctx, pid_t pid)
  1742. {
  1743. struct plugin_data *iter;
  1744. for (iter = ctx->plugins; iter; iter = iter->next)
  1745. if (iter->pid == pid)
  1746. return iter;
  1747. return NULL;
  1748. }
  1749. static bool
  1750. plugin_zombify (struct plugin_data *plugin)
  1751. {
  1752. if (plugin->is_zombie)
  1753. return false;
  1754. // FIXME: make sure that we don't remove entries from the poller while we
  1755. // still may have stuff to read; maybe just check that the read pipe is
  1756. // empty before closing it... and then on EOF check if `pid == -1' and
  1757. // only then dispose of it (it'd be best to simulate that both of these
  1758. // cases may happen).
  1759. ssize_t poller_idx =
  1760. poller_find_by_fd (&plugin->ctx->poller, plugin->write_fd);
  1761. if (poller_idx != -1)
  1762. poller_remove_at_index (&plugin->ctx->poller, poller_idx);
  1763. // TODO: try to flush the write buffer (non-blocking)?
  1764. // The plugin should terminate itself after it receives EOF.
  1765. xclose (plugin->write_fd);
  1766. plugin->write_fd = -1;
  1767. // Make it a pseudo-anonymous zombie. In this state we process any
  1768. // remaining commands it attempts to send to us before it finally dies.
  1769. str_map_set (&plugin->ctx->plugins_by_name, plugin->name, NULL);
  1770. plugin->is_zombie = true;
  1771. return true;
  1772. }
  1773. static void
  1774. on_plugin_writable (const struct pollfd *fd, struct plugin_data *plugin)
  1775. {
  1776. struct bot_context *ctx = plugin->ctx;
  1777. struct str *buf = &plugin->write_buffer;
  1778. size_t written_total = 0;
  1779. // TODO: see "Advanced Programming in the UNIX Environment" Figure C.19;
  1780. // check for any unexpected behaviour that might occur
  1781. if (fd->revents != POLLOUT)
  1782. print_debug ("poller fd %d: revents: %d", fd->fd, fd->revents);
  1783. while (written_total != buf->len)
  1784. {
  1785. ssize_t n_written = write (fd->fd, buf->str + written_total,
  1786. buf->len - written_total);
  1787. if (n_written < 0)
  1788. {
  1789. if (errno == EAGAIN)
  1790. break;
  1791. if (!soft_assert (errno == EINTR) && !plugin->is_zombie)
  1792. {
  1793. print_debug ("%s: %s", "recv", strerror (errno));
  1794. print_error ("failure on writing to plugin `%s',"
  1795. " therefore I'm unloading it", plugin->name);
  1796. plugin_zombify (plugin);
  1797. break;
  1798. }
  1799. }
  1800. // This may be equivalent to EAGAIN on some implementations
  1801. if (n_written == 0)
  1802. break;
  1803. written_total += n_written;
  1804. }
  1805. if (written_total != 0)
  1806. str_remove_slice (buf, 0, written_total);
  1807. if (buf->len == 0)
  1808. {
  1809. // Everything has been written, there's no need to end up in here again
  1810. ssize_t index = poller_find_by_fd (&ctx->poller, fd->fd);
  1811. if (index != -1)
  1812. poller_remove_at_index (&ctx->poller, index);
  1813. }
  1814. }
  1815. static void
  1816. plugin_queue_write (struct plugin_data *plugin)
  1817. {
  1818. if (plugin->is_zombie)
  1819. return;
  1820. // Don't let the write buffer grow infinitely. If there's a ton of data
  1821. // waiting to be processed by the plugin, it usually means there's something
  1822. // wrong with it (such as someone stopping the process).
  1823. if (plugin->write_buffer.len >= (1 << 20))
  1824. {
  1825. print_warning ("plugin `%s' does not seem to process messages fast"
  1826. " enough, I'm unloading it", plugin->name);
  1827. plugin_zombify (plugin);
  1828. return;
  1829. }
  1830. poller_set (&plugin->ctx->poller, plugin->write_fd, POLLOUT,
  1831. (poller_dispatcher_func) on_plugin_writable, plugin);
  1832. }
  1833. static void
  1834. plugin_send (struct plugin_data *plugin, const char *format, ...)
  1835. ATTRIBUTE_PRINTF (2, 3);
  1836. static void
  1837. plugin_send (struct plugin_data *plugin, const char *format, ...)
  1838. {
  1839. va_list ap;
  1840. if (g_debug_mode)
  1841. {
  1842. fprintf (stderr, "[%s] <-- \"", plugin->name);
  1843. va_start (ap, format);
  1844. vfprintf (stderr, format, ap);
  1845. va_end (ap);
  1846. fputs ("\"\n", stderr);
  1847. }
  1848. va_start (ap, format);
  1849. str_append_vprintf (&plugin->write_buffer, format, ap);
  1850. va_end (ap);
  1851. str_append (&plugin->write_buffer, "\r\n");
  1852. plugin_queue_write (plugin);
  1853. }
  1854. static void
  1855. plugin_process_message (const struct irc_message *msg,
  1856. const char *raw, void *user_data)
  1857. {
  1858. struct plugin_data *plugin = user_data;
  1859. struct bot_context *ctx = plugin->ctx;
  1860. if (g_debug_mode)
  1861. fprintf (stderr, "[%s] --> \"%s\"\n", plugin->name, raw);
  1862. if (!strcasecmp (msg->command, plugin_ipc_command))
  1863. {
  1864. // Replies are sent in the order in which they came in, so there's
  1865. // no need to attach a special identifier to them. It might be
  1866. // desirable in some cases, though.
  1867. if (msg->params.len < 1)
  1868. return;
  1869. const char *command = msg->params.vector[0];
  1870. if (!strcasecmp (command, "register"))
  1871. {
  1872. // Register for relaying of IRC traffic
  1873. plugin->initialized = true;
  1874. // Flush any queued up traffic here. The point of queuing it in
  1875. // the first place is so that we don't have to wait for plugin
  1876. // initialization during startup.
  1877. //
  1878. // Note that if we start filtering data coming to the plugins e.g.
  1879. // based on what it tells us upon registration, we might need to
  1880. // filter `queued_output' as well.
  1881. str_append_str (&plugin->write_buffer, &plugin->queued_output);
  1882. str_free (&plugin->queued_output);
  1883. // NOTE: this may trigger the buffer length check
  1884. plugin_queue_write (plugin);
  1885. }
  1886. else if (!strcasecmp (command, "get_config"))
  1887. {
  1888. if (msg->params.len < 2)
  1889. return;
  1890. const char *value =
  1891. str_map_find (&ctx->config, msg->params.vector[1]);
  1892. // TODO: escape the value (although there's no need to ATM)
  1893. plugin_send (plugin, "%s :%s",
  1894. plugin_ipc_command, value ? value : "");
  1895. }
  1896. else if (!strcasecmp (command, "print"))
  1897. {
  1898. if (msg->params.len < 2)
  1899. return;
  1900. printf ("%s", msg->params.vector[1]);
  1901. }
  1902. }
  1903. else if (plugin->initialized)
  1904. {
  1905. // Pass everything else through to the IRC server
  1906. irc_send (ctx, "%s", raw);
  1907. }
  1908. }
  1909. static void
  1910. on_plugin_readable (const struct pollfd *fd, struct plugin_data *plugin)
  1911. {
  1912. // TODO: see "Advanced Programming in the UNIX Environment" Figure C.19;
  1913. // check for any unexpected behaviour that might occur
  1914. if (fd->revents != POLLIN)
  1915. print_debug ("poller fd %d: revents: %d", fd->fd, fd->revents);
  1916. // TODO: see if I can reuse irc_fill_read_buffer()
  1917. struct str *buf = &plugin->read_buffer;
  1918. while (true)
  1919. {
  1920. str_ensure_space (buf, 512 + 1);
  1921. ssize_t n_read = read (fd->fd, buf->str + buf->len,
  1922. buf->alloc - buf->len - 1);
  1923. if (n_read < 0)
  1924. {
  1925. if (errno == EAGAIN)
  1926. break;
  1927. if (soft_assert (errno == EINTR))
  1928. continue;
  1929. if (!plugin->is_zombie)
  1930. {
  1931. print_error ("failure on reading from plugin `%s',"
  1932. " therefore I'm unloading it", plugin->name);
  1933. plugin_zombify (plugin);
  1934. }
  1935. return;
  1936. }
  1937. // EOF; hopefully it will die soon (maybe it already has)
  1938. if (n_read == 0)
  1939. break;
  1940. buf->str[buf->len += n_read] = '\0';
  1941. if (buf->len >= (1 << 20))
  1942. {
  1943. // XXX: this isn't really the best flood prevention mechanism,
  1944. // but it wasn't even supposed to be one.
  1945. if (plugin->is_zombie)
  1946. {
  1947. print_error ("a zombie of plugin `%s' is trying to flood us,"
  1948. " therefore I'm killing it", plugin->name);
  1949. kill (plugin->pid, SIGKILL);
  1950. }
  1951. else
  1952. {
  1953. print_error ("plugin `%s' seems to spew out data frantically,"
  1954. " therefore I'm unloading it", plugin->name);
  1955. plugin_zombify (plugin);
  1956. }
  1957. return;
  1958. }
  1959. }
  1960. // Hold it in the buffer while we're disconnected
  1961. struct bot_context *ctx = plugin->ctx;
  1962. if (ctx->irc_fd != -1 && ctx->irc_ready)
  1963. irc_process_buffer (buf, plugin_process_message, plugin);
  1964. }
  1965. static bool
  1966. is_valid_plugin_name (const char *name)
  1967. {
  1968. if (!*name)
  1969. return false;
  1970. for (const char *p = name; *p; p++)
  1971. if (!isgraph (*p) || *p == '/')
  1972. return false;
  1973. return true;
  1974. }
  1975. static bool
  1976. plugin_load (struct bot_context *ctx, const char *name, struct error **e)
  1977. {
  1978. const char *plugin_dir = str_map_find (&ctx->config, "plugin_dir");
  1979. if (!plugin_dir)
  1980. {
  1981. error_set (e, PLUGIN_ERROR, PLUGIN_ERROR_LOADING_FAILED,
  1982. "plugin directory not set");
  1983. return false;
  1984. }
  1985. if (!is_valid_plugin_name (name))
  1986. {
  1987. error_set (e, PLUGIN_ERROR, PLUGIN_ERROR_LOADING_FAILED,
  1988. "invalid plugin name");
  1989. return false;
  1990. }
  1991. if (str_map_find (&ctx->plugins_by_name, name))
  1992. {
  1993. error_set (e, PLUGIN_ERROR, PLUGIN_ERROR_ALREADY_LOADED,
  1994. "the plugin has already been loaded");
  1995. return false;
  1996. }
  1997. int stdin_pipe[2];
  1998. if (pipe (stdin_pipe) == -1)
  1999. {
  2000. error_set (e, PLUGIN_ERROR, PLUGIN_ERROR_LOADING_FAILED, "%s: %s: %s",
  2001. "failed to load the plugin", "pipe", strerror (errno));
  2002. goto fail_1;
  2003. }
  2004. int stdout_pipe[2];
  2005. if (pipe (stdout_pipe) == -1)
  2006. {
  2007. error_set (e, PLUGIN_ERROR, PLUGIN_ERROR_LOADING_FAILED, "%s: %s: %s",
  2008. "failed to load the plugin", "pipe", strerror (errno));
  2009. goto fail_2;
  2010. }
  2011. set_cloexec (stdin_pipe[1]);
  2012. set_cloexec (stdout_pipe[0]);
  2013. pid_t pid = fork ();
  2014. if (pid == -1)
  2015. {
  2016. error_set (e, PLUGIN_ERROR, PLUGIN_ERROR_LOADING_FAILED, "%s: %s: %s",
  2017. "failed to load the plugin", "fork", strerror (errno));
  2018. goto fail_3;
  2019. }
  2020. if (pid == 0)
  2021. {
  2022. // Redirect the child's stdin and stdout to the pipes
  2023. hard_assert (dup2 (stdin_pipe[0], STDIN_FILENO) != -1);
  2024. hard_assert (dup2 (stdout_pipe[1], STDOUT_FILENO) != -1);
  2025. xclose (stdin_pipe[0]);
  2026. xclose (stdout_pipe[1]);
  2027. struct str pathname;
  2028. str_init (&pathname);
  2029. str_append (&pathname, plugin_dir);
  2030. str_append_c (&pathname, '/');
  2031. str_append (&pathname, name);
  2032. // Restore some of the signal handling
  2033. signal (SIGPIPE, SIG_DFL);
  2034. char *const argv[] = { pathname.str, NULL };
  2035. execve (argv[0], argv, environ);
  2036. // We will collect the failure later via SIGCHLD
  2037. print_fatal ("%s: %s: %s",
  2038. "failed to load the plugin", "exec", strerror (errno));
  2039. _exit (EXIT_FAILURE);
  2040. }
  2041. xclose (stdin_pipe[0]);
  2042. xclose (stdout_pipe[1]);
  2043. set_blocking (stdout_pipe[0], false);
  2044. set_blocking (stdin_pipe[1], false);
  2045. struct plugin_data *plugin = xmalloc (sizeof *plugin);
  2046. plugin_data_init (plugin);
  2047. plugin->ctx = ctx;
  2048. plugin->pid = pid;
  2049. plugin->name = xstrdup (name);
  2050. plugin->read_fd = stdout_pipe[0];
  2051. plugin->write_fd = stdin_pipe[1];
  2052. LIST_PREPEND (ctx->plugins, plugin);
  2053. str_map_set (&ctx->plugins_by_name, name, plugin);
  2054. poller_set (&ctx->poller, stdout_pipe[0], POLLIN,
  2055. (poller_dispatcher_func) on_plugin_readable, plugin);
  2056. return true;
  2057. fail_3:
  2058. xclose (stdout_pipe[0]);
  2059. xclose (stdout_pipe[1]);
  2060. fail_2:
  2061. xclose (stdin_pipe[0]);
  2062. xclose (stdin_pipe[1]);
  2063. fail_1:
  2064. return false;
  2065. }
  2066. static bool
  2067. plugin_unload (struct bot_context *ctx, const char *name, struct error **e)
  2068. {
  2069. struct plugin_data *plugin = str_map_find (&ctx->plugins_by_name, name);
  2070. if (!plugin)
  2071. {
  2072. error_set (e, PLUGIN_ERROR, PLUGIN_ERROR_NOT_LOADED,
  2073. "no such plugin is loaded");
  2074. return false;
  2075. }
  2076. plugin_zombify (plugin);
  2077. // TODO: add a `kill zombies' command to forcefully get rid of processes
  2078. // that do not understand the request.
  2079. // TODO: set a timeout before we go for a kill automatically (and if this
  2080. // was a reload request, try to bring the plugin back up)
  2081. return true;
  2082. }
  2083. static void
  2084. plugin_load_all_from_config (struct bot_context *ctx)
  2085. {
  2086. const char *plugin_list = str_map_find (&ctx->config, "plugins");
  2087. if (!plugin_list)
  2088. return;
  2089. struct str_vector plugins;
  2090. str_vector_init (&plugins);
  2091. split_str_ignore_empty (plugin_list, ',', &plugins);
  2092. for (size_t i = 0; i < plugins.len; i++)
  2093. {
  2094. char *name = strip_str_in_place (plugins.vector[i], " ");
  2095. struct error *e = NULL;
  2096. if (!plugin_load (ctx, name, &e))
  2097. {
  2098. print_error ("plugin `%s' failed to load: %s", name, e->message);
  2099. error_free (e);
  2100. }
  2101. }
  2102. str_vector_free (&plugins);
  2103. }
  2104. // --- Main program ------------------------------------------------------------
  2105. static bool
  2106. parse_bot_command (const char *s, const char *command, const char **following)
  2107. {
  2108. size_t command_len = strlen (command);
  2109. if (strncasecmp (s, command, command_len))
  2110. return false;
  2111. s += command_len;
  2112. // Expect a word boundary, so that we don't respond to invalid things
  2113. if (isalnum (*s))
  2114. return false;
  2115. // Ignore any initial spaces; the rest is the command's argument
  2116. while (isblank (*s))
  2117. s++;
  2118. *following = s;
  2119. return true;
  2120. }
  2121. static void
  2122. split_bot_command_argument_list (const char *arguments, struct str_vector *out)
  2123. {
  2124. split_str_ignore_empty (arguments, ',', out);
  2125. for (size_t i = 0; i < out->len; )
  2126. {
  2127. if (!*strip_str_in_place (out->vector[i], " \t"))
  2128. str_vector_remove (out, i);
  2129. else
  2130. i++;
  2131. }
  2132. }
  2133. static bool
  2134. is_private_message (const struct irc_message *msg)
  2135. {
  2136. hard_assert (msg->params.len);
  2137. return !strchr ("#&+!", *msg->params.vector[0]);
  2138. }
  2139. static bool
  2140. is_sent_by_admin (struct bot_context *ctx, const struct irc_message *msg)
  2141. {
  2142. const char *admin = str_map_find (&ctx->config, "admin");
  2143. // No administrator set -> everyone is an administrator
  2144. if (!admin)
  2145. return true;
  2146. // TODO: precompile the regex
  2147. struct error *e = NULL;
  2148. if (regex_match (admin, msg->prefix, NULL))
  2149. return true;
  2150. if (e)
  2151. {
  2152. print_error ("%s: %s", "invalid admin mask", e->message);
  2153. error_free (e);
  2154. return true;
  2155. }
  2156. return false;
  2157. }
  2158. static void respond_to_user (struct bot_context *ctx, const struct
  2159. irc_message *msg, const char *format, ...) ATTRIBUTE_PRINTF (3, 4);
  2160. static void
  2161. respond_to_user (struct bot_context *ctx, const struct irc_message *msg,
  2162. const char *format, ...)
  2163. {
  2164. if (!soft_assert (msg->prefix && msg->params.len))
  2165. return;
  2166. char nick[strcspn (msg->prefix, "!") + 1];
  2167. strncpy (nick, msg->prefix, sizeof nick - 1);
  2168. nick[sizeof nick - 1] = '\0';
  2169. struct str text;
  2170. va_list ap;
  2171. str_init (&text);
  2172. va_start (ap, format);
  2173. str_append_vprintf (&text, format, ap);
  2174. va_end (ap);
  2175. if (is_private_message (msg))
  2176. irc_send (ctx, "PRIVMSG %s :%s", nick, text.str);
  2177. else
  2178. irc_send (ctx, "PRIVMSG %s :%s: %s",
  2179. msg->params.vector[0], nick, text.str);
  2180. str_free (&text);
  2181. }
  2182. static void
  2183. process_plugin_load (struct bot_context *ctx,
  2184. const struct irc_message *msg, const char *name)
  2185. {
  2186. struct error *e = NULL;
  2187. if (plugin_load (ctx, name, &e))
  2188. respond_to_user (ctx, msg, "plugin `%s' queued for loading", name);
  2189. else
  2190. {
  2191. respond_to_user (ctx, msg, "plugin `%s' could not be loaded: %s",
  2192. name, e->message);
  2193. error_free (e);
  2194. }
  2195. }
  2196. static void
  2197. process_plugin_unload (struct bot_context *ctx,
  2198. const struct irc_message *msg, const char *name)
  2199. {
  2200. struct error *e = NULL;
  2201. if (plugin_unload (ctx, name, &e))
  2202. respond_to_user (ctx, msg, "plugin `%s' unloaded", name);
  2203. else
  2204. {
  2205. respond_to_user (ctx, msg, "plugin `%s' could not be unloaded: %s",
  2206. name, e->message);
  2207. error_free (e);
  2208. }
  2209. }
  2210. static void
  2211. process_plugin_reload (struct bot_context *ctx,
  2212. const struct irc_message *msg, const char *name)
  2213. {
  2214. // So far the only error that can occur is that the plugin hasn't been
  2215. // loaded, which in this case doesn't really matter.
  2216. plugin_unload (ctx, name, NULL);
  2217. process_plugin_load (ctx, msg, name);
  2218. }
  2219. static void
  2220. process_privmsg (struct bot_context *ctx, const struct irc_message *msg)
  2221. {
  2222. if (!is_sent_by_admin (ctx, msg))
  2223. return;
  2224. if (msg->params.len < 2)
  2225. return;
  2226. const char *prefix = str_map_find (&ctx->config, "prefix");
  2227. hard_assert (prefix != NULL); // We have a default value for this
  2228. // For us to recognize the command, it has to start with the prefix,
  2229. // with the exception of PM's sent directly to us.
  2230. const char *text = msg->params.vector[1];
  2231. if (!strncmp (text, prefix, strlen (prefix)))
  2232. text += strlen (prefix);
  2233. else if (!is_private_message (msg))
  2234. return;
  2235. const char *following;
  2236. struct str_vector list;
  2237. str_vector_init (&list);
  2238. if (parse_bot_command (text, "quote", &following))
  2239. // This seems to replace tons of random stupid commands
  2240. irc_send (ctx, "%s", following);
  2241. else if (parse_bot_command (text, "quit", &following))
  2242. {
  2243. // We actually need this command (instead of just `quote') because we
  2244. // could try to reconnect to the server automatically otherwise.
  2245. if (*following)
  2246. irc_send (ctx, "QUIT :%s", following);
  2247. else
  2248. irc_send (ctx, "QUIT");
  2249. initiate_quit (ctx);
  2250. }
  2251. else if (parse_bot_command (text, "status", &following))
  2252. {
  2253. struct str report;
  2254. str_init (&report);
  2255. const char *reason = getenv (g_startup_reason_str);
  2256. if (!reason)
  2257. reason = "launched normally";
  2258. str_append_printf (&report, "\x02startup reason:\x0f %s, ", reason);
  2259. str_append (&report, "\x02plugins:\x0f ");
  2260. size_t zombies = 0;
  2261. for (struct plugin_data *plugin = ctx->plugins;
  2262. plugin; plugin = plugin->next)
  2263. {
  2264. if (plugin->is_zombie)
  2265. zombies++;
  2266. else
  2267. str_append_printf (&report, "%s, ", plugin->name);
  2268. }
  2269. if (!ctx->plugins)
  2270. str_append (&report, "\x02none\x0f, ");
  2271. str_append_printf (&report, "\x02zombies:\x0f %zu", zombies);
  2272. respond_to_user (ctx, msg, "%s", report.str);
  2273. str_free (&report);
  2274. }
  2275. else if (parse_bot_command (text, "load", &following))
  2276. {
  2277. split_bot_command_argument_list (following, &list);
  2278. for (size_t i = 0; i < list.len; i++)
  2279. process_plugin_load (ctx, msg, list.vector[i]);
  2280. }
  2281. else if (parse_bot_command (text, "reload", &following))
  2282. {
  2283. split_bot_command_argument_list (following, &list);
  2284. for (size_t i = 0; i < list.len; i++)
  2285. process_plugin_reload (ctx, msg, list.vector[i]);
  2286. }
  2287. else if (parse_bot_command (text, "unload", &following))
  2288. {
  2289. split_bot_command_argument_list (following, &list);
  2290. for (size_t i = 0; i < list.len; i++)
  2291. process_plugin_unload (ctx, msg, list.vector[i]);
  2292. }
  2293. str_vector_free (&list);
  2294. }
  2295. static void
  2296. irc_process_message (const struct irc_message *msg,
  2297. const char *raw, void *user_data)
  2298. {
  2299. struct bot_context *ctx = user_data;
  2300. if (g_debug_mode)
  2301. fprintf (stderr, "[%s] ==> \"%s\"\n", "IRC", raw);
  2302. // This should be as minimal as possible, I don't want to have the whole bot
  2303. // written in C, especially when I have this overengineered plugin system.
  2304. // Therefore the very basic functionality only.
  2305. //
  2306. // I should probably even rip out the autojoin...
  2307. // First forward the message to all the plugins
  2308. for (struct plugin_data *plugin = ctx->plugins;
  2309. plugin; plugin = plugin->next)
  2310. {
  2311. if (plugin->is_zombie)
  2312. continue;
  2313. if (plugin->initialized)
  2314. plugin_send (plugin, "%s", raw);
  2315. else
  2316. // TODO: make sure that this buffer doesn't get too large either
  2317. str_append_printf (&plugin->queued_output, "%s\r\n", raw);
  2318. }
  2319. if (!strcasecmp (msg->command, "PING"))
  2320. {
  2321. if (msg->params.len)
  2322. irc_send (ctx, "PONG :%s", msg->params.vector[0]);
  2323. else
  2324. irc_send (ctx, "PONG");
  2325. }
  2326. else if (!ctx->irc_ready && (!strcasecmp (msg->command, "MODE")
  2327. || !strcasecmp (msg->command, "376") // RPL_ENDOFMOTD
  2328. || !strcasecmp (msg->command, "422"))) // ERR_NOMOTD
  2329. {
  2330. print_status ("successfully connected");
  2331. ctx->irc_ready = true;
  2332. const char *autojoin = str_map_find (&ctx->config, "autojoin");
  2333. if (autojoin)
  2334. irc_send (ctx, "JOIN :%s", autojoin);
  2335. }
  2336. else if (!strcasecmp (msg->command, "PRIVMSG"))
  2337. process_privmsg (ctx, msg);
  2338. }
  2339. enum irc_read_result
  2340. {
  2341. IRC_READ_OK, ///< Some data were read successfully
  2342. IRC_READ_EOF, ///< The server has closed connection
  2343. IRC_READ_AGAIN, ///< No more data at the moment
  2344. IRC_READ_ERROR ///< General connection failure
  2345. };
  2346. static enum irc_read_result
  2347. irc_fill_read_buffer_ssl (struct bot_context *ctx, struct str *buf)
  2348. {
  2349. int n_read;
  2350. start:
  2351. n_read = SSL_read (ctx->ssl, buf->str + buf->len,
  2352. buf->alloc - buf->len - 1 /* null byte */);
  2353. const char *error_info = NULL;
  2354. switch (SSL_get_error (ctx->ssl, n_read))
  2355. {
  2356. case SSL_ERROR_NONE:
  2357. buf->str[buf->len += n_read] = '\0';
  2358. return IRC_READ_AGAIN;
  2359. case SSL_ERROR_ZERO_RETURN:
  2360. return IRC_READ_EOF;
  2361. case SSL_ERROR_WANT_READ:
  2362. return IRC_READ_AGAIN;
  2363. case SSL_ERROR_WANT_WRITE:
  2364. {
  2365. // Let it finish the handshake as we don't poll for writability;
  2366. // any errors are to be collected by SSL_read() in the next iteration
  2367. struct pollfd pfd = { .fd = ctx->irc_fd, .events = POLLOUT };
  2368. soft_assert (poll (&pfd, 1, 0) > 0);
  2369. goto start;
  2370. }
  2371. case SSL_ERROR_SYSCALL:
  2372. {
  2373. int err;
  2374. if ((err = ERR_get_error ()))
  2375. error_info = ERR_error_string (err, NULL);
  2376. else if (n_read == 0)
  2377. return IRC_READ_EOF;
  2378. else
  2379. {
  2380. if (errno == EINTR)
  2381. goto start;
  2382. error_info = strerror (errno);
  2383. }
  2384. break;
  2385. }
  2386. case SSL_ERROR_SSL:
  2387. default:
  2388. error_info = ERR_error_string (ERR_get_error (), NULL);
  2389. }
  2390. print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
  2391. return IRC_READ_ERROR;
  2392. }
  2393. static enum irc_read_result
  2394. irc_fill_read_buffer (struct bot_context *ctx, struct str *buf)
  2395. {
  2396. ssize_t n_read;
  2397. start:
  2398. n_read = recv (ctx->irc_fd, buf->str + buf->len,
  2399. buf->alloc - buf->len - 1 /* null byte */, 0);
  2400. if (n_read > 0)
  2401. {
  2402. buf->str[buf->len += n_read] = '\0';
  2403. return IRC_READ_OK;
  2404. }
  2405. if (n_read == 0)
  2406. return IRC_READ_EOF;
  2407. if (errno == EAGAIN)
  2408. return IRC_READ_AGAIN;
  2409. if (errno == EINTR)
  2410. goto start;
  2411. print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
  2412. return IRC_READ_ERROR;
  2413. }
  2414. static bool irc_connect (struct bot_context *ctx, struct error **e);
  2415. static void
  2416. irc_try_reconnect (struct bot_context *ctx)
  2417. {
  2418. if (!soft_assert (ctx->irc_fd == -1))
  2419. return;
  2420. const char *reconnect_str = str_map_find (&ctx->config, "reconnect");
  2421. hard_assert (reconnect_str != NULL); // We have a default value for this
  2422. bool reconnect;
  2423. if (!set_boolean_if_valid (&reconnect, reconnect_str))
  2424. {
  2425. print_fatal ("invalid configuration value for `%s'", "recover");
  2426. try_finish_quit (ctx);
  2427. return;
  2428. }
  2429. if (!reconnect)
  2430. return;
  2431. const char *delay_str = str_map_find (&ctx->config, "reconnect_delay");
  2432. hard_assert (delay_str != NULL); // We have a default value for this
  2433. char *end_ptr;
  2434. errno = 0;
  2435. long delay = strtol (delay_str, &end_ptr, 10);
  2436. if (errno != 0 || end_ptr == delay_str || *end_ptr)
  2437. {
  2438. print_error ("invalid configuration value for `%s'",
  2439. "reconnect_delay");
  2440. delay = 0;
  2441. }
  2442. while (true)
  2443. {
  2444. // TODO: this would be better suited by a timeout event;
  2445. // remember to update try_finish_quit() etc. to reflect this
  2446. print_status ("trying to reconnect in %ld seconds...", delay);
  2447. sleep (delay);
  2448. struct error *e = NULL;
  2449. if (irc_connect (ctx, &e))
  2450. break;
  2451. print_error ("%s", e->message);
  2452. error_free (e);
  2453. }
  2454. // TODO: inform plugins about the new connection
  2455. }
  2456. static void
  2457. on_irc_disconnected (struct bot_context *ctx)
  2458. {
  2459. // Get rid of the dead socket etc.
  2460. if (ctx->ssl)
  2461. {
  2462. SSL_free (ctx->ssl);
  2463. ctx->ssl = NULL;
  2464. SSL_CTX_free (ctx->ssl_ctx);
  2465. ctx->ssl_ctx = NULL;
  2466. }
  2467. ssize_t i = poller_find_by_fd (&ctx->poller, ctx->irc_fd);
  2468. if (i != -1)
  2469. poller_remove_at_index (&ctx->poller, i);
  2470. xclose (ctx->irc_fd);
  2471. ctx->irc_fd = -1;
  2472. // TODO: inform plugins about the disconnect event
  2473. if (ctx->quitting)
  2474. {
  2475. // Unload all plugins
  2476. // TODO: wait for a few seconds and then send SIGKILL to all plugins
  2477. for (struct plugin_data *plugin = ctx->plugins;
  2478. plugin; plugin = plugin->next)
  2479. plugin_zombify (plugin);
  2480. try_finish_quit (ctx);
  2481. return;
  2482. }
  2483. irc_try_reconnect (ctx);
  2484. }
  2485. static void
  2486. on_irc_readable (const struct pollfd *fd, struct bot_context *ctx)
  2487. {
  2488. if (fd->revents != POLLIN)
  2489. print_debug ("poller fd %d: revents: %d", fd->fd, fd->revents);
  2490. (void) set_blocking (ctx->irc_fd, false);
  2491. struct str *buf = &ctx->read_buffer;
  2492. enum irc_read_result (*fill_buffer)(struct bot_context *, struct str *)
  2493. = ctx->ssl
  2494. ? irc_fill_read_buffer_ssl
  2495. : irc_fill_read_buffer;
  2496. bool disconnected = false;
  2497. while (true)
  2498. {
  2499. str_ensure_space (buf, 512);
  2500. switch (fill_buffer (ctx, buf))
  2501. {
  2502. case IRC_READ_AGAIN:
  2503. goto end;
  2504. case IRC_READ_ERROR:
  2505. print_error ("reading from the IRC server failed");
  2506. disconnected = true;
  2507. goto end;
  2508. case IRC_READ_EOF:
  2509. print_status ("the IRC server closed the connection");
  2510. disconnected = true;
  2511. goto end;
  2512. case IRC_READ_OK:
  2513. break;
  2514. }
  2515. if (buf->len >= (1 << 20))
  2516. {
  2517. print_fatal ("the IRC server seems to spew out data frantically");
  2518. irc_shutdown (ctx);
  2519. goto end;
  2520. }
  2521. }
  2522. end:
  2523. (void) set_blocking (ctx->irc_fd, true);
  2524. irc_process_buffer (buf, irc_process_message, ctx);
  2525. if (disconnected)
  2526. on_irc_disconnected (ctx);
  2527. }
  2528. static bool
  2529. irc_connect (struct bot_context *ctx, struct error **e)
  2530. {
  2531. const char *irc_host = str_map_find (&ctx->config, "irc_host");
  2532. const char *irc_port = str_map_find (&ctx->config, "irc_port");
  2533. const char *ssl_use_str = str_map_find (&ctx->config, "ssl_use");
  2534. const char *nickname = str_map_find (&ctx->config, "nickname");
  2535. const char *username = str_map_find (&ctx->config, "username");
  2536. const char *fullname = str_map_find (&ctx->config, "fullname");
  2537. // We have a default value for these
  2538. hard_assert (irc_port && ssl_use_str);
  2539. hard_assert (nickname && username && fullname);
  2540. // TODO: again, get rid of `struct error' in here. The question is: how
  2541. // do we tell our caller that he should not try to reconnect?
  2542. if (!irc_host)
  2543. {
  2544. error_set (e, CONNECT_ERROR, CONNECT_ERROR_INVALID_CONFIGURATION,
  2545. "no hostname specified in configuration");
  2546. return false;
  2547. }
  2548. bool use_ssl;
  2549. if (!set_boolean_if_valid (&use_ssl, ssl_use_str))
  2550. {
  2551. error_set (e, CONNECT_ERROR, CONNECT_ERROR_INVALID_CONFIGURATION,
  2552. "invalid configuration value for `%s'", "use_ssl");
  2553. return false;
  2554. }
  2555. if (!irc_establish_connection (ctx, irc_host, irc_port, use_ssl, e))
  2556. return false;
  2557. // TODO: set a timeout on the socket, something like 30 minutes, then we
  2558. // should ideally send a PING... or just forcefully reconnect.
  2559. //
  2560. // TODO: in exec try: 1/ set blocking, 2/ setsockopt() SO_LINGER,
  2561. // (struct linger) { .l_onoff = true; .l_linger = 1 /* 1s should do */; }
  2562. // 3/ /* O_CLOEXEC */ But only if the QUIT message proves unreliable.
  2563. poller_set (&ctx->poller, ctx->irc_fd, POLLIN,
  2564. (poller_dispatcher_func) on_irc_readable, ctx);
  2565. // TODO: probably check for errors from these calls as well
  2566. irc_send (ctx, "NICK %s", nickname);
  2567. irc_send (ctx, "USER %s 8 * :%s", username, fullname);
  2568. return true;
  2569. }
  2570. static void
  2571. on_signal_pipe_readable (const struct pollfd *fd, struct bot_context *ctx)
  2572. {
  2573. char *dummy;
  2574. (void) read (fd->fd, &dummy, 1);
  2575. // XXX: do we need to check if we have a connection?
  2576. if (g_termination_requested && !ctx->quitting)
  2577. {
  2578. irc_send (ctx, "QUIT :Terminated by signal");
  2579. initiate_quit (ctx);
  2580. }
  2581. // Reap all dead children (since the pipe may overflow, we ask waitpid()
  2582. // to return all the zombies it knows about).
  2583. while (true)
  2584. {
  2585. int status;
  2586. pid_t zombie = waitpid (-1, &status, WNOHANG);
  2587. if (zombie == -1)
  2588. {
  2589. // No children to wait on
  2590. if (errno == ECHILD)
  2591. break;
  2592. hard_assert (errno == EINTR);
  2593. continue;
  2594. }
  2595. if (zombie == 0)
  2596. break;
  2597. struct plugin_data *plugin = plugin_find_by_pid (ctx, zombie);
  2598. // Something has died but we don't recognize it (re-exec?)
  2599. if (!soft_assert (plugin != NULL))
  2600. continue;
  2601. // TODO: callbacks on children death, so that we may tell the user
  2602. // "plugin `name' died like a dirty jewish pig"; use `status'
  2603. if (!plugin->is_zombie && WIFSIGNALED (status))
  2604. {
  2605. char *notes = "";
  2606. #ifdef WCOREDUMP
  2607. if (WCOREDUMP (status))
  2608. notes = " (core dumped)";
  2609. #endif
  2610. print_warning ("Plugin `%s' died from signal %d%s",
  2611. plugin->name, WTERMSIG (status), notes);
  2612. }
  2613. // Let's go through the zombie state to simplify things a bit
  2614. // TODO: might not be a completely bad idea to restart the plugin
  2615. plugin_zombify (plugin);
  2616. plugin->pid = -1;
  2617. ssize_t poller_idx = poller_find_by_fd (&ctx->poller, plugin->read_fd);
  2618. if (poller_idx != -1)
  2619. poller_remove_at_index (&ctx->poller, poller_idx);
  2620. xclose (plugin->read_fd);
  2621. plugin->read_fd = -1;
  2622. LIST_UNLINK (ctx->plugins, plugin);
  2623. plugin_data_free (plugin);
  2624. free (plugin);
  2625. // Living child processes block us from quitting
  2626. try_finish_quit (ctx);
  2627. }
  2628. }
  2629. static void
  2630. write_default_configuration (const char *filename)
  2631. {
  2632. struct str path, base;
  2633. int status = EXIT_SUCCESS;
  2634. str_init (&path);
  2635. str_init (&base);
  2636. if (filename)
  2637. {
  2638. char *tmp = xstrdup (filename);
  2639. str_append (&path, dirname (tmp));
  2640. strcpy (tmp, filename);
  2641. str_append (&base, basename (tmp));
  2642. free (tmp);
  2643. }
  2644. else
  2645. {
  2646. get_xdg_home_dir (&path, "XDG_CONFIG_HOME", ".config");
  2647. str_append (&path, "/" PROGRAM_NAME);
  2648. str_append (&base, PROGRAM_NAME ".conf");
  2649. }
  2650. struct error *e = NULL;
  2651. if (!mkdir_with_parents (path.str, &e))
  2652. {
  2653. print_fatal ("%s", e->message);
  2654. status = EXIT_FAILURE;
  2655. goto out;
  2656. }
  2657. str_append_c (&path, '/');
  2658. str_append_str (&path, &base);
  2659. FILE *fp = fopen (path.str, "w");
  2660. if (!fp)
  2661. {
  2662. print_fatal ("could not open `%s' for writing: %s",
  2663. path.str, strerror (errno));
  2664. status = EXIT_FAILURE;
  2665. goto out;
  2666. }
  2667. errno = 0;
  2668. for (size_t i = 0; i < N_ELEMENTS (g_config_table); i++)
  2669. {
  2670. const struct config_item *item = g_config_table + i;
  2671. fprintf (fp, "# %s\n", item->description);
  2672. if (item->default_value)
  2673. fprintf (fp, "%s=%s\n", item->key, item->default_value);
  2674. else
  2675. fprintf (fp, "#%s=\n", item->key);
  2676. }
  2677. fclose (fp);
  2678. if (errno)
  2679. {
  2680. print_fatal ("writing to `%s' failed: %s", path.str, strerror (errno));
  2681. status = EXIT_FAILURE;
  2682. goto out;
  2683. }
  2684. print_status ("configuration written to `%s'", path.str);
  2685. out:
  2686. str_free (&path);
  2687. str_free (&base);
  2688. exit (status);
  2689. }
  2690. static void
  2691. print_usage (const char *program_name)
  2692. {
  2693. fprintf (stderr,
  2694. "Usage: %s [OPTION]...\n"
  2695. "Experimental IRC bot.\n"
  2696. "\n"
  2697. " -d, --debug run in debug mode\n"
  2698. " -h, --help display this help and exit\n"
  2699. " -V, --version output version information and exit\n"
  2700. " --write-default-cfg [filename]\n"
  2701. " write a default configuration file and exit\n",
  2702. program_name);
  2703. }
  2704. int
  2705. main (int argc, char *argv[])
  2706. {
  2707. const char *invocation_name = argv[0];
  2708. str_vector_init (&g_original_argv);
  2709. str_vector_add_vector (&g_original_argv, argv);
  2710. static struct option opts[] =
  2711. {
  2712. { "debug", no_argument, NULL, 'd' },
  2713. { "help", no_argument, NULL, 'h' },
  2714. { "version", no_argument, NULL, 'V' },
  2715. { "write-default-cfg", optional_argument, NULL, 'w' },
  2716. { NULL, 0, NULL, 0 }
  2717. };
  2718. while (1)
  2719. {
  2720. int c, opt_index;
  2721. c = getopt_long (argc, argv, "dhV", opts, &opt_index);
  2722. if (c == -1)
  2723. break;
  2724. switch (c)
  2725. {
  2726. case 'd':
  2727. g_debug_mode = true;
  2728. break;
  2729. case 'h':
  2730. print_usage (invocation_name);
  2731. exit (EXIT_SUCCESS);
  2732. case 'V':
  2733. printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
  2734. exit (EXIT_SUCCESS);
  2735. case 'w':
  2736. write_default_configuration (optarg);
  2737. abort ();
  2738. default:
  2739. print_fatal ("error in options");
  2740. exit (EXIT_FAILURE);
  2741. }
  2742. }
  2743. print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting");
  2744. setup_signal_handlers ();
  2745. SSL_library_init ();
  2746. atexit (EVP_cleanup);
  2747. SSL_load_error_strings ();
  2748. atexit (ERR_free_strings);
  2749. struct bot_context ctx;
  2750. bot_context_init (&ctx);
  2751. struct error *e = NULL;
  2752. if (!read_config_file (&ctx.config, &e))
  2753. {
  2754. print_fatal ("error loading configuration: %s", e->message);
  2755. error_free (e);
  2756. exit (EXIT_FAILURE);
  2757. }
  2758. setup_recovery_handler (&ctx);
  2759. poller_set (&ctx.poller, g_signal_pipe[0], POLLIN,
  2760. (poller_dispatcher_func) on_signal_pipe_readable, &ctx);
  2761. plugin_load_all_from_config (&ctx);
  2762. if (!irc_connect (&ctx, &e))
  2763. {
  2764. print_error ("%s", e->message);
  2765. error_free (e);
  2766. exit (EXIT_FAILURE);
  2767. }
  2768. // TODO: clean re-exec support; to save the state I can either use argv,
  2769. // argp, or I can create a temporary file, unlink it and use the FD
  2770. // (mkstemp() on a `struct str' constructed from XDG_RUNTIME_DIR, TMPDIR
  2771. // or /tmp as a last resort + PROGRAM_NAME + ".XXXXXX" -> unlink();
  2772. // remember to use O_CREAT | O_EXCL). The state needs to be versioned.
  2773. // Unfortunately I cannot de/serialize SSL state.
  2774. ctx.polling = true;
  2775. while (ctx.polling)
  2776. poller_run (&ctx.poller);
  2777. bot_context_free (&ctx);
  2778. str_vector_free (&g_original_argv);
  2779. return EXIT_SUCCESS;
  2780. }