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.

1998 lines
47KB

  1. /*
  2. * common.c: common functionality
  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 <time.h>
  31. #include <limits.h>
  32. #include <unistd.h>
  33. #include <sys/wait.h>
  34. #include <sys/stat.h>
  35. #include <sys/time.h>
  36. #include <fcntl.h>
  37. #include <poll.h>
  38. #include <signal.h>
  39. #include <strings.h>
  40. #include <regex.h>
  41. #include <libgen.h>
  42. #include <syslog.h>
  43. #include <fnmatch.h>
  44. #include <sys/socket.h>
  45. #include <sys/types.h>
  46. #include <netinet/in.h>
  47. #include <netdb.h>
  48. #ifndef NI_MAXHOST
  49. #define NI_MAXHOST 1025
  50. #endif // ! NI_MAXHOST
  51. #ifndef NI_MAXSERV
  52. #define NI_MAXSERV 32
  53. #endif // ! NI_MAXSERV
  54. #include <getopt.h>
  55. #include <openssl/ssl.h>
  56. #include <openssl/err.h>
  57. #include "siphash.h"
  58. extern char **environ;
  59. #ifdef _POSIX_MONOTONIC_CLOCK
  60. #define CLOCK_BEST CLOCK_MONOTONIC
  61. #else // ! _POSIX_MONOTIC_CLOCK
  62. #define CLOCK_BEST CLOCK_REALTIME
  63. #endif // ! _POSIX_MONOTONIC_CLOCK
  64. #if defined __GNUC__
  65. #define ATTRIBUTE_PRINTF(x, y) __attribute__ ((format (printf, x, y)))
  66. #else // ! __GNUC__
  67. #define ATTRIBUTE_PRINTF(x, y)
  68. #endif // ! __GNUC__
  69. #if defined __GNUC__ && __GNUC__ >= 4
  70. #define ATTRIBUTE_SENTINEL __attribute__ ((sentinel))
  71. #else // ! __GNUC__ || __GNUC__ < 4
  72. #define ATTRIBUTE_SENTINEL
  73. #endif // ! __GNUC__ || __GNUC__ < 4
  74. #define N_ELEMENTS(a) (sizeof (a) / sizeof ((a)[0]))
  75. #define BLOCK_START do {
  76. #define BLOCK_END } while (0)
  77. // --- Logging -----------------------------------------------------------------
  78. static void
  79. log_message_syslog (int prio, const char *quote, const char *fmt, va_list ap)
  80. {
  81. va_list va;
  82. va_copy (va, ap);
  83. int size = vsnprintf (NULL, 0, fmt, va);
  84. va_end (va);
  85. if (size < 0)
  86. return;
  87. char buf[size + 1];
  88. if (vsnprintf (buf, sizeof buf, fmt, ap) >= 0)
  89. syslog (prio, "%s%s", quote, buf);
  90. }
  91. static void
  92. log_message_stdio (int prio, const char *quote, const char *fmt, va_list ap)
  93. {
  94. (void) prio;
  95. FILE *stream = stderr;
  96. fputs (quote, stream);
  97. vfprintf (stream, fmt, ap);
  98. fputs ("\n", stream);
  99. }
  100. static void (*g_log_message_real) (int, const char *, const char *, va_list)
  101. = log_message_stdio;
  102. static void
  103. log_message (int priority, const char *quote, const char *fmt, ...)
  104. ATTRIBUTE_PRINTF (3, 4);
  105. static void
  106. log_message (int priority, const char *quote, const char *fmt, ...)
  107. {
  108. va_list ap;
  109. va_start (ap, fmt);
  110. g_log_message_real (priority, quote, fmt, ap);
  111. va_end (ap);
  112. }
  113. // `fatal' is reserved for unexpected failures that would harm further operation
  114. #define print_fatal(...) log_message (LOG_ERR, "fatal: ", __VA_ARGS__)
  115. #define print_error(...) log_message (LOG_ERR, "error: ", __VA_ARGS__)
  116. #define print_warning(...) log_message (LOG_WARNING, "warning: ", __VA_ARGS__)
  117. #define print_status(...) log_message (LOG_INFO, "-- ", __VA_ARGS__)
  118. #define exit_fatal(...) \
  119. BLOCK_START \
  120. print_fatal (__VA_ARGS__); \
  121. exit (EXIT_FAILURE); \
  122. BLOCK_END
  123. // --- Debugging and assertions ------------------------------------------------
  124. // We should check everything that may possibly fail with at least a soft
  125. // assertion, so that any causes for problems don't slip us by silently.
  126. //
  127. // `g_soft_asserts_are_deadly' may be useful while running inside a debugger.
  128. static bool g_debug_mode; ///< Debug messages are printed
  129. static bool g_soft_asserts_are_deadly; ///< soft_assert() aborts as well
  130. #define print_debug(...) \
  131. BLOCK_START \
  132. if (g_debug_mode) \
  133. log_message (LOG_DEBUG, "debug: ", __VA_ARGS__); \
  134. BLOCK_END
  135. static void
  136. assertion_failure_handler (bool is_fatal, const char *file, int line,
  137. const char *function, const char *condition)
  138. {
  139. if (is_fatal)
  140. {
  141. print_fatal ("assertion failed [%s:%d in function %s]: %s",
  142. file, line, function, condition);
  143. abort ();
  144. }
  145. else
  146. print_debug ("assertion failed [%s:%d in function %s]: %s",
  147. file, line, function, condition);
  148. }
  149. #define soft_assert(condition) \
  150. ((condition) ? true : \
  151. (assertion_failure_handler (g_soft_asserts_are_deadly, \
  152. __FILE__, __LINE__, __func__, #condition), false))
  153. #define hard_assert(condition) \
  154. ((condition) ? (void) 0 : \
  155. assertion_failure_handler (true, \
  156. __FILE__, __LINE__, __func__, #condition))
  157. // --- Safe memory management --------------------------------------------------
  158. // When a memory allocation fails and we need the memory, we're usually pretty
  159. // much fucked. Use the non-prefixed versions when there's a legitimate
  160. // worry that an unrealistic amount of memory may be requested for allocation.
  161. // XXX: it's not a good idea to use print_message() as it may want to allocate
  162. // further memory for printf() and the output streams. That may fail.
  163. static void *
  164. xmalloc (size_t n)
  165. {
  166. void *p = malloc (n);
  167. if (!p)
  168. exit_fatal ("malloc: %s", strerror (errno));
  169. return p;
  170. }
  171. static void *
  172. xcalloc (size_t n, size_t m)
  173. {
  174. void *p = calloc (n, m);
  175. if (!p && n && m)
  176. exit_fatal ("calloc: %s", strerror (errno));
  177. return p;
  178. }
  179. static void *
  180. xrealloc (void *o, size_t n)
  181. {
  182. void *p = realloc (o, n);
  183. if (!p && n)
  184. exit_fatal ("realloc: %s", strerror (errno));
  185. return p;
  186. }
  187. static void *
  188. xreallocarray (void *o, size_t n, size_t m)
  189. {
  190. if (m && n > SIZE_MAX / m)
  191. {
  192. errno = ENOMEM;
  193. exit_fatal ("reallocarray: %s", strerror (errno));
  194. }
  195. return xrealloc (o, n * m);
  196. }
  197. static char *
  198. xstrdup (const char *s)
  199. {
  200. return strcpy (xmalloc (strlen (s) + 1), s);
  201. }
  202. static char *
  203. xstrndup (const char *s, size_t n)
  204. {
  205. size_t size = strlen (s);
  206. if (n > size)
  207. n = size;
  208. char *copy = xmalloc (n + 1);
  209. memcpy (copy, s, n);
  210. copy[n] = '\0';
  211. return copy;
  212. }
  213. // --- Double-linked list helpers ----------------------------------------------
  214. #define LIST_HEADER(type) \
  215. struct type *next; \
  216. struct type *prev;
  217. #define LIST_PREPEND(head, link) \
  218. BLOCK_START \
  219. (link)->prev = NULL; \
  220. (link)->next = (head); \
  221. if ((link)->next) \
  222. (link)->next->prev = (link); \
  223. (head) = (link); \
  224. BLOCK_END
  225. #define LIST_UNLINK(head, link) \
  226. BLOCK_START \
  227. if ((link)->prev) \
  228. (link)->prev->next = (link)->next; \
  229. else \
  230. (head) = (link)->next; \
  231. if ((link)->next) \
  232. (link)->next->prev = (link)->prev; \
  233. BLOCK_END
  234. // --- Dynamically allocated string array --------------------------------------
  235. struct str_vector
  236. {
  237. char **vector;
  238. size_t len;
  239. size_t alloc;
  240. };
  241. static void
  242. str_vector_init (struct str_vector *self)
  243. {
  244. self->alloc = 4;
  245. self->len = 0;
  246. self->vector = xcalloc (sizeof *self->vector, self->alloc);
  247. }
  248. static void
  249. str_vector_free (struct str_vector *self)
  250. {
  251. unsigned i;
  252. for (i = 0; i < self->len; i++)
  253. free (self->vector[i]);
  254. free (self->vector);
  255. self->vector = NULL;
  256. }
  257. static void
  258. str_vector_reset (struct str_vector *self)
  259. {
  260. str_vector_free (self);
  261. str_vector_init (self);
  262. }
  263. static void
  264. str_vector_add_owned (struct str_vector *self, char *s)
  265. {
  266. self->vector[self->len] = s;
  267. if (++self->len >= self->alloc)
  268. self->vector = xreallocarray (self->vector,
  269. sizeof *self->vector, (self->alloc <<= 1));
  270. self->vector[self->len] = NULL;
  271. }
  272. static void
  273. str_vector_add (struct str_vector *self, const char *s)
  274. {
  275. str_vector_add_owned (self, xstrdup (s));
  276. }
  277. static void
  278. str_vector_add_args (struct str_vector *self, const char *s, ...)
  279. ATTRIBUTE_SENTINEL;
  280. static void
  281. str_vector_add_args (struct str_vector *self, const char *s, ...)
  282. {
  283. va_list ap;
  284. va_start (ap, s);
  285. while (s)
  286. {
  287. str_vector_add (self, s);
  288. s = va_arg (ap, const char *);
  289. }
  290. va_end (ap);
  291. }
  292. static void
  293. str_vector_add_vector (struct str_vector *self, char **vector)
  294. {
  295. while (*vector)
  296. str_vector_add (self, *vector++);
  297. }
  298. static void
  299. str_vector_remove (struct str_vector *self, size_t i)
  300. {
  301. hard_assert (i < self->len);
  302. free (self->vector[i]);
  303. memmove (self->vector + i, self->vector + i + 1,
  304. (self->len-- - i) * sizeof *self->vector);
  305. }
  306. // --- Dynamically allocated strings -------------------------------------------
  307. // Basically a string builder to abstract away manual memory management.
  308. struct str
  309. {
  310. char *str; ///< String data, null terminated
  311. size_t alloc; ///< How many bytes are allocated
  312. size_t len; ///< How long the string actually is
  313. };
  314. /// We don't care about allocations that are way too large for the content, as
  315. /// long as the allocation is below the given threshold. (Trivial heuristics.)
  316. #define STR_SHRINK_THRESHOLD (1 << 20)
  317. static void
  318. str_init (struct str *self)
  319. {
  320. self->alloc = 16;
  321. self->len = 0;
  322. self->str = strcpy (xmalloc (self->alloc), "");
  323. }
  324. static void
  325. str_free (struct str *self)
  326. {
  327. free (self->str);
  328. self->str = NULL;
  329. self->alloc = 0;
  330. self->len = 0;
  331. }
  332. static void
  333. str_reset (struct str *self)
  334. {
  335. str_free (self);
  336. str_init (self);
  337. }
  338. static char *
  339. str_steal (struct str *self)
  340. {
  341. char *str = self->str;
  342. self->str = NULL;
  343. str_free (self);
  344. return str;
  345. }
  346. static void
  347. str_ensure_space (struct str *self, size_t n)
  348. {
  349. // We allocate at least one more byte for the terminating null character
  350. size_t new_alloc = self->alloc;
  351. while (new_alloc <= self->len + n)
  352. new_alloc <<= 1;
  353. if (new_alloc != self->alloc)
  354. self->str = xrealloc (self->str, (self->alloc = new_alloc));
  355. }
  356. static void
  357. str_append_data (struct str *self, const char *data, size_t n)
  358. {
  359. str_ensure_space (self, n);
  360. memcpy (self->str + self->len, data, n);
  361. self->len += n;
  362. self->str[self->len] = '\0';
  363. }
  364. static void
  365. str_append_c (struct str *self, char c)
  366. {
  367. str_append_data (self, &c, 1);
  368. }
  369. static void
  370. str_append (struct str *self, const char *s)
  371. {
  372. str_append_data (self, s, strlen (s));
  373. }
  374. static void
  375. str_append_str (struct str *self, const struct str *another)
  376. {
  377. str_append_data (self, another->str, another->len);
  378. }
  379. static int
  380. str_append_vprintf (struct str *self, const char *fmt, va_list va)
  381. {
  382. va_list ap;
  383. int size;
  384. va_copy (ap, va);
  385. size = vsnprintf (NULL, 0, fmt, ap);
  386. va_end (ap);
  387. if (size < 0)
  388. return -1;
  389. va_copy (ap, va);
  390. str_ensure_space (self, size);
  391. size = vsnprintf (self->str + self->len, self->alloc - self->len, fmt, ap);
  392. va_end (ap);
  393. if (size > 0)
  394. self->len += size;
  395. return size;
  396. }
  397. static int
  398. str_append_printf (struct str *self, const char *fmt, ...)
  399. ATTRIBUTE_PRINTF (2, 3);
  400. static int
  401. str_append_printf (struct str *self, const char *fmt, ...)
  402. {
  403. va_list ap;
  404. va_start (ap, fmt);
  405. int size = str_append_vprintf (self, fmt, ap);
  406. va_end (ap);
  407. return size;
  408. }
  409. static void
  410. str_remove_slice (struct str *self, size_t start, size_t length)
  411. {
  412. size_t end = start + length;
  413. hard_assert (end <= self->len);
  414. memmove (self->str + start, self->str + end, self->len - end);
  415. self->str[self->len -= length] = '\0';
  416. // Shrink the string if the allocation becomes way too large
  417. if (self->alloc >= STR_SHRINK_THRESHOLD && self->len < (self->alloc >> 2))
  418. self->str = xrealloc (self->str, self->alloc >>= 2);
  419. }
  420. // --- Errors ------------------------------------------------------------------
  421. // Error reporting utilities. Inspired by GError, only much simpler.
  422. struct error
  423. {
  424. char *message; ///< Textual description of the event
  425. };
  426. static void
  427. error_set (struct error **e, const char *message, ...) ATTRIBUTE_PRINTF (2, 3);
  428. static void
  429. error_set (struct error **e, const char *message, ...)
  430. {
  431. if (!e)
  432. return;
  433. va_list ap;
  434. va_start (ap, message);
  435. int size = vsnprintf (NULL, 0, message, ap);
  436. va_end (ap);
  437. hard_assert (size >= 0);
  438. struct error *tmp = xmalloc (sizeof *tmp);
  439. tmp->message = xmalloc (size + 1);
  440. va_start (ap, message);
  441. size = vsnprintf (tmp->message, size + 1, message, ap);
  442. va_end (ap);
  443. hard_assert (size >= 0);
  444. soft_assert (*e == NULL);
  445. *e = tmp;
  446. }
  447. static void
  448. error_free (struct error *e)
  449. {
  450. free (e->message);
  451. free (e);
  452. }
  453. static void
  454. error_propagate (struct error **destination, struct error *source)
  455. {
  456. if (!destination)
  457. {
  458. error_free (source);
  459. return;
  460. }
  461. soft_assert (*destination == NULL);
  462. *destination = source;
  463. }
  464. // --- String hash map ---------------------------------------------------------
  465. // The most basic <string, managed pointer> map (or associative array).
  466. struct str_map_link
  467. {
  468. LIST_HEADER (str_map_link)
  469. void *data; ///< Payload
  470. size_t key_length; ///< Length of the key without '\0'
  471. char key[]; ///< The key for this link
  472. };
  473. struct str_map
  474. {
  475. struct str_map_link **map; ///< The hash table data itself
  476. size_t alloc; ///< Number of allocated entries
  477. size_t len; ///< Number of entries in the table
  478. void (*free) (void *); ///< Callback to destruct the payload
  479. /// Callback that transforms all key values for storage and comparison;
  480. /// has to behave exactly like strxfrm().
  481. size_t (*key_xfrm) (char *dest, const char *src, size_t n);
  482. };
  483. // As long as you don't remove the current entry, you can modify the map.
  484. // Use `link' directly to access the data.
  485. struct str_map_iter
  486. {
  487. struct str_map *map; ///< The map we're iterating
  488. size_t next_index; ///< Next table index to search
  489. struct str_map_link *link; ///< Current link
  490. };
  491. #define STR_MAP_MIN_ALLOC 16
  492. typedef void (*str_map_free_func) (void *);
  493. static void
  494. str_map_init (struct str_map *self)
  495. {
  496. self->alloc = STR_MAP_MIN_ALLOC;
  497. self->len = 0;
  498. self->free = NULL;
  499. self->key_xfrm = NULL;
  500. self->map = xcalloc (self->alloc, sizeof *self->map);
  501. }
  502. static void
  503. str_map_free (struct str_map *self)
  504. {
  505. struct str_map_link **iter, **end = self->map + self->alloc;
  506. struct str_map_link *link, *tmp;
  507. for (iter = self->map; iter < end; iter++)
  508. for (link = *iter; link; link = tmp)
  509. {
  510. tmp = link->next;
  511. if (self->free)
  512. self->free (link->data);
  513. free (link);
  514. }
  515. free (self->map);
  516. self->map = NULL;
  517. }
  518. static void
  519. str_map_iter_init (struct str_map_iter *self, struct str_map *map)
  520. {
  521. self->map = map;
  522. self->next_index = 0;
  523. self->link = NULL;
  524. }
  525. static void *
  526. str_map_iter_next (struct str_map_iter *self)
  527. {
  528. struct str_map *map = self->map;
  529. if (self->link)
  530. self->link = self->link->next;
  531. while (!self->link)
  532. {
  533. if (self->next_index >= map->alloc)
  534. return NULL;
  535. self->link = map->map[self->next_index++];
  536. }
  537. return self->link->data;
  538. }
  539. static uint64_t
  540. str_map_hash (const char *s, size_t len)
  541. {
  542. static unsigned char key[16] = "SipHash 2-4 key!";
  543. return siphash (key, (const void *) s, len);
  544. }
  545. static uint64_t
  546. str_map_pos (struct str_map *self, const char *s)
  547. {
  548. size_t mask = self->alloc - 1;
  549. return str_map_hash (s, strlen (s)) & mask;
  550. }
  551. static uint64_t
  552. str_map_link_hash (struct str_map_link *self)
  553. {
  554. return str_map_hash (self->key, self->key_length);
  555. }
  556. static void
  557. str_map_resize (struct str_map *self, size_t new_size)
  558. {
  559. struct str_map_link **old_map = self->map;
  560. size_t i, old_size = self->alloc;
  561. // Only powers of two, so that we don't need to compute the modulo
  562. hard_assert ((new_size & (new_size - 1)) == 0);
  563. size_t mask = new_size - 1;
  564. self->alloc = new_size;
  565. self->map = xcalloc (self->alloc, sizeof *self->map);
  566. for (i = 0; i < old_size; i++)
  567. {
  568. struct str_map_link *iter = old_map[i], *next_iter;
  569. while (iter)
  570. {
  571. next_iter = iter->next;
  572. uint64_t pos = str_map_link_hash (iter) & mask;
  573. LIST_PREPEND (self->map[pos], iter);
  574. iter = next_iter;
  575. }
  576. }
  577. free (old_map);
  578. }
  579. static void
  580. str_map_set_real (struct str_map *self, const char *key, void *value)
  581. {
  582. uint64_t pos = str_map_pos (self, key);
  583. struct str_map_link *iter = self->map[pos];
  584. for (; iter; iter = iter->next)
  585. {
  586. if (strcmp (key, iter->key))
  587. continue;
  588. // Storing the same data doesn't destroy it
  589. if (self->free && value != iter->data)
  590. self->free (iter->data);
  591. if (value)
  592. {
  593. iter->data = value;
  594. return;
  595. }
  596. LIST_UNLINK (self->map[pos], iter);
  597. free (iter);
  598. self->len--;
  599. // The array should be at least 1/4 full
  600. if (self->alloc >= (STR_MAP_MIN_ALLOC << 2)
  601. && self->len < (self->alloc >> 2))
  602. str_map_resize (self, self->alloc >> 2);
  603. return;
  604. }
  605. if (!value)
  606. return;
  607. if (self->len >= self->alloc)
  608. {
  609. str_map_resize (self, self->alloc << 1);
  610. pos = str_map_pos (self, key);
  611. }
  612. // Link in a new element for the given <key, value> pair
  613. size_t key_length = strlen (key);
  614. struct str_map_link *link = xmalloc (sizeof *link + key_length + 1);
  615. link->data = value;
  616. link->key_length = key_length;
  617. memcpy (link->key, key, key_length + 1);
  618. LIST_PREPEND (self->map[pos], link);
  619. self->len++;
  620. }
  621. static void
  622. str_map_set (struct str_map *self, const char *key, void *value)
  623. {
  624. if (!self->key_xfrm)
  625. {
  626. str_map_set_real (self, key, value);
  627. return;
  628. }
  629. char tmp[self->key_xfrm (NULL, key, 0) + 1];
  630. self->key_xfrm (tmp, key, sizeof tmp);
  631. str_map_set_real (self, tmp, value);
  632. }
  633. static void *
  634. str_map_find_real (struct str_map *self, const char *key)
  635. {
  636. struct str_map_link *iter = self->map[str_map_pos (self, key)];
  637. for (; iter; iter = iter->next)
  638. if (!strcmp (key, (const char *) iter + sizeof *iter))
  639. return iter->data;
  640. return NULL;
  641. }
  642. static void *
  643. str_map_find (struct str_map *self, const char *key)
  644. {
  645. if (!self->key_xfrm)
  646. return str_map_find_real (self, key);
  647. char tmp[self->key_xfrm (NULL, key, 0) + 1];
  648. self->key_xfrm (tmp, key, sizeof tmp);
  649. return str_map_find_real (self, tmp);
  650. }
  651. // --- File descriptor utilities -----------------------------------------------
  652. static void
  653. set_cloexec (int fd)
  654. {
  655. soft_assert (fcntl (fd, F_SETFD, fcntl (fd, F_GETFD) | FD_CLOEXEC) != -1);
  656. }
  657. static bool
  658. set_blocking (int fd, bool blocking)
  659. {
  660. int flags = fcntl (fd, F_GETFL);
  661. hard_assert (flags != -1);
  662. bool prev = !(flags & O_NONBLOCK);
  663. if (blocking)
  664. flags &= ~O_NONBLOCK;
  665. else
  666. flags |= O_NONBLOCK;
  667. hard_assert (fcntl (fd, F_SETFL, flags) != -1);
  668. return prev;
  669. }
  670. static void
  671. xclose (int fd)
  672. {
  673. while (close (fd) == -1)
  674. if (!soft_assert (errno == EINTR))
  675. break;
  676. }
  677. // --- Polling -----------------------------------------------------------------
  678. // Basically the poor man's GMainLoop/libev/libuv. It might make some sense
  679. // to instead use those tested and proven libraries but we don't need much
  680. // and it's interesting to implement.
  681. // At the moment the FD's are stored in an unsorted array. This is not ideal
  682. // complexity-wise but I don't think I have much of a choice with poll(),
  683. // and neither with epoll for that matter.
  684. //
  685. // unsorted array sorted array
  686. // search O(n) O(log n) [O(log log n)]
  687. // insert by fd O(n) O(n)
  688. // delete by fd O(n) O(n)
  689. //
  690. // Insertion in the unsorted array can be reduced to O(1) if I maintain a
  691. // bitmap of present FD's but that's still not a huge win.
  692. //
  693. // I don't expect this to be much of an issue, as there are typically not going
  694. // to be that many FD's to watch, and the linear approach is cache-friendly.
  695. typedef void (*poller_dispatcher_func) (const struct pollfd *, void *);
  696. typedef void (*poller_timer_func) (void *);
  697. #define POLLER_MIN_ALLOC 16
  698. struct poller_timer_info
  699. {
  700. int64_t when; ///< When is the timer to expire
  701. poller_timer_func dispatcher; ///< Event dispatcher
  702. void *user_data; ///< User data
  703. };
  704. struct poller_timers
  705. {
  706. struct poller_timer_info *info; ///< Min-heap of timers
  707. size_t len; ///< Number of scheduled timers
  708. size_t alloc; ///< Number of timers allocated
  709. };
  710. static void
  711. poller_timers_init (struct poller_timers *self)
  712. {
  713. self->alloc = POLLER_MIN_ALLOC;
  714. self->len = 0;
  715. self->info = xmalloc (self->alloc * sizeof *self->info);
  716. }
  717. static void
  718. poller_timers_free (struct poller_timers *self)
  719. {
  720. free (self->info);
  721. }
  722. static int64_t
  723. poller_timers_get_current_time (void)
  724. {
  725. #ifdef _POSIX_TIMERS
  726. struct timespec tp;
  727. hard_assert (clock_gettime (CLOCK_BEST, &tp) != -1);
  728. return (int64_t) tp.tv_sec * 1000 + (int64_t) tp.tv_nsec / 1000000;
  729. #else
  730. struct timeval tp;
  731. gettimeofday (&tp, NULL);
  732. return (int64_t) tp.tv_sec * 1000 + (int64_t) tp.tv_usec / 1000;
  733. #endif
  734. }
  735. static void
  736. poller_timers_heapify_down (struct poller_timers *self, size_t index)
  737. {
  738. typedef struct poller_timer_info info_t;
  739. info_t *end = self->info + self->len;
  740. while (true)
  741. {
  742. info_t *parent = self->info + index;
  743. info_t *left = self->info + 2 * index + 1;
  744. info_t *right = self->info + 2 * index + 2;
  745. info_t *largest = parent;
  746. if (left < end && left->when > largest->when)
  747. largest = left;
  748. if (right < end && right->when > largest->when)
  749. largest = right;
  750. if (parent == largest)
  751. break;
  752. info_t tmp = *parent;
  753. *parent = *largest;
  754. *largest = tmp;
  755. index = largest - self->info;
  756. }
  757. }
  758. static void
  759. poller_timers_remove_at_index (struct poller_timers *self, size_t index)
  760. {
  761. hard_assert (index < self->len);
  762. if (index == --self->len)
  763. return;
  764. self->info[index] = self->info[self->len];
  765. poller_timers_heapify_down (self, index);
  766. }
  767. static void
  768. poller_timers_dispatch (struct poller_timers *self)
  769. {
  770. int64_t now = poller_timers_get_current_time ();
  771. while (self->len && self->info->when <= now)
  772. {
  773. struct poller_timer_info info = *self->info;
  774. poller_timers_remove_at_index (self, 0);
  775. info.dispatcher (info.user_data);
  776. }
  777. }
  778. static void
  779. poller_timers_heapify_up (struct poller_timers *self, size_t index)
  780. {
  781. while (index != 0)
  782. {
  783. size_t parent = (index - 1) / 2;
  784. if (self->info[parent].when <= self->info[index].when)
  785. break;
  786. struct poller_timer_info tmp = self->info[parent];
  787. self->info[parent] = self->info[index];
  788. self->info[index] = tmp;
  789. index = parent;
  790. }
  791. }
  792. static ssize_t
  793. poller_timers_find (struct poller_timers *self,
  794. poller_timer_func dispatcher, void *data)
  795. {
  796. // NOTE: there may be duplicates.
  797. for (size_t i = 0; i < self->len; i++)
  798. if (self->info[i].dispatcher == dispatcher
  799. && self->info[i].user_data == data)
  800. return i;
  801. return -1;
  802. }
  803. static ssize_t
  804. poller_timers_find_by_data (struct poller_timers *self, void *data)
  805. {
  806. for (size_t i = 0; i < self->len; i++)
  807. if (self->info[i].user_data == data)
  808. return i;
  809. return -1;
  810. }
  811. static void
  812. poller_timers_add (struct poller_timers *self,
  813. poller_timer_func dispatcher, void *data, int timeout_ms)
  814. {
  815. if (self->len == self->alloc)
  816. self->info = xreallocarray (self->info,
  817. self->alloc <<= 1, sizeof *self->info);
  818. self->info[self->len] = (struct poller_timer_info) {
  819. .when = poller_timers_get_current_time () + timeout_ms,
  820. .dispatcher = dispatcher, .user_data = data };
  821. poller_timers_heapify_up (self, self->len++);
  822. }
  823. static int
  824. poller_timers_get_poll_timeout (struct poller_timers *self)
  825. {
  826. if (!self->len)
  827. return -1;
  828. int64_t timeout = self->info->when - poller_timers_get_current_time ();
  829. if (timeout <= 0)
  830. return 0;
  831. if (timeout > INT_MAX)
  832. return INT_MAX;
  833. return timeout;
  834. }
  835. #ifdef __linux__
  836. // I don't really need this, I've basically implemented this just because I can.
  837. #include <sys/epoll.h>
  838. struct poller_info
  839. {
  840. int fd; ///< Our file descriptor
  841. short events; ///< The poll() events we registered for
  842. poller_dispatcher_func dispatcher; ///< Event dispatcher
  843. void *user_data; ///< User data
  844. };
  845. struct poller
  846. {
  847. int epoll_fd; ///< The epoll FD
  848. struct poller_info **info; ///< Information associated with each FD
  849. struct epoll_event *revents; ///< Output array for epoll_wait()
  850. size_t len; ///< Number of polled descriptors
  851. size_t alloc; ///< Number of entries allocated
  852. struct poller_timers timers; ///< Timeouts
  853. /// Index of the element in `revents' that's about to be dispatched next.
  854. int dispatch_next;
  855. /// The total number of entries stored in `revents' by epoll_wait().
  856. int dispatch_total;
  857. };
  858. static void
  859. poller_init (struct poller *self)
  860. {
  861. self->epoll_fd = epoll_create (POLLER_MIN_ALLOC);
  862. hard_assert (self->epoll_fd != -1);
  863. set_cloexec (self->epoll_fd);
  864. self->len = 0;
  865. self->alloc = POLLER_MIN_ALLOC;
  866. self->info = xcalloc (self->alloc, sizeof *self->info);
  867. self->revents = xcalloc (self->alloc, sizeof *self->revents);
  868. poller_timers_init (&self->timers);
  869. self->dispatch_next = 0;
  870. self->dispatch_total = 0;
  871. }
  872. static void
  873. poller_free (struct poller *self)
  874. {
  875. for (size_t i = 0; i < self->len; i++)
  876. {
  877. struct poller_info *info = self->info[i];
  878. hard_assert (epoll_ctl (self->epoll_fd,
  879. EPOLL_CTL_DEL, info->fd, (void *) "") != -1);
  880. free (info);
  881. }
  882. poller_timers_free (&self->timers);
  883. xclose (self->epoll_fd);
  884. free (self->info);
  885. free (self->revents);
  886. }
  887. static ssize_t
  888. poller_find_by_fd (struct poller *self, int fd)
  889. {
  890. for (size_t i = 0; i < self->len; i++)
  891. if (self->info[i]->fd == fd)
  892. return i;
  893. return -1;
  894. }
  895. static void
  896. poller_ensure_space (struct poller *self)
  897. {
  898. if (self->len < self->alloc)
  899. return;
  900. self->alloc <<= 1;
  901. hard_assert (self->alloc != 0);
  902. self->revents = xreallocarray
  903. (self->revents, sizeof *self->revents, self->alloc);
  904. self->info = xreallocarray
  905. (self->info, sizeof *self->info, self->alloc);
  906. }
  907. static short
  908. poller_epoll_to_poll_events (uint32_t events)
  909. {
  910. short result = 0;
  911. if (events & EPOLLIN) result |= POLLIN;
  912. if (events & EPOLLOUT) result |= POLLOUT;
  913. if (events & EPOLLERR) result |= POLLERR;
  914. if (events & EPOLLHUP) result |= POLLHUP;
  915. if (events & EPOLLPRI) result |= POLLPRI;
  916. return result;
  917. }
  918. static uint32_t
  919. poller_poll_to_epoll_events (short events)
  920. {
  921. uint32_t result = 0;
  922. if (events & POLLIN) result |= EPOLLIN;
  923. if (events & POLLOUT) result |= EPOLLOUT;
  924. if (events & POLLERR) result |= EPOLLERR;
  925. if (events & POLLHUP) result |= EPOLLHUP;
  926. if (events & POLLPRI) result |= EPOLLPRI;
  927. return result;
  928. }
  929. static void
  930. poller_set (struct poller *self, int fd, short events,
  931. poller_dispatcher_func dispatcher, void *data)
  932. {
  933. ssize_t index = poller_find_by_fd (self, fd);
  934. bool modifying = true;
  935. if (index == -1)
  936. {
  937. poller_ensure_space (self);
  938. self->info[index = self->len++] = xcalloc (1, sizeof **self->info);
  939. modifying = false;
  940. }
  941. struct poller_info *info = self->info[index];
  942. info->fd = fd;
  943. info->events = events;
  944. info->dispatcher = dispatcher;
  945. info->user_data = data;
  946. struct epoll_event event;
  947. event.events = poller_poll_to_epoll_events (events);
  948. event.data.ptr = info;
  949. hard_assert (epoll_ctl (self->epoll_fd,
  950. modifying ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, fd, &event) != -1);
  951. }
  952. static void
  953. poller_remove_from_dispatch (struct poller *self,
  954. const struct poller_info *info)
  955. {
  956. if (!self->dispatch_total)
  957. return;
  958. int i;
  959. for (i = self->dispatch_next; i < self->dispatch_total; i++)
  960. if (self->revents[i].data.ptr == info)
  961. break;
  962. if (i == self->dispatch_total)
  963. return;
  964. if (i != --self->dispatch_total)
  965. self->revents[i] = self->revents[self->dispatch_total];
  966. }
  967. static void
  968. poller_remove_at_index (struct poller *self, size_t index)
  969. {
  970. hard_assert (index < self->len);
  971. struct poller_info *info = self->info[index];
  972. poller_remove_from_dispatch (self, info);
  973. hard_assert (epoll_ctl (self->epoll_fd,
  974. EPOLL_CTL_DEL, info->fd, (void *) "") != -1);
  975. free (info);
  976. if (index != --self->len)
  977. self->info[index] = self->info[self->len];
  978. }
  979. static void
  980. poller_run (struct poller *self)
  981. {
  982. // Not reentrant
  983. hard_assert (!self->dispatch_total);
  984. int n_fds;
  985. do
  986. n_fds = epoll_wait (self->epoll_fd, self->revents, self->len,
  987. poller_timers_get_poll_timeout (&self->timers));
  988. while (n_fds == -1 && errno == EINTR);
  989. if (n_fds == -1)
  990. exit_fatal ("%s: %s", "epoll", strerror (errno));
  991. poller_timers_dispatch (&self->timers);
  992. self->dispatch_next = 0;
  993. self->dispatch_total = n_fds;
  994. while (self->dispatch_next < self->dispatch_total)
  995. {
  996. struct epoll_event *revents = self->revents + self->dispatch_next;
  997. struct poller_info *info = revents->data.ptr;
  998. struct pollfd pfd;
  999. pfd.fd = info->fd;
  1000. pfd.revents = poller_epoll_to_poll_events (revents->events);
  1001. pfd.events = info->events;
  1002. self->dispatch_next++;
  1003. info->dispatcher (&pfd, info->user_data);
  1004. }
  1005. self->dispatch_next = 0;
  1006. self->dispatch_total = 0;
  1007. }
  1008. #else // !__linux__
  1009. struct poller_info
  1010. {
  1011. poller_dispatcher_func dispatcher; ///< Event dispatcher
  1012. void *user_data; ///< User data
  1013. };
  1014. struct poller
  1015. {
  1016. struct pollfd *fds; ///< Polled descriptors
  1017. struct poller_info *fds_info; ///< Additional information for each FD
  1018. size_t len; ///< Number of polled descriptors
  1019. size_t alloc; ///< Number of entries allocated
  1020. struct poller_timers timers; ///< Timers
  1021. int dispatch_next; ///< The next dispatched FD or -1
  1022. };
  1023. static void
  1024. poller_init (struct poller *self)
  1025. {
  1026. self->alloc = POLLER_MIN_ALLOC;
  1027. self->len = 0;
  1028. self->fds = xcalloc (self->alloc, sizeof *self->fds);
  1029. self->fds_info = xcalloc (self->alloc, sizeof *self->fds_info);
  1030. poller_timers_init (&self->timers);
  1031. self->dispatch_next = -1;
  1032. }
  1033. static void
  1034. poller_free (struct poller *self)
  1035. {
  1036. free (self->fds);
  1037. free (self->fds_info);
  1038. poller_timers_free (&self->timers);
  1039. }
  1040. static ssize_t
  1041. poller_find_by_fd (struct poller *self, int fd)
  1042. {
  1043. for (size_t i = 0; i < self->len; i++)
  1044. if (self->fds[i].fd == fd)
  1045. return i;
  1046. return -1;
  1047. }
  1048. static void
  1049. poller_ensure_space (struct poller *self)
  1050. {
  1051. if (self->len < self->alloc)
  1052. return;
  1053. self->alloc <<= 1;
  1054. self->fds = xreallocarray (self->fds, sizeof *self->fds, self->alloc);
  1055. self->fds_info = xreallocarray
  1056. (self->fds_info, sizeof *self->fds_info, self->alloc);
  1057. }
  1058. static void
  1059. poller_set (struct poller *self, int fd, short events,
  1060. poller_dispatcher_func dispatcher, void *data)
  1061. {
  1062. ssize_t index = poller_find_by_fd (self, fd);
  1063. if (index == -1)
  1064. {
  1065. poller_ensure_space (self);
  1066. index = self->len++;
  1067. }
  1068. struct pollfd *new_entry = self->fds + index;
  1069. memset (new_entry, 0, sizeof *new_entry);
  1070. new_entry->fd = fd;
  1071. new_entry->events = events;
  1072. self->fds_info[self->len] = (struct poller_info) { dispatcher, data };
  1073. }
  1074. static void
  1075. poller_remove_at_index (struct poller *self, size_t index)
  1076. {
  1077. hard_assert (index < self->len);
  1078. if (index == --self->len)
  1079. return;
  1080. // Make sure that we don't disrupt the dispatch loop; kind of crude
  1081. if ((int) index < self->dispatch_next)
  1082. {
  1083. memmove (self->fds + index, self->fds + index + 1,
  1084. (self->len - index) * sizeof *self->fds);
  1085. memmove (self->fds_info + index, self->fds_info + index + 1,
  1086. (self->len - index) * sizeof *self->fds_info);
  1087. self->dispatch_next--;
  1088. }
  1089. else
  1090. {
  1091. self->fds[index] = self->fds[self->len];
  1092. self->fds_info[index] = self->fds_info[self->len];
  1093. }
  1094. }
  1095. static void
  1096. poller_run (struct poller *self)
  1097. {
  1098. // Not reentrant
  1099. hard_assert (self->dispatch_next == -1);
  1100. int result;
  1101. do
  1102. result = poll (self->fds, self->len,
  1103. poller_timers_get_poll_timeout (&self->timers));
  1104. while (result == -1 && errno == EINTR);
  1105. if (result == -1)
  1106. exit_fatal ("%s: %s", "poll", strerror (errno));
  1107. poller_timers_dispatch (&self->timers);
  1108. for (int i = 0; i < (int) self->len; )
  1109. {
  1110. struct pollfd pfd = self->fds[i];
  1111. if (!pfd.revents)
  1112. continue;
  1113. struct poller_info *info = self->fds_info + i;
  1114. self->dispatch_next = ++i;
  1115. info->dispatcher (&pfd, info->user_data);
  1116. i = self->dispatch_next;
  1117. }
  1118. self->dispatch_next = -1;
  1119. }
  1120. #endif // !__linux__
  1121. // --- Utilities ---------------------------------------------------------------
  1122. static void
  1123. split_str_ignore_empty (const char *s, char delimiter, struct str_vector *out)
  1124. {
  1125. const char *begin = s, *end;
  1126. while ((end = strchr (begin, delimiter)))
  1127. {
  1128. if (begin != end)
  1129. str_vector_add_owned (out, xstrndup (begin, end - begin));
  1130. begin = ++end;
  1131. }
  1132. if (*begin)
  1133. str_vector_add (out, begin);
  1134. }
  1135. static char *
  1136. strip_str_in_place (char *s, const char *stripped_chars)
  1137. {
  1138. char *end = s + strlen (s);
  1139. while (end > s && strchr (stripped_chars, end[-1]))
  1140. *--end = '\0';
  1141. char *start = s + strspn (s, stripped_chars);
  1142. if (start > s)
  1143. memmove (s, start, end - start + 1);
  1144. return s;
  1145. }
  1146. static char *
  1147. join_str_vector (const struct str_vector *v, char delimiter)
  1148. {
  1149. if (!v->len)
  1150. return xstrdup ("");
  1151. struct str result;
  1152. str_init (&result);
  1153. str_append (&result, v->vector[0]);
  1154. for (size_t i = 1; i < v->len; i++)
  1155. str_append_printf (&result, "%c%s", delimiter, v->vector[i]);
  1156. return str_steal (&result);
  1157. }
  1158. static char *xstrdup_printf (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
  1159. static char *
  1160. xstrdup_printf (const char *format, ...)
  1161. {
  1162. va_list ap;
  1163. struct str tmp;
  1164. str_init (&tmp);
  1165. va_start (ap, format);
  1166. str_append_vprintf (&tmp, format, ap);
  1167. va_end (ap);
  1168. return str_steal (&tmp);
  1169. }
  1170. static bool
  1171. str_append_env_path (struct str *output, const char *var, bool only_absolute)
  1172. {
  1173. const char *value = getenv (var);
  1174. if (!value || (only_absolute && *value != '/'))
  1175. return false;
  1176. str_append (output, value);
  1177. return true;
  1178. }
  1179. static void
  1180. get_xdg_home_dir (struct str *output, const char *var, const char *def)
  1181. {
  1182. str_reset (output);
  1183. if (!str_append_env_path (output, var, true))
  1184. {
  1185. str_append_env_path (output, "HOME", false);
  1186. str_append_c (output, '/');
  1187. str_append (output, def);
  1188. }
  1189. }
  1190. static void
  1191. get_xdg_config_dirs (struct str_vector *out)
  1192. {
  1193. struct str config_home;
  1194. str_init (&config_home);
  1195. get_xdg_home_dir (&config_home, "XDG_CONFIG_HOME", ".config");
  1196. str_vector_add (out, config_home.str);
  1197. str_free (&config_home);
  1198. const char *xdg_config_dirs;
  1199. if ((xdg_config_dirs = getenv ("XDG_CONFIG_DIRS")))
  1200. split_str_ignore_empty (xdg_config_dirs, ':', out);
  1201. }
  1202. static char *
  1203. resolve_config_filename (const char *filename)
  1204. {
  1205. // Absolute path is absolute
  1206. if (*filename == '/')
  1207. return xstrdup (filename);
  1208. struct str_vector paths;
  1209. str_vector_init (&paths);
  1210. get_xdg_config_dirs (&paths);
  1211. struct str file;
  1212. str_init (&file);
  1213. char *result = NULL;
  1214. for (unsigned i = 0; i < paths.len; i++)
  1215. {
  1216. // As per spec, relative paths are ignored
  1217. if (*paths.vector[i] != '/')
  1218. continue;
  1219. str_reset (&file);
  1220. str_append_printf (&file, "%s/" PROGRAM_NAME "/%s",
  1221. paths.vector[i], filename);
  1222. struct stat st;
  1223. if (!stat (file.str, &st))
  1224. {
  1225. result = str_steal (&file);
  1226. break;
  1227. }
  1228. }
  1229. str_vector_free (&paths);
  1230. str_free (&file);
  1231. return result;
  1232. }
  1233. static bool
  1234. ensure_directory_existence (const char *path, struct error **e)
  1235. {
  1236. struct stat st;
  1237. if (stat (path, &st))
  1238. {
  1239. if (mkdir (path, S_IRWXU | S_IRWXG | S_IRWXO))
  1240. {
  1241. error_set (e, "cannot create directory `%s': %s",
  1242. path, strerror (errno));
  1243. return false;
  1244. }
  1245. }
  1246. else if (!S_ISDIR (st.st_mode))
  1247. {
  1248. error_set (e, "cannot create directory `%s': %s",
  1249. path, "file exists but is not a directory");
  1250. return false;
  1251. }
  1252. return true;
  1253. }
  1254. static bool
  1255. mkdir_with_parents (char *path, struct error **e)
  1256. {
  1257. char *p = path;
  1258. // XXX: This is prone to the TOCTTOU problem. The solution would be to
  1259. // rewrite the function using the {mkdir,fstat}at() functions from
  1260. // POSIX.1-2008, ideally returning a file descriptor to the open
  1261. // directory, with the current code as a fallback. Or to use chdir().
  1262. while ((p = strchr (p + 1, '/')))
  1263. {
  1264. *p = '\0';
  1265. bool success = ensure_directory_existence (path, e);
  1266. *p = '/';
  1267. if (!success)
  1268. return false;
  1269. }
  1270. return ensure_directory_existence (path, e);
  1271. }
  1272. static bool
  1273. set_boolean_if_valid (bool *out, const char *s)
  1274. {
  1275. if (!strcasecmp (s, "yes")) *out = true;
  1276. else if (!strcasecmp (s, "no")) *out = false;
  1277. else if (!strcasecmp (s, "on")) *out = true;
  1278. else if (!strcasecmp (s, "off")) *out = false;
  1279. else if (!strcasecmp (s, "true")) *out = true;
  1280. else if (!strcasecmp (s, "false")) *out = false;
  1281. else return false;
  1282. return true;
  1283. }
  1284. static bool
  1285. xstrtoul (unsigned long *out, const char *s, int base)
  1286. {
  1287. char *end;
  1288. errno = 0;
  1289. *out = strtoul (s, &end, base);
  1290. return errno == 0 && !*end && end != s;
  1291. }
  1292. static bool
  1293. read_line (FILE *fp, struct str *s)
  1294. {
  1295. int c;
  1296. bool at_end = true;
  1297. str_reset (s);
  1298. while ((c = fgetc (fp)) != EOF)
  1299. {
  1300. at_end = false;
  1301. if (c == '\r')
  1302. continue;
  1303. if (c == '\n')
  1304. break;
  1305. str_append_c (s, c);
  1306. }
  1307. return !at_end;
  1308. }
  1309. #define XSSL_ERROR_TRY_AGAIN INT_MAX
  1310. /// A small wrapper around SSL_get_error() to simplify further handling
  1311. static int
  1312. xssl_get_error (SSL *ssl, int result, const char **error_info)
  1313. {
  1314. int error = SSL_get_error (ssl, result);
  1315. switch (error)
  1316. {
  1317. case SSL_ERROR_NONE:
  1318. case SSL_ERROR_ZERO_RETURN:
  1319. case SSL_ERROR_WANT_READ:
  1320. case SSL_ERROR_WANT_WRITE:
  1321. return error;
  1322. case SSL_ERROR_SYSCALL:
  1323. if ((error = ERR_get_error ()))
  1324. *error_info = ERR_error_string (error, NULL);
  1325. else if (result == 0)
  1326. // An EOF that's not according to the protocol is still an EOF
  1327. return SSL_ERROR_ZERO_RETURN;
  1328. else
  1329. {
  1330. if (errno == EINTR)
  1331. return XSSL_ERROR_TRY_AGAIN;
  1332. *error_info = strerror (errno);
  1333. }
  1334. return SSL_ERROR_SSL;
  1335. default:
  1336. if ((error = ERR_get_error ()))
  1337. *error_info = ERR_error_string (error, NULL);
  1338. else
  1339. *error_info = "Unknown error";
  1340. return SSL_ERROR_SSL;
  1341. }
  1342. }
  1343. static char *
  1344. format_host_port_pair (const char *host, const char *port)
  1345. {
  1346. // IPv6 addresses mess with the "colon notation"; let's go with RFC 2732
  1347. if (strchr (host, ':'))
  1348. return xstrdup_printf ("[%s]:%s", host, port);
  1349. return xstrdup_printf ("%s:%s", host, port);
  1350. }
  1351. // --- Regular expressions -----------------------------------------------------
  1352. static regex_t *
  1353. regex_compile (const char *regex, int flags, struct error **e)
  1354. {
  1355. regex_t *re = xmalloc (sizeof *re);
  1356. int err = regcomp (re, regex, flags);
  1357. if (!err)
  1358. return re;
  1359. char buf[regerror (err, re, NULL, 0)];
  1360. regerror (err, re, buf, sizeof buf);
  1361. free (re);
  1362. error_set (e, "%s: %s", "failed to compile regular expression", buf);
  1363. return NULL;
  1364. }
  1365. static void
  1366. regex_free (void *regex)
  1367. {
  1368. regfree (regex);
  1369. free (regex);
  1370. }
  1371. // The cost of hashing a string is likely to be significantly smaller than that
  1372. // of compiling the whole regular expression anew, so here is a simple cache.
  1373. // Adding basic support for subgroups is easy: check `re_nsub' and output into
  1374. // a `struct str_vector' (if all we want is the substrings).
  1375. static void
  1376. regex_cache_init (struct str_map *cache)
  1377. {
  1378. str_map_init (cache);
  1379. cache->free = regex_free;
  1380. }
  1381. static bool
  1382. regex_cache_match (struct str_map *cache, const char *regex, int flags,
  1383. const char *s, struct error **e)
  1384. {
  1385. regex_t *re = str_map_find (cache, regex);
  1386. if (!re)
  1387. {
  1388. re = regex_compile (regex, flags, e);
  1389. if (!re)
  1390. return false;
  1391. str_map_set (cache, regex, re);
  1392. }
  1393. return regexec (re, s, 0, NULL, 0) != REG_NOMATCH;
  1394. }
  1395. // --- IRC utilities -----------------------------------------------------------
  1396. struct irc_message
  1397. {
  1398. struct str_map tags; ///< IRC 3.2 message tags
  1399. char *prefix; ///< Message prefix
  1400. char *command; ///< IRC command
  1401. struct str_vector params; ///< Command parameters
  1402. };
  1403. static void
  1404. irc_parse_message_tags (const char *tags, struct str_map *out)
  1405. {
  1406. struct str_vector v;
  1407. str_vector_init (&v);
  1408. split_str_ignore_empty (tags, ';', &v);
  1409. for (size_t i = 0; i < v.len; i++)
  1410. {
  1411. char *key = v.vector[i], *equal_sign = strchr (key, '=');
  1412. if (equal_sign)
  1413. {
  1414. *equal_sign = '\0';
  1415. str_map_set (out, key, xstrdup (equal_sign + 1));
  1416. }
  1417. else
  1418. str_map_set (out, key, xstrdup (""));
  1419. }
  1420. str_vector_free (&v);
  1421. }
  1422. static void
  1423. irc_parse_message (struct irc_message *msg, const char *line)
  1424. {
  1425. str_map_init (&msg->tags);
  1426. msg->tags.free = free;
  1427. msg->prefix = NULL;
  1428. msg->command = NULL;
  1429. str_vector_init (&msg->params);
  1430. // IRC 3.2 message tags
  1431. if (*line == '@')
  1432. {
  1433. size_t tags_len = strcspn (++line, " ");
  1434. char *tags = xstrndup (line, tags_len);
  1435. irc_parse_message_tags (tags, &msg->tags);
  1436. free (tags);
  1437. line += tags_len;
  1438. while (*line == ' ')
  1439. line++;
  1440. }
  1441. // Prefix
  1442. if (*line == ':')
  1443. {
  1444. size_t prefix_len = strcspn (++line, " ");
  1445. msg->prefix = xstrndup (line, prefix_len);
  1446. line += prefix_len;
  1447. }
  1448. // Command name
  1449. {
  1450. while (*line == ' ')
  1451. line++;
  1452. size_t cmd_len = strcspn (line, " ");
  1453. msg->command = xstrndup (line, cmd_len);
  1454. line += cmd_len;
  1455. }
  1456. // Arguments
  1457. while (true)
  1458. {
  1459. while (*line == ' ')
  1460. line++;
  1461. if (*line == ':')
  1462. {
  1463. str_vector_add (&msg->params, ++line);
  1464. break;
  1465. }
  1466. size_t param_len = strcspn (line, " ");
  1467. if (!param_len)
  1468. break;
  1469. str_vector_add_owned (&msg->params, xstrndup (line, param_len));
  1470. line += param_len;
  1471. }
  1472. }
  1473. static void
  1474. irc_free_message (struct irc_message *msg)
  1475. {
  1476. str_map_free (&msg->tags);
  1477. free (msg->prefix);
  1478. free (msg->command);
  1479. str_vector_free (&msg->params);
  1480. }
  1481. static void
  1482. irc_process_buffer (struct str *buf,
  1483. void (*callback)(const struct irc_message *, const char *, void *),
  1484. void *user_data)
  1485. {
  1486. char *start = buf->str, *end = start + buf->len;
  1487. for (char *p = start; p + 1 < end; p++)
  1488. {
  1489. // Split the input on newlines
  1490. if (p[0] != '\r' || p[1] != '\n')
  1491. continue;
  1492. *p = 0;
  1493. struct irc_message msg;
  1494. irc_parse_message (&msg, start);
  1495. callback (&msg, start, user_data);
  1496. irc_free_message (&msg);
  1497. start = p + 2;
  1498. }
  1499. // XXX: we might want to just advance some kind of an offset to avoid
  1500. // moving memory around unnecessarily.
  1501. str_remove_slice (buf, 0, start - buf->str);
  1502. }
  1503. static int
  1504. irc_tolower (int c)
  1505. {
  1506. if (c == '[') return '{';
  1507. if (c == ']') return '}';
  1508. if (c == '\\') return '|';
  1509. if (c == '~') return '^';
  1510. return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c;
  1511. }
  1512. static size_t
  1513. irc_strxfrm (char *dest, const char *src, size_t n)
  1514. {
  1515. size_t len = strlen (src);
  1516. while (n-- && (*dest++ = irc_tolower (*src++)))
  1517. ;
  1518. return len;
  1519. }
  1520. static int
  1521. irc_strcmp (const char *a, const char *b)
  1522. {
  1523. int x;
  1524. while (*a || *b)
  1525. if ((x = irc_tolower (*a++) - irc_tolower (*b++)))
  1526. return x;
  1527. return 0;
  1528. }
  1529. static int
  1530. irc_fnmatch (const char *pattern, const char *string)
  1531. {
  1532. size_t pattern_size = strlen (pattern) + 1;
  1533. size_t string_size = strlen (string) + 1;
  1534. char x_pattern[pattern_size], x_string[string_size];
  1535. irc_strxfrm (x_pattern, pattern, pattern_size);
  1536. irc_strxfrm (x_string, string, string_size);
  1537. return fnmatch (x_pattern, x_string, 0);
  1538. }
  1539. // --- Configuration -----------------------------------------------------------
  1540. // The keys are stripped of surrounding whitespace, the values are not.
  1541. struct config_item
  1542. {
  1543. const char *key;
  1544. const char *default_value;
  1545. const char *description;
  1546. };
  1547. static void
  1548. load_config_defaults (struct str_map *config, const struct config_item *table)
  1549. {
  1550. for (; table->key != NULL; table++)
  1551. if (table->default_value)
  1552. str_map_set (config, table->key, xstrdup (table->default_value));
  1553. else
  1554. str_map_set (config, table->key, NULL);
  1555. }
  1556. static bool
  1557. read_config_file (struct str_map *config, struct error **e)
  1558. {
  1559. char *filename = resolve_config_filename (PROGRAM_NAME ".conf");
  1560. if (!filename)
  1561. return true;
  1562. FILE *fp = fopen (filename, "r");
  1563. if (!fp)
  1564. {
  1565. error_set (e, "could not open `%s' for reading: %s",
  1566. filename, strerror (errno));
  1567. return false;
  1568. }
  1569. struct str line;
  1570. str_init (&line);
  1571. bool errors = false;
  1572. for (unsigned line_no = 1; read_line (fp, &line); line_no++)
  1573. {
  1574. char *start = line.str;
  1575. if (*start == '#')
  1576. continue;
  1577. while (isspace (*start))
  1578. start++;
  1579. char *end = strchr (start, '=');
  1580. if (end)
  1581. {
  1582. char *value = end + 1;
  1583. do
  1584. *end = '\0';
  1585. while (isspace (*--end));
  1586. str_map_set (config, start, xstrdup (value));
  1587. }
  1588. else if (*start)
  1589. {
  1590. error_set (e, "line %u in config: %s", line_no, "malformed input");
  1591. errors = true;
  1592. break;
  1593. }
  1594. }
  1595. str_free (&line);
  1596. fclose (fp);
  1597. return !errors;
  1598. }
  1599. static char *
  1600. write_default_config (const char *filename, const char *prolog,
  1601. const struct config_item *table, struct error **e)
  1602. {
  1603. struct str path, base;
  1604. str_init (&path);
  1605. str_init (&base);
  1606. if (filename)
  1607. {
  1608. char *tmp = xstrdup (filename);
  1609. str_append (&path, dirname (tmp));
  1610. strcpy (tmp, filename);
  1611. str_append (&base, basename (tmp));
  1612. free (tmp);
  1613. }
  1614. else
  1615. {
  1616. get_xdg_home_dir (&path, "XDG_CONFIG_HOME", ".config");
  1617. str_append (&path, "/" PROGRAM_NAME);
  1618. str_append (&base, PROGRAM_NAME ".conf");
  1619. }
  1620. if (!mkdir_with_parents (path.str, e))
  1621. goto error;
  1622. str_append_c (&path, '/');
  1623. str_append_str (&path, &base);
  1624. FILE *fp = fopen (path.str, "w");
  1625. if (!fp)
  1626. {
  1627. error_set (e, "could not open `%s' for writing: %s",
  1628. path.str, strerror (errno));
  1629. goto error;
  1630. }
  1631. if (prolog)
  1632. fputs (prolog, fp);
  1633. errno = 0;
  1634. for (; table->key != NULL; table++)
  1635. {
  1636. fprintf (fp, "# %s\n", table->description);
  1637. if (table->default_value)
  1638. fprintf (fp, "%s=%s\n", table->key, table->default_value);
  1639. else
  1640. fprintf (fp, "#%s=\n", table->key);
  1641. }
  1642. fclose (fp);
  1643. if (errno)
  1644. {
  1645. error_set (e, "writing to `%s' failed: %s", path.str, strerror (errno));
  1646. goto error;
  1647. }
  1648. str_free (&base);
  1649. return str_steal (&path);
  1650. error:
  1651. str_free (&base);
  1652. str_free (&path);
  1653. return NULL;
  1654. }
  1655. static void
  1656. call_write_default_config (const char *hint, const struct config_item *table)
  1657. {
  1658. static const char *prolog =
  1659. "# " PROGRAM_NAME " " PROGRAM_VERSION " configuration file\n"
  1660. "#\n"
  1661. "# Relative paths are searched for in ${XDG_CONFIG_HOME:-~/.config}\n"
  1662. "# /" PROGRAM_NAME " as well as in $XDG_CONFIG_DIRS/" PROGRAM_NAME "\n"
  1663. "\n";
  1664. struct error *e = NULL;
  1665. char *filename = write_default_config (hint, prolog, table, &e);
  1666. if (!filename)
  1667. {
  1668. print_error ("%s", e->message);
  1669. error_free (e);
  1670. exit (EXIT_FAILURE);
  1671. }
  1672. print_status ("configuration written to `%s'", filename);
  1673. free (filename);
  1674. }