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.

3161 lines
87KB

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