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.

1773 lines
41KB

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