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.
 
 
 
 
 
 

3178 lines
88 KiB

  1. /*
  2. * kike.c: the experimental IRC daemon
  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. #include "config.h"
  21. #undef PROGRAM_NAME
  22. #define PROGRAM_NAME "kike"
  23. #include "common.c"
  24. #include "kike-replies.c"
  25. #include <nl_types.h>
  26. // --- Configuration (application-specific) ------------------------------------
  27. static struct config_item g_config_table[] =
  28. {
  29. { "server_name", NULL, "Server name" },
  30. { "server_info", "My server", "Brief server description" },
  31. { "motd", NULL, "MOTD filename" },
  32. { "catalog", NULL, "catgets localization catalog" },
  33. { "bind_host", NULL, "Address of the IRC server" },
  34. { "bind_port", "6667", "Port of the IRC server" },
  35. { "ssl_cert", NULL, "Server SSL certificate (PEM)" },
  36. { "ssl_key", NULL, "Server SSL private key (PEM)" },
  37. { "operators", NULL, "IRCop SSL cert. fingerprints" },
  38. { "max_connections", "0", "Global connection limit" },
  39. { "ping_interval", "180", "Interval between PING's (sec)" },
  40. { NULL, NULL, NULL }
  41. };
  42. // --- Signals -----------------------------------------------------------------
  43. static int g_signal_pipe[2]; ///< A pipe used to signal... signals
  44. /// Program termination has been requested by a signal
  45. static volatile sig_atomic_t g_termination_requested;
  46. static void
  47. sigterm_handler (int signum)
  48. {
  49. (void) signum;
  50. g_termination_requested = true;
  51. int original_errno = errno;
  52. if (write (g_signal_pipe[1], "t", 1) == -1)
  53. soft_assert (errno == EAGAIN);
  54. errno = original_errno;
  55. }
  56. static void
  57. setup_signal_handlers (void)
  58. {
  59. if (pipe (g_signal_pipe) == -1)
  60. exit_fatal ("%s: %s", "pipe", strerror (errno));
  61. set_cloexec (g_signal_pipe[0]);
  62. set_cloexec (g_signal_pipe[1]);
  63. // So that the pipe cannot overflow; it would make write() block within
  64. // the signal handler, which is something we really don't want to happen.
  65. // The same holds true for read().
  66. set_blocking (g_signal_pipe[0], false);
  67. set_blocking (g_signal_pipe[1], false);
  68. signal (SIGPIPE, SIG_IGN);
  69. struct sigaction sa;
  70. sa.sa_flags = SA_RESTART;
  71. sigemptyset (&sa.sa_mask);
  72. sa.sa_handler = sigterm_handler;
  73. if (sigaction (SIGINT, &sa, NULL) == -1
  74. || sigaction (SIGTERM, &sa, NULL) == -1)
  75. exit_fatal ("%s: %s", "sigaction", strerror (errno));
  76. }
  77. // --- Rate limiter ------------------------------------------------------------
  78. struct flood_detector
  79. {
  80. unsigned interval; ///< Interval for the limit
  81. unsigned limit; ///< Maximum number of events allowed
  82. time_t *timestamps; ///< Timestamps of last events
  83. unsigned pos; ///< Index of the oldest event
  84. };
  85. static void
  86. flood_detector_init (struct flood_detector *self,
  87. unsigned interval, unsigned limit)
  88. {
  89. self->interval = interval;
  90. self->limit = limit;
  91. self->timestamps = xcalloc (limit + 1, sizeof *self->timestamps);
  92. self->pos = 0;
  93. }
  94. static void
  95. flood_detector_free (struct flood_detector *self)
  96. {
  97. free (self->timestamps);
  98. }
  99. static bool
  100. flood_detector_check (struct flood_detector *self)
  101. {
  102. time_t now = time (NULL);
  103. self->timestamps[self->pos++] = now;
  104. if (self->pos > self->limit)
  105. self->pos = 0;
  106. time_t begin = now - self->interval;
  107. size_t count = 0;
  108. for (size_t i = 0; i <= self->limit; i++)
  109. if (self->timestamps[i] >= begin)
  110. count++;
  111. return count <= self->limit;
  112. }
  113. // --- IRC token validation ----------------------------------------------------
  114. // Use the enum only if applicable and a simple boolean isn't sufficient.
  115. enum validation_result
  116. {
  117. VALIDATION_OK,
  118. VALIDATION_ERROR_EMPTY,
  119. VALIDATION_ERROR_TOO_LONG,
  120. VALIDATION_ERROR_INVALID
  121. };
  122. // Everything as per RFC 2812
  123. #define IRC_MAX_NICKNAME 9
  124. #define IRC_MAX_HOSTNAME 63
  125. #define IRC_MAX_CHANNEL_NAME 50
  126. #define IRC_MAX_MESSAGE_LENGTH 510
  127. static bool
  128. irc_regex_match (const char *regex, const char *s)
  129. {
  130. static struct str_map cache;
  131. static bool initialized;
  132. if (!initialized)
  133. {
  134. regex_cache_init (&cache);
  135. initialized = true;
  136. }
  137. struct error *e = NULL;
  138. bool result = regex_cache_match (&cache, regex,
  139. REG_EXTENDED | REG_NOSUB, s, &e);
  140. hard_assert (!e);
  141. return result;
  142. }
  143. static const char *
  144. irc_validate_to_str (enum validation_result result)
  145. {
  146. switch (result)
  147. {
  148. case VALIDATION_OK: return "success";
  149. case VALIDATION_ERROR_EMPTY: return "the value is empty";
  150. case VALIDATION_ERROR_INVALID: return "invalid format";
  151. case VALIDATION_ERROR_TOO_LONG: return "the value is too long";
  152. default: abort ();
  153. }
  154. }
  155. // Anything to keep it as short as possible
  156. #define SN "[0-9A-Za-z][-0-9A-Za-z]*[0-9A-Za-z]*"
  157. #define N4 "[0-9]{1,3}"
  158. #define N6 "[0-9ABCDEFabcdef]{1,}"
  159. #define LE "A-Za-z"
  160. #define SP "][\\\\`_^{|}"
  161. static enum validation_result
  162. irc_validate_hostname (const char *hostname)
  163. {
  164. if (!*hostname)
  165. return VALIDATION_ERROR_EMPTY;
  166. if (!irc_regex_match ("^" SN "(\\." SN ")*$", hostname))
  167. return VALIDATION_ERROR_INVALID;
  168. if (strlen (hostname) > IRC_MAX_HOSTNAME)
  169. return VALIDATION_ERROR_TOO_LONG;
  170. return VALIDATION_OK;
  171. }
  172. static bool
  173. irc_is_valid_hostaddr (const char *hostaddr)
  174. {
  175. if (irc_regex_match ("^" N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr)
  176. || irc_regex_match ("^" N6 ":" N6 ":" N6 ":" N6 ":"
  177. N6 ":" N6 ":" N6 ":" N6 "$", hostaddr)
  178. || irc_regex_match ("^0:0:0:0:0:(0|[Ff]{4}):"
  179. N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr))
  180. return true;
  181. return false;
  182. }
  183. static bool
  184. irc_is_valid_host (const char *host)
  185. {
  186. return irc_validate_hostname (host) == VALIDATION_OK
  187. || irc_is_valid_hostaddr (host);
  188. }
  189. static bool
  190. irc_is_valid_user (const char *user)
  191. {
  192. return irc_regex_match ("^[^\r\n @]+$", user);
  193. }
  194. static bool
  195. irc_validate_nickname (const char *nickname)
  196. {
  197. if (!*nickname)
  198. return VALIDATION_ERROR_EMPTY;
  199. if (!irc_regex_match ("^[" SP LE "][" SP LE "0-9-]*$", nickname))
  200. return VALIDATION_ERROR_INVALID;
  201. if (strlen (nickname) > IRC_MAX_NICKNAME)
  202. return VALIDATION_ERROR_TOO_LONG;
  203. return VALIDATION_OK;
  204. }
  205. static enum validation_result
  206. irc_validate_channel_name (const char *channel_name)
  207. {
  208. if (!*channel_name)
  209. return VALIDATION_ERROR_EMPTY;
  210. if (*channel_name != '#' || strpbrk (channel_name, "\7\r\n ,:"))
  211. return VALIDATION_ERROR_INVALID;
  212. if (strlen (channel_name) > IRC_MAX_CHANNEL_NAME)
  213. return VALIDATION_ERROR_TOO_LONG;
  214. return VALIDATION_OK;
  215. }
  216. static bool
  217. irc_is_valid_key (const char *key)
  218. {
  219. // XXX: should be 7-bit as well but whatever
  220. return irc_regex_match ("^[^\r\n\f\t\v ]{1,23}$", key);
  221. }
  222. #undef SN
  223. #undef N4
  224. #undef N6
  225. #undef LE
  226. #undef SP
  227. static bool
  228. irc_is_valid_user_mask (const char *mask)
  229. {
  230. return irc_regex_match ("^[^!@]+![^!@]+@[^@!]+$", mask);
  231. }
  232. static bool
  233. irc_is_valid_fingerprint (const char *fp)
  234. {
  235. return irc_regex_match ("^[a-fA-F0-9]{40}$", fp);
  236. }
  237. // --- Clients (equals users) --------------------------------------------------
  238. #define IRC_SUPPORTED_USER_MODES "aiwros"
  239. enum
  240. {
  241. IRC_USER_MODE_INVISIBLE = (1 << 0),
  242. IRC_USER_MODE_RX_WALLOPS = (1 << 1),
  243. IRC_USER_MODE_RESTRICTED = (1 << 2),
  244. IRC_USER_MODE_OPERATOR = (1 << 3),
  245. IRC_USER_MODE_RX_SERVER_NOTICES = (1 << 4)
  246. };
  247. struct client
  248. {
  249. LIST_HEADER (client)
  250. struct server_context *ctx; ///< Server context
  251. int socket_fd; ///< The TCP socket
  252. struct str read_buffer; ///< Unprocessed input
  253. struct str write_buffer; ///< Output yet to be sent out
  254. bool initialized; ///< Has any data been received yet?
  255. bool registered; ///< The user has registered
  256. bool closing_link; ///< Closing link
  257. bool ssl_rx_want_tx; ///< SSL_read() wants to write
  258. bool ssl_tx_want_rx; ///< SSL_write() wants to read
  259. SSL *ssl; ///< SSL connection
  260. char *ssl_cert_fingerprint; ///< Client certificate fingerprint
  261. char *nickname; ///< IRC nickname (main identifier)
  262. char *username; ///< IRC username
  263. char *realname; ///< IRC realname (e-mail)
  264. char *hostname; ///< Hostname shown to the network
  265. char *address; ///< Full address including port
  266. unsigned mode; ///< User's mode
  267. char *away_message; ///< Away message
  268. time_t last_active; ///< Last PRIVMSG, to get idle time
  269. struct flood_detector antiflood; ///< Flood detector
  270. };
  271. static void
  272. client_init (struct client *self)
  273. {
  274. memset (self, 0, sizeof *self);
  275. self->socket_fd = -1;
  276. str_init (&self->read_buffer);
  277. str_init (&self->write_buffer);
  278. // TODO: make this configurable and more fine-grained
  279. flood_detector_init (&self->antiflood, 10, 20);
  280. }
  281. static void
  282. client_free (struct client *self)
  283. {
  284. if (!soft_assert (self->socket_fd == -1))
  285. xclose (self->socket_fd);
  286. if (self->ssl)
  287. SSL_free (self->ssl);
  288. str_free (&self->read_buffer);
  289. str_free (&self->write_buffer);
  290. free (self->nickname);
  291. free (self->username);
  292. free (self->realname);
  293. free (self->hostname);
  294. free (self->address);
  295. free (self->away_message);
  296. flood_detector_free (&self->antiflood);
  297. }
  298. static void client_close_link (struct client *, const char *);
  299. static void client_send (struct client *, const char *, ...)
  300. ATTRIBUTE_PRINTF (2, 3);
  301. static void client_cancel_timers (struct client *);
  302. static void client_set_kill_timer (struct client *);
  303. static void client_update_poller (struct client *, const struct pollfd *);
  304. // --- Channels ----------------------------------------------------------------
  305. #define IRC_SUPPORTED_CHAN_MODES "ov" "beI" "imnqpst" "kl"
  306. enum
  307. {
  308. IRC_CHAN_MODE_INVITE_ONLY = (1 << 0),
  309. IRC_CHAN_MODE_MODERATED = (1 << 1),
  310. IRC_CHAN_MODE_NO_OUTSIDE_MSGS = (1 << 2),
  311. IRC_CHAN_MODE_QUIET = (1 << 3),
  312. IRC_CHAN_MODE_PRIVATE = (1 << 4),
  313. IRC_CHAN_MODE_SECRET = (1 << 5),
  314. IRC_CHAN_MODE_PROTECTED_TOPIC = (1 << 6),
  315. IRC_CHAN_MODE_OPERATOR = (1 << 7),
  316. IRC_CHAN_MODE_VOICE = (1 << 8)
  317. };
  318. struct channel_user
  319. {
  320. LIST_HEADER (channel_user)
  321. unsigned modes;
  322. struct client *c;
  323. };
  324. struct channel
  325. {
  326. struct server_context *ctx; ///< Server context
  327. char *name; ///< Channel name
  328. unsigned modes; ///< Channel modes
  329. char *key; ///< Channel key
  330. long user_limit; ///< User limit or -1
  331. char *topic; ///< Channel topic
  332. struct channel_user *users; ///< Channel users
  333. struct str_vector ban_list; ///< Ban list
  334. struct str_vector exception_list; ///< Exceptions from bans
  335. struct str_vector invite_list; ///< Exceptions from +I
  336. };
  337. static struct channel *
  338. channel_new (void)
  339. {
  340. struct channel *self = xcalloc (1, sizeof *self);
  341. self->user_limit = -1;
  342. self->topic = xstrdup ("");
  343. str_vector_init (&self->ban_list);
  344. str_vector_init (&self->exception_list);
  345. str_vector_init (&self->invite_list);
  346. return self;
  347. }
  348. static void
  349. channel_delete (struct channel *self)
  350. {
  351. free (self->name);
  352. free (self->key);
  353. free (self->topic);
  354. struct channel_user *link, *tmp;
  355. for (link = self->users; link; link = tmp)
  356. {
  357. tmp = link->next;
  358. free (link);
  359. }
  360. str_vector_free (&self->ban_list);
  361. str_vector_free (&self->exception_list);
  362. str_vector_free (&self->invite_list);
  363. free (self);
  364. }
  365. static char *
  366. channel_get_mode (struct channel *self, bool disclose_secrets)
  367. {
  368. struct str mode;
  369. str_init (&mode);
  370. unsigned m = self->modes;
  371. if (m & IRC_CHAN_MODE_INVITE_ONLY) str_append_c (&mode, 'i');
  372. if (m & IRC_CHAN_MODE_MODERATED) str_append_c (&mode, 'm');
  373. if (m & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) str_append_c (&mode, 'n');
  374. if (m & IRC_CHAN_MODE_QUIET) str_append_c (&mode, 'q');
  375. if (m & IRC_CHAN_MODE_PRIVATE) str_append_c (&mode, 'p');
  376. if (m & IRC_CHAN_MODE_SECRET) str_append_c (&mode, 's');
  377. if (m & IRC_CHAN_MODE_PROTECTED_TOPIC) str_append_c (&mode, 't');
  378. if (self->user_limit != -1) str_append_c (&mode, 'l');
  379. if (self->key) str_append_c (&mode, 'k');
  380. // XXX: is it correct to split it? Try it on an existing implementation.
  381. if (disclose_secrets)
  382. {
  383. if (self->user_limit != -1)
  384. str_append_printf (&mode, " %ld", self->user_limit);
  385. if (self->key)
  386. str_append_printf (&mode, " %s", self->key);
  387. }
  388. return str_steal (&mode);
  389. }
  390. static struct channel_user *
  391. channel_get_user (const struct channel *chan, const struct client *c)
  392. {
  393. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  394. if (iter->c == c)
  395. return iter;
  396. return NULL;
  397. }
  398. static struct channel_user *
  399. channel_add_user (struct channel *chan, struct client *c)
  400. {
  401. struct channel_user *link = xcalloc (1, sizeof *link);
  402. link->c = c;
  403. LIST_PREPEND (chan->users, link);
  404. return link;
  405. }
  406. static void
  407. channel_remove_user (struct channel *chan, struct channel_user *user)
  408. {
  409. LIST_UNLINK (chan->users, user);
  410. free (user);
  411. }
  412. static size_t
  413. channel_user_count (const struct channel *chan)
  414. {
  415. size_t result = 0;
  416. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  417. result++;
  418. return result;
  419. }
  420. // --- IRC server context ------------------------------------------------------
  421. struct server_context
  422. {
  423. int *listen_fds; ///< Listening socket FD's
  424. size_t n_listen_fds; ///< Number of listening sockets
  425. SSL_CTX *ssl_ctx; ///< SSL context
  426. struct client *clients; ///< Clients
  427. unsigned n_clients; ///< Current number of connections
  428. struct str_map users; ///< Maps nicknames to clients
  429. struct str_map channels; ///< Maps channel names to data
  430. struct str_map handlers; ///< Message handlers
  431. struct poller poller; ///< Manages polled description
  432. bool quitting; ///< User requested quitting
  433. bool polling; ///< The event loop is running
  434. struct str_map config; ///< Server configuration
  435. char *server_name; ///< Our server name
  436. unsigned ping_interval; ///< Ping interval in seconds
  437. unsigned max_connections; ///< Max. connections allowed or 0
  438. struct str_vector motd; ///< MOTD (none if empty)
  439. nl_catd catalog; ///< Message catalog for server msgs
  440. struct str_map operators; ///< SSL cert. fingerprints for IRCops
  441. };
  442. static void
  443. server_context_init (struct server_context *self)
  444. {
  445. self->listen_fds = NULL;
  446. self->n_listen_fds = 0;
  447. self->clients = NULL;
  448. self->n_clients = 0;
  449. str_map_init (&self->users);
  450. self->users.key_xfrm = irc_strxfrm;
  451. str_map_init (&self->channels);
  452. self->channels.key_xfrm = irc_strxfrm;
  453. self->channels.free = (void (*) (void *)) channel_delete;
  454. str_map_init (&self->handlers);
  455. self->handlers.key_xfrm = irc_strxfrm;
  456. poller_init (&self->poller);
  457. self->quitting = false;
  458. self->polling = false;
  459. str_map_init (&self->config);
  460. self->config.free = free;
  461. load_config_defaults (&self->config, g_config_table);
  462. self->server_name = NULL;
  463. self->ping_interval = 0;
  464. self->max_connections = 0;
  465. str_vector_init (&self->motd);
  466. self->catalog = (nl_catd) -1;
  467. str_map_init (&self->operators);
  468. // The regular irc_strxfrm() is sufficient for fingerprints
  469. self->operators.key_xfrm = irc_strxfrm;
  470. }
  471. static void
  472. server_context_free (struct server_context *self)
  473. {
  474. str_map_free (&self->config);
  475. for (size_t i = 0; i < self->n_listen_fds; i++)
  476. xclose (self->listen_fds[i]);
  477. free (self->listen_fds);
  478. if (self->ssl_ctx)
  479. SSL_CTX_free (self->ssl_ctx);
  480. struct client *link, *tmp;
  481. for (link = self->clients; link; link = tmp)
  482. {
  483. tmp = link->next;
  484. client_free (link);
  485. free (link);
  486. }
  487. free (self->server_name);
  488. str_map_free (&self->users);
  489. str_map_free (&self->channels);
  490. str_map_free (&self->handlers);
  491. poller_free (&self->poller);
  492. str_vector_free (&self->motd);
  493. if (self->catalog != (nl_catd) -1)
  494. catclose (self->catalog);
  495. str_map_free (&self->operators);
  496. }
  497. static const char *
  498. irc_get_text (struct server_context *ctx, int id, const char *def)
  499. {
  500. if (!soft_assert (def != NULL))
  501. def = "";
  502. if (ctx->catalog == (nl_catd) -1)
  503. return def;
  504. return catgets (ctx->catalog, 1, id, def);
  505. }
  506. static void
  507. irc_try_finish_quit (struct server_context *ctx)
  508. {
  509. if (!ctx->n_clients && ctx->quitting)
  510. ctx->polling = false;
  511. }
  512. static void
  513. irc_initiate_quit (struct server_context *ctx)
  514. {
  515. print_status ("shutting down");
  516. for (struct client *iter = ctx->clients; iter; iter = iter->next)
  517. if (!iter->closing_link)
  518. client_close_link (iter, "Shutting down");
  519. for (size_t i = 0; i < ctx->n_listen_fds; i++)
  520. {
  521. ssize_t index = poller_find_by_fd (&ctx->poller, ctx->listen_fds[i]);
  522. if (soft_assert (index != -1))
  523. poller_remove_at_index (&ctx->poller, index);
  524. xclose (ctx->listen_fds[i]);
  525. }
  526. ctx->n_listen_fds = 0;
  527. ctx->quitting = true;
  528. irc_try_finish_quit (ctx);
  529. }
  530. static struct channel *
  531. irc_channel_create (struct server_context *ctx, const char *name)
  532. {
  533. struct channel *chan = channel_new ();
  534. chan->ctx = ctx;
  535. chan->name = xstrdup (name);
  536. str_map_set (&ctx->channels, name, chan);
  537. return chan;
  538. }
  539. static void
  540. irc_channel_destroy_if_empty (struct server_context *ctx, struct channel *chan)
  541. {
  542. if (!chan->users)
  543. str_map_set (&ctx->channels, chan->name, NULL);
  544. }
  545. static void
  546. irc_send_to_roommates (struct client *c, const char *message)
  547. {
  548. struct str_map targets;
  549. str_map_init (&targets);
  550. targets.key_xfrm = irc_strxfrm;
  551. struct str_map_iter iter;
  552. str_map_iter_init (&iter, &c->ctx->channels);
  553. struct channel *chan;
  554. while ((chan = str_map_iter_next (&iter)))
  555. {
  556. if (chan->modes & IRC_CHAN_MODE_QUIET
  557. || !channel_get_user (chan, c))
  558. continue;
  559. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  560. str_map_set (&targets, iter->c->nickname, iter->c);
  561. }
  562. str_map_iter_init (&iter, &targets);
  563. struct client *target;
  564. while ((target = str_map_iter_next (&iter)))
  565. if (target != c)
  566. client_send (target, "%s", message);
  567. }
  568. // --- Clients (continued) -----------------------------------------------------
  569. static void
  570. client_mode_to_str (unsigned m, struct str *out)
  571. {
  572. if (m & IRC_USER_MODE_INVISIBLE) str_append_c (out, 'i');
  573. if (m & IRC_USER_MODE_RX_WALLOPS) str_append_c (out, 'w');
  574. if (m & IRC_USER_MODE_RESTRICTED) str_append_c (out, 'r');
  575. if (m & IRC_USER_MODE_OPERATOR) str_append_c (out, 'o');
  576. if (m & IRC_USER_MODE_RX_SERVER_NOTICES) str_append_c (out, 's');
  577. }
  578. static char *
  579. client_get_mode (struct client *self)
  580. {
  581. struct str mode;
  582. str_init (&mode);
  583. if (self->away_message)
  584. str_append_c (&mode, 'a');
  585. client_mode_to_str (self->mode, &mode);
  586. return str_steal (&mode);
  587. }
  588. static void
  589. client_send_str (struct client *c, const struct str *s)
  590. {
  591. hard_assert (c->initialized && !c->closing_link);
  592. // TODO: kill the connection above some "SendQ" threshold (careful!)
  593. str_append_data (&c->write_buffer, s->str,
  594. s->len > IRC_MAX_MESSAGE_LENGTH ? IRC_MAX_MESSAGE_LENGTH : s->len);
  595. str_append (&c->write_buffer, "\r\n");
  596. // XXX: we might want to move this elsewhere, so that it doesn't get called
  597. // as often; it's going to cause a lot of syscalls with epoll.
  598. client_update_poller (c, NULL);
  599. }
  600. static void
  601. client_send (struct client *c, const char *format, ...)
  602. {
  603. struct str tmp;
  604. str_init (&tmp);
  605. va_list ap;
  606. va_start (ap, format);
  607. str_append_vprintf (&tmp, format, ap);
  608. va_end (ap);
  609. client_send_str (c, &tmp);
  610. str_free (&tmp);
  611. }
  612. static void
  613. client_unregister (struct client *c, const char *reason)
  614. {
  615. if (!c->registered)
  616. return;
  617. char *message = xstrdup_printf (":%s!%s@%s QUIT :%s",
  618. c->nickname, c->username, c->hostname, reason);
  619. irc_send_to_roommates (c, message);
  620. free (message);
  621. struct str_map_iter iter;
  622. str_map_iter_init (&iter, &c->ctx->channels);
  623. struct channel *chan, *next = str_map_iter_next (&iter);
  624. for (chan = next; chan; chan = next)
  625. {
  626. next = str_map_iter_next (&iter);
  627. struct channel_user *user;
  628. if (!(user = channel_get_user (chan, c)))
  629. continue;
  630. channel_remove_user (chan, user);
  631. irc_channel_destroy_if_empty (c->ctx, chan);
  632. }
  633. str_map_set (&c->ctx->users, c->nickname, NULL);
  634. free (c->nickname);
  635. c->nickname = NULL;
  636. c->registered = false;
  637. }
  638. static void
  639. client_kill (struct client *c, const char *reason)
  640. {
  641. client_unregister (c, reason ? reason : "Client exited");
  642. struct server_context *ctx = c->ctx;
  643. ssize_t i = poller_find_by_fd (&ctx->poller, c->socket_fd);
  644. if (i != -1)
  645. poller_remove_at_index (&ctx->poller, i);
  646. client_cancel_timers (c);
  647. if (c->ssl)
  648. (void) SSL_shutdown (c->ssl);
  649. xclose (c->socket_fd);
  650. print_debug ("closed connection to %s (%s)",
  651. c->address, reason ? reason : "Reason omitted");
  652. c->socket_fd = -1;
  653. client_free (c);
  654. LIST_UNLINK (ctx->clients, c);
  655. ctx->n_clients--;
  656. free (c);
  657. irc_try_finish_quit (ctx);
  658. }
  659. static void
  660. client_close_link (struct client *c, const char *reason)
  661. {
  662. if (!soft_assert (!c->closing_link))
  663. return;
  664. // We push an `ERROR' message to the write buffer and let the poller send
  665. // it, with some arbitrary timeout. The `closing_link' state makes sure
  666. // that a/ we ignore any successive messages, and b/ that the connection
  667. // is killed after the write buffer is transferred and emptied.
  668. client_send (c, "ERROR :Closing Link: %s[%s] (%s)", c->nickname,
  669. c->hostname /* TODO host IP? */, reason);
  670. c->closing_link = true;
  671. client_unregister (c, reason);
  672. client_set_kill_timer (c);
  673. }
  674. static bool
  675. client_in_mask_list (const struct client *c, const struct str_vector *mask)
  676. {
  677. char *client = xstrdup_printf ("%s!%s@%s",
  678. c->nickname, c->username, c->hostname);
  679. bool result = false;
  680. for (size_t i = 0; i < mask->len; i++)
  681. if (!irc_fnmatch (mask->vector[i], client))
  682. {
  683. result = true;
  684. break;
  685. }
  686. free (client);
  687. return result;
  688. }
  689. static char *
  690. client_get_ssl_cert_fingerprint (struct client *c)
  691. {
  692. if (!c->ssl)
  693. return NULL;
  694. X509 *peer_cert = SSL_get_peer_certificate (c->ssl);
  695. if (!peer_cert)
  696. return NULL;
  697. int cert_len = i2d_X509 (peer_cert, NULL);
  698. if (cert_len < 0)
  699. return NULL;
  700. unsigned char cert[cert_len], *p = cert;
  701. if (i2d_X509 (peer_cert, &p) < 0)
  702. return NULL;
  703. unsigned char hash[SHA_DIGEST_LENGTH];
  704. SHA1 (cert, cert_len, hash);
  705. struct str fingerprint;
  706. str_init (&fingerprint);
  707. for (size_t i = 0; i < sizeof hash; i++)
  708. str_append_printf (&fingerprint, "%02x", hash[i]);
  709. return str_steal (&fingerprint);
  710. }
  711. // --- Timers ------------------------------------------------------------------
  712. static void
  713. client_cancel_timers (struct client *c)
  714. {
  715. ssize_t i;
  716. struct poller_timers *timers = &c->ctx->poller.timers;
  717. while ((i = poller_timers_find_by_data (timers, c)) != -1)
  718. poller_timers_remove_at_index (timers, i);
  719. }
  720. static void
  721. client_set_timer (struct client *c, poller_timer_fn fn, unsigned interval)
  722. {
  723. client_cancel_timers (c);
  724. poller_timers_add (&c->ctx->poller.timers, fn, c, interval * 1000);
  725. }
  726. static void
  727. on_client_kill_timer (void *user_data)
  728. {
  729. struct client *c = user_data;
  730. hard_assert (!c->initialized || c->closing_link);
  731. client_kill (c, NULL);
  732. }
  733. static void
  734. client_set_kill_timer (struct client *c)
  735. {
  736. client_set_timer (c, on_client_kill_timer, c->ctx->ping_interval);
  737. }
  738. static void
  739. on_client_timeout_timer (void *user_data)
  740. {
  741. struct client *c = user_data;
  742. char *reason = xstrdup_printf
  743. ("Ping timeout: >%u seconds", c->ctx->ping_interval);
  744. client_close_link (c, reason);
  745. free (reason);
  746. }
  747. static void
  748. on_client_ping_timer (void *user_data)
  749. {
  750. struct client *c = user_data;
  751. hard_assert (!c->closing_link);
  752. client_send (c, "PING :%s", c->ctx->server_name);
  753. client_set_timer (c, on_client_timeout_timer, c->ctx->ping_interval);
  754. }
  755. static void
  756. client_set_ping_timer (struct client *c)
  757. {
  758. client_set_timer (c, on_client_ping_timer, c->ctx->ping_interval);
  759. }
  760. // --- IRC command handling ----------------------------------------------------
  761. // XXX: this way we cannot typecheck the arguments, so we must be careful
  762. static void
  763. irc_send_reply (struct client *c, int id, ...)
  764. {
  765. struct str tmp;
  766. str_init (&tmp);
  767. va_list ap;
  768. va_start (ap, id);
  769. str_append_printf (&tmp, ":%s %03d %s ",
  770. c->ctx->server_name, id, c->nickname ? c->nickname : "");
  771. str_append_vprintf (&tmp,
  772. irc_get_text (c->ctx, id, g_default_replies[id]), ap);
  773. va_end (ap);
  774. client_send_str (c, &tmp);
  775. str_free (&tmp);
  776. }
  777. #define RETURN_WITH_REPLY(c, ...) \
  778. BLOCK_START \
  779. irc_send_reply ((c), __VA_ARGS__); \
  780. return; \
  781. BLOCK_END
  782. static void
  783. irc_send_motd (struct client *c)
  784. {
  785. struct server_context *ctx = c->ctx;
  786. if (!ctx->motd.len)
  787. RETURN_WITH_REPLY (c, IRC_ERR_NOMOTD);
  788. irc_send_reply (c, IRC_RPL_MOTDSTART, ctx->server_name);
  789. for (size_t i = 0; i < ctx->motd.len; i++)
  790. irc_send_reply (c, IRC_RPL_MOTD, ctx->motd.vector[i]);
  791. irc_send_reply (c, IRC_RPL_ENDOFMOTD);
  792. }
  793. static void
  794. irc_send_lusers (struct client *c)
  795. {
  796. int n_users = 0, n_services = 0, n_opers = 0, n_unknown = 0;
  797. for (struct client *link = c->ctx->clients; link; link = link->next)
  798. {
  799. if (link->registered)
  800. n_users++;
  801. else
  802. n_unknown++;
  803. if (link->mode & IRC_USER_MODE_OPERATOR)
  804. n_opers++;
  805. }
  806. int n_channels = 0;
  807. struct str_map_iter iter;
  808. str_map_iter_init (&iter, &c->ctx->channels);
  809. struct channel *chan;
  810. while ((chan = str_map_iter_next (&iter)))
  811. if (!(chan->modes & IRC_CHAN_MODE_SECRET)
  812. || channel_get_user (chan, c))
  813. n_channels++;
  814. irc_send_reply (c, IRC_RPL_LUSERCLIENT,
  815. n_users, n_services, 1 /* servers total */);
  816. if (n_opers)
  817. irc_send_reply (c, IRC_RPL_LUSEROP, n_opers);
  818. if (n_unknown)
  819. irc_send_reply (c, IRC_RPL_LUSERUNKNOWN, n_unknown);
  820. if (n_channels)
  821. irc_send_reply (c, IRC_RPL_LUSERCHANNELS, n_channels);
  822. irc_send_reply (c, IRC_RPL_LUSERME,
  823. n_users + n_services + n_unknown, 0 /* peer servers */);
  824. }
  825. static bool
  826. irc_is_this_me (struct server_context *ctx, const char *target)
  827. {
  828. // Target servers can also be matched by their users
  829. return !irc_fnmatch (target, ctx->server_name)
  830. || str_map_find (&ctx->users, target);
  831. }
  832. static void
  833. irc_try_finish_registration (struct client *c)
  834. {
  835. struct server_context *ctx = c->ctx;
  836. if (!c->nickname || !c->username || !c->realname)
  837. return;
  838. c->registered = true;
  839. irc_send_reply (c, IRC_RPL_WELCOME, c->nickname, c->username, c->hostname);
  840. irc_send_reply (c, IRC_RPL_YOURHOST, ctx->server_name, PROGRAM_VERSION);
  841. // The purpose of this message eludes me
  842. irc_send_reply (c, IRC_RPL_CREATED, __DATE__);
  843. irc_send_reply (c, IRC_RPL_MYINFO, ctx->server_name, PROGRAM_VERSION,
  844. IRC_SUPPORTED_USER_MODES, IRC_SUPPORTED_CHAN_MODES);
  845. irc_send_lusers (c);
  846. irc_send_motd (c);
  847. char *mode = client_get_mode (c);
  848. if (*mode)
  849. client_send (c, ":%s MODE %s :+%s", c->nickname, c->nickname, mode);
  850. free (mode);
  851. hard_assert (c->ssl_cert_fingerprint == NULL);
  852. if ((c->ssl_cert_fingerprint = client_get_ssl_cert_fingerprint (c)))
  853. client_send (c, ":%s NOTICE %s :"
  854. "Your SSL client certificate fingerprint is %s",
  855. ctx->server_name, c->nickname, c->ssl_cert_fingerprint);
  856. }
  857. static void
  858. irc_handle_pass (const struct irc_message *msg, struct client *c)
  859. {
  860. if (c->registered)
  861. irc_send_reply (c, IRC_ERR_ALREADYREGISTERED);
  862. else if (msg->params.len < 1)
  863. irc_send_reply (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  864. // We have SSL client certificates for this purpose; ignoring
  865. }
  866. static void
  867. irc_handle_nick (const struct irc_message *msg, struct client *c)
  868. {
  869. struct server_context *ctx = c->ctx;
  870. if (msg->params.len < 1)
  871. RETURN_WITH_REPLY (c, IRC_ERR_NONICKNAMEGIVEN);
  872. const char *nickname = msg->params.vector[0];
  873. if (irc_validate_nickname (nickname) != VALIDATION_OK)
  874. RETURN_WITH_REPLY (c, IRC_ERR_ERRONEOUSNICKNAME, nickname);
  875. struct client *client = str_map_find (&ctx->users, nickname);
  876. if (client && client != c)
  877. RETURN_WITH_REPLY (c, IRC_ERR_NICKNAMEINUSE, nickname);
  878. if (c->registered)
  879. {
  880. char *message = xstrdup_printf (":%s!%s@%s NICK :%s",
  881. c->nickname, c->username, c->hostname, nickname);
  882. irc_send_to_roommates (c, message);
  883. client_send (c, "%s", message);
  884. free (message);
  885. }
  886. // Release the old nickname and allocate a new one
  887. if (c->nickname)
  888. {
  889. str_map_set (&ctx->users, c->nickname, NULL);
  890. free (c->nickname);
  891. }
  892. c->nickname = xstrdup (nickname);
  893. str_map_set (&ctx->users, nickname, c);
  894. if (!c->registered)
  895. irc_try_finish_registration (c);
  896. }
  897. static void
  898. irc_handle_user (const struct irc_message *msg, struct client *c)
  899. {
  900. if (c->registered)
  901. RETURN_WITH_REPLY (c, IRC_ERR_ALREADYREGISTERED);
  902. if (msg->params.len < 4)
  903. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  904. const char *username = msg->params.vector[0];
  905. const char *mode = msg->params.vector[1];
  906. const char *realname = msg->params.vector[3];
  907. // Unfortunately the protocol doesn't give us any means of rejecting it
  908. if (!irc_is_valid_user (username))
  909. username = "xxx";
  910. free (c->username);
  911. c->username = xstrdup (username);
  912. free (c->realname);
  913. c->realname = xstrdup (realname);
  914. unsigned long m;
  915. if (xstrtoul (&m, mode, 10))
  916. {
  917. if (m & 4) c->mode |= IRC_USER_MODE_RX_WALLOPS;
  918. if (m & 8) c->mode |= IRC_USER_MODE_INVISIBLE;
  919. }
  920. irc_try_finish_registration (c);
  921. }
  922. static void
  923. irc_handle_userhost (const struct irc_message *msg, struct client *c)
  924. {
  925. if (msg->params.len < 1)
  926. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  927. struct str reply;
  928. str_init (&reply);
  929. for (size_t i = 0; i < 5 && i < msg->params.len; i++)
  930. {
  931. const char *nick = msg->params.vector[i];
  932. struct client *target = str_map_find (&c->ctx->users, nick);
  933. if (!target)
  934. continue;
  935. if (i)
  936. str_append_c (&reply, ' ');
  937. str_append (&reply, nick);
  938. if (target->mode & IRC_USER_MODE_OPERATOR)
  939. str_append_c (&reply, '*');
  940. str_append_printf (&reply, "=%c%s@%s",
  941. target->away_message ? '-' : '+',
  942. target->username, target->hostname);
  943. }
  944. irc_send_reply (c, IRC_RPL_USERHOST, reply.str);
  945. str_free (&reply);
  946. }
  947. static void
  948. irc_handle_lusers (const struct irc_message *msg, struct client *c)
  949. {
  950. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  951. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  952. else
  953. irc_send_lusers (c);
  954. }
  955. static void
  956. irc_handle_motd (const struct irc_message *msg, struct client *c)
  957. {
  958. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  959. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  960. else
  961. irc_send_motd (c);
  962. }
  963. static void
  964. irc_handle_ping (const struct irc_message *msg, struct client *c)
  965. {
  966. // XXX: the RFC is pretty incomprehensible about the exact usage
  967. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  968. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  969. else if (msg->params.len < 1)
  970. irc_send_reply (c, IRC_ERR_NOORIGIN);
  971. else
  972. client_send (c, ":%s PONG :%s",
  973. c->ctx->server_name, msg->params.vector[0]);
  974. }
  975. static void
  976. irc_handle_pong (const struct irc_message *msg, struct client *c)
  977. {
  978. // We are the only server, so we don't have to care too much
  979. if (msg->params.len < 1)
  980. irc_send_reply (c, IRC_ERR_NOORIGIN);
  981. else
  982. // Set a new timer to send another PING
  983. client_set_ping_timer (c);
  984. }
  985. static void
  986. irc_handle_quit (const struct irc_message *msg, struct client *c)
  987. {
  988. char *reason = xstrdup_printf ("Quit: %s",
  989. msg->params.len > 0 ? msg->params.vector[0] : c->nickname);
  990. client_close_link (c, reason);
  991. free (reason);
  992. }
  993. static void
  994. irc_handle_time (const struct irc_message *msg, struct client *c)
  995. {
  996. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  997. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  998. char buf[32];
  999. time_t now = time (NULL);
  1000. struct tm tm;
  1001. strftime (buf, sizeof buf, "%a %b %d %Y %T", localtime_r (&now, &tm));
  1002. irc_send_reply (c, IRC_RPL_TIME, c->ctx->server_name, buf);
  1003. }
  1004. static void
  1005. irc_handle_version (const struct irc_message *msg, struct client *c)
  1006. {
  1007. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1008. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1009. else
  1010. irc_send_reply (c, IRC_RPL_VERSION, PROGRAM_VERSION, g_debug_mode,
  1011. c->ctx->server_name, PROGRAM_NAME " " PROGRAM_VERSION);
  1012. }
  1013. static void
  1014. irc_channel_multicast (struct channel *chan, const char *message,
  1015. struct client *except)
  1016. {
  1017. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  1018. if (iter->c != except)
  1019. client_send (iter->c, "%s", message);
  1020. }
  1021. static bool
  1022. irc_modify_mode (unsigned *mask, unsigned mode, bool add)
  1023. {
  1024. unsigned orig = *mask;
  1025. if (add)
  1026. *mask |= mode;
  1027. else
  1028. *mask &= ~mode;
  1029. return *mask != orig;
  1030. }
  1031. static void
  1032. irc_update_user_mode (struct client *c, unsigned new_mode)
  1033. {
  1034. unsigned old_mode = c->mode;
  1035. c->mode = new_mode;
  1036. unsigned added = new_mode & ~old_mode;
  1037. unsigned removed = old_mode & ~new_mode;
  1038. struct str diff;
  1039. str_init (&diff);
  1040. if (added)
  1041. {
  1042. str_append_c (&diff, '+');
  1043. client_mode_to_str (added, &diff);
  1044. }
  1045. if (removed)
  1046. {
  1047. str_append_c (&diff, '-');
  1048. client_mode_to_str (removed, &diff);
  1049. }
  1050. if (diff.len)
  1051. client_send (c, ":%s MODE %s :%s",
  1052. c->nickname, c->nickname, diff.str);
  1053. str_free (&diff);
  1054. }
  1055. static void
  1056. irc_handle_user_mode_change (struct client *c, const char *mode_string)
  1057. {
  1058. unsigned new_mode = c->mode;
  1059. bool adding = true;
  1060. while (*mode_string)
  1061. switch (*mode_string++)
  1062. {
  1063. case '+': adding = true; break;
  1064. case '-': adding = false; break;
  1065. case 'a':
  1066. // Ignore, the client should use AWAY
  1067. break;
  1068. case 'i':
  1069. irc_modify_mode (&new_mode, IRC_USER_MODE_INVISIBLE, adding);
  1070. break;
  1071. case 'w':
  1072. irc_modify_mode (&new_mode, IRC_USER_MODE_RX_WALLOPS, adding);
  1073. break;
  1074. case 'r':
  1075. // It's not possible to un-restrict yourself
  1076. if (adding)
  1077. new_mode |= IRC_USER_MODE_RESTRICTED;
  1078. break;
  1079. case 'o':
  1080. if (!adding)
  1081. new_mode &= ~IRC_USER_MODE_OPERATOR;
  1082. else if (c->ssl_cert_fingerprint
  1083. && str_map_find (&c->ctx->operators, c->ssl_cert_fingerprint))
  1084. new_mode |= IRC_USER_MODE_OPERATOR;
  1085. else
  1086. client_send (c, ":%s NOTICE %s :Either you're not using an SSL"
  1087. " client certificate, or the fingerprint doesn't match",
  1088. c->ctx->server_name, c->nickname);
  1089. break;
  1090. case 's':
  1091. irc_modify_mode (&new_mode, IRC_USER_MODE_RX_SERVER_NOTICES, adding);
  1092. break;
  1093. default:
  1094. RETURN_WITH_REPLY (c, IRC_ERR_UMODEUNKNOWNFLAG);
  1095. }
  1096. irc_update_user_mode (c, new_mode);
  1097. }
  1098. static void
  1099. irc_send_channel_list (struct client *c, const char *channel_name,
  1100. const struct str_vector *list, int reply, int end_reply)
  1101. {
  1102. for (size_t i = 0; i < list->len; i++)
  1103. irc_send_reply (c, reply, channel_name, list->vector[i]);
  1104. irc_send_reply (c, end_reply, channel_name);
  1105. }
  1106. static char *
  1107. irc_check_expand_user_mask (const char *mask)
  1108. {
  1109. struct str result;
  1110. str_init (&result);
  1111. str_append (&result, mask);
  1112. // Make sure it is a complete mask
  1113. if (!strchr (result.str, '!'))
  1114. str_append (&result, "!*");
  1115. if (!strchr (result.str, '@'))
  1116. str_append (&result, "@*");
  1117. // And validate whatever the result is
  1118. if (!irc_is_valid_user_mask (result.str))
  1119. {
  1120. str_free (&result);
  1121. return NULL;
  1122. }
  1123. return str_steal (&result);
  1124. }
  1125. static void
  1126. irc_handle_chan_mode_change (struct client *c,
  1127. struct channel *chan, char *params[])
  1128. {
  1129. struct channel_user *user = channel_get_user (chan, c);
  1130. // This is by far the worst command to implement from the whole RFC;
  1131. // don't blame me if it doesn't work exactly as expected.
  1132. struct str added; struct str_vector added_params;
  1133. struct str removed; struct str_vector removed_params;
  1134. str_init (&added); str_vector_init (&added_params);
  1135. str_init (&removed); str_vector_init (&removed_params);
  1136. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1137. // TODO: try to convert this madness into functions; that will most
  1138. // likely require creating a special parser class
  1139. #define NEEDS_OPER \
  1140. if (!user || (!(user->modes & IRC_CHAN_MODE_OPERATOR) \
  1141. && !(c->mode & IRC_USER_MODE_OPERATOR))) \
  1142. { \
  1143. irc_send_reply (c, IRC_ERR_CHANOPRIVSNEEDED, chan->name); \
  1144. continue; \
  1145. }
  1146. #define HANDLE_USER(mode) \
  1147. if (!(target = *params)) \
  1148. continue; \
  1149. params++; \
  1150. NEEDS_OPER \
  1151. if (!(client = str_map_find (&c->ctx->users, target))) \
  1152. irc_send_reply (c, IRC_ERR_NOSUCHNICK, target); \
  1153. else if (!(target_user = channel_get_user (chan, client))) \
  1154. irc_send_reply (c, IRC_ERR_USERNOTINCHANNEL, \
  1155. target, chan->name); \
  1156. else if (irc_modify_mode (&target_user->modes, (mode), adding)) \
  1157. { \
  1158. str_append_c (output, mode_char); \
  1159. str_vector_add (output_params, client->nickname); \
  1160. }
  1161. #define HANDLE_LIST(list, list_msg, end_msg) \
  1162. { \
  1163. if (!(target = *params)) \
  1164. { \
  1165. if (adding) \
  1166. irc_send_channel_list (c, chan->name, list, list_msg, end_msg); \
  1167. continue; \
  1168. } \
  1169. params++; \
  1170. NEEDS_OPER \
  1171. char *mask = irc_check_expand_user_mask (target); \
  1172. if (!mask) \
  1173. continue; \
  1174. size_t i; \
  1175. for (i = 0; i < (list)->len; i++) \
  1176. if (!irc_strcmp ((list)->vector[i], mask)) \
  1177. break; \
  1178. if (!((i != (list)->len) ^ adding)) \
  1179. { \
  1180. free (mask); \
  1181. continue; \
  1182. } \
  1183. if (adding) \
  1184. str_vector_add ((list), mask); \
  1185. else \
  1186. str_vector_remove ((list), i); \
  1187. str_append_c (output, mode_char); \
  1188. str_vector_add (output_params, mask); \
  1189. free (mask); \
  1190. }
  1191. #define HANDLE_MODE(mode) \
  1192. NEEDS_OPER \
  1193. if (irc_modify_mode (&chan->modes, (mode), adding)) \
  1194. str_append_c (output, mode_char);
  1195. #define REMOVE_MODE(removed_mode, removed_char) \
  1196. if (adding && irc_modify_mode (&chan->modes, (removed_mode), false)) \
  1197. str_append_c (&removed, (removed_char));
  1198. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1199. const char *mode_string;
  1200. while ((mode_string = *params++))
  1201. {
  1202. bool adding = true;
  1203. struct str *output = &added;
  1204. struct str_vector *output_params = &added_params;
  1205. const char *target;
  1206. struct channel_user *target_user;
  1207. struct client *client;
  1208. char mode_char;
  1209. while (*mode_string)
  1210. switch ((mode_char = *mode_string++))
  1211. {
  1212. case '+':
  1213. adding = true;
  1214. output = &added;
  1215. output_params = &added_params;
  1216. break;
  1217. case '-':
  1218. adding = false;
  1219. output = &removed;
  1220. output_params = &removed_params;
  1221. break;
  1222. case 'o': HANDLE_USER (IRC_CHAN_MODE_OPERATOR) break;
  1223. case 'v': HANDLE_USER (IRC_CHAN_MODE_VOICE) break;
  1224. case 'i': HANDLE_MODE (IRC_CHAN_MODE_INVITE_ONLY) break;
  1225. case 'm': HANDLE_MODE (IRC_CHAN_MODE_MODERATED) break;
  1226. case 'n': HANDLE_MODE (IRC_CHAN_MODE_NO_OUTSIDE_MSGS) break;
  1227. case 'q': HANDLE_MODE (IRC_CHAN_MODE_QUIET) break;
  1228. case 't': HANDLE_MODE (IRC_CHAN_MODE_PROTECTED_TOPIC) break;
  1229. case 'p':
  1230. HANDLE_MODE (IRC_CHAN_MODE_PRIVATE)
  1231. REMOVE_MODE (IRC_CHAN_MODE_SECRET, 's')
  1232. break;
  1233. case 's':
  1234. HANDLE_MODE (IRC_CHAN_MODE_SECRET)
  1235. REMOVE_MODE (IRC_CHAN_MODE_PRIVATE, 'p')
  1236. break;
  1237. case 'b':
  1238. HANDLE_LIST (&chan->ban_list,
  1239. IRC_RPL_BANLIST, IRC_RPL_ENDOFBANLIST)
  1240. break;
  1241. case 'e':
  1242. HANDLE_LIST (&chan->exception_list,
  1243. IRC_RPL_EXCEPTLIST, IRC_RPL_ENDOFEXCEPTLIST)
  1244. break;
  1245. case 'I':
  1246. HANDLE_LIST (&chan->invite_list,
  1247. IRC_RPL_INVITELIST, IRC_RPL_ENDOFINVITELIST)
  1248. break;
  1249. case 'k':
  1250. NEEDS_OPER
  1251. if (!adding)
  1252. {
  1253. if (!(target = *params))
  1254. continue;
  1255. params++;
  1256. if (!chan->key || irc_strcmp (target, chan->key))
  1257. continue;
  1258. str_append_c (&removed, mode_char);
  1259. str_vector_add (&removed_params, chan->key);
  1260. free (chan->key);
  1261. chan->key = NULL;
  1262. }
  1263. else if (!(target = *params))
  1264. continue;
  1265. else
  1266. {
  1267. params++;
  1268. if (chan->key)
  1269. irc_send_reply (c, IRC_ERR_KEYSET, chan->name);
  1270. else
  1271. {
  1272. chan->key = xstrdup (target);
  1273. str_append_c (&added, mode_char);
  1274. str_vector_add (&added_params, chan->key);
  1275. }
  1276. }
  1277. break;
  1278. case 'l':
  1279. NEEDS_OPER
  1280. if (!adding)
  1281. {
  1282. if (chan->user_limit == -1)
  1283. continue;
  1284. chan->user_limit = -1;
  1285. str_append_c (&removed, mode_char);
  1286. }
  1287. else if (!(target = *params))
  1288. continue;
  1289. else
  1290. {
  1291. params++;
  1292. unsigned long x;
  1293. if (xstrtoul (&x, target, 10) && x > 0 && x <= LONG_MAX)
  1294. {
  1295. chan->user_limit = x;
  1296. str_append_c (&added, mode_char);
  1297. str_vector_add (&added_params, target);
  1298. }
  1299. }
  1300. break;
  1301. default:
  1302. RETURN_WITH_REPLY (c, IRC_ERR_UNKNOWNMODE);
  1303. }
  1304. }
  1305. #undef NEEDS_OPER
  1306. #undef HANDLE_USER
  1307. #undef HANDLE_LIST
  1308. #undef HANDLE_MODE
  1309. #undef REMOVE_MODE
  1310. if (added.len || removed.len)
  1311. {
  1312. struct str message;
  1313. str_init (&message);
  1314. str_append_printf (&message, ":%s!%s@%s MODE %s ",
  1315. c->nickname, c->username, c->hostname, chan->name);
  1316. if (added.len)
  1317. str_append_printf (&message, "+%s", added.str);
  1318. if (removed.len)
  1319. str_append_printf (&message, "-%s", removed.str);
  1320. for (size_t i = 0; i < added_params.len; i++)
  1321. str_append_printf (&message, " %s", added_params.vector[i]);
  1322. for (size_t i = 0; i < removed_params.len; i++)
  1323. str_append_printf (&message, " %s", removed_params.vector[i]);
  1324. irc_channel_multicast (chan, message.str, NULL);
  1325. str_free (&message);
  1326. }
  1327. str_free (&added); str_vector_free (&added_params);
  1328. str_free (&removed); str_vector_free (&removed_params);
  1329. }
  1330. static void
  1331. irc_handle_mode (const struct irc_message *msg, struct client *c)
  1332. {
  1333. if (msg->params.len < 1)
  1334. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1335. const char *target = msg->params.vector[0];
  1336. struct client *client = str_map_find (&c->ctx->users, target);
  1337. if (client)
  1338. {
  1339. if (irc_strcmp (target, c->nickname))
  1340. RETURN_WITH_REPLY (c, IRC_ERR_USERSDONTMATCH);
  1341. if (msg->params.len < 2)
  1342. {
  1343. char *mode = client_get_mode (client);
  1344. irc_send_reply (c, IRC_RPL_UMODEIS, mode);
  1345. free (mode);
  1346. }
  1347. else
  1348. irc_handle_user_mode_change (c, msg->params.vector[1]);
  1349. return;
  1350. }
  1351. struct channel *chan = str_map_find (&c->ctx->channels, target);
  1352. if (chan)
  1353. {
  1354. if (msg->params.len < 2)
  1355. {
  1356. char *mode = channel_get_mode (chan, channel_get_user (chan, c));
  1357. irc_send_reply (c, IRC_RPL_CHANNELMODEIS, target, mode);
  1358. free (mode);
  1359. }
  1360. else
  1361. irc_handle_chan_mode_change (c, chan, &msg->params.vector[1]);
  1362. return;
  1363. }
  1364. irc_send_reply (c, IRC_ERR_NOSUCHNICK, target);
  1365. }
  1366. static void
  1367. irc_handle_user_message (const struct irc_message *msg, struct client *c,
  1368. const char *command, bool allow_away_reply)
  1369. {
  1370. if (msg->params.len < 1)
  1371. RETURN_WITH_REPLY (c, IRC_ERR_NORECIPIENT, msg->command);
  1372. if (msg->params.len < 2 || !*msg->params.vector[1])
  1373. RETURN_WITH_REPLY (c, IRC_ERR_NOTEXTTOSEND);
  1374. const char *target = msg->params.vector[0];
  1375. const char *text = msg->params.vector[1];
  1376. struct client *client = str_map_find (&c->ctx->users, target);
  1377. if (client)
  1378. {
  1379. client_send (client, ":%s!%s@%s %s %s :%s",
  1380. c->nickname, c->username, c->hostname, command, target, text);
  1381. if (allow_away_reply && client->away_message)
  1382. irc_send_reply (c, IRC_RPL_AWAY, target, client->away_message);
  1383. return;
  1384. }
  1385. struct channel *chan = str_map_find (&c->ctx->channels, target);
  1386. if (chan)
  1387. {
  1388. struct channel_user *user = channel_get_user (chan, c);
  1389. if ((chan->modes & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) && !user)
  1390. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1391. if ((chan->modes & IRC_CHAN_MODE_MODERATED) && (!user ||
  1392. !(user->modes & (IRC_CHAN_MODE_VOICE | IRC_CHAN_MODE_OPERATOR))))
  1393. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1394. if (client_in_mask_list (c, &chan->ban_list)
  1395. && !client_in_mask_list (c, &chan->exception_list))
  1396. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1397. char *message = xstrdup_printf (":%s!%s@%s %s %s :%s",
  1398. c->nickname, c->username, c->hostname, command, target, text);
  1399. irc_channel_multicast (chan, message, c);
  1400. free (message);
  1401. return;
  1402. }
  1403. irc_send_reply (c, IRC_ERR_NOSUCHNICK, target);
  1404. }
  1405. static void
  1406. irc_handle_privmsg (const struct irc_message *msg, struct client *c)
  1407. {
  1408. irc_handle_user_message (msg, c, "PRIVMSG", true);
  1409. // Let's not care too much about success or failure
  1410. c->last_active = time (NULL);
  1411. }
  1412. static void
  1413. irc_handle_notice (const struct irc_message *msg, struct client *c)
  1414. {
  1415. irc_handle_user_message (msg, c, "NOTICE", false);
  1416. }
  1417. static void
  1418. irc_send_rpl_list (struct client *c, const struct channel *chan)
  1419. {
  1420. int visible = 0;
  1421. for (struct channel_user *user = chan->users;
  1422. user; user = user->next)
  1423. visible++;
  1424. irc_send_reply (c, IRC_RPL_LIST, chan->name, visible, chan->topic);
  1425. }
  1426. static void
  1427. irc_handle_list (const struct irc_message *msg, struct client *c)
  1428. {
  1429. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1430. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1431. struct channel *chan;
  1432. if (msg->params.len == 0)
  1433. {
  1434. struct str_map_iter iter;
  1435. str_map_iter_init (&iter, &c->ctx->channels);
  1436. while ((chan = str_map_iter_next (&iter)))
  1437. if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1438. || channel_get_user (chan, c))
  1439. irc_send_rpl_list (c, chan);
  1440. }
  1441. else
  1442. {
  1443. struct str_vector channels;
  1444. str_vector_init (&channels);
  1445. split_str_ignore_empty (msg->params.vector[0], ',', &channels);
  1446. for (size_t i = 0; i < channels.len; i++)
  1447. if ((chan = str_map_find (&c->ctx->channels, channels.vector[i]))
  1448. && (!(chan->modes & IRC_CHAN_MODE_SECRET)
  1449. || channel_get_user (chan, c)))
  1450. irc_send_rpl_list (c, chan);
  1451. str_vector_free (&channels);
  1452. }
  1453. irc_send_reply (c, IRC_RPL_LISTEND);
  1454. }
  1455. static void
  1456. irc_send_rpl_namreply (struct client *c, const struct channel *chan)
  1457. {
  1458. struct str_vector nicks;
  1459. str_vector_init (&nicks);
  1460. char type = '=';
  1461. if (chan->modes & IRC_CHAN_MODE_SECRET)
  1462. type = '@';
  1463. else if (chan->modes & IRC_CHAN_MODE_PRIVATE)
  1464. type = '*';
  1465. bool on_channel = channel_get_user (chan, c);
  1466. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  1467. {
  1468. if (!on_channel && (iter->c->mode & IRC_USER_MODE_INVISIBLE))
  1469. continue;
  1470. struct str result;
  1471. str_init (&result);
  1472. if (iter->modes & IRC_CHAN_MODE_OPERATOR)
  1473. str_append_c (&result, '@');
  1474. else if (iter->modes & IRC_CHAN_MODE_VOICE)
  1475. str_append_c (&result, '+');
  1476. str_append (&result, iter->c->nickname);
  1477. str_vector_add_owned (&nicks, str_steal (&result));
  1478. }
  1479. if (nicks.len)
  1480. {
  1481. // FIXME: split it into multiple messages if it's too long
  1482. char *reply = join_str_vector (&nicks, ' ');
  1483. irc_send_reply (c, IRC_RPL_NAMREPLY, type, chan->name, reply);
  1484. free (reply);
  1485. }
  1486. str_vector_free (&nicks);
  1487. }
  1488. static void
  1489. irc_handle_names (const struct irc_message *msg, struct client *c)
  1490. {
  1491. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1492. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1493. struct channel *chan;
  1494. if (msg->params.len == 0)
  1495. {
  1496. struct str_map_iter iter;
  1497. str_map_iter_init (&iter, &c->ctx->channels);
  1498. while ((chan = str_map_iter_next (&iter)))
  1499. if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1500. || channel_get_user (chan, c))
  1501. irc_send_rpl_namreply (c, chan);
  1502. // TODO
  1503. // If no <channel> parameter is given, a list of all channels and their
  1504. // occupants is returned. At the end of this list, a list of users who
  1505. // are visible but either not on any channel or not on a visible channel
  1506. // are listed as being on `channel' "*".
  1507. irc_send_reply (c, IRC_RPL_ENDOFNAMES, "*");
  1508. }
  1509. else
  1510. {
  1511. struct str_vector channels;
  1512. str_vector_init (&channels);
  1513. split_str_ignore_empty (msg->params.vector[0], ',', &channels);
  1514. for (size_t i = 0; i < channels.len; i++)
  1515. if ((chan = str_map_find (&c->ctx->channels, channels.vector[i]))
  1516. && (!(chan->modes & IRC_CHAN_MODE_SECRET)
  1517. || channel_get_user (chan, c)))
  1518. {
  1519. irc_send_rpl_namreply (c, chan);
  1520. irc_send_reply (c, IRC_RPL_ENDOFNAMES, channels.vector[i]);
  1521. }
  1522. str_vector_free (&channels);
  1523. }
  1524. }
  1525. static void
  1526. irc_send_rpl_whoreply (struct client *c, const struct channel *chan,
  1527. const struct client *target)
  1528. {
  1529. struct str chars;
  1530. str_init (&chars);
  1531. str_append_c (&chars, target->away_message ? 'G' : 'H');
  1532. if (target->mode & IRC_USER_MODE_OPERATOR)
  1533. str_append_c (&chars, '*');
  1534. struct channel_user *user;
  1535. if (chan && (user = channel_get_user (chan, target)))
  1536. {
  1537. if (user->modes & IRC_CHAN_MODE_OPERATOR)
  1538. str_append_c (&chars, '@');
  1539. else if (user->modes & IRC_CHAN_MODE_VOICE)
  1540. str_append_c (&chars, '+');
  1541. }
  1542. irc_send_reply (c, IRC_RPL_WHOREPLY, chan ? chan->name : "*",
  1543. target->username, target->hostname, target->ctx->server_name,
  1544. target->nickname, chars.str, 0 /* hop count */, target->realname);
  1545. str_free (&chars);
  1546. }
  1547. static void
  1548. irc_match_send_rpl_whoreply (struct client *c, struct client *target,
  1549. const char *mask)
  1550. {
  1551. bool is_roommate = false;
  1552. struct str_map_iter iter;
  1553. str_map_iter_init (&iter, &c->ctx->channels);
  1554. struct channel *chan;
  1555. while ((chan = str_map_iter_next (&iter)))
  1556. if (channel_get_user (chan, target) && channel_get_user (chan, c))
  1557. {
  1558. is_roommate = true;
  1559. break;
  1560. }
  1561. if ((target->mode & IRC_USER_MODE_INVISIBLE) && !is_roommate)
  1562. return;
  1563. if (irc_fnmatch (mask, target->hostname)
  1564. && irc_fnmatch (mask, target->nickname)
  1565. && irc_fnmatch (mask, target->realname)
  1566. && irc_fnmatch (mask, c->ctx->server_name))
  1567. return;
  1568. // Try to find a channel they're on that's visible to us
  1569. struct channel *user_chan = NULL;
  1570. str_map_iter_init (&iter, &c->ctx->channels);
  1571. while ((chan = str_map_iter_next (&iter)))
  1572. if (channel_get_user (chan, target)
  1573. && (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1574. || channel_get_user (chan, c)))
  1575. {
  1576. user_chan = chan;
  1577. break;
  1578. }
  1579. irc_send_rpl_whoreply (c, user_chan, target);
  1580. }
  1581. static void
  1582. irc_handle_who (const struct irc_message *msg, struct client *c)
  1583. {
  1584. bool only_ops = msg->params.len > 1 && !strcmp (msg->params.vector[1], "o");
  1585. const char *shown_mask = msg->params.vector[0], *used_mask;
  1586. if (!shown_mask)
  1587. used_mask = shown_mask = "*";
  1588. else if (!strcmp (shown_mask, "0"))
  1589. used_mask = "*";
  1590. else
  1591. used_mask = shown_mask;
  1592. struct channel *chan;
  1593. if ((chan = str_map_find (&c->ctx->channels, used_mask)))
  1594. {
  1595. bool on_chan = !!channel_get_user (chan, c);
  1596. if (on_chan || !(chan->modes & IRC_CHAN_MODE_SECRET))
  1597. for (struct channel_user *iter = chan->users;
  1598. iter; iter = iter->next)
  1599. {
  1600. if ((on_chan || !(iter->c->mode & IRC_USER_MODE_INVISIBLE))
  1601. && (!only_ops || (iter->c->mode & IRC_USER_MODE_OPERATOR)))
  1602. irc_send_rpl_whoreply (c, chan, iter->c);
  1603. }
  1604. }
  1605. else
  1606. {
  1607. struct str_map_iter iter;
  1608. str_map_iter_init (&iter, &c->ctx->users);
  1609. struct client *target;
  1610. while ((target = str_map_iter_next (&iter)))
  1611. if (!only_ops || (target->mode & IRC_USER_MODE_OPERATOR))
  1612. irc_match_send_rpl_whoreply (c, target, used_mask);
  1613. }
  1614. irc_send_reply (c, IRC_RPL_ENDOFWHO, shown_mask);
  1615. }
  1616. static void
  1617. irc_send_whois_reply (struct client *c, const struct client *target)
  1618. {
  1619. const char *nick = target->nickname;
  1620. irc_send_reply (c, IRC_RPL_WHOISUSER, nick, target->username,
  1621. target->hostname, target->realname);
  1622. irc_send_reply (c, IRC_RPL_WHOISSERVER, nick, target->ctx->server_name,
  1623. str_map_find (&c->ctx->config, "server_info"));
  1624. if (target->mode & IRC_USER_MODE_OPERATOR)
  1625. irc_send_reply (c, IRC_RPL_WHOISOPERATOR, nick);
  1626. irc_send_reply (c, IRC_RPL_WHOISIDLE, nick,
  1627. (int) (time (NULL) - target->last_active));
  1628. if (target->away_message)
  1629. irc_send_reply (c, IRC_RPL_AWAY, nick, target->away_message);
  1630. struct str_map_iter iter;
  1631. str_map_iter_init (&iter, &c->ctx->channels);
  1632. struct channel *chan;
  1633. struct channel_user *channel_user;
  1634. while ((chan = str_map_iter_next (&iter)))
  1635. if ((channel_user = channel_get_user (chan, target))
  1636. && (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1637. || channel_get_user (chan, c)))
  1638. {
  1639. struct str item;
  1640. str_init (&item);
  1641. if (channel_user->modes & IRC_CHAN_MODE_OPERATOR)
  1642. str_append_c (&item, '@');
  1643. else if (channel_user->modes & IRC_CHAN_MODE_VOICE)
  1644. str_append_c (&item, '+');
  1645. str_append (&item, chan->name);
  1646. str_append_c (&item, ' ');
  1647. // TODO: try to merge the results into as few messages as possible
  1648. irc_send_reply (c, IRC_RPL_WHOISCHANNELS, nick, item.str);
  1649. str_free (&item);
  1650. }
  1651. irc_send_reply (c, IRC_RPL_ENDOFWHOIS, nick);
  1652. }
  1653. static void
  1654. irc_handle_whois (const struct irc_message *msg, struct client *c)
  1655. {
  1656. if (msg->params.len < 1)
  1657. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1658. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1659. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1660. struct str_vector masks;
  1661. str_vector_init (&masks);
  1662. const char *masks_str = msg->params.vector[msg->params.len > 1];
  1663. split_str_ignore_empty (masks_str, ',', &masks);
  1664. for (size_t i = 0; i < masks.len; i++)
  1665. {
  1666. const char *mask = masks.vector[i];
  1667. struct client *target;
  1668. if (!strpbrk (mask, "*?"))
  1669. {
  1670. if (!(target = str_map_find (&c->ctx->users, mask)))
  1671. irc_send_reply (c, IRC_ERR_NOSUCHNICK, mask);
  1672. else
  1673. irc_send_whois_reply (c, target);
  1674. }
  1675. else
  1676. {
  1677. struct str_map_iter iter;
  1678. str_map_iter_init (&iter, &c->ctx->users);
  1679. bool found = false;
  1680. while ((target = str_map_iter_next (&iter))
  1681. && !irc_fnmatch (mask, target->nickname))
  1682. {
  1683. irc_send_whois_reply (c, target);
  1684. found = true;
  1685. }
  1686. if (!found)
  1687. irc_send_reply (c, IRC_ERR_NOSUCHNICK, mask);
  1688. }
  1689. }
  1690. str_vector_free (&masks);
  1691. }
  1692. static void
  1693. irc_send_rpl_topic (struct client *c, struct channel *chan)
  1694. {
  1695. if (!*chan->topic)
  1696. irc_send_reply (c, IRC_RPL_NOTOPIC, chan->name);
  1697. else
  1698. irc_send_reply (c, IRC_RPL_TOPIC, chan->name, chan->topic);
  1699. }
  1700. static void
  1701. irc_handle_topic (const struct irc_message *msg, struct client *c)
  1702. {
  1703. if (msg->params.len < 1)
  1704. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1705. const char *target = msg->params.vector[0];
  1706. struct channel *chan = str_map_find (&c->ctx->channels, target);
  1707. if (!chan)
  1708. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, target);
  1709. if (msg->params.len < 2)
  1710. {
  1711. irc_send_rpl_topic (c, chan);
  1712. return;
  1713. }
  1714. struct channel_user *user = channel_get_user (chan, c);
  1715. if (!user)
  1716. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, target);
  1717. if ((chan->modes & IRC_CHAN_MODE_PROTECTED_TOPIC)
  1718. && !(user->modes & IRC_CHAN_MODE_OPERATOR))
  1719. RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, target);
  1720. free (chan->topic);
  1721. chan->topic = xstrdup (msg->params.vector[1]);
  1722. char *message = xstrdup_printf (":%s!%s@%s TOPIC %s :%s",
  1723. c->nickname, c->username, c->hostname, target, chan->topic);
  1724. irc_channel_multicast (chan, message, NULL);
  1725. free (message);
  1726. }
  1727. static void
  1728. irc_try_part (struct client *c, const char *channel_name, const char *reason)
  1729. {
  1730. if (!reason)
  1731. reason = c->nickname;
  1732. struct channel *chan;
  1733. if (!(chan = str_map_find (&c->ctx->channels, channel_name)))
  1734. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name);
  1735. struct channel_user *user;
  1736. if (!(user = channel_get_user (chan, c)))
  1737. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
  1738. char *message = xstrdup_printf (":%s!%s@%s PART %s :%s",
  1739. c->nickname, c->username, c->hostname, channel_name, reason);
  1740. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  1741. irc_channel_multicast (chan, message, NULL);
  1742. else
  1743. client_send (c, "%s", message);
  1744. free (message);
  1745. channel_remove_user (chan, user);
  1746. irc_channel_destroy_if_empty (c->ctx, chan);
  1747. }
  1748. static void
  1749. irc_part_all_channels (struct client *c)
  1750. {
  1751. struct str_map_iter iter;
  1752. str_map_iter_init (&iter, &c->ctx->channels);
  1753. struct channel *chan, *next = str_map_iter_next (&iter);
  1754. for (chan = next; chan; chan = next)
  1755. {
  1756. // We have to be careful here, the channel might get destroyed
  1757. next = str_map_iter_next (&iter);
  1758. if (channel_get_user (chan, c))
  1759. irc_try_part (c, chan->name, NULL);
  1760. }
  1761. }
  1762. static void
  1763. irc_handle_part (const struct irc_message *msg, struct client *c)
  1764. {
  1765. if (msg->params.len < 1)
  1766. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1767. const char *reason = msg->params.len > 1 ? msg->params.vector[1] : NULL;
  1768. struct str_vector channels;
  1769. str_vector_init (&channels);
  1770. split_str_ignore_empty (msg->params.vector[0], ',', &channels);
  1771. for (size_t i = 0; i < channels.len; i++)
  1772. irc_try_part (c, channels.vector[i], reason);
  1773. str_vector_free (&channels);
  1774. }
  1775. static void
  1776. irc_try_kick (struct client *c, const char *channel_name, const char *nick,
  1777. const char *reason)
  1778. {
  1779. struct channel *chan;
  1780. if (!(chan = str_map_find (&c->ctx->channels, channel_name)))
  1781. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name);
  1782. struct channel_user *user;
  1783. if (!(user = channel_get_user (chan, c)))
  1784. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
  1785. if (!(user->modes & IRC_CHAN_MODE_OPERATOR))
  1786. RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, channel_name);
  1787. struct client *client;
  1788. if (!(client = str_map_find (&c->ctx->users, nick))
  1789. || !(user = channel_get_user (chan, client)))
  1790. RETURN_WITH_REPLY (c, IRC_ERR_USERNOTINCHANNEL, nick, channel_name);
  1791. char *message = xstrdup_printf (":%s!%s@%s KICK %s %s :%s",
  1792. c->nickname, c->username, c->hostname, channel_name, nick, reason);
  1793. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  1794. irc_channel_multicast (chan, message, NULL);
  1795. else
  1796. client_send (c, "%s", message);
  1797. free (message);
  1798. channel_remove_user (chan, user);
  1799. irc_channel_destroy_if_empty (c->ctx, chan);
  1800. }
  1801. static void
  1802. irc_handle_kick (const struct irc_message *msg, struct client *c)
  1803. {
  1804. if (msg->params.len < 2)
  1805. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1806. const char *reason = c->nickname;
  1807. if (msg->params.len > 2)
  1808. reason = msg->params.vector[2];
  1809. struct str_vector channels;
  1810. struct str_vector users;
  1811. str_vector_init (&channels);
  1812. str_vector_init (&users);
  1813. split_str_ignore_empty (msg->params.vector[0], ',', &channels);
  1814. split_str_ignore_empty (msg->params.vector[1], ',', &users);
  1815. if (channels.len == 1)
  1816. for (size_t i = 0; i < users.len; i++)
  1817. irc_try_kick (c, channels.vector[0], users.vector[i], reason);
  1818. else
  1819. for (size_t i = 0; i < channels.len && i < users.len; i++)
  1820. irc_try_kick (c, channels.vector[i], users.vector[i], reason);
  1821. str_vector_free (&channels);
  1822. str_vector_free (&users);
  1823. }
  1824. static void
  1825. irc_try_join (struct client *c, const char *channel_name, const char *key)
  1826. {
  1827. struct channel *chan = str_map_find (&c->ctx->channels, channel_name);
  1828. unsigned user_mode = 0;
  1829. if (!chan)
  1830. {
  1831. if (irc_validate_channel_name (channel_name) != VALIDATION_OK)
  1832. RETURN_WITH_REPLY (c, IRC_ERR_BADCHANMASK, channel_name);
  1833. chan = irc_channel_create (c->ctx, channel_name);
  1834. user_mode = IRC_CHAN_MODE_OPERATOR;
  1835. }
  1836. else if (channel_get_user (chan, c))
  1837. return;
  1838. if ((chan->modes & IRC_CHAN_MODE_INVITE_ONLY)
  1839. && !client_in_mask_list (c, &chan->invite_list))
  1840. // TODO: exceptions caused by INVITE
  1841. RETURN_WITH_REPLY (c, IRC_ERR_INVITEONLYCHAN, channel_name);
  1842. if (chan->key && (!key || strcmp (key, chan->key)))
  1843. RETURN_WITH_REPLY (c, IRC_ERR_BADCHANNELKEY, channel_name);
  1844. if (chan->user_limit != -1
  1845. && channel_user_count (chan) >= (size_t) chan->user_limit)
  1846. RETURN_WITH_REPLY (c, IRC_ERR_CHANNELISFULL, channel_name);
  1847. if (client_in_mask_list (c, &chan->ban_list)
  1848. && !client_in_mask_list (c, &chan->exception_list))
  1849. RETURN_WITH_REPLY (c, IRC_ERR_BANNEDFROMCHAN, channel_name);
  1850. channel_add_user (chan, c)->modes = user_mode;
  1851. char *message = xstrdup_printf (":%s!%s@%s JOIN %s",
  1852. c->nickname, c->username, c->hostname, channel_name);
  1853. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  1854. irc_channel_multicast (chan, message, NULL);
  1855. else
  1856. client_send (c, "%s", message);
  1857. free (message);
  1858. irc_send_rpl_topic (c, chan);
  1859. irc_send_rpl_namreply (c, chan);
  1860. irc_send_reply (c, IRC_RPL_ENDOFNAMES, chan->name);
  1861. }
  1862. static void
  1863. irc_handle_join (const struct irc_message *msg, struct client *c)
  1864. {
  1865. if (msg->params.len < 1)
  1866. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1867. if (!strcmp (msg->params.vector[0], "0"))
  1868. {
  1869. irc_part_all_channels (c);
  1870. return;
  1871. }
  1872. struct str_vector channels;
  1873. struct str_vector keys;
  1874. str_vector_init (&channels);
  1875. str_vector_init (&keys);
  1876. split_str_ignore_empty (msg->params.vector[0], ',', &channels);
  1877. if (msg->params.len > 1)
  1878. split_str_ignore_empty (msg->params.vector[1], ',', &keys);
  1879. for (size_t i = 0; i < channels.len; i++)
  1880. irc_try_join (c, channels.vector[i],
  1881. i < keys.len ? keys.vector[i] : NULL);
  1882. str_vector_free (&channels);
  1883. str_vector_free (&keys);
  1884. }
  1885. static void
  1886. irc_handle_summon (const struct irc_message *msg, struct client *c)
  1887. {
  1888. (void) msg;
  1889. irc_send_reply (c, IRC_ERR_SUMMONDISABLED);
  1890. }
  1891. static void
  1892. irc_handle_users (const struct irc_message *msg, struct client *c)
  1893. {
  1894. (void) msg;
  1895. irc_send_reply (c, IRC_ERR_USERSDISABLED);
  1896. }
  1897. static void
  1898. irc_handle_away (const struct irc_message *msg, struct client *c)
  1899. {
  1900. if (msg->params.len < 1)
  1901. {
  1902. free (c->away_message);
  1903. c->away_message = NULL;
  1904. irc_send_reply (c, IRC_RPL_UNAWAY);
  1905. }
  1906. else
  1907. {
  1908. free (c->away_message);
  1909. c->away_message = xstrdup (msg->params.vector[0]);
  1910. irc_send_reply (c, IRC_RPL_NOWAWAY);
  1911. }
  1912. }
  1913. static void
  1914. irc_handle_ison (const struct irc_message *msg, struct client *c)
  1915. {
  1916. if (msg->params.len < 1)
  1917. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1918. struct str result;
  1919. str_init (&result);
  1920. const char *nick;
  1921. if (str_map_find (&c->ctx->users, (nick = msg->params.vector[0])))
  1922. str_append (&result, nick);
  1923. for (size_t i = 1; i < msg->params.len; i++)
  1924. if (str_map_find (&c->ctx->users, (nick = msg->params.vector[i])))
  1925. str_append_printf (&result, " %s", nick);
  1926. irc_send_reply (c, IRC_RPL_ISON, result.str);
  1927. str_free (&result);
  1928. }
  1929. static void
  1930. irc_handle_admin (const struct irc_message *msg, struct client *c)
  1931. {
  1932. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1933. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1934. irc_send_reply (c, IRC_ERR_NOADMININFO, c->ctx->server_name);
  1935. }
  1936. static void
  1937. irc_handle_kill (const struct irc_message *msg, struct client *c)
  1938. {
  1939. if (msg->params.len < 2)
  1940. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1941. if (!(c->mode & IRC_USER_MODE_OPERATOR))
  1942. RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES);
  1943. struct client *target;
  1944. if (!(target = str_map_find (&c->ctx->users, msg->params.vector[0])))
  1945. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHNICK, msg->params.vector[0]);
  1946. char *reason = xstrdup_printf ("Killed by %s: %s",
  1947. c->nickname, msg->params.vector[1]);
  1948. client_close_link (target, reason);
  1949. free (reason);
  1950. }
  1951. static void
  1952. irc_handle_die (const struct irc_message *msg, struct client *c)
  1953. {
  1954. (void) msg;
  1955. if (!(c->mode & IRC_USER_MODE_OPERATOR))
  1956. RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES);
  1957. if (!c->ctx->quitting)
  1958. irc_initiate_quit (c->ctx);
  1959. }
  1960. // -----------------------------------------------------------------------------
  1961. struct irc_command
  1962. {
  1963. const char *name;
  1964. bool requires_registration;
  1965. void (*handler) (const struct irc_message *, struct client *);
  1966. };
  1967. static void
  1968. irc_register_handlers (struct server_context *ctx)
  1969. {
  1970. // TODO: add an index for IRC_ERR_NOSUCHSERVER validation?
  1971. // TODO: add a minimal parameter count?
  1972. // TODO: add a field for oper-only commands?
  1973. static const struct irc_command message_handlers[] =
  1974. {
  1975. { "PASS", false, irc_handle_pass },
  1976. { "NICK", false, irc_handle_nick },
  1977. { "USER", false, irc_handle_user },
  1978. { "USERHOST", true, irc_handle_userhost },
  1979. { "LUSERS", true, irc_handle_lusers },
  1980. { "MOTD", true, irc_handle_motd },
  1981. { "PING", true, irc_handle_ping },
  1982. { "PONG", false, irc_handle_pong },
  1983. { "QUIT", false, irc_handle_quit },
  1984. { "TIME", true, irc_handle_time },
  1985. { "VERSION", true, irc_handle_version },
  1986. { "USERS", true, irc_handle_users },
  1987. { "SUMMON", true, irc_handle_summon },
  1988. { "AWAY", true, irc_handle_away },
  1989. { "ADMIN", true, irc_handle_admin },
  1990. { "MODE", true, irc_handle_mode },
  1991. { "PRIVMSG", true, irc_handle_privmsg },
  1992. { "NOTICE", true, irc_handle_notice },
  1993. { "JOIN", true, irc_handle_join },
  1994. { "PART", true, irc_handle_part },
  1995. { "KICK", true, irc_handle_kick },
  1996. { "TOPIC", true, irc_handle_topic },
  1997. { "LIST", true, irc_handle_list },
  1998. { "NAMES", true, irc_handle_names },
  1999. { "WHO", true, irc_handle_who },
  2000. { "WHOIS", true, irc_handle_whois },
  2001. { "ISON", true, irc_handle_ison },
  2002. { "KILL", true, irc_handle_kill },
  2003. { "DIE", true, irc_handle_die },
  2004. };
  2005. for (size_t i = 0; i < N_ELEMENTS (message_handlers); i++)
  2006. {
  2007. const struct irc_command *cmd = &message_handlers[i];
  2008. str_map_set (&ctx->handlers, cmd->name, (void *) cmd);
  2009. }
  2010. }
  2011. static void
  2012. irc_process_message (const struct irc_message *msg,
  2013. const char *raw, void *user_data)
  2014. {
  2015. (void) raw;
  2016. struct client *c = user_data;
  2017. if (c->closing_link)
  2018. return;
  2019. if (!flood_detector_check (&c->antiflood))
  2020. {
  2021. client_close_link (c, "Excess flood");
  2022. return;
  2023. }
  2024. struct irc_command *cmd = str_map_find (&c->ctx->handlers, msg->command);
  2025. if (!cmd)
  2026. irc_send_reply (c, IRC_ERR_UNKNOWNCOMMAND, msg->command);
  2027. else if (cmd->requires_registration && !c->registered)
  2028. irc_send_reply (c, IRC_ERR_NOTREGISTERED);
  2029. else
  2030. cmd->handler (msg, c);
  2031. }
  2032. // --- Network I/O -------------------------------------------------------------
  2033. static bool
  2034. irc_try_read (struct client *c)
  2035. {
  2036. struct str *buf = &c->read_buffer;
  2037. ssize_t n_read;
  2038. while (true)
  2039. {
  2040. str_ensure_space (buf, 512);
  2041. n_read = recv (c->socket_fd, buf->str + buf->len,
  2042. buf->alloc - buf->len - 1 /* null byte */, 0);
  2043. if (n_read > 0)
  2044. {
  2045. buf->str[buf->len += n_read] = '\0';
  2046. // TODO: discard characters above the 512 character limit
  2047. irc_process_buffer (buf, irc_process_message, c);
  2048. continue;
  2049. }
  2050. if (n_read == 0)
  2051. {
  2052. client_kill (c, NULL);
  2053. return false;
  2054. }
  2055. if (errno == EAGAIN)
  2056. return true;
  2057. if (errno == EINTR)
  2058. continue;
  2059. print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
  2060. client_kill (c, strerror (errno));
  2061. return false;
  2062. }
  2063. }
  2064. static bool
  2065. irc_try_read_ssl (struct client *c)
  2066. {
  2067. if (c->ssl_tx_want_rx)
  2068. return true;
  2069. struct str *buf = &c->read_buffer;
  2070. c->ssl_rx_want_tx = false;
  2071. while (true)
  2072. {
  2073. str_ensure_space (buf, 512);
  2074. int n_read = SSL_read (c->ssl, buf->str + buf->len,
  2075. buf->alloc - buf->len - 1 /* null byte */);
  2076. const char *error_info = NULL;
  2077. switch (xssl_get_error (c->ssl, n_read, &error_info))
  2078. {
  2079. case SSL_ERROR_NONE:
  2080. buf->str[buf->len += n_read] = '\0';
  2081. // TODO: discard characters above the 512 character limit
  2082. irc_process_buffer (buf, irc_process_message, c);
  2083. continue;
  2084. case SSL_ERROR_ZERO_RETURN:
  2085. client_kill (c, NULL);
  2086. return false;
  2087. case SSL_ERROR_WANT_READ:
  2088. return true;
  2089. case SSL_ERROR_WANT_WRITE:
  2090. c->ssl_rx_want_tx = true;
  2091. return true;
  2092. case XSSL_ERROR_TRY_AGAIN:
  2093. continue;
  2094. default:
  2095. print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
  2096. client_kill (c, error_info);
  2097. return false;
  2098. }
  2099. }
  2100. }
  2101. static bool
  2102. irc_try_write (struct client *c)
  2103. {
  2104. struct str *buf = &c->write_buffer;
  2105. ssize_t n_written;
  2106. while (buf->len)
  2107. {
  2108. n_written = send (c->socket_fd, buf->str, buf->len, 0);
  2109. if (n_written >= 0)
  2110. {
  2111. str_remove_slice (buf, 0, n_written);
  2112. continue;
  2113. }
  2114. if (errno == EAGAIN)
  2115. return true;
  2116. if (errno == EINTR)
  2117. continue;
  2118. print_debug ("%s: %s: %s", __func__, "send", strerror (errno));
  2119. client_kill (c, strerror (errno));
  2120. return false;
  2121. }
  2122. return true;
  2123. }
  2124. static bool
  2125. irc_try_write_ssl (struct client *c)
  2126. {
  2127. if (c->ssl_rx_want_tx)
  2128. return true;
  2129. struct str *buf = &c->write_buffer;
  2130. c->ssl_tx_want_rx = false;
  2131. while (buf->len)
  2132. {
  2133. int n_written = SSL_write (c->ssl, buf->str, buf->len);
  2134. const char *error_info = NULL;
  2135. switch (xssl_get_error (c->ssl, n_written, &error_info))
  2136. {
  2137. case SSL_ERROR_NONE:
  2138. str_remove_slice (buf, 0, n_written);
  2139. continue;
  2140. case SSL_ERROR_ZERO_RETURN:
  2141. client_kill (c, NULL);
  2142. return false;
  2143. case SSL_ERROR_WANT_WRITE:
  2144. return true;
  2145. case SSL_ERROR_WANT_READ:
  2146. c->ssl_tx_want_rx = true;
  2147. return true;
  2148. case XSSL_ERROR_TRY_AGAIN:
  2149. continue;
  2150. default:
  2151. print_debug ("%s: %s: %s", __func__, "SSL_write", error_info);
  2152. client_kill (c, error_info);
  2153. return false;
  2154. }
  2155. }
  2156. return true;
  2157. }
  2158. static bool
  2159. irc_autodetect_ssl (struct client *c)
  2160. {
  2161. // Trivial SSL/TLS autodetection. The first block of data returned by
  2162. // recv() must be at least three bytes long for this to work reliably,
  2163. // but that should not pose a problem in practice.
  2164. //
  2165. // SSL2: 1xxx xxxx | xxxx xxxx | <1>
  2166. // (message length) (client hello)
  2167. // SSL3/TLS: <22> | <3> | xxxx xxxx
  2168. // (handshake)| (protocol version)
  2169. //
  2170. // Such byte sequences should never occur at the beginning of regular IRC
  2171. // communication, which usually begins with USER/NICK/PASS/SERVICE.
  2172. char buf[3];
  2173. start:
  2174. switch (recv (c->socket_fd, buf, sizeof buf, MSG_PEEK))
  2175. {
  2176. case 3:
  2177. if ((buf[0] & 0x80) && buf[2] == 1)
  2178. return true;
  2179. case 2:
  2180. if (buf[0] == 22 && buf[1] == 3)
  2181. return true;
  2182. break;
  2183. case 1:
  2184. if (buf[0] == 22)
  2185. return true;
  2186. break;
  2187. case 0:
  2188. break;
  2189. default:
  2190. if (errno == EINTR)
  2191. goto start;
  2192. }
  2193. return false;
  2194. }
  2195. static bool
  2196. client_initialize_ssl (struct client *c)
  2197. {
  2198. const char *error_info = NULL;
  2199. if (!c->ctx->ssl_ctx)
  2200. {
  2201. error_info = "SSL support disabled";
  2202. goto error_ssl_1;
  2203. }
  2204. c->ssl = SSL_new (c->ctx->ssl_ctx);
  2205. if (!c->ssl)
  2206. goto error_ssl_1;
  2207. if (!SSL_set_fd (c->ssl, c->socket_fd))
  2208. goto error_ssl_2;
  2209. SSL_set_accept_state (c->ssl);
  2210. return true;
  2211. error_ssl_2:
  2212. SSL_free (c->ssl);
  2213. c->ssl = NULL;
  2214. error_ssl_1:
  2215. // XXX: these error strings are really nasty; also there could be
  2216. // multiple errors on the OpenSSL stack.
  2217. if (!error_info)
  2218. error_info = ERR_error_string (ERR_get_error (), NULL);
  2219. print_debug ("could not initialize SSL for %s: %s", c->address, error_info);
  2220. return false;
  2221. }
  2222. static void
  2223. on_client_ready (const struct pollfd *pfd, void *user_data)
  2224. {
  2225. struct client *c = user_data;
  2226. if (!c->initialized)
  2227. {
  2228. hard_assert (pfd->events == POLLIN);
  2229. if (irc_autodetect_ssl (c) && !client_initialize_ssl (c))
  2230. {
  2231. client_kill (c, NULL);
  2232. return;
  2233. }
  2234. c->initialized = true;
  2235. client_set_ping_timer (c);
  2236. }
  2237. if (c->ssl)
  2238. {
  2239. // Reads may want to write, writes may want to read, poll() may
  2240. // return unexpected things in `revents'... let's try both
  2241. if (!irc_try_read_ssl (c) || !irc_try_write_ssl (c))
  2242. return;
  2243. }
  2244. else if (!irc_try_read (c) || !irc_try_write (c))
  2245. return;
  2246. client_update_poller (c, pfd);
  2247. // The purpose of the `closing_link' state is to transfer the `ERROR'
  2248. if (c->closing_link && !c->write_buffer.len)
  2249. client_kill (c, NULL);
  2250. }
  2251. static void
  2252. client_update_poller (struct client *c, const struct pollfd *pfd)
  2253. {
  2254. int new_events = POLLIN;
  2255. if (c->ssl)
  2256. {
  2257. if (c->write_buffer.len || c->ssl_rx_want_tx)
  2258. new_events |= POLLOUT;
  2259. // While we're waiting for an opposite event, we ignore the original
  2260. if (c->ssl_rx_want_tx) new_events &= ~POLLIN;
  2261. if (c->ssl_tx_want_rx) new_events &= ~POLLOUT;
  2262. }
  2263. else if (c->write_buffer.len)
  2264. new_events |= POLLOUT;
  2265. hard_assert (new_events != 0);
  2266. if (!pfd || pfd->events != new_events)
  2267. poller_set (&c->ctx->poller, c->socket_fd, new_events,
  2268. (poller_dispatcher_fn) on_client_ready, c);
  2269. }
  2270. static void
  2271. on_irc_client_available (const struct pollfd *pfd, void *user_data)
  2272. {
  2273. (void) pfd;
  2274. struct server_context *ctx = user_data;
  2275. while (true)
  2276. {
  2277. // XXX: `struct sockaddr_storage' is not the most portable thing
  2278. struct sockaddr_storage peer;
  2279. socklen_t peer_len = sizeof peer;
  2280. int fd = accept (pfd->fd, (struct sockaddr *) &peer, &peer_len);
  2281. if (fd == -1)
  2282. {
  2283. if (errno == EAGAIN)
  2284. break;
  2285. if (errno == EINTR
  2286. || errno == ECONNABORTED)
  2287. continue;
  2288. // TODO: handle resource exhaustion (EMFILE, ENFILE) specially
  2289. // (stop accepting new connections and wait until we close some;
  2290. // also set a timer in case of ENFILE).
  2291. print_fatal ("%s: %s", "accept", strerror (errno));
  2292. irc_initiate_quit (ctx);
  2293. break;
  2294. }
  2295. if (ctx->max_connections != 0 && ctx->n_clients >= ctx->max_connections)
  2296. {
  2297. print_debug ("connection limit reached, refusing connection");
  2298. close (fd);
  2299. continue;
  2300. }
  2301. char host[NI_MAXHOST] = "unknown", port[NI_MAXSERV] = "unknown";
  2302. int err = getnameinfo ((struct sockaddr *) &peer, peer_len,
  2303. host, sizeof host, port, sizeof port, NI_NUMERICSERV);
  2304. if (err)
  2305. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  2306. char *address = format_host_port_pair (host, port);
  2307. print_debug ("accepted connection from %s", address);
  2308. struct client *c = xmalloc (sizeof *c);
  2309. client_init (c);
  2310. c->ctx = ctx;
  2311. c->socket_fd = fd;
  2312. c->hostname = xstrdup (host);
  2313. c->address = address;
  2314. c->last_active = time (NULL);
  2315. LIST_PREPEND (ctx->clients, c);
  2316. ctx->n_clients++;
  2317. set_blocking (fd, false);
  2318. client_update_poller (c, NULL);
  2319. client_set_kill_timer (c);
  2320. }
  2321. }
  2322. // --- Application setup -------------------------------------------------------
  2323. static int
  2324. irc_ssl_verify_callback (int verify_ok, X509_STORE_CTX *ctx)
  2325. {
  2326. (void) verify_ok;
  2327. (void) ctx;
  2328. // We only want to provide additional privileges based on the client's
  2329. // certificate, so let's not terminate the connection because of a failure.
  2330. return 1;
  2331. }
  2332. static bool
  2333. irc_initialize_ssl (struct server_context *ctx, struct error **e)
  2334. {
  2335. const char *ssl_cert = str_map_find (&ctx->config, "ssl_cert");
  2336. const char *ssl_key = str_map_find (&ctx->config, "ssl_key");
  2337. // Only try to enable SSL support if the user configures it; it is not
  2338. // a failure if no one has requested it.
  2339. if (!ssl_cert && !ssl_key)
  2340. return true;
  2341. if (!ssl_cert)
  2342. error_set (e, "no SSL certificate set");
  2343. else if (!ssl_key)
  2344. error_set (e, "no SSL private key set");
  2345. if (!ssl_cert || !ssl_key)
  2346. return false;
  2347. char *cert_path = resolve_config_filename (ssl_cert);
  2348. char *key_path = resolve_config_filename (ssl_key);
  2349. if (!cert_path)
  2350. error_set (e, "%s: %s", "cannot open file", ssl_cert);
  2351. else if (!key_path)
  2352. error_set (e, "%s: %s", "cannot open file", ssl_key);
  2353. if (!cert_path || !key_path)
  2354. return false;
  2355. ctx->ssl_ctx = SSL_CTX_new (SSLv23_server_method ());
  2356. if (!ctx->ssl_ctx)
  2357. {
  2358. // XXX: these error strings are really nasty; also there could be
  2359. // multiple errors on the OpenSSL stack.
  2360. error_set (e, "%s: %s", "could not initialize SSL",
  2361. ERR_error_string (ERR_get_error (), NULL));
  2362. goto error_ssl_1;
  2363. }
  2364. SSL_CTX_set_verify (ctx->ssl_ctx,
  2365. SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, irc_ssl_verify_callback);
  2366. // XXX: maybe we should call SSL_CTX_set_options() for some workarounds
  2367. const unsigned char session_id_context[SSL_MAX_SSL_SESSION_ID_LENGTH]
  2368. = PROGRAM_NAME;
  2369. (void) SSL_CTX_set_session_id_context (ctx->ssl_ctx,
  2370. session_id_context, sizeof session_id_context);
  2371. // XXX: perhaps we should read the files ourselves for better messages
  2372. if (!SSL_CTX_use_certificate_chain_file (ctx->ssl_ctx, cert_path))
  2373. {
  2374. error_set (e, "%s: %s", "setting the SSL client certificate failed",
  2375. ERR_error_string (ERR_get_error (), NULL));
  2376. goto error_ssl_2;
  2377. }
  2378. if (!SSL_CTX_use_PrivateKey_file (ctx->ssl_ctx, key_path, SSL_FILETYPE_PEM))
  2379. {
  2380. error_set (e, "%s: %s", "setting the SSL private key failed",
  2381. ERR_error_string (ERR_get_error (), NULL));
  2382. goto error_ssl_2;
  2383. }
  2384. // TODO: SSL_CTX_check_private_key()? It has probably already been checked
  2385. // by SSL_CTX_use_PrivateKey_file() above.
  2386. // Gah, spare me your awkward semantics, I just want to push data!
  2387. // XXX: do we want SSL_MODE_AUTO_RETRY as well? I guess not.
  2388. SSL_CTX_set_mode (ctx->ssl_ctx,
  2389. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
  2390. return true;
  2391. error_ssl_2:
  2392. SSL_CTX_free (ctx->ssl_ctx);
  2393. ctx->ssl_ctx = NULL;
  2394. error_ssl_1:
  2395. return false;
  2396. }
  2397. static bool
  2398. irc_initialize_catalog (struct server_context *ctx, struct error **e)
  2399. {
  2400. hard_assert (ctx->catalog == (nl_catd) -1);
  2401. const char *catalog = str_map_find (&ctx->config, "catalog");
  2402. if (!catalog)
  2403. return true;
  2404. char *path = resolve_config_filename (catalog);
  2405. if (!path)
  2406. {
  2407. error_set (e, "%s: %s", "cannot open file", catalog);
  2408. return false;
  2409. }
  2410. ctx->catalog = catopen (path, NL_CAT_LOCALE);
  2411. free (path);
  2412. if (ctx->catalog == (nl_catd) -1)
  2413. {
  2414. error_set (e, "%s: %s",
  2415. "failed reading the message catalog file", strerror (errno));
  2416. return false;
  2417. }
  2418. return true;
  2419. }
  2420. static bool
  2421. irc_initialize_motd (struct server_context *ctx, struct error **e)
  2422. {
  2423. hard_assert (ctx->motd.len == 0);
  2424. const char *motd = str_map_find (&ctx->config, "motd");
  2425. if (!motd)
  2426. return true;
  2427. char *path = resolve_config_filename (motd);
  2428. if (!path)
  2429. {
  2430. error_set (e, "%s: %s", "cannot open file", motd);
  2431. return false;
  2432. }
  2433. FILE *fp = fopen (path, "r");
  2434. free (path);
  2435. if (!fp)
  2436. {
  2437. error_set (e, "%s: %s",
  2438. "failed reading the MOTD file", strerror (errno));
  2439. return false;
  2440. }
  2441. struct str line;
  2442. str_init (&line);
  2443. while (read_line (fp, &line))
  2444. str_vector_add_owned (&ctx->motd, str_steal (&line));
  2445. str_free (&line);
  2446. fclose (fp);
  2447. return true;
  2448. }
  2449. /// This function handles values that require validation before their first use,
  2450. /// or some kind of a transformation (such as conversion to an integer) needs
  2451. /// to be done before they can be used directly.
  2452. static bool
  2453. irc_parse_config (struct server_context *ctx, struct error **e)
  2454. {
  2455. unsigned long ul;
  2456. #define PARSE_UNSIGNED(name, min, max) \
  2457. const char *name = str_map_find (&ctx->config, #name); \
  2458. hard_assert (name != NULL); \
  2459. if (!xstrtoul (&ul, name, 10) || ul > max || ul < min) \
  2460. { \
  2461. error_set (e, "invalid configuration value for `%s': %s", \
  2462. #name, "the number is invalid or out of range"); \
  2463. return false; \
  2464. } \
  2465. ctx->name = ul
  2466. PARSE_UNSIGNED (ping_interval, 1, UINT_MAX);
  2467. PARSE_UNSIGNED (max_connections, 0, UINT_MAX);
  2468. bool result = true;
  2469. struct str_vector fingerprints;
  2470. str_vector_init (&fingerprints);
  2471. const char *operators = str_map_find (&ctx->config, "operators");
  2472. if (operators)
  2473. split_str_ignore_empty (operators, ',', &fingerprints);
  2474. for (size_t i = 0; i < fingerprints.len; i++)
  2475. {
  2476. const char *key = fingerprints.vector[i];
  2477. if (!irc_is_valid_fingerprint (key))
  2478. {
  2479. error_set (e, "invalid configuration value for `%s': %s",
  2480. "operators", "invalid fingerprint value");
  2481. result = false;
  2482. break;
  2483. }
  2484. str_map_set (&ctx->operators, key, (void *) 1);
  2485. }
  2486. str_vector_free (&fingerprints);
  2487. return result;
  2488. }
  2489. static bool
  2490. irc_initialize_server_name (struct server_context *ctx, struct error **e)
  2491. {
  2492. enum validation_result res;
  2493. const char *server_name = str_map_find (&ctx->config, "server_name");
  2494. if (server_name)
  2495. {
  2496. res = irc_validate_hostname (server_name);
  2497. if (res != VALIDATION_OK)
  2498. {
  2499. error_set (e, "invalid configuration value for `%s': %s",
  2500. "server_name", irc_validate_to_str (res));
  2501. return false;
  2502. }
  2503. ctx->server_name = xstrdup (server_name);
  2504. }
  2505. else
  2506. {
  2507. long host_name_max = sysconf (_SC_HOST_NAME_MAX);
  2508. if (host_name_max <= 0)
  2509. host_name_max = _POSIX_HOST_NAME_MAX;
  2510. char hostname[host_name_max + 1];
  2511. if (gethostname (hostname, sizeof hostname))
  2512. {
  2513. error_set (e, "%s: %s",
  2514. "getting the hostname failed", strerror (errno));
  2515. return false;
  2516. }
  2517. res = irc_validate_hostname (hostname);
  2518. if (res != VALIDATION_OK)
  2519. {
  2520. error_set (e,
  2521. "`%s' is not set and the hostname (`%s') cannot be used: %s",
  2522. "server_name", hostname, irc_validate_to_str (res));
  2523. return false;
  2524. }
  2525. ctx->server_name = xstrdup (hostname);
  2526. }
  2527. return true;
  2528. }
  2529. static int
  2530. irc_listen (struct addrinfo *gai_iter)
  2531. {
  2532. int fd = socket (gai_iter->ai_family,
  2533. gai_iter->ai_socktype, gai_iter->ai_protocol);
  2534. if (fd == -1)
  2535. return -1;
  2536. set_cloexec (fd);
  2537. int yes = 1;
  2538. soft_assert (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
  2539. &yes, sizeof yes) != -1);
  2540. soft_assert (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
  2541. &yes, sizeof yes) != -1);
  2542. char host[NI_MAXHOST], port[NI_MAXSERV];
  2543. host[0] = port[0] = '\0';
  2544. int err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
  2545. host, sizeof host, port, sizeof port,
  2546. NI_NUMERICHOST | NI_NUMERICSERV);
  2547. if (err)
  2548. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  2549. char *address = format_host_port_pair (host, port);
  2550. if (bind (fd, gai_iter->ai_addr, gai_iter->ai_addrlen))
  2551. print_error ("bind to %s failed: %s", address, strerror (errno));
  2552. else if (listen (fd, 16 /* arbitrary number */))
  2553. print_error ("listen on %s failed: %s", address, strerror (errno));
  2554. else
  2555. {
  2556. print_status ("listening on %s", address);
  2557. free (address);
  2558. return fd;
  2559. }
  2560. free (address);
  2561. xclose (fd);
  2562. return -1;
  2563. }
  2564. static void
  2565. irc_listen_resolve (struct server_context *ctx,
  2566. const char *host, const char *port, struct addrinfo *gai_hints)
  2567. {
  2568. struct addrinfo *gai_result, *gai_iter;
  2569. int err = getaddrinfo (host, port, gai_hints, &gai_result);
  2570. if (err)
  2571. {
  2572. char *address = format_host_port_pair (host, port);
  2573. print_error ("bind to %s failed: %s: %s",
  2574. address, "getaddrinfo", gai_strerror (err));
  2575. free (address);
  2576. return;
  2577. }
  2578. int fd;
  2579. for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next)
  2580. {
  2581. if ((fd = irc_listen (gai_iter)) == -1)
  2582. continue;
  2583. ctx->listen_fds[ctx->n_listen_fds++] = fd;
  2584. set_blocking (fd, false);
  2585. poller_set (&ctx->poller, fd, POLLIN,
  2586. (poller_dispatcher_fn) on_irc_client_available, ctx);
  2587. break;
  2588. }
  2589. freeaddrinfo (gai_result);
  2590. }
  2591. static bool
  2592. irc_setup_listen_fds (struct server_context *ctx, struct error **e)
  2593. {
  2594. const char *bind_host = str_map_find (&ctx->config, "bind_host");
  2595. const char *bind_port = str_map_find (&ctx->config, "bind_port");
  2596. hard_assert (bind_port != NULL); // We have a default value for this
  2597. struct addrinfo gai_hints;
  2598. memset (&gai_hints, 0, sizeof gai_hints);
  2599. gai_hints.ai_socktype = SOCK_STREAM;
  2600. gai_hints.ai_flags = AI_PASSIVE;
  2601. struct str_vector ports;
  2602. str_vector_init (&ports);
  2603. split_str_ignore_empty (bind_port, ',', &ports);
  2604. ctx->listen_fds = xcalloc (ports.len, sizeof *ctx->listen_fds);
  2605. for (size_t i = 0; i < ports.len; i++)
  2606. irc_listen_resolve (ctx, bind_host, ports.vector[i], &gai_hints);
  2607. str_vector_free (&ports);
  2608. if (!ctx->n_listen_fds)
  2609. {
  2610. error_set (e, "%s: %s",
  2611. "network setup failed", "no ports to listen on");
  2612. return false;
  2613. }
  2614. return true;
  2615. }
  2616. // --- Main --------------------------------------------------------------------
  2617. static void
  2618. on_signal_pipe_readable (const struct pollfd *fd, struct server_context *ctx)
  2619. {
  2620. char *dummy;
  2621. (void) read (fd->fd, &dummy, 1);
  2622. if (g_termination_requested && !ctx->quitting)
  2623. irc_initiate_quit (ctx);
  2624. }
  2625. static void
  2626. daemonize (void)
  2627. {
  2628. // TODO: create and lock a PID file?
  2629. print_status ("daemonizing...");
  2630. if (chdir ("/"))
  2631. exit_fatal ("%s: %s", "chdir", strerror (errno));
  2632. pid_t pid;
  2633. if ((pid = fork ()) < 0)
  2634. exit_fatal ("%s: %s", "fork", strerror (errno));
  2635. else if (pid)
  2636. exit (EXIT_SUCCESS);
  2637. setsid ();
  2638. signal (SIGHUP, SIG_IGN);
  2639. if ((pid = fork ()) < 0)
  2640. exit_fatal ("%s: %s", "fork", strerror (errno));
  2641. else if (pid)
  2642. exit (EXIT_SUCCESS);
  2643. openlog (PROGRAM_NAME, LOG_NDELAY | LOG_NOWAIT | LOG_PID, 0);
  2644. g_log_message_real = log_message_syslog;
  2645. // XXX: we may close our own descriptors this way, crippling ourselves
  2646. for (int i = 0; i < 3; i++)
  2647. xclose (i);
  2648. int tty = open ("/dev/null", O_RDWR);
  2649. if (tty != 0 || dup (0) != 1 || dup (0) != 2)
  2650. exit_fatal ("failed to reopen FD's: %s", strerror (errno));
  2651. }
  2652. static void
  2653. print_usage (const char *program_name)
  2654. {
  2655. fprintf (stderr,
  2656. "Usage: %s [OPTION]...\n"
  2657. "Experimental IRC server.\n"
  2658. "\n"
  2659. " -d, --debug run in debug mode (do not daemonize)\n"
  2660. " -h, --help display this help and exit\n"
  2661. " -V, --version output version information and exit\n"
  2662. " --write-default-cfg [filename]\n"
  2663. " write a default configuration file and exit\n",
  2664. program_name);
  2665. }
  2666. int
  2667. main (int argc, char *argv[])
  2668. {
  2669. const char *invocation_name = argv[0];
  2670. static struct option opts[] =
  2671. {
  2672. { "debug", no_argument, NULL, 'd' },
  2673. { "help", no_argument, NULL, 'h' },
  2674. { "version", no_argument, NULL, 'V' },
  2675. { "write-default-cfg", optional_argument, NULL, 'w' },
  2676. { NULL, 0, NULL, 0 }
  2677. };
  2678. while (1)
  2679. {
  2680. int c, opt_index;
  2681. c = getopt_long (argc, argv, "dhV", opts, &opt_index);
  2682. if (c == -1)
  2683. break;
  2684. switch (c)
  2685. {
  2686. case 'd':
  2687. g_debug_mode = true;
  2688. break;
  2689. case 'h':
  2690. print_usage (invocation_name);
  2691. exit (EXIT_SUCCESS);
  2692. case 'V':
  2693. printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
  2694. exit (EXIT_SUCCESS);
  2695. case 'w':
  2696. call_write_default_config (optarg, g_config_table);
  2697. exit (EXIT_SUCCESS);
  2698. default:
  2699. print_error ("wrong options");
  2700. exit (EXIT_FAILURE);
  2701. }
  2702. }
  2703. print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting");
  2704. setup_signal_handlers ();
  2705. SSL_library_init ();
  2706. atexit (EVP_cleanup);
  2707. SSL_load_error_strings ();
  2708. // XXX: ERR_load_BIO_strings()? Anything else?
  2709. atexit (ERR_free_strings);
  2710. struct server_context ctx;
  2711. server_context_init (&ctx);
  2712. irc_register_handlers (&ctx);
  2713. struct error *e = NULL;
  2714. if (!read_config_file (&ctx.config, &e))
  2715. {
  2716. print_error ("error loading configuration: %s", e->message);
  2717. error_free (e);
  2718. exit (EXIT_FAILURE);
  2719. }
  2720. poller_set (&ctx.poller, g_signal_pipe[0], POLLIN,
  2721. (poller_dispatcher_fn) on_signal_pipe_readable, &ctx);
  2722. if (!irc_initialize_ssl (&ctx, &e)
  2723. || !irc_initialize_server_name (&ctx, &e)
  2724. || !irc_initialize_motd (&ctx, &e)
  2725. || !irc_initialize_catalog (&ctx, &e)
  2726. || !irc_parse_config (&ctx, &e)
  2727. || !irc_setup_listen_fds (&ctx, &e))
  2728. {
  2729. print_error ("%s", e->message);
  2730. error_free (e);
  2731. exit (EXIT_FAILURE);
  2732. }
  2733. if (!g_debug_mode)
  2734. daemonize ();
  2735. ctx.polling = true;
  2736. while (ctx.polling)
  2737. poller_run (&ctx.poller);
  2738. server_context_free (&ctx);
  2739. return EXIT_SUCCESS;
  2740. }