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.

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