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.

4092 lines
113KB

  1. /*
  2. * kike.c: the experimental IRC daemon
  3. *
  4. * Copyright (c) 2014 - 2016, Přemysl Janouch <p.janouch@gmail.com>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  13. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  15. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  16. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. *
  18. */
  19. #include "config.h"
  20. #define PROGRAM_NAME "kike"
  21. #define WANT_SYSLOG_LOGGING
  22. #include "common.c"
  23. #include "kike-replies.c"
  24. #include <nl_types.h>
  25. enum { PIPE_READ, PIPE_WRITE };
  26. // FIXME: don't use time_t to compute time deltas
  27. // --- Configuration (application-specific) ------------------------------------
  28. // Just get rid of the crappiest ciphers available by default
  29. #define DEFAULT_CIPHERS "DEFAULT:!MEDIUM:!LOW"
  30. static struct simple_config_item g_config_table[] =
  31. {
  32. { "pid_file", NULL, "Path or name of the PID file" },
  33. { "server_name", NULL, "Server name" },
  34. { "server_info", "My server", "Brief server description" },
  35. { "motd", NULL, "MOTD filename" },
  36. { "catalog", NULL, "catgets localization catalog" },
  37. { "bind_host", NULL, "Address of the IRC server" },
  38. { "bind_port", "6667", "Port of the IRC server" },
  39. { "tls_cert", NULL, "Server TLS certificate (PEM)" },
  40. { "tls_key", NULL, "Server TLS private key (PEM)" },
  41. { "tls_ciphers", DEFAULT_CIPHERS, "OpenSSL cipher list" },
  42. { "operators", NULL, "IRCop TLS cert. fingerprints" },
  43. { "max_connections", "0", "Global connection limit" },
  44. { "ping_interval", "180", "Interval between PING's (sec)" },
  45. { NULL, NULL, NULL }
  46. };
  47. // --- Signals -----------------------------------------------------------------
  48. static int g_signal_pipe[2]; ///< A pipe used to signal... signals
  49. /// Program termination has been requested by a signal
  50. static volatile sig_atomic_t g_termination_requested;
  51. static void
  52. sigterm_handler (int signum)
  53. {
  54. (void) signum;
  55. g_termination_requested = true;
  56. int original_errno = errno;
  57. if (write (g_signal_pipe[1], "t", 1) == -1)
  58. soft_assert (errno == EAGAIN);
  59. errno = original_errno;
  60. }
  61. static void
  62. setup_signal_handlers (void)
  63. {
  64. if (pipe (g_signal_pipe) == -1)
  65. exit_fatal ("%s: %s", "pipe", strerror (errno));
  66. set_cloexec (g_signal_pipe[0]);
  67. set_cloexec (g_signal_pipe[1]);
  68. // So that the pipe cannot overflow; it would make write() block within
  69. // the signal handler, which is something we really don't want to happen.
  70. // The same holds true for read().
  71. set_blocking (g_signal_pipe[0], false);
  72. set_blocking (g_signal_pipe[1], false);
  73. signal (SIGPIPE, SIG_IGN);
  74. struct sigaction sa;
  75. sa.sa_flags = SA_RESTART;
  76. sigemptyset (&sa.sa_mask);
  77. sa.sa_handler = sigterm_handler;
  78. if (sigaction (SIGINT, &sa, NULL) == -1
  79. || sigaction (SIGTERM, &sa, NULL) == -1)
  80. exit_fatal ("%s: %s", "sigaction", strerror (errno));
  81. }
  82. // --- Rate limiter ------------------------------------------------------------
  83. struct flood_detector
  84. {
  85. unsigned interval; ///< Interval for the limit
  86. unsigned limit; ///< Maximum number of events allowed
  87. time_t *timestamps; ///< Timestamps of last events
  88. unsigned pos; ///< Index of the oldest event
  89. };
  90. static void
  91. flood_detector_init (struct flood_detector *self,
  92. unsigned interval, unsigned limit)
  93. {
  94. self->interval = interval;
  95. self->limit = limit;
  96. self->timestamps = xcalloc (limit + 1, sizeof *self->timestamps);
  97. self->pos = 0;
  98. }
  99. static void
  100. flood_detector_free (struct flood_detector *self)
  101. {
  102. free (self->timestamps);
  103. }
  104. static bool
  105. flood_detector_check (struct flood_detector *self)
  106. {
  107. time_t now = time (NULL);
  108. self->timestamps[self->pos++] = now;
  109. if (self->pos > self->limit)
  110. self->pos = 0;
  111. time_t begin = now - self->interval;
  112. size_t count = 0;
  113. for (size_t i = 0; i <= self->limit; i++)
  114. if (self->timestamps[i] >= begin)
  115. count++;
  116. return count <= self->limit;
  117. }
  118. // --- IRC token validation ----------------------------------------------------
  119. // Use the enum only if applicable and a simple boolean isn't sufficient.
  120. enum validation_result
  121. {
  122. VALIDATION_OK,
  123. VALIDATION_ERROR_EMPTY,
  124. VALIDATION_ERROR_TOO_LONG,
  125. VALIDATION_ERROR_INVALID
  126. };
  127. // Everything as per RFC 2812
  128. #define IRC_MAX_NICKNAME 9
  129. #define IRC_MAX_HOSTNAME 63
  130. #define IRC_MAX_CHANNEL_NAME 50
  131. #define IRC_MAX_MESSAGE_LENGTH 510
  132. static bool
  133. irc_regex_match (const char *regex, const char *s)
  134. {
  135. static struct str_map cache;
  136. static bool initialized;
  137. if (!initialized)
  138. {
  139. regex_cache_init (&cache);
  140. initialized = true;
  141. }
  142. struct error *e = NULL;
  143. bool result = regex_cache_match (&cache, regex,
  144. REG_EXTENDED | REG_NOSUB, s, &e);
  145. hard_assert (!e);
  146. return result;
  147. }
  148. static const char *
  149. irc_validate_to_str (enum validation_result result)
  150. {
  151. switch (result)
  152. {
  153. case VALIDATION_OK: return "success";
  154. case VALIDATION_ERROR_EMPTY: return "the value is empty";
  155. case VALIDATION_ERROR_INVALID: return "invalid format";
  156. case VALIDATION_ERROR_TOO_LONG: return "the value is too long";
  157. default: abort ();
  158. }
  159. }
  160. // Anything to keep it as short as possible
  161. #define SN "[0-9A-Za-z][-0-9A-Za-z]*[0-9A-Za-z]*"
  162. #define N4 "[0-9]{1,3}"
  163. #define N6 "[0-9ABCDEFabcdef]{1,}"
  164. #define LE "A-Za-z"
  165. #define SP "][\\\\`_^{|}"
  166. static enum validation_result
  167. irc_validate_hostname (const char *hostname)
  168. {
  169. if (!*hostname)
  170. return VALIDATION_ERROR_EMPTY;
  171. if (!irc_regex_match ("^" SN "(\\." SN ")*$", hostname))
  172. return VALIDATION_ERROR_INVALID;
  173. if (strlen (hostname) > IRC_MAX_HOSTNAME)
  174. return VALIDATION_ERROR_TOO_LONG;
  175. return VALIDATION_OK;
  176. }
  177. static bool
  178. irc_is_valid_hostaddr (const char *hostaddr)
  179. {
  180. if (irc_regex_match ("^" N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr)
  181. || irc_regex_match ("^" N6 ":" N6 ":" N6 ":" N6 ":"
  182. N6 ":" N6 ":" N6 ":" N6 "$", hostaddr)
  183. || irc_regex_match ("^0:0:0:0:0:(0|[Ff]{4}):"
  184. N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr))
  185. return true;
  186. return false;
  187. }
  188. static bool
  189. irc_is_valid_host (const char *host)
  190. {
  191. return irc_validate_hostname (host) == VALIDATION_OK
  192. || irc_is_valid_hostaddr (host);
  193. }
  194. static bool
  195. irc_is_valid_user (const char *user)
  196. {
  197. return irc_regex_match ("^[^\r\n @]+$", user);
  198. }
  199. static bool
  200. irc_validate_nickname (const char *nickname)
  201. {
  202. if (!*nickname)
  203. return VALIDATION_ERROR_EMPTY;
  204. if (!irc_regex_match ("^[" SP LE "][" SP LE "0-9-]*$", nickname))
  205. return VALIDATION_ERROR_INVALID;
  206. if (strlen (nickname) > IRC_MAX_NICKNAME)
  207. return VALIDATION_ERROR_TOO_LONG;
  208. return VALIDATION_OK;
  209. }
  210. static enum validation_result
  211. irc_validate_channel_name (const char *channel_name)
  212. {
  213. if (!*channel_name)
  214. return VALIDATION_ERROR_EMPTY;
  215. if (*channel_name != '#' || strpbrk (channel_name, "\7\r\n ,:"))
  216. return VALIDATION_ERROR_INVALID;
  217. if (strlen (channel_name) > IRC_MAX_CHANNEL_NAME)
  218. return VALIDATION_ERROR_TOO_LONG;
  219. return VALIDATION_OK;
  220. }
  221. static bool
  222. irc_is_valid_key (const char *key)
  223. {
  224. // XXX: should be 7-bit as well but whatever
  225. return irc_regex_match ("^[^\r\n\f\t\v ]{1,23}$", key);
  226. }
  227. #undef SN
  228. #undef N4
  229. #undef N6
  230. #undef LE
  231. #undef SP
  232. static bool
  233. irc_is_valid_user_mask (const char *mask)
  234. {
  235. return irc_regex_match ("^[^!@]+![^!@]+@[^@!]+$", mask);
  236. }
  237. static bool
  238. irc_is_valid_fingerprint (const char *fp)
  239. {
  240. return irc_regex_match ("^[a-fA-F0-9]{40}$", fp);
  241. }
  242. // --- Clients (equals users) --------------------------------------------------
  243. #define IRC_SUPPORTED_USER_MODES "aiwros"
  244. enum
  245. {
  246. IRC_USER_MODE_INVISIBLE = (1 << 0),
  247. IRC_USER_MODE_RX_WALLOPS = (1 << 1),
  248. IRC_USER_MODE_RESTRICTED = (1 << 2),
  249. IRC_USER_MODE_OPERATOR = (1 << 3),
  250. IRC_USER_MODE_RX_SERVER_NOTICES = (1 << 4)
  251. };
  252. enum
  253. {
  254. IRC_CAP_MULTI_PREFIX = (1 << 0),
  255. IRC_CAP_INVITE_NOTIFY = (1 << 1),
  256. IRC_CAP_ECHO_MESSAGE = (1 << 2),
  257. IRC_CAP_USERHOST_IN_NAMES = (1 << 3),
  258. IRC_CAP_SERVER_TIME = (1 << 4)
  259. };
  260. struct client
  261. {
  262. LIST_HEADER (struct client)
  263. struct server_context *ctx; ///< Server context
  264. time_t opened; ///< When the connection was opened
  265. size_t n_sent_messages; ///< Number of sent messages total
  266. size_t sent_bytes; ///< Number of sent bytes total
  267. size_t n_received_messages; ///< Number of received messages total
  268. size_t received_bytes; ///< Number of received bytes total
  269. int socket_fd; ///< The TCP socket
  270. struct str read_buffer; ///< Unprocessed input
  271. struct str write_buffer; ///< Output yet to be sent out
  272. struct poller_fd socket_event; ///< The socket can be read/written to
  273. struct poller_timer ping_timer; ///< We should send a ping
  274. struct poller_timer timeout_timer; ///< Connection seems to be dead
  275. struct poller_timer kill_timer; ///< Hard kill timeout
  276. unsigned long cap_version; ///< CAP protocol version
  277. unsigned caps_enabled; ///< Enabled capabilities
  278. unsigned initialized : 1; ///< Has any data been received yet?
  279. unsigned cap_negotiating : 1; ///< Negotiating capabilities
  280. unsigned registered : 1; ///< The user has registered
  281. unsigned closing_link : 1; ///< Closing link
  282. unsigned half_closed : 1; ///< Closing link: conn. is half-closed
  283. unsigned ssl_rx_want_tx : 1; ///< SSL_read() wants to write
  284. unsigned ssl_tx_want_rx : 1; ///< SSL_write() wants to read
  285. SSL *ssl; ///< SSL connection
  286. char *ssl_cert_fingerprint; ///< Client certificate fingerprint
  287. char *nickname; ///< IRC nickname (main identifier)
  288. char *username; ///< IRC username
  289. char *realname; ///< IRC realname (e-mail)
  290. char *hostname; ///< Hostname shown to the network
  291. char *port; ///< Port of the peer as a string
  292. char *address; ///< Full address
  293. unsigned mode; ///< User's mode
  294. char *away_message; ///< Away message
  295. time_t last_active; ///< Last PRIVMSG, to get idle time
  296. struct str_map invites; ///< Channel invitations by operators
  297. struct flood_detector antiflood; ///< Flood detector
  298. struct async_getnameinfo *gni; ///< Backwards DNS resolution
  299. struct poller_timer gni_timer; ///< Backwards DNS resolution timeout
  300. };
  301. static struct client *
  302. client_new (void)
  303. {
  304. struct client *self = xcalloc (1, sizeof *self);
  305. self->socket_fd = -1;
  306. str_init (&self->read_buffer);
  307. str_init (&self->write_buffer);
  308. self->cap_version = 301;
  309. // TODO: make this configurable and more fine-grained
  310. flood_detector_init (&self->antiflood, 10, 20);
  311. str_map_init (&self->invites);
  312. self->invites.key_xfrm = irc_strxfrm;
  313. return self;
  314. }
  315. static void
  316. client_destroy (struct client *self)
  317. {
  318. if (!soft_assert (self->socket_fd == -1))
  319. xclose (self->socket_fd);
  320. if (self->ssl)
  321. SSL_free (self->ssl);
  322. str_free (&self->read_buffer);
  323. str_free (&self->write_buffer);
  324. free (self->nickname);
  325. free (self->username);
  326. free (self->realname);
  327. free (self->hostname);
  328. free (self->port);
  329. free (self->address);
  330. free (self->away_message);
  331. flood_detector_free (&self->antiflood);
  332. str_map_free (&self->invites);
  333. if (self->gni)
  334. async_cancel (&self->gni->async);
  335. free (self);
  336. }
  337. static void client_close_link (struct client *c, const char *reason);
  338. static void client_kill (struct client *c, const char *reason);
  339. static void client_send (struct client *, const char *, ...)
  340. ATTRIBUTE_PRINTF (2, 3);
  341. static void client_cancel_timers (struct client *);
  342. static void client_set_kill_timer (struct client *);
  343. static void client_update_poller (struct client *, const struct pollfd *);
  344. // --- Channels ----------------------------------------------------------------
  345. #define IRC_SUPPORTED_CHAN_MODES "ov" "beI" "imnqpst" "kl"
  346. enum
  347. {
  348. IRC_CHAN_MODE_INVITE_ONLY = (1 << 0),
  349. IRC_CHAN_MODE_MODERATED = (1 << 1),
  350. IRC_CHAN_MODE_NO_OUTSIDE_MSGS = (1 << 2),
  351. IRC_CHAN_MODE_QUIET = (1 << 3),
  352. IRC_CHAN_MODE_PRIVATE = (1 << 4),
  353. IRC_CHAN_MODE_SECRET = (1 << 5),
  354. IRC_CHAN_MODE_PROTECTED_TOPIC = (1 << 6),
  355. IRC_CHAN_MODE_OPERATOR = (1 << 7),
  356. IRC_CHAN_MODE_VOICE = (1 << 8)
  357. };
  358. struct channel_user
  359. {
  360. LIST_HEADER (struct channel_user)
  361. unsigned modes;
  362. struct client *c;
  363. };
  364. struct channel
  365. {
  366. struct server_context *ctx; ///< Server context
  367. char *name; ///< Channel name
  368. unsigned modes; ///< Channel modes
  369. char *key; ///< Channel key
  370. long user_limit; ///< User limit or -1
  371. time_t created; ///< Creation time
  372. char *topic; ///< Channel topic
  373. char *topic_who; ///< Who set the topic
  374. time_t topic_time; ///< When the topic was set
  375. struct channel_user *users; ///< Channel users
  376. struct str_vector ban_list; ///< Ban list
  377. struct str_vector exception_list; ///< Exceptions from bans
  378. struct str_vector invite_list; ///< Exceptions from +I
  379. };
  380. static struct channel *
  381. channel_new (void)
  382. {
  383. struct channel *self = xcalloc (1, sizeof *self);
  384. self->user_limit = -1;
  385. self->topic = xstrdup ("");
  386. str_vector_init (&self->ban_list);
  387. str_vector_init (&self->exception_list);
  388. str_vector_init (&self->invite_list);
  389. return self;
  390. }
  391. static void
  392. channel_delete (struct channel *self)
  393. {
  394. free (self->name);
  395. free (self->key);
  396. free (self->topic);
  397. free (self->topic_who);
  398. struct channel_user *link, *tmp;
  399. for (link = self->users; link; link = tmp)
  400. {
  401. tmp = link->next;
  402. free (link);
  403. }
  404. str_vector_free (&self->ban_list);
  405. str_vector_free (&self->exception_list);
  406. str_vector_free (&self->invite_list);
  407. free (self);
  408. }
  409. static char *
  410. channel_get_mode (struct channel *self, bool disclose_secrets)
  411. {
  412. struct str mode;
  413. str_init (&mode);
  414. unsigned m = self->modes;
  415. if (m & IRC_CHAN_MODE_INVITE_ONLY) str_append_c (&mode, 'i');
  416. if (m & IRC_CHAN_MODE_MODERATED) str_append_c (&mode, 'm');
  417. if (m & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) str_append_c (&mode, 'n');
  418. if (m & IRC_CHAN_MODE_QUIET) str_append_c (&mode, 'q');
  419. if (m & IRC_CHAN_MODE_PRIVATE) str_append_c (&mode, 'p');
  420. if (m & IRC_CHAN_MODE_SECRET) str_append_c (&mode, 's');
  421. if (m & IRC_CHAN_MODE_PROTECTED_TOPIC) str_append_c (&mode, 't');
  422. if (self->user_limit != -1) str_append_c (&mode, 'l');
  423. if (self->key) str_append_c (&mode, 'k');
  424. // XXX: is it correct to split it? Try it on an existing implementation.
  425. if (disclose_secrets)
  426. {
  427. if (self->user_limit != -1)
  428. str_append_printf (&mode, " %ld", self->user_limit);
  429. if (self->key)
  430. str_append_printf (&mode, " %s", self->key);
  431. }
  432. return str_steal (&mode);
  433. }
  434. static struct channel_user *
  435. channel_get_user (const struct channel *chan, const struct client *c)
  436. {
  437. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  438. if (iter->c == c)
  439. return iter;
  440. return NULL;
  441. }
  442. static struct channel_user *
  443. channel_add_user (struct channel *chan, struct client *c)
  444. {
  445. struct channel_user *link = xcalloc (1, sizeof *link);
  446. link->c = c;
  447. LIST_PREPEND (chan->users, link);
  448. return link;
  449. }
  450. static void
  451. channel_remove_user (struct channel *chan, struct channel_user *user)
  452. {
  453. LIST_UNLINK (chan->users, user);
  454. free (user);
  455. }
  456. static size_t
  457. channel_user_count (const struct channel *chan)
  458. {
  459. size_t result = 0;
  460. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  461. result++;
  462. return result;
  463. }
  464. // --- IRC server context ------------------------------------------------------
  465. struct whowas_info
  466. {
  467. char *nickname; ///< IRC nickname
  468. char *username; ///< IRC username
  469. char *realname; ///< IRC realname
  470. char *hostname; ///< Hostname shown to the network
  471. };
  472. struct whowas_info *
  473. whowas_info_new (struct client *c)
  474. {
  475. struct whowas_info *self = xmalloc (sizeof *self);
  476. self->nickname = xstrdup (c->nickname);
  477. self->username = xstrdup (c->username);
  478. self->realname = xstrdup (c->realname);
  479. self->hostname = xstrdup (c->hostname);
  480. return self;
  481. }
  482. static void
  483. whowas_info_destroy (struct whowas_info *self)
  484. {
  485. free (self->nickname);
  486. free (self->username);
  487. free (self->realname);
  488. free (self->hostname);
  489. free (self);
  490. }
  491. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  492. struct irc_command
  493. {
  494. const char *name;
  495. bool requires_registration;
  496. void (*handler) (const struct irc_message *, struct client *);
  497. size_t n_received; ///< Number of commands received
  498. size_t bytes_received; ///< Number of bytes received total
  499. };
  500. struct server_context
  501. {
  502. int *listen_fds; ///< Listening socket FD's
  503. struct poller_fd *listen_events; ///< New connections available
  504. size_t n_listen_fds; ///< Number of listening sockets
  505. time_t started; ///< When has the server been started
  506. SSL_CTX *ssl_ctx; ///< SSL context
  507. struct client *clients; ///< Clients
  508. unsigned n_clients; ///< Current number of connections
  509. struct str_map users; ///< Maps nicknames to clients
  510. struct str_map channels; ///< Maps channel names to data
  511. struct str_map handlers; ///< Message handlers
  512. struct str_map cap_handlers; ///< CAP message handlers
  513. struct str_map whowas; ///< WHOWAS registry
  514. struct poller poller; ///< Manages polled description
  515. struct poller_timer quit_timer; ///< Quit timeout timer
  516. bool quitting; ///< User requested quitting
  517. bool polling; ///< The event loop is running
  518. struct poller_fd signal_event; ///< Got a signal
  519. struct str_map config; ///< Server configuration
  520. char *server_name; ///< Our server name
  521. unsigned ping_interval; ///< Ping interval in seconds
  522. unsigned max_connections; ///< Max. connections allowed or 0
  523. struct str_vector motd; ///< MOTD (none if empty)
  524. nl_catd catalog; ///< Message catalog for server msgs
  525. struct str_map operators; ///< TLS cert. fingerprints for IRCops
  526. };
  527. static void
  528. on_irc_quit_timeout (void *user_data)
  529. {
  530. struct server_context *ctx = user_data;
  531. struct client *iter, *next;
  532. for (iter = ctx->clients; iter; iter = next)
  533. {
  534. next = iter->next;
  535. // irc_initiate_quit() has already unregistered the client
  536. client_kill (iter, "Shutting down");
  537. }
  538. }
  539. static void
  540. server_context_init (struct server_context *self)
  541. {
  542. memset (self, 0, sizeof *self);
  543. str_map_init (&self->users);
  544. self->users.key_xfrm = irc_strxfrm;
  545. str_map_init (&self->channels);
  546. self->channels.key_xfrm = irc_strxfrm;
  547. self->channels.free = (void (*) (void *)) channel_delete;
  548. str_map_init (&self->handlers);
  549. self->handlers.key_xfrm = irc_strxfrm;
  550. str_map_init (&self->cap_handlers);
  551. self->cap_handlers.key_xfrm = irc_strxfrm;
  552. str_map_init (&self->whowas);
  553. self->whowas.key_xfrm = irc_strxfrm;
  554. self->whowas.free = (void (*) (void *)) whowas_info_destroy;
  555. poller_init (&self->poller);
  556. poller_timer_init (&self->quit_timer, &self->poller);
  557. self->quit_timer.dispatcher = on_irc_quit_timeout;
  558. self->quit_timer.user_data = self;
  559. str_map_init (&self->config);
  560. self->config.free = free;
  561. simple_config_load_defaults (&self->config, g_config_table);
  562. str_vector_init (&self->motd);
  563. self->catalog = (nl_catd) -1;
  564. str_map_init (&self->operators);
  565. // The regular irc_strxfrm() is sufficient for fingerprints
  566. self->operators.key_xfrm = irc_strxfrm;
  567. }
  568. static void
  569. server_context_free (struct server_context *self)
  570. {
  571. str_map_free (&self->config);
  572. for (size_t i = 0; i < self->n_listen_fds; i++)
  573. {
  574. xclose (self->listen_fds[i]);
  575. self->listen_events[i].closed = true;
  576. poller_fd_reset (&self->listen_events[i]);
  577. }
  578. free (self->listen_fds);
  579. free (self->listen_events);
  580. hard_assert (!self->clients);
  581. if (self->ssl_ctx)
  582. SSL_CTX_free (self->ssl_ctx);
  583. free (self->server_name);
  584. str_map_free (&self->users);
  585. str_map_free (&self->channels);
  586. str_map_free (&self->handlers);
  587. str_map_free (&self->cap_handlers);
  588. str_map_free (&self->whowas);
  589. poller_free (&self->poller);
  590. str_vector_free (&self->motd);
  591. if (self->catalog != (nl_catd) -1)
  592. catclose (self->catalog);
  593. str_map_free (&self->operators);
  594. }
  595. static const char *
  596. irc_get_text (struct server_context *ctx, int id, const char *def)
  597. {
  598. if (!soft_assert (def != NULL))
  599. def = "";
  600. if (ctx->catalog == (nl_catd) -1)
  601. return def;
  602. return catgets (ctx->catalog, 1, id, def);
  603. }
  604. static void
  605. irc_try_finish_quit (struct server_context *ctx)
  606. {
  607. if (!ctx->n_clients && ctx->quitting)
  608. {
  609. poller_timer_reset (&ctx->quit_timer);
  610. ctx->polling = false;
  611. }
  612. }
  613. static void
  614. irc_initiate_quit (struct server_context *ctx)
  615. {
  616. print_status ("shutting down");
  617. for (size_t i = 0; i < ctx->n_listen_fds; i++)
  618. {
  619. xclose (ctx->listen_fds[i]);
  620. ctx->listen_events[i].closed = true;
  621. poller_fd_reset (&ctx->listen_events[i]);
  622. }
  623. ctx->n_listen_fds = 0;
  624. for (struct client *iter = ctx->clients; iter; iter = iter->next)
  625. if (!iter->closing_link)
  626. client_close_link (iter, "Shutting down");
  627. ctx->quitting = true;
  628. poller_timer_set (&ctx->quit_timer, 5000);
  629. irc_try_finish_quit (ctx);
  630. }
  631. static struct channel *
  632. irc_channel_create (struct server_context *ctx, const char *name)
  633. {
  634. struct channel *chan = channel_new ();
  635. chan->ctx = ctx;
  636. chan->name = xstrdup (name);
  637. chan->created = time (NULL);
  638. str_map_set (&ctx->channels, name, chan);
  639. return chan;
  640. }
  641. static void
  642. irc_channel_destroy_if_empty (struct server_context *ctx, struct channel *chan)
  643. {
  644. if (!chan->users)
  645. str_map_set (&ctx->channels, chan->name, NULL);
  646. }
  647. static void
  648. irc_send_to_roommates (struct client *c, const char *message)
  649. {
  650. struct str_map targets;
  651. str_map_init (&targets);
  652. targets.key_xfrm = irc_strxfrm;
  653. struct str_map_iter iter;
  654. str_map_iter_init (&iter, &c->ctx->channels);
  655. struct channel *chan;
  656. while ((chan = str_map_iter_next (&iter)))
  657. {
  658. if (chan->modes & IRC_CHAN_MODE_QUIET
  659. || !channel_get_user (chan, c))
  660. continue;
  661. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  662. str_map_set (&targets, iter->c->nickname, iter->c);
  663. }
  664. str_map_iter_init (&iter, &targets);
  665. struct client *target;
  666. while ((target = str_map_iter_next (&iter)))
  667. if (target != c)
  668. client_send (target, "%s", message);
  669. }
  670. // --- Clients (continued) -----------------------------------------------------
  671. static void
  672. client_mode_to_str (unsigned m, struct str *out)
  673. {
  674. if (m & IRC_USER_MODE_INVISIBLE) str_append_c (out, 'i');
  675. if (m & IRC_USER_MODE_RX_WALLOPS) str_append_c (out, 'w');
  676. if (m & IRC_USER_MODE_RESTRICTED) str_append_c (out, 'r');
  677. if (m & IRC_USER_MODE_OPERATOR) str_append_c (out, 'o');
  678. if (m & IRC_USER_MODE_RX_SERVER_NOTICES) str_append_c (out, 's');
  679. }
  680. static char *
  681. client_get_mode (struct client *self)
  682. {
  683. struct str mode;
  684. str_init (&mode);
  685. if (self->away_message)
  686. str_append_c (&mode, 'a');
  687. client_mode_to_str (self->mode, &mode);
  688. return str_steal (&mode);
  689. }
  690. static void
  691. client_send_str (struct client *c, const struct str *s)
  692. {
  693. hard_assert (!c->closing_link);
  694. size_t old_sendq = c->write_buffer.len;
  695. // So far there's only one message tag we use, so we can do it simple;
  696. // note that a 1024-character limit applies to messages with tags on
  697. if (c->caps_enabled & IRC_CAP_SERVER_TIME)
  698. {
  699. long milliseconds; char buf[32]; struct tm tm;
  700. time_t now = unixtime_msec (&milliseconds);
  701. if (soft_assert (strftime (buf, sizeof buf,
  702. "%Y-%m-%dT%T", gmtime_r (&now, &tm))))
  703. str_append_printf (&c->write_buffer,
  704. "@time=%s.%03ldZ ", buf, milliseconds);
  705. }
  706. // TODO: kill the connection above some "SendQ" threshold (careful!)
  707. str_append_data (&c->write_buffer, s->str,
  708. MIN (s->len, IRC_MAX_MESSAGE_LENGTH));
  709. str_append (&c->write_buffer, "\r\n");
  710. // XXX: we might want to move this elsewhere, so that it doesn't get called
  711. // as often; it's going to cause a lot of syscalls with epoll.
  712. client_update_poller (c, NULL);
  713. // Technically we haven't sent it yet but that's a minor detail
  714. c->n_sent_messages++;
  715. c->sent_bytes += c->write_buffer.len - old_sendq;
  716. }
  717. static void
  718. client_send (struct client *c, const char *format, ...)
  719. {
  720. struct str tmp;
  721. str_init (&tmp);
  722. va_list ap;
  723. va_start (ap, format);
  724. str_append_vprintf (&tmp, format, ap);
  725. va_end (ap);
  726. client_send_str (c, &tmp);
  727. str_free (&tmp);
  728. }
  729. static void
  730. client_add_to_whowas (struct client *c)
  731. {
  732. // Only keeping one entry for each nickname
  733. // TODO: make sure this list doesn't get too long, for example by
  734. // putting them in a linked list ordered by time
  735. str_map_set (&c->ctx->whowas, c->nickname, whowas_info_new (c));
  736. }
  737. static void
  738. client_unregister (struct client *c, const char *reason)
  739. {
  740. if (!c->registered)
  741. return;
  742. char *message = xstrdup_printf (":%s!%s@%s QUIT :%s",
  743. c->nickname, c->username, c->hostname, reason);
  744. irc_send_to_roommates (c, message);
  745. free (message);
  746. struct str_map_unset_iter iter;
  747. str_map_unset_iter_init (&iter, &c->ctx->channels);
  748. struct channel *chan;
  749. while ((chan = str_map_unset_iter_next (&iter)))
  750. {
  751. struct channel_user *user;
  752. if (!(user = channel_get_user (chan, c)))
  753. continue;
  754. channel_remove_user (chan, user);
  755. irc_channel_destroy_if_empty (c->ctx, chan);
  756. }
  757. str_map_unset_iter_free (&iter);
  758. client_add_to_whowas (c);
  759. str_map_set (&c->ctx->users, c->nickname, NULL);
  760. free (c->nickname);
  761. c->nickname = NULL;
  762. c->registered = false;
  763. }
  764. static void
  765. client_kill (struct client *c, const char *reason)
  766. {
  767. struct server_context *ctx = c->ctx;
  768. client_unregister (c, reason ? reason : "Client exited");
  769. if (c->address)
  770. // Only log the event if address resolution has finished
  771. print_debug ("closed connection to %s (%s)", c->address,
  772. reason ? reason : "");
  773. if (c->ssl)
  774. // Note that we might have already called this once, but that is fine
  775. (void) SSL_shutdown (c->ssl);
  776. xclose (c->socket_fd);
  777. c->socket_fd = -1;
  778. c->socket_event.closed = true;
  779. poller_fd_reset (&c->socket_event);
  780. client_cancel_timers (c);
  781. LIST_UNLINK (ctx->clients, c);
  782. ctx->n_clients--;
  783. client_destroy (c);
  784. irc_try_finish_quit (ctx);
  785. }
  786. static void
  787. client_close_link (struct client *c, const char *reason)
  788. {
  789. // Let's just cut the connection, the client can try again later.
  790. // We also want to avoid accidentally setting poller events before
  791. // address resolution has finished.
  792. if (!c->initialized)
  793. {
  794. client_kill (c, reason);
  795. return;
  796. }
  797. if (!soft_assert (!c->closing_link))
  798. return;
  799. // We push an `ERROR' message to the write buffer and let the poller send
  800. // it, with some arbitrary timeout. The `closing_link' state makes sure
  801. // that a/ we ignore any successive messages, and b/ that the connection
  802. // is killed after the write buffer is transferred and emptied.
  803. client_send (c, "ERROR :Closing Link: %s[%s] (%s)",
  804. c->nickname ? c->nickname : "*",
  805. c->hostname /* TODO host IP? */, reason);
  806. c->closing_link = true;
  807. client_unregister (c, reason);
  808. client_set_kill_timer (c);
  809. }
  810. static bool
  811. client_in_mask_list (const struct client *c, const struct str_vector *mask)
  812. {
  813. char *client = xstrdup_printf ("%s!%s@%s",
  814. c->nickname, c->username, c->hostname);
  815. bool result = false;
  816. for (size_t i = 0; i < mask->len; i++)
  817. if (!irc_fnmatch (mask->vector[i], client))
  818. {
  819. result = true;
  820. break;
  821. }
  822. free (client);
  823. return result;
  824. }
  825. static char *
  826. client_get_ssl_cert_fingerprint (struct client *c)
  827. {
  828. if (!c->ssl)
  829. return NULL;
  830. X509 *peer_cert = SSL_get_peer_certificate (c->ssl);
  831. if (!peer_cert)
  832. return NULL;
  833. int cert_len = i2d_X509 (peer_cert, NULL);
  834. if (cert_len < 0)
  835. return NULL;
  836. unsigned char cert[cert_len], *p = cert;
  837. if (i2d_X509 (peer_cert, &p) < 0)
  838. return NULL;
  839. unsigned char hash[SHA_DIGEST_LENGTH];
  840. SHA1 (cert, cert_len, hash);
  841. struct str fingerprint;
  842. str_init (&fingerprint);
  843. for (size_t i = 0; i < sizeof hash; i++)
  844. str_append_printf (&fingerprint, "%02x", hash[i]);
  845. return str_steal (&fingerprint);
  846. }
  847. // --- Timers ------------------------------------------------------------------
  848. static void
  849. client_cancel_timers (struct client *c)
  850. {
  851. poller_timer_reset (&c->kill_timer);
  852. poller_timer_reset (&c->timeout_timer);
  853. poller_timer_reset (&c->ping_timer);
  854. poller_timer_reset (&c->gni_timer);
  855. }
  856. static void
  857. client_set_timer (struct client *c,
  858. struct poller_timer *timer, unsigned interval)
  859. {
  860. client_cancel_timers (c);
  861. poller_timer_set (timer, interval * 1000);
  862. }
  863. static void
  864. on_client_kill_timer (struct client *c)
  865. {
  866. hard_assert (!c->initialized || c->closing_link);
  867. client_kill (c, NULL);
  868. }
  869. static void
  870. client_set_kill_timer (struct client *c)
  871. {
  872. client_set_timer (c, &c->kill_timer, c->ctx->ping_interval);
  873. }
  874. static void
  875. on_client_timeout_timer (struct client *c)
  876. {
  877. char *reason = xstrdup_printf
  878. ("Ping timeout: >%u seconds", c->ctx->ping_interval);
  879. client_close_link (c, reason);
  880. free (reason);
  881. }
  882. static void
  883. on_client_ping_timer (struct client *c)
  884. {
  885. hard_assert (!c->closing_link);
  886. client_send (c, "PING :%s", c->ctx->server_name);
  887. client_set_timer (c, &c->timeout_timer, c->ctx->ping_interval);
  888. }
  889. static void
  890. client_set_ping_timer (struct client *c)
  891. {
  892. client_set_timer (c, &c->ping_timer, c->ctx->ping_interval);
  893. }
  894. // --- IRC command handling ----------------------------------------------------
  895. static void
  896. irc_make_reply (struct client *c, int id, va_list ap, struct str *output)
  897. {
  898. str_append_printf (output, ":%s %03d %s ",
  899. c->ctx->server_name, id, c->nickname ? c->nickname : "*");
  900. str_append_vprintf (output,
  901. irc_get_text (c->ctx, id, g_default_replies[id]), ap);
  902. }
  903. // XXX: this way we cannot typecheck the arguments, so we must be careful
  904. static void
  905. irc_send_reply (struct client *c, int id, ...)
  906. {
  907. struct str reply;
  908. str_init (&reply);
  909. va_list ap;
  910. va_start (ap, id);
  911. irc_make_reply (c, id, ap, &reply);
  912. va_end (ap);
  913. client_send_str (c, &reply);
  914. str_free (&reply);
  915. }
  916. /// Send a space-separated list of words across as many replies as needed
  917. static void
  918. irc_send_reply_vector (struct client *c, int id, char **items, ...)
  919. {
  920. struct str common;
  921. str_init (&common);
  922. va_list ap;
  923. va_start (ap, items);
  924. irc_make_reply (c, id, ap, &common);
  925. va_end (ap);
  926. // We always send at least one message (there might be a client that
  927. // expects us to send this message at least once)
  928. do
  929. {
  930. struct str reply;
  931. str_init (&reply);
  932. str_append_str (&reply, &common);
  933. // If not even a single item fits in the limit (which may happen,
  934. // in theory) it just gets cropped. We could also skip it.
  935. if (*items)
  936. str_append (&reply, *items++);
  937. // Append as many items as fits in a single message
  938. while (*items
  939. && reply.len + 1 + strlen (*items) <= IRC_MAX_MESSAGE_LENGTH)
  940. str_append_printf (&reply, " %s", *items++);
  941. client_send_str (c, &reply);
  942. str_free (&reply);
  943. }
  944. while (*items);
  945. str_free (&common);
  946. }
  947. #define RETURN_WITH_REPLY(c, ...) \
  948. BLOCK_START \
  949. irc_send_reply ((c), __VA_ARGS__); \
  950. return; \
  951. BLOCK_END
  952. static void
  953. irc_send_motd (struct client *c)
  954. {
  955. struct server_context *ctx = c->ctx;
  956. if (!ctx->motd.len)
  957. RETURN_WITH_REPLY (c, IRC_ERR_NOMOTD);
  958. irc_send_reply (c, IRC_RPL_MOTDSTART, ctx->server_name);
  959. for (size_t i = 0; i < ctx->motd.len; i++)
  960. irc_send_reply (c, IRC_RPL_MOTD, ctx->motd.vector[i]);
  961. irc_send_reply (c, IRC_RPL_ENDOFMOTD);
  962. }
  963. static void
  964. irc_send_lusers (struct client *c)
  965. {
  966. int n_users = 0, n_services = 0, n_opers = 0, n_unknown = 0;
  967. for (struct client *link = c->ctx->clients; link; link = link->next)
  968. {
  969. if (link->registered)
  970. n_users++;
  971. else
  972. n_unknown++;
  973. if (link->mode & IRC_USER_MODE_OPERATOR)
  974. n_opers++;
  975. }
  976. int n_channels = 0;
  977. struct str_map_iter iter;
  978. str_map_iter_init (&iter, &c->ctx->channels);
  979. struct channel *chan;
  980. while ((chan = str_map_iter_next (&iter)))
  981. if (!(chan->modes & IRC_CHAN_MODE_SECRET)
  982. || channel_get_user (chan, c))
  983. n_channels++;
  984. irc_send_reply (c, IRC_RPL_LUSERCLIENT,
  985. n_users, n_services, 1 /* servers total */);
  986. if (n_opers)
  987. irc_send_reply (c, IRC_RPL_LUSEROP, n_opers);
  988. if (n_unknown)
  989. irc_send_reply (c, IRC_RPL_LUSERUNKNOWN, n_unknown);
  990. if (n_channels)
  991. irc_send_reply (c, IRC_RPL_LUSERCHANNELS, n_channels);
  992. irc_send_reply (c, IRC_RPL_LUSERME,
  993. n_users + n_services + n_unknown, 0 /* peer servers */);
  994. }
  995. static bool
  996. irc_is_this_me (struct server_context *ctx, const char *target)
  997. {
  998. // Target servers can also be matched by their users
  999. return !irc_fnmatch (target, ctx->server_name)
  1000. || str_map_find (&ctx->users, target);
  1001. }
  1002. static void
  1003. irc_send_isupport (struct client *c)
  1004. {
  1005. // Only # channels, +e supported, +I supported, unlimited arguments to MODE
  1006. irc_send_reply (c, IRC_RPL_ISUPPORT, "CHANTYPES=# EXCEPTS INVEX MODES"
  1007. " TARGMAX=WHOIS:,LIST:,NAMES:,PRIVMSG:1,NOTICE:1,KICK:"
  1008. " NICKLEN=" XSTRINGIFY (IRC_MAX_NICKNAME)
  1009. " CHANNELLEN=" XSTRINGIFY (IRC_MAX_CHANNEL_NAME));
  1010. }
  1011. static void
  1012. irc_try_finish_registration (struct client *c)
  1013. {
  1014. struct server_context *ctx = c->ctx;
  1015. if (!c->nickname || !c->username || !c->realname)
  1016. return;
  1017. if (c->registered || c->cap_negotiating)
  1018. return;
  1019. c->registered = true;
  1020. irc_send_reply (c, IRC_RPL_WELCOME, c->nickname, c->username, c->hostname);
  1021. irc_send_reply (c, IRC_RPL_YOURHOST, ctx->server_name, PROGRAM_VERSION);
  1022. // The purpose of this message eludes me
  1023. irc_send_reply (c, IRC_RPL_CREATED, __DATE__);
  1024. irc_send_reply (c, IRC_RPL_MYINFO, ctx->server_name, PROGRAM_VERSION,
  1025. IRC_SUPPORTED_USER_MODES, IRC_SUPPORTED_CHAN_MODES);
  1026. irc_send_isupport (c);
  1027. irc_send_lusers (c);
  1028. irc_send_motd (c);
  1029. char *mode = client_get_mode (c);
  1030. if (*mode)
  1031. client_send (c, ":%s MODE %s :+%s", c->nickname, c->nickname, mode);
  1032. free (mode);
  1033. hard_assert (c->ssl_cert_fingerprint == NULL);
  1034. if ((c->ssl_cert_fingerprint = client_get_ssl_cert_fingerprint (c)))
  1035. client_send (c, ":%s NOTICE %s :"
  1036. "Your TLS client certificate fingerprint is %s",
  1037. ctx->server_name, c->nickname, c->ssl_cert_fingerprint);
  1038. str_map_set (&ctx->whowas, c->nickname, NULL);
  1039. }
  1040. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1041. // IRCv3 capability negotiation. See http://ircv3.org for details.
  1042. struct irc_cap_args
  1043. {
  1044. const char *subcommand; ///< The subcommand being processed
  1045. const char *full_params; ///< Whole parameter string
  1046. struct str_vector params; ///< Split parameters
  1047. const char *target; ///< Target parameter for replies
  1048. };
  1049. static struct
  1050. {
  1051. unsigned flag; ///< Flag
  1052. const char *name; ///< Name of the capability
  1053. }
  1054. irc_cap_table[] =
  1055. {
  1056. { IRC_CAP_MULTI_PREFIX, "multi-prefix" },
  1057. { IRC_CAP_INVITE_NOTIFY, "invite-notify" },
  1058. { IRC_CAP_ECHO_MESSAGE, "echo-message" },
  1059. { IRC_CAP_USERHOST_IN_NAMES, "userhost-in-names" },
  1060. { IRC_CAP_SERVER_TIME, "server-time" },
  1061. };
  1062. static void
  1063. irc_handle_cap_ls (struct client *c, struct irc_cap_args *a)
  1064. {
  1065. if (a->params.len == 1
  1066. && !xstrtoul (&c->cap_version, a->params.vector[0], 10))
  1067. irc_send_reply (c, IRC_ERR_INVALIDCAPCMD,
  1068. a->subcommand, "Ignoring invalid protocol version number");
  1069. c->cap_negotiating = true;
  1070. client_send (c, ":%s CAP %s LS :multi-prefix invite-notify echo-message"
  1071. " userhost-in-names server-time", c->ctx->server_name, a->target);
  1072. }
  1073. static void
  1074. irc_handle_cap_list (struct client *c, struct irc_cap_args *a)
  1075. {
  1076. struct str_vector caps;
  1077. str_vector_init (&caps);
  1078. for (size_t i = 0; i < N_ELEMENTS (irc_cap_table); i++)
  1079. if (c->caps_enabled & irc_cap_table[i].flag)
  1080. str_vector_add (&caps, irc_cap_table[i].name);
  1081. char *caps_str = join_str_vector (&caps, ' ');
  1082. str_vector_free (&caps);
  1083. client_send (c, ":%s CAP %s LIST :%s",
  1084. c->ctx->server_name, a->target, caps_str);
  1085. free (caps_str);
  1086. }
  1087. static unsigned
  1088. irc_decode_capability (const char *name)
  1089. {
  1090. for (size_t i = 0; i < N_ELEMENTS (irc_cap_table); i++)
  1091. if (!strcmp (irc_cap_table[i].name, name))
  1092. return irc_cap_table[i].flag;
  1093. return 0;
  1094. }
  1095. static void
  1096. irc_handle_cap_req (struct client *c, struct irc_cap_args *a)
  1097. {
  1098. c->cap_negotiating = true;
  1099. unsigned new_caps = c->caps_enabled;
  1100. bool success = true;
  1101. for (size_t i = 0; i < a->params.len; i++)
  1102. {
  1103. bool removing = false;
  1104. const char *name = a->params.vector[i];
  1105. if (*name == '-')
  1106. {
  1107. removing = true;
  1108. name++;
  1109. }
  1110. unsigned cap;
  1111. if (!(cap = irc_decode_capability (name)))
  1112. success = false;
  1113. else if (removing)
  1114. new_caps &= ~cap;
  1115. else
  1116. new_caps |= cap;
  1117. }
  1118. if (success)
  1119. {
  1120. c->caps_enabled = new_caps;
  1121. client_send (c, ":%s CAP %s ACK :%s",
  1122. c->ctx->server_name, a->target, a->full_params);
  1123. }
  1124. else
  1125. client_send (c, ":%s CAP %s NAK :%s",
  1126. c->ctx->server_name, a->target, a->full_params);
  1127. }
  1128. static void
  1129. irc_handle_cap_ack (struct client *c, struct irc_cap_args *a)
  1130. {
  1131. if (a->params.len)
  1132. irc_send_reply (c, IRC_ERR_INVALIDCAPCMD,
  1133. a->subcommand, "No acknowledgable capabilities supported");
  1134. }
  1135. static void
  1136. irc_handle_cap_end (struct client *c, struct irc_cap_args *a)
  1137. {
  1138. (void) a;
  1139. c->cap_negotiating = false;
  1140. irc_try_finish_registration (c);
  1141. }
  1142. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1143. struct irc_cap_command
  1144. {
  1145. const char *name;
  1146. void (*handler) (struct client *, struct irc_cap_args *);
  1147. };
  1148. static void
  1149. irc_register_cap_handlers (struct server_context *ctx)
  1150. {
  1151. static const struct irc_cap_command cap_handlers[] =
  1152. {
  1153. { "LS", irc_handle_cap_ls },
  1154. { "LIST", irc_handle_cap_list },
  1155. { "REQ", irc_handle_cap_req },
  1156. { "ACK", irc_handle_cap_ack },
  1157. { "END", irc_handle_cap_end },
  1158. };
  1159. for (size_t i = 0; i < N_ELEMENTS (cap_handlers); i++)
  1160. {
  1161. const struct irc_cap_command *cmd = &cap_handlers[i];
  1162. str_map_set (&ctx->cap_handlers, cmd->name, (void *) cmd);
  1163. }
  1164. }
  1165. static void
  1166. irc_handle_cap (const struct irc_message *msg, struct client *c)
  1167. {
  1168. if (msg->params.len < 1)
  1169. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1170. struct irc_cap_args args;
  1171. args.target = c->nickname ? c->nickname : "*";
  1172. args.subcommand = msg->params.vector[0];
  1173. args.full_params = "";
  1174. str_vector_init (&args.params);
  1175. if (msg->params.len > 1)
  1176. {
  1177. args.full_params = msg->params.vector[1];
  1178. cstr_split_ignore_empty (args.full_params, ' ', &args.params);
  1179. }
  1180. struct irc_cap_command *cmd =
  1181. str_map_find (&c->ctx->cap_handlers, args.subcommand);
  1182. if (!cmd)
  1183. irc_send_reply (c, IRC_ERR_INVALIDCAPCMD,
  1184. args.subcommand, "Invalid CAP subcommand");
  1185. else
  1186. cmd->handler (c, &args);
  1187. str_vector_free (&args.params);
  1188. }
  1189. static void
  1190. irc_handle_pass (const struct irc_message *msg, struct client *c)
  1191. {
  1192. if (c->registered)
  1193. irc_send_reply (c, IRC_ERR_ALREADYREGISTERED);
  1194. else if (msg->params.len < 1)
  1195. irc_send_reply (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1196. // We have TLS client certificates for this purpose; ignoring
  1197. }
  1198. static void
  1199. irc_handle_nick (const struct irc_message *msg, struct client *c)
  1200. {
  1201. struct server_context *ctx = c->ctx;
  1202. if (msg->params.len < 1)
  1203. RETURN_WITH_REPLY (c, IRC_ERR_NONICKNAMEGIVEN);
  1204. const char *nickname = msg->params.vector[0];
  1205. if (irc_validate_nickname (nickname) != VALIDATION_OK)
  1206. RETURN_WITH_REPLY (c, IRC_ERR_ERRONEOUSNICKNAME, nickname);
  1207. struct client *client = str_map_find (&ctx->users, nickname);
  1208. if (client && client != c)
  1209. RETURN_WITH_REPLY (c, IRC_ERR_NICKNAMEINUSE, nickname);
  1210. if (c->registered)
  1211. {
  1212. client_add_to_whowas (c);
  1213. char *message = xstrdup_printf (":%s!%s@%s NICK :%s",
  1214. c->nickname, c->username, c->hostname, nickname);
  1215. irc_send_to_roommates (c, message);
  1216. client_send (c, "%s", message);
  1217. free (message);
  1218. }
  1219. // Release the old nickname and allocate a new one
  1220. if (c->nickname)
  1221. {
  1222. str_map_set (&ctx->users, c->nickname, NULL);
  1223. free (c->nickname);
  1224. }
  1225. c->nickname = xstrdup (nickname);
  1226. str_map_set (&ctx->users, nickname, c);
  1227. if (!c->registered)
  1228. irc_try_finish_registration (c);
  1229. }
  1230. static void
  1231. irc_handle_user (const struct irc_message *msg, struct client *c)
  1232. {
  1233. if (c->registered)
  1234. RETURN_WITH_REPLY (c, IRC_ERR_ALREADYREGISTERED);
  1235. if (msg->params.len < 4)
  1236. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1237. const char *username = msg->params.vector[0];
  1238. const char *mode = msg->params.vector[1];
  1239. const char *realname = msg->params.vector[3];
  1240. // Unfortunately the protocol doesn't give us any means of rejecting it
  1241. if (!irc_is_valid_user (username))
  1242. username = "xxx";
  1243. free (c->username);
  1244. c->username = xstrdup (username);
  1245. free (c->realname);
  1246. c->realname = xstrdup (realname);
  1247. unsigned long m;
  1248. if (xstrtoul (&m, mode, 10))
  1249. {
  1250. if (m & 4) c->mode |= IRC_USER_MODE_RX_WALLOPS;
  1251. if (m & 8) c->mode |= IRC_USER_MODE_INVISIBLE;
  1252. }
  1253. irc_try_finish_registration (c);
  1254. }
  1255. static void
  1256. irc_handle_userhost (const struct irc_message *msg, struct client *c)
  1257. {
  1258. if (msg->params.len < 1)
  1259. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1260. struct str reply;
  1261. str_init (&reply);
  1262. for (size_t i = 0; i < 5 && i < msg->params.len; i++)
  1263. {
  1264. const char *nick = msg->params.vector[i];
  1265. struct client *target = str_map_find (&c->ctx->users, nick);
  1266. if (!target)
  1267. continue;
  1268. if (i)
  1269. str_append_c (&reply, ' ');
  1270. str_append (&reply, nick);
  1271. if (target->mode & IRC_USER_MODE_OPERATOR)
  1272. str_append_c (&reply, '*');
  1273. str_append_printf (&reply, "=%c%s@%s",
  1274. target->away_message ? '-' : '+',
  1275. target->username, target->hostname);
  1276. }
  1277. irc_send_reply (c, IRC_RPL_USERHOST, reply.str);
  1278. str_free (&reply);
  1279. }
  1280. static void
  1281. irc_handle_lusers (const struct irc_message *msg, struct client *c)
  1282. {
  1283. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1284. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1285. else
  1286. irc_send_lusers (c);
  1287. }
  1288. static void
  1289. irc_handle_motd (const struct irc_message *msg, struct client *c)
  1290. {
  1291. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1292. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1293. else
  1294. irc_send_motd (c);
  1295. }
  1296. static void
  1297. irc_handle_ping (const struct irc_message *msg, struct client *c)
  1298. {
  1299. // XXX: the RFC is pretty incomprehensible about the exact usage
  1300. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1301. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1302. else if (msg->params.len < 1)
  1303. irc_send_reply (c, IRC_ERR_NOORIGIN);
  1304. else
  1305. client_send (c, ":%s PONG :%s",
  1306. c->ctx->server_name, msg->params.vector[0]);
  1307. }
  1308. static void
  1309. irc_handle_pong (const struct irc_message *msg, struct client *c)
  1310. {
  1311. // We are the only server, so we don't have to care too much
  1312. if (msg->params.len < 1)
  1313. irc_send_reply (c, IRC_ERR_NOORIGIN);
  1314. else
  1315. // Set a new timer to send another PING
  1316. client_set_ping_timer (c);
  1317. }
  1318. static void
  1319. irc_handle_quit (const struct irc_message *msg, struct client *c)
  1320. {
  1321. char *reason = xstrdup_printf ("Quit: %s",
  1322. msg->params.len > 0 ? msg->params.vector[0] : c->nickname);
  1323. client_close_link (c, reason);
  1324. free (reason);
  1325. }
  1326. static void
  1327. irc_handle_time (const struct irc_message *msg, struct client *c)
  1328. {
  1329. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1330. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1331. char buf[32];
  1332. time_t now = time (NULL);
  1333. struct tm tm;
  1334. strftime (buf, sizeof buf, "%a %b %d %Y %T", localtime_r (&now, &tm));
  1335. irc_send_reply (c, IRC_RPL_TIME, c->ctx->server_name, buf);
  1336. }
  1337. static void
  1338. irc_handle_version (const struct irc_message *msg, struct client *c)
  1339. {
  1340. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1341. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1342. irc_send_reply (c, IRC_RPL_VERSION, PROGRAM_VERSION, g_debug_mode,
  1343. c->ctx->server_name, PROGRAM_NAME " " PROGRAM_VERSION);
  1344. irc_send_isupport (c);
  1345. }
  1346. static void
  1347. irc_channel_multicast (struct channel *chan, const char *message,
  1348. struct client *except)
  1349. {
  1350. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  1351. if (iter->c != except)
  1352. client_send (iter->c, "%s", message);
  1353. }
  1354. static bool
  1355. irc_modify_mode (unsigned *mask, unsigned mode, bool add)
  1356. {
  1357. unsigned orig = *mask;
  1358. if (add)
  1359. *mask |= mode;
  1360. else
  1361. *mask &= ~mode;
  1362. return *mask != orig;
  1363. }
  1364. static void
  1365. irc_update_user_mode (struct client *c, unsigned new_mode)
  1366. {
  1367. unsigned old_mode = c->mode;
  1368. c->mode = new_mode;
  1369. unsigned added = new_mode & ~old_mode;
  1370. unsigned removed = old_mode & ~new_mode;
  1371. struct str diff;
  1372. str_init (&diff);
  1373. if (added)
  1374. {
  1375. str_append_c (&diff, '+');
  1376. client_mode_to_str (added, &diff);
  1377. }
  1378. if (removed)
  1379. {
  1380. str_append_c (&diff, '-');
  1381. client_mode_to_str (removed, &diff);
  1382. }
  1383. if (diff.len)
  1384. client_send (c, ":%s MODE %s :%s",
  1385. c->nickname, c->nickname, diff.str);
  1386. str_free (&diff);
  1387. }
  1388. static void
  1389. irc_handle_user_mode_change (struct client *c, const char *mode_string)
  1390. {
  1391. unsigned new_mode = c->mode;
  1392. bool adding = true;
  1393. while (*mode_string)
  1394. switch (*mode_string++)
  1395. {
  1396. case '+': adding = true; break;
  1397. case '-': adding = false; break;
  1398. case 'a':
  1399. // Ignore, the client should use AWAY
  1400. break;
  1401. case 'i':
  1402. irc_modify_mode (&new_mode, IRC_USER_MODE_INVISIBLE, adding);
  1403. break;
  1404. case 'w':
  1405. irc_modify_mode (&new_mode, IRC_USER_MODE_RX_WALLOPS, adding);
  1406. break;
  1407. case 'r':
  1408. // It's not possible to un-restrict yourself
  1409. if (adding)
  1410. new_mode |= IRC_USER_MODE_RESTRICTED;
  1411. break;
  1412. case 'o':
  1413. if (!adding)
  1414. new_mode &= ~IRC_USER_MODE_OPERATOR;
  1415. else if (c->ssl_cert_fingerprint
  1416. && str_map_find (&c->ctx->operators, c->ssl_cert_fingerprint))
  1417. new_mode |= IRC_USER_MODE_OPERATOR;
  1418. else
  1419. client_send (c, ":%s NOTICE %s :Either you're not using an TLS"
  1420. " client certificate, or the fingerprint doesn't match",
  1421. c->ctx->server_name, c->nickname);
  1422. break;
  1423. case 's':
  1424. irc_modify_mode (&new_mode, IRC_USER_MODE_RX_SERVER_NOTICES, adding);
  1425. break;
  1426. default:
  1427. RETURN_WITH_REPLY (c, IRC_ERR_UMODEUNKNOWNFLAG);
  1428. }
  1429. irc_update_user_mode (c, new_mode);
  1430. }
  1431. static void
  1432. irc_send_channel_list (struct client *c, const char *channel_name,
  1433. const struct str_vector *list, int reply, int end_reply)
  1434. {
  1435. for (size_t i = 0; i < list->len; i++)
  1436. irc_send_reply (c, reply, channel_name, list->vector[i]);
  1437. irc_send_reply (c, end_reply, channel_name);
  1438. }
  1439. static char *
  1440. irc_check_expand_user_mask (const char *mask)
  1441. {
  1442. struct str result;
  1443. str_init (&result);
  1444. str_append (&result, mask);
  1445. // Make sure it is a complete mask
  1446. if (!strchr (result.str, '!'))
  1447. str_append (&result, "!*");
  1448. if (!strchr (result.str, '@'))
  1449. str_append (&result, "@*");
  1450. // And validate whatever the result is
  1451. if (!irc_is_valid_user_mask (result.str))
  1452. {
  1453. str_free (&result);
  1454. return NULL;
  1455. }
  1456. return str_steal (&result);
  1457. }
  1458. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1459. // Channel MODE command handling. This is by far the worst command to implement
  1460. // from the whole RFC; don't blame me if it doesn't work exactly as expected.
  1461. struct mode_processor
  1462. {
  1463. // Inputs to set after initialization:
  1464. char **params; ///< Mode string parameters
  1465. struct client *c; ///< Who does the changes
  1466. struct channel *channel; ///< The channel we're modifying
  1467. struct channel_user *user; ///< Presence of the client in the chan
  1468. // Internals:
  1469. bool adding; ///< Currently adding modes
  1470. char mode_char; ///< Currently processed mode char
  1471. struct str added; ///< Added modes
  1472. struct str removed; ///< Removed modes
  1473. struct str_vector added_params; ///< Params for added modes
  1474. struct str_vector removed_params; ///< Params for removed modes
  1475. struct str *output; ///< "added" or "removed"
  1476. struct str_vector *output_params; ///< Similarly for "*_params"
  1477. };
  1478. static void
  1479. mode_processor_init (struct mode_processor *self)
  1480. {
  1481. memset (self, 0, sizeof *self);
  1482. str_init (&self->added);
  1483. str_init (&self->removed);
  1484. str_vector_init (&self->added_params);
  1485. str_vector_init (&self->removed_params);
  1486. }
  1487. static void
  1488. mode_processor_free (struct mode_processor *self)
  1489. {
  1490. str_free (&self->added);
  1491. str_free (&self->removed);
  1492. str_vector_free (&self->added_params);
  1493. str_vector_free (&self->removed_params);
  1494. }
  1495. static const char *
  1496. mode_processor_next_param (struct mode_processor *self)
  1497. {
  1498. if (!*self->params)
  1499. return NULL;
  1500. return *self->params++;
  1501. }
  1502. static bool
  1503. mode_processor_check_operator (struct mode_processor *self)
  1504. {
  1505. if ((self->user && (self->user->modes & IRC_CHAN_MODE_OPERATOR))
  1506. || (self->c->mode & IRC_USER_MODE_OPERATOR))
  1507. return true;
  1508. irc_send_reply (self->c, IRC_ERR_CHANOPRIVSNEEDED, self->channel->name);
  1509. return false;
  1510. }
  1511. static void
  1512. mode_processor_do_user (struct mode_processor *self, int mode)
  1513. {
  1514. const char *target = mode_processor_next_param (self);
  1515. if (!mode_processor_check_operator (self) || !target)
  1516. return;
  1517. struct client *client;
  1518. struct channel_user *target_user;
  1519. if (!(client = str_map_find (&self->c->ctx->users, target)))
  1520. irc_send_reply (self->c, IRC_ERR_NOSUCHNICK, target);
  1521. else if (!(target_user = channel_get_user (self->channel, client)))
  1522. irc_send_reply (self->c, IRC_ERR_USERNOTINCHANNEL,
  1523. target, self->channel->name);
  1524. else if (irc_modify_mode (&target_user->modes, mode, self->adding))
  1525. {
  1526. str_append_c (self->output, self->mode_char);
  1527. str_vector_add (self->output_params, client->nickname);
  1528. }
  1529. }
  1530. static bool
  1531. mode_processor_do_chan (struct mode_processor *self, int mode)
  1532. {
  1533. if (!mode_processor_check_operator (self)
  1534. || !irc_modify_mode (&self->channel->modes, mode, self->adding))
  1535. return false;
  1536. str_append_c (self->output, self->mode_char);
  1537. return true;
  1538. }
  1539. static void
  1540. mode_processor_do_chan_remove
  1541. (struct mode_processor *self, char mode_char, int mode)
  1542. {
  1543. if (self->adding
  1544. && irc_modify_mode (&self->channel->modes, mode, false))
  1545. str_append_c (&self->removed, mode_char);
  1546. }
  1547. static void
  1548. mode_processor_do_list (struct mode_processor *self,
  1549. struct str_vector *list, int list_msg, int end_msg)
  1550. {
  1551. const char *target = mode_processor_next_param (self);
  1552. if (!target)
  1553. {
  1554. if (self->adding)
  1555. irc_send_channel_list (self->c, self->channel->name,
  1556. list, list_msg, end_msg);
  1557. return;
  1558. }
  1559. if (!mode_processor_check_operator (self))
  1560. return;
  1561. char *mask = irc_check_expand_user_mask (target);
  1562. if (!mask)
  1563. return;
  1564. size_t i;
  1565. for (i = 0; i < list->len; i++)
  1566. if (!irc_strcmp (list->vector[i], mask))
  1567. break;
  1568. bool found = i != list->len;
  1569. if ((found ^ self->adding))
  1570. {
  1571. if (self->adding)
  1572. str_vector_add (list, mask);
  1573. else
  1574. str_vector_remove (list, i);
  1575. str_append_c (self->output, self->mode_char);
  1576. str_vector_add (self->output_params, mask);
  1577. }
  1578. free (mask);
  1579. }
  1580. static void
  1581. mode_processor_do_key (struct mode_processor *self)
  1582. {
  1583. const char *target = mode_processor_next_param (self);
  1584. if (!mode_processor_check_operator (self) || !target)
  1585. return;
  1586. if (!self->adding)
  1587. {
  1588. if (!self->channel->key || irc_strcmp (target, self->channel->key))
  1589. return;
  1590. str_append_c (&self->removed, self->mode_char);
  1591. str_vector_add (&self->removed_params, self->channel->key);
  1592. free (self->channel->key);
  1593. self->channel->key = NULL;
  1594. }
  1595. else if (!irc_is_valid_key (target))
  1596. // TODO: we should notify the user somehow
  1597. return;
  1598. else if (self->channel->key)
  1599. irc_send_reply (self->c, IRC_ERR_KEYSET, self->channel->name);
  1600. else
  1601. {
  1602. self->channel->key = xstrdup (target);
  1603. str_append_c (&self->added, self->mode_char);
  1604. str_vector_add (&self->added_params, self->channel->key);
  1605. }
  1606. }
  1607. static void
  1608. mode_processor_do_limit (struct mode_processor *self)
  1609. {
  1610. if (!mode_processor_check_operator (self))
  1611. return;
  1612. const char *target;
  1613. if (!self->adding)
  1614. {
  1615. if (self->channel->user_limit == -1)
  1616. return;
  1617. self->channel->user_limit = -1;
  1618. str_append_c (&self->removed, self->mode_char);
  1619. }
  1620. else if ((target = mode_processor_next_param (self)))
  1621. {
  1622. unsigned long x;
  1623. if (xstrtoul (&x, target, 10) && x > 0 && x <= LONG_MAX)
  1624. {
  1625. self->channel->user_limit = x;
  1626. str_append_c (&self->added, self->mode_char);
  1627. str_vector_add (&self->added_params, target);
  1628. }
  1629. }
  1630. }
  1631. static bool
  1632. mode_processor_step (struct mode_processor *self, char mode_char)
  1633. {
  1634. switch ((self->mode_char = mode_char))
  1635. {
  1636. case '+':
  1637. self->adding = true;
  1638. self->output = &self->added;
  1639. self->output_params = &self->added_params;
  1640. break;
  1641. case '-':
  1642. self->adding = false;
  1643. self->output = &self->removed;
  1644. self->output_params = &self->removed_params;
  1645. break;
  1646. #define USER(mode) mode_processor_do_user (self, (mode))
  1647. #define CHAN(mode) mode_processor_do_chan (self, (mode))
  1648. case 'o': USER (IRC_CHAN_MODE_OPERATOR); break;
  1649. case 'v': USER (IRC_CHAN_MODE_VOICE); break;
  1650. case 'i': CHAN (IRC_CHAN_MODE_INVITE_ONLY); break;
  1651. case 'm': CHAN (IRC_CHAN_MODE_MODERATED); break;
  1652. case 'n': CHAN (IRC_CHAN_MODE_NO_OUTSIDE_MSGS); break;
  1653. case 'q': CHAN (IRC_CHAN_MODE_QUIET); break;
  1654. case 't': CHAN (IRC_CHAN_MODE_PROTECTED_TOPIC); break;
  1655. case 'p':
  1656. if (CHAN (IRC_CHAN_MODE_PRIVATE))
  1657. mode_processor_do_chan_remove (self, 's', IRC_CHAN_MODE_SECRET);
  1658. break;
  1659. case 's':
  1660. if (CHAN (IRC_CHAN_MODE_SECRET))
  1661. mode_processor_do_chan_remove (self, 'p', IRC_CHAN_MODE_PRIVATE);
  1662. break;
  1663. #undef USER
  1664. #undef CHAN
  1665. case 'b':
  1666. mode_processor_do_list (self, &self->channel->ban_list,
  1667. IRC_RPL_BANLIST, IRC_RPL_ENDOFBANLIST);
  1668. break;
  1669. case 'e':
  1670. mode_processor_do_list (self, &self->channel->exception_list,
  1671. IRC_RPL_EXCEPTLIST, IRC_RPL_ENDOFEXCEPTLIST);
  1672. break;
  1673. case 'I':
  1674. mode_processor_do_list (self, &self->channel->invite_list,
  1675. IRC_RPL_INVITELIST, IRC_RPL_ENDOFINVITELIST);
  1676. break;
  1677. case 'k':
  1678. mode_processor_do_key (self);
  1679. break;
  1680. case 'l':
  1681. mode_processor_do_limit (self);
  1682. break;
  1683. default:
  1684. // It's not safe to continue, results could be undesired
  1685. irc_send_reply (self->c, IRC_ERR_UNKNOWNMODE,
  1686. mode_char, self->channel->name);
  1687. return false;
  1688. }
  1689. return true;
  1690. }
  1691. static void
  1692. irc_handle_chan_mode_change
  1693. (struct client *c, struct channel *chan, char *params[])
  1694. {
  1695. struct mode_processor p;
  1696. mode_processor_init (&p);
  1697. p.params = params;
  1698. p.channel = chan;
  1699. p.c = c;
  1700. p.user = channel_get_user (chan, c);
  1701. const char *mode_string;
  1702. while ((mode_string = mode_processor_next_param (&p)))
  1703. {
  1704. mode_processor_step (&p, '+');
  1705. while (*mode_string)
  1706. if (!mode_processor_step (&p, *mode_string++))
  1707. break;
  1708. }
  1709. // TODO: limit to three changes with parameter per command
  1710. if (p.added.len || p.removed.len)
  1711. {
  1712. struct str message;
  1713. str_init (&message);
  1714. str_append_printf (&message, ":%s!%s@%s MODE %s ",
  1715. p.c->nickname, p.c->username, p.c->hostname,
  1716. p.channel->name);
  1717. if (p.added.len)
  1718. str_append_printf (&message, "+%s", p.added.str);
  1719. if (p.removed.len)
  1720. str_append_printf (&message, "-%s", p.removed.str);
  1721. for (size_t i = 0; i < p.added_params.len; i++)
  1722. str_append_printf (&message, " %s", p.added_params.vector[i]);
  1723. for (size_t i = 0; i < p.removed_params.len; i++)
  1724. str_append_printf (&message, " %s", p.removed_params.vector[i]);
  1725. irc_channel_multicast (p.channel, message.str, NULL);
  1726. str_free (&message);
  1727. }
  1728. mode_processor_free (&p);
  1729. }
  1730. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1731. static void
  1732. irc_handle_mode (const struct irc_message *msg, struct client *c)
  1733. {
  1734. if (msg->params.len < 1)
  1735. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1736. const char *target = msg->params.vector[0];
  1737. struct client *client = str_map_find (&c->ctx->users, target);
  1738. struct channel *chan = str_map_find (&c->ctx->channels, target);
  1739. if (client)
  1740. {
  1741. if (irc_strcmp (target, c->nickname))
  1742. RETURN_WITH_REPLY (c, IRC_ERR_USERSDONTMATCH);
  1743. if (msg->params.len < 2)
  1744. {
  1745. char *mode = client_get_mode (client);
  1746. irc_send_reply (c, IRC_RPL_UMODEIS, mode);
  1747. free (mode);
  1748. }
  1749. else
  1750. irc_handle_user_mode_change (c, msg->params.vector[1]);
  1751. }
  1752. else if (chan)
  1753. {
  1754. if (msg->params.len < 2)
  1755. {
  1756. char *mode = channel_get_mode (chan, channel_get_user (chan, c));
  1757. irc_send_reply (c, IRC_RPL_CHANNELMODEIS, target, mode);
  1758. irc_send_reply (c, IRC_RPL_CREATIONTIME,
  1759. target, (long long) chan->created);
  1760. free (mode);
  1761. }
  1762. else
  1763. irc_handle_chan_mode_change (c, chan, &msg->params.vector[1]);
  1764. }
  1765. else
  1766. irc_send_reply (c, IRC_ERR_NOSUCHNICK, target);
  1767. }
  1768. static void
  1769. irc_handle_user_message (const struct irc_message *msg, struct client *c,
  1770. const char *command, bool allow_away_reply)
  1771. {
  1772. if (msg->params.len < 1)
  1773. RETURN_WITH_REPLY (c, IRC_ERR_NORECIPIENT, msg->command);
  1774. if (msg->params.len < 2 || !*msg->params.vector[1])
  1775. RETURN_WITH_REPLY (c, IRC_ERR_NOTEXTTOSEND);
  1776. const char *target = msg->params.vector[0];
  1777. const char *text = msg->params.vector[1];
  1778. struct client *client = str_map_find (&c->ctx->users, target);
  1779. if (client)
  1780. {
  1781. client_send (client, ":%s!%s@%s %s %s :%s",
  1782. c->nickname, c->username, c->hostname, command, target, text);
  1783. if (allow_away_reply && client->away_message)
  1784. irc_send_reply (c, IRC_RPL_AWAY, target, client->away_message);
  1785. // Acknowledging a message from the client to itself would be silly
  1786. if (client != c && (c->caps_enabled & IRC_CAP_ECHO_MESSAGE))
  1787. client_send (c, ":%s!%s@%s %s %s :%s",
  1788. c->nickname, c->username, c->hostname, command, target, text);
  1789. return;
  1790. }
  1791. struct channel *chan = str_map_find (&c->ctx->channels, target);
  1792. if (chan)
  1793. {
  1794. struct channel_user *user = channel_get_user (chan, c);
  1795. if ((chan->modes & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) && !user)
  1796. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1797. if ((chan->modes & IRC_CHAN_MODE_MODERATED) && (!user ||
  1798. !(user->modes & (IRC_CHAN_MODE_VOICE | IRC_CHAN_MODE_OPERATOR))))
  1799. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1800. if (client_in_mask_list (c, &chan->ban_list)
  1801. && !client_in_mask_list (c, &chan->exception_list))
  1802. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1803. char *message = xstrdup_printf (":%s!%s@%s %s %s :%s",
  1804. c->nickname, c->username, c->hostname, command, target, text);
  1805. irc_channel_multicast (chan, message,
  1806. (c->caps_enabled & IRC_CAP_ECHO_MESSAGE) ? NULL : c);
  1807. free (message);
  1808. return;
  1809. }
  1810. irc_send_reply (c, IRC_ERR_NOSUCHNICK, target);
  1811. }
  1812. static void
  1813. irc_handle_privmsg (const struct irc_message *msg, struct client *c)
  1814. {
  1815. irc_handle_user_message (msg, c, "PRIVMSG", true);
  1816. // Let's not care too much about success or failure
  1817. c->last_active = time (NULL);
  1818. }
  1819. static void
  1820. irc_handle_notice (const struct irc_message *msg, struct client *c)
  1821. {
  1822. irc_handle_user_message (msg, c, "NOTICE", false);
  1823. }
  1824. static void
  1825. irc_send_rpl_list (struct client *c, const struct channel *chan)
  1826. {
  1827. int visible = 0;
  1828. for (struct channel_user *user = chan->users;
  1829. user; user = user->next)
  1830. visible++;
  1831. irc_send_reply (c, IRC_RPL_LIST, chan->name, visible, chan->topic);
  1832. }
  1833. static void
  1834. irc_handle_list (const struct irc_message *msg, struct client *c)
  1835. {
  1836. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1837. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1838. struct channel *chan;
  1839. if (msg->params.len == 0)
  1840. {
  1841. struct str_map_iter iter;
  1842. str_map_iter_init (&iter, &c->ctx->channels);
  1843. while ((chan = str_map_iter_next (&iter)))
  1844. if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1845. || channel_get_user (chan, c))
  1846. irc_send_rpl_list (c, chan);
  1847. }
  1848. else
  1849. {
  1850. struct str_vector channels;
  1851. str_vector_init (&channels);
  1852. cstr_split_ignore_empty (msg->params.vector[0], ',', &channels);
  1853. for (size_t i = 0; i < channels.len; i++)
  1854. if ((chan = str_map_find (&c->ctx->channels, channels.vector[i]))
  1855. && (!(chan->modes & IRC_CHAN_MODE_SECRET)
  1856. || channel_get_user (chan, c)))
  1857. irc_send_rpl_list (c, chan);
  1858. str_vector_free (&channels);
  1859. }
  1860. irc_send_reply (c, IRC_RPL_LISTEND);
  1861. }
  1862. static void
  1863. irc_append_prefixes (struct client *c, struct channel_user *user,
  1864. struct str *output)
  1865. {
  1866. struct str prefixes;
  1867. str_init (&prefixes);
  1868. if (user->modes & IRC_CHAN_MODE_OPERATOR) str_append_c (&prefixes, '@');
  1869. if (user->modes & IRC_CHAN_MODE_VOICE) str_append_c (&prefixes, '+');
  1870. if (prefixes.len)
  1871. {
  1872. if (c->caps_enabled & IRC_CAP_MULTI_PREFIX)
  1873. str_append (output, prefixes.str);
  1874. else
  1875. str_append_c (output, prefixes.str[0]);
  1876. }
  1877. str_free (&prefixes);
  1878. }
  1879. static char *
  1880. irc_make_rpl_namreply_item
  1881. (struct client *c, struct client *target, struct channel_user *user)
  1882. {
  1883. struct str result;
  1884. str_init (&result);
  1885. if (user)
  1886. irc_append_prefixes (c, user, &result);
  1887. str_append (&result, target->nickname);
  1888. if (c->caps_enabled & IRC_CAP_USERHOST_IN_NAMES)
  1889. str_append_printf (&result,
  1890. "!%s@%s", target->username, target->hostname);
  1891. return str_steal (&result);
  1892. }
  1893. static void
  1894. irc_send_rpl_namreply (struct client *c, const struct channel *chan,
  1895. struct str_map *used_nicks)
  1896. {
  1897. struct str_vector nicks;
  1898. str_vector_init (&nicks);
  1899. char type = '=';
  1900. if (chan->modes & IRC_CHAN_MODE_SECRET)
  1901. type = '@';
  1902. else if (chan->modes & IRC_CHAN_MODE_PRIVATE)
  1903. type = '*';
  1904. bool on_channel = channel_get_user (chan, c);
  1905. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  1906. {
  1907. if (!on_channel && (iter->c->mode & IRC_USER_MODE_INVISIBLE))
  1908. continue;
  1909. if (used_nicks)
  1910. str_map_set (used_nicks, iter->c->nickname, (void *) 1);
  1911. str_vector_add_owned (&nicks,
  1912. irc_make_rpl_namreply_item (c, iter->c, iter));
  1913. }
  1914. irc_send_reply_vector (c, IRC_RPL_NAMREPLY,
  1915. nicks.vector, type, chan->name, "");
  1916. str_vector_free (&nicks);
  1917. }
  1918. static void
  1919. irc_send_disassociated_names (struct client *c, struct str_map *used)
  1920. {
  1921. struct str_vector nicks;
  1922. str_vector_init (&nicks);
  1923. struct str_map_iter iter;
  1924. str_map_iter_init (&iter, &c->ctx->users);
  1925. struct client *target;
  1926. while ((target = str_map_iter_next (&iter)))
  1927. {
  1928. if ((target->mode & IRC_USER_MODE_INVISIBLE)
  1929. || str_map_find (used, target->nickname))
  1930. continue;
  1931. str_vector_add_owned (&nicks,
  1932. irc_make_rpl_namreply_item (c, target, NULL));
  1933. }
  1934. if (nicks.len)
  1935. irc_send_reply_vector (c, IRC_RPL_NAMREPLY,
  1936. nicks.vector, '*', "*", "");
  1937. str_vector_free (&nicks);
  1938. }
  1939. static void
  1940. irc_handle_names (const struct irc_message *msg, struct client *c)
  1941. {
  1942. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1943. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1944. struct channel *chan;
  1945. if (msg->params.len == 0)
  1946. {
  1947. struct str_map used;
  1948. str_map_init (&used);
  1949. used.key_xfrm = irc_strxfrm;
  1950. struct str_map_iter iter;
  1951. str_map_iter_init (&iter, &c->ctx->channels);
  1952. while ((chan = str_map_iter_next (&iter)))
  1953. if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1954. || channel_get_user (chan, c))
  1955. irc_send_rpl_namreply (c, chan, &used);
  1956. // Also send all visible users we haven't listed yet
  1957. irc_send_disassociated_names (c, &used);
  1958. str_map_free (&used);
  1959. irc_send_reply (c, IRC_RPL_ENDOFNAMES, "*");
  1960. }
  1961. else
  1962. {
  1963. struct str_vector channels;
  1964. str_vector_init (&channels);
  1965. cstr_split_ignore_empty (msg->params.vector[0], ',', &channels);
  1966. for (size_t i = 0; i < channels.len; i++)
  1967. if ((chan = str_map_find (&c->ctx->channels, channels.vector[i]))
  1968. && (!(chan->modes & IRC_CHAN_MODE_SECRET)
  1969. || channel_get_user (chan, c)))
  1970. {
  1971. irc_send_rpl_namreply (c, chan, NULL);
  1972. irc_send_reply (c, IRC_RPL_ENDOFNAMES, channels.vector[i]);
  1973. }
  1974. str_vector_free (&channels);
  1975. }
  1976. }
  1977. static void
  1978. irc_send_rpl_whoreply (struct client *c, const struct channel *chan,
  1979. const struct client *target)
  1980. {
  1981. struct str chars;
  1982. str_init (&chars);
  1983. str_append_c (&chars, target->away_message ? 'G' : 'H');
  1984. if (target->mode & IRC_USER_MODE_OPERATOR)
  1985. str_append_c (&chars, '*');
  1986. struct channel_user *user;
  1987. if (chan && (user = channel_get_user (chan, target)))
  1988. irc_append_prefixes (c, user, &chars);
  1989. irc_send_reply (c, IRC_RPL_WHOREPLY, chan ? chan->name : "*",
  1990. target->username, target->hostname, target->ctx->server_name,
  1991. target->nickname, chars.str, 0 /* hop count */, target->realname);
  1992. str_free (&chars);
  1993. }
  1994. static void
  1995. irc_match_send_rpl_whoreply (struct client *c, struct client *target,
  1996. const char *mask)
  1997. {
  1998. bool is_roommate = false;
  1999. struct str_map_iter iter;
  2000. str_map_iter_init (&iter, &c->ctx->channels);
  2001. struct channel *chan;
  2002. while ((chan = str_map_iter_next (&iter)))
  2003. if (channel_get_user (chan, target) && channel_get_user (chan, c))
  2004. {
  2005. is_roommate = true;
  2006. break;
  2007. }
  2008. if ((target->mode & IRC_USER_MODE_INVISIBLE) && !is_roommate)
  2009. return;
  2010. if (irc_fnmatch (mask, target->hostname)
  2011. && irc_fnmatch (mask, target->nickname)
  2012. && irc_fnmatch (mask, target->realname)
  2013. && irc_fnmatch (mask, c->ctx->server_name))
  2014. return;
  2015. // Try to find a channel they're on that's visible to us
  2016. struct channel *user_chan = NULL;
  2017. str_map_iter_init (&iter, &c->ctx->channels);
  2018. while ((chan = str_map_iter_next (&iter)))
  2019. if (channel_get_user (chan, target)
  2020. && (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  2021. || channel_get_user (chan, c)))
  2022. {
  2023. user_chan = chan;
  2024. break;
  2025. }
  2026. irc_send_rpl_whoreply (c, user_chan, target);
  2027. }
  2028. static void
  2029. irc_handle_who (const struct irc_message *msg, struct client *c)
  2030. {
  2031. bool only_ops = msg->params.len > 1 && !strcmp (msg->params.vector[1], "o");
  2032. const char *shown_mask = msg->params.vector[0], *used_mask;
  2033. if (!shown_mask)
  2034. used_mask = shown_mask = "*";
  2035. else if (!strcmp (shown_mask, "0"))
  2036. used_mask = "*";
  2037. else
  2038. used_mask = shown_mask;
  2039. struct channel *chan;
  2040. if ((chan = str_map_find (&c->ctx->channels, used_mask)))
  2041. {
  2042. bool on_chan = !!channel_get_user (chan, c);
  2043. if (on_chan || !(chan->modes & IRC_CHAN_MODE_SECRET))
  2044. for (struct channel_user *iter = chan->users;
  2045. iter; iter = iter->next)
  2046. {
  2047. if ((on_chan || !(iter->c->mode & IRC_USER_MODE_INVISIBLE))
  2048. && (!only_ops || (iter->c->mode & IRC_USER_MODE_OPERATOR)))
  2049. irc_send_rpl_whoreply (c, chan, iter->c);
  2050. }
  2051. }
  2052. else
  2053. {
  2054. struct str_map_iter iter;
  2055. str_map_iter_init (&iter, &c->ctx->users);
  2056. struct client *target;
  2057. while ((target = str_map_iter_next (&iter)))
  2058. if (!only_ops || (target->mode & IRC_USER_MODE_OPERATOR))
  2059. irc_match_send_rpl_whoreply (c, target, used_mask);
  2060. }
  2061. irc_send_reply (c, IRC_RPL_ENDOFWHO, shown_mask);
  2062. }
  2063. static void
  2064. irc_send_whois_reply (struct client *c, const struct client *target)
  2065. {
  2066. const char *nick = target->nickname;
  2067. irc_send_reply (c, IRC_RPL_WHOISUSER, nick,
  2068. target->username, target->hostname, target->realname);
  2069. irc_send_reply (c, IRC_RPL_WHOISSERVER, nick, target->ctx->server_name,
  2070. str_map_find (&c->ctx->config, "server_info"));
  2071. if (target->mode & IRC_USER_MODE_OPERATOR)
  2072. irc_send_reply (c, IRC_RPL_WHOISOPERATOR, nick);
  2073. irc_send_reply (c, IRC_RPL_WHOISIDLE, nick,
  2074. (int) (time (NULL) - target->last_active));
  2075. if (target->away_message)
  2076. irc_send_reply (c, IRC_RPL_AWAY, nick, target->away_message);
  2077. struct str_vector channels;
  2078. str_vector_init (&channels);
  2079. struct str_map_iter iter;
  2080. str_map_iter_init (&iter, &c->ctx->channels);
  2081. struct channel *chan;
  2082. struct channel_user *channel_user;
  2083. while ((chan = str_map_iter_next (&iter)))
  2084. if ((channel_user = channel_get_user (chan, target))
  2085. && (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  2086. || channel_get_user (chan, c)))
  2087. {
  2088. struct str item;
  2089. str_init (&item);
  2090. if (channel_user->modes & IRC_CHAN_MODE_OPERATOR)
  2091. str_append_c (&item, '@');
  2092. else if (channel_user->modes & IRC_CHAN_MODE_VOICE)
  2093. str_append_c (&item, '+');
  2094. str_append (&item, chan->name);
  2095. str_vector_add_owned (&channels, str_steal (&item));
  2096. }
  2097. irc_send_reply_vector (c, IRC_RPL_WHOISCHANNELS, channels.vector, nick, "");
  2098. str_vector_free (&channels);
  2099. irc_send_reply (c, IRC_RPL_ENDOFWHOIS, nick);
  2100. }
  2101. static void
  2102. irc_handle_whois (const struct irc_message *msg, struct client *c)
  2103. {
  2104. if (msg->params.len < 1)
  2105. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2106. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  2107. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  2108. struct str_vector masks;
  2109. str_vector_init (&masks);
  2110. const char *masks_str = msg->params.vector[msg->params.len > 1];
  2111. cstr_split_ignore_empty (masks_str, ',', &masks);
  2112. for (size_t i = 0; i < masks.len; i++)
  2113. {
  2114. const char *mask = masks.vector[i];
  2115. struct client *target;
  2116. if (!strpbrk (mask, "*?"))
  2117. {
  2118. if (!(target = str_map_find (&c->ctx->users, mask)))
  2119. irc_send_reply (c, IRC_ERR_NOSUCHNICK, mask);
  2120. else
  2121. irc_send_whois_reply (c, target);
  2122. }
  2123. else
  2124. {
  2125. struct str_map_iter iter;
  2126. str_map_iter_init (&iter, &c->ctx->users);
  2127. bool found = false;
  2128. while ((target = str_map_iter_next (&iter))
  2129. && !irc_fnmatch (mask, target->nickname))
  2130. {
  2131. irc_send_whois_reply (c, target);
  2132. found = true;
  2133. }
  2134. if (!found)
  2135. irc_send_reply (c, IRC_ERR_NOSUCHNICK, mask);
  2136. }
  2137. }
  2138. str_vector_free (&masks);
  2139. }
  2140. static void
  2141. irc_handle_whowas (const struct irc_message *msg, struct client *c)
  2142. {
  2143. if (msg->params.len < 1)
  2144. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2145. if (msg->params.len > 2 && !irc_is_this_me (c->ctx, msg->params.vector[2]))
  2146. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[2]);
  2147. // The "count" parameter is ignored, we only store one entry for a nick
  2148. struct str_vector nicks;
  2149. str_vector_init (&nicks);
  2150. cstr_split_ignore_empty (msg->params.vector[0], ',', &nicks);
  2151. for (size_t i = 0; i < nicks.len; i++)
  2152. {
  2153. const char *nick = nicks.vector[i];
  2154. struct whowas_info *info = str_map_find (&c->ctx->whowas, nick);
  2155. if (!info)
  2156. irc_send_reply (c, IRC_ERR_WASNOSUCHNICK, nick);
  2157. else
  2158. {
  2159. irc_send_reply (c, IRC_RPL_WHOWASUSER, nick,
  2160. info->username, info->hostname, info->realname);
  2161. irc_send_reply (c, IRC_RPL_WHOISSERVER, nick, c->ctx->server_name,
  2162. str_map_find (&c->ctx->config, "server_info"));
  2163. }
  2164. irc_send_reply (c, IRC_RPL_ENDOFWHOWAS, nick);
  2165. }
  2166. str_vector_free (&nicks);
  2167. }
  2168. static void
  2169. irc_send_rpl_topic (struct client *c, struct channel *chan)
  2170. {
  2171. if (!*chan->topic)
  2172. irc_send_reply (c, IRC_RPL_NOTOPIC, chan->name);
  2173. else
  2174. {
  2175. irc_send_reply (c, IRC_RPL_TOPIC, chan->name, chan->topic);
  2176. irc_send_reply (c, IRC_RPL_TOPICWHOTIME,
  2177. chan->name, chan->topic_who, (long long) chan->topic_time);
  2178. }
  2179. }
  2180. static void
  2181. irc_handle_topic (const struct irc_message *msg, struct client *c)
  2182. {
  2183. if (msg->params.len < 1)
  2184. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2185. const char *target = msg->params.vector[0];
  2186. struct channel *chan = str_map_find (&c->ctx->channels, target);
  2187. if (!chan)
  2188. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, target);
  2189. if (msg->params.len < 2)
  2190. {
  2191. irc_send_rpl_topic (c, chan);
  2192. return;
  2193. }
  2194. struct channel_user *user = channel_get_user (chan, c);
  2195. if (!user)
  2196. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, target);
  2197. if ((chan->modes & IRC_CHAN_MODE_PROTECTED_TOPIC)
  2198. && !(user->modes & IRC_CHAN_MODE_OPERATOR))
  2199. RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, target);
  2200. free (chan->topic);
  2201. free (chan->topic_who);
  2202. chan->topic = xstrdup (msg->params.vector[1]);
  2203. chan->topic_who = xstrdup_printf
  2204. ("%s!%s@%s", c->nickname, c->username, c->hostname);
  2205. chan->topic_time = time (NULL);
  2206. char *message = xstrdup_printf (":%s!%s@%s TOPIC %s :%s",
  2207. c->nickname, c->username, c->hostname, target, chan->topic);
  2208. irc_channel_multicast (chan, message, NULL);
  2209. free (message);
  2210. }
  2211. static void
  2212. irc_try_part (struct client *c, const char *channel_name, const char *reason)
  2213. {
  2214. if (!reason)
  2215. reason = c->nickname;
  2216. struct channel *chan;
  2217. if (!(chan = str_map_find (&c->ctx->channels, channel_name)))
  2218. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name);
  2219. struct channel_user *user;
  2220. if (!(user = channel_get_user (chan, c)))
  2221. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
  2222. char *message = xstrdup_printf (":%s!%s@%s PART %s :%s",
  2223. c->nickname, c->username, c->hostname, channel_name, reason);
  2224. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  2225. irc_channel_multicast (chan, message, NULL);
  2226. else
  2227. client_send (c, "%s", message);
  2228. free (message);
  2229. channel_remove_user (chan, user);
  2230. irc_channel_destroy_if_empty (c->ctx, chan);
  2231. }
  2232. static void
  2233. irc_part_all_channels (struct client *c)
  2234. {
  2235. // We have to be careful here, the channel might get destroyed
  2236. struct str_map_unset_iter iter;
  2237. str_map_unset_iter_init (&iter, &c->ctx->channels);
  2238. struct channel *chan;
  2239. while ((chan = str_map_unset_iter_next (&iter)))
  2240. if (channel_get_user (chan, c))
  2241. irc_try_part (c, chan->name, NULL);
  2242. str_map_unset_iter_free (&iter);
  2243. }
  2244. static void
  2245. irc_handle_part (const struct irc_message *msg, struct client *c)
  2246. {
  2247. if (msg->params.len < 1)
  2248. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2249. const char *reason = msg->params.len > 1 ? msg->params.vector[1] : NULL;
  2250. struct str_vector channels;
  2251. str_vector_init (&channels);
  2252. cstr_split_ignore_empty (msg->params.vector[0], ',', &channels);
  2253. for (size_t i = 0; i < channels.len; i++)
  2254. irc_try_part (c, channels.vector[i], reason);
  2255. str_vector_free (&channels);
  2256. }
  2257. static void
  2258. irc_try_kick (struct client *c, const char *channel_name, const char *nick,
  2259. const char *reason)
  2260. {
  2261. struct channel *chan;
  2262. if (!(chan = str_map_find (&c->ctx->channels, channel_name)))
  2263. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name);
  2264. struct channel_user *user;
  2265. if (!(user = channel_get_user (chan, c)))
  2266. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
  2267. if (!(user->modes & IRC_CHAN_MODE_OPERATOR))
  2268. RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, channel_name);
  2269. struct client *client;
  2270. if (!(client = str_map_find (&c->ctx->users, nick))
  2271. || !(user = channel_get_user (chan, client)))
  2272. RETURN_WITH_REPLY (c, IRC_ERR_USERNOTINCHANNEL, nick, channel_name);
  2273. char *message = xstrdup_printf (":%s!%s@%s KICK %s %s :%s",
  2274. c->nickname, c->username, c->hostname, channel_name, nick, reason);
  2275. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  2276. irc_channel_multicast (chan, message, NULL);
  2277. else
  2278. client_send (c, "%s", message);
  2279. free (message);
  2280. channel_remove_user (chan, user);
  2281. irc_channel_destroy_if_empty (c->ctx, chan);
  2282. }
  2283. static void
  2284. irc_handle_kick (const struct irc_message *msg, struct client *c)
  2285. {
  2286. if (msg->params.len < 2)
  2287. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2288. const char *reason = c->nickname;
  2289. if (msg->params.len > 2)
  2290. reason = msg->params.vector[2];
  2291. struct str_vector channels;
  2292. struct str_vector users;
  2293. str_vector_init (&channels);
  2294. str_vector_init (&users);
  2295. cstr_split_ignore_empty (msg->params.vector[0], ',', &channels);
  2296. cstr_split_ignore_empty (msg->params.vector[1], ',', &users);
  2297. if (channels.len == 1)
  2298. for (size_t i = 0; i < users.len; i++)
  2299. irc_try_kick (c, channels.vector[0], users.vector[i], reason);
  2300. else
  2301. for (size_t i = 0; i < channels.len && i < users.len; i++)
  2302. irc_try_kick (c, channels.vector[i], users.vector[i], reason);
  2303. str_vector_free (&channels);
  2304. str_vector_free (&users);
  2305. }
  2306. static void
  2307. irc_send_invite_notifications
  2308. (struct channel *chan, struct client *c, struct client *target)
  2309. {
  2310. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  2311. if (iter->c != target && iter->c->caps_enabled & IRC_CAP_INVITE_NOTIFY)
  2312. client_send (iter->c, ":%s!%s@%s INVITE %s %s",
  2313. c->nickname, c->username, c->hostname,
  2314. target->nickname, chan->name);
  2315. }
  2316. static void
  2317. irc_handle_invite (const struct irc_message *msg, struct client *c)
  2318. {
  2319. if (msg->params.len < 2)
  2320. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2321. const char *target = msg->params.vector[0];
  2322. const char *channel_name = msg->params.vector[1];
  2323. struct client *client = str_map_find (&c->ctx->users, target);
  2324. if (!client)
  2325. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHNICK, target);
  2326. struct channel *chan = str_map_find (&c->ctx->channels, channel_name);
  2327. if (chan)
  2328. {
  2329. struct channel_user *inviting_user;
  2330. if (!(inviting_user = channel_get_user (chan, c)))
  2331. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
  2332. if (channel_get_user (chan, client))
  2333. RETURN_WITH_REPLY (c, IRC_ERR_USERONCHANNEL, target, channel_name);
  2334. if ((inviting_user->modes & IRC_CHAN_MODE_OPERATOR))
  2335. str_map_set (&client->invites, channel_name, (void *) 1);
  2336. else if ((chan->modes & IRC_CHAN_MODE_INVITE_ONLY))
  2337. RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, channel_name);
  2338. // It's not specified when and how we should send out invite-notify
  2339. if (chan->modes & IRC_CHAN_MODE_INVITE_ONLY)
  2340. irc_send_invite_notifications (chan, c, client);
  2341. }
  2342. client_send (client, ":%s!%s@%s INVITE %s %s",
  2343. c->nickname, c->username, c->hostname, client->nickname, channel_name);
  2344. if (client->away_message)
  2345. irc_send_reply (c, IRC_RPL_AWAY,
  2346. client->nickname, client->away_message);
  2347. irc_send_reply (c, IRC_RPL_INVITING, client->nickname, channel_name);
  2348. }
  2349. static void
  2350. irc_try_join (struct client *c, const char *channel_name, const char *key)
  2351. {
  2352. struct channel *chan = str_map_find (&c->ctx->channels, channel_name);
  2353. unsigned user_mode = 0;
  2354. if (!chan)
  2355. {
  2356. if (irc_validate_channel_name (channel_name) != VALIDATION_OK)
  2357. RETURN_WITH_REPLY (c, IRC_ERR_BADCHANMASK, channel_name);
  2358. chan = irc_channel_create (c->ctx, channel_name);
  2359. user_mode = IRC_CHAN_MODE_OPERATOR;
  2360. }
  2361. else if (channel_get_user (chan, c))
  2362. return;
  2363. bool invited_by_chanop = str_map_find (&c->invites, channel_name);
  2364. if ((chan->modes & IRC_CHAN_MODE_INVITE_ONLY)
  2365. && !client_in_mask_list (c, &chan->invite_list)
  2366. && !invited_by_chanop)
  2367. RETURN_WITH_REPLY (c, IRC_ERR_INVITEONLYCHAN, channel_name);
  2368. if (chan->key && (!key || strcmp (key, chan->key)))
  2369. RETURN_WITH_REPLY (c, IRC_ERR_BADCHANNELKEY, channel_name);
  2370. if (chan->user_limit != -1
  2371. && channel_user_count (chan) >= (size_t) chan->user_limit)
  2372. RETURN_WITH_REPLY (c, IRC_ERR_CHANNELISFULL, channel_name);
  2373. if (client_in_mask_list (c, &chan->ban_list)
  2374. && !client_in_mask_list (c, &chan->exception_list)
  2375. && !invited_by_chanop)
  2376. RETURN_WITH_REPLY (c, IRC_ERR_BANNEDFROMCHAN, channel_name);
  2377. // Destroy any invitation as there's no other way to get rid of it
  2378. str_map_set (&c->invites, channel_name, NULL);
  2379. channel_add_user (chan, c)->modes = user_mode;
  2380. char *message = xstrdup_printf (":%s!%s@%s JOIN %s",
  2381. c->nickname, c->username, c->hostname, channel_name);
  2382. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  2383. irc_channel_multicast (chan, message, NULL);
  2384. else
  2385. client_send (c, "%s", message);
  2386. free (message);
  2387. irc_send_rpl_topic (c, chan);
  2388. irc_send_rpl_namreply (c, chan, NULL);
  2389. irc_send_reply (c, IRC_RPL_ENDOFNAMES, chan->name);
  2390. }
  2391. static void
  2392. irc_handle_join (const struct irc_message *msg, struct client *c)
  2393. {
  2394. if (msg->params.len < 1)
  2395. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2396. if (!strcmp (msg->params.vector[0], "0"))
  2397. {
  2398. irc_part_all_channels (c);
  2399. return;
  2400. }
  2401. struct str_vector channels;
  2402. struct str_vector keys;
  2403. str_vector_init (&channels);
  2404. str_vector_init (&keys);
  2405. cstr_split_ignore_empty (msg->params.vector[0], ',', &channels);
  2406. if (msg->params.len > 1)
  2407. cstr_split_ignore_empty (msg->params.vector[1], ',', &keys);
  2408. for (size_t i = 0; i < channels.len; i++)
  2409. irc_try_join (c, channels.vector[i],
  2410. i < keys.len ? keys.vector[i] : NULL);
  2411. str_vector_free (&channels);
  2412. str_vector_free (&keys);
  2413. }
  2414. static void
  2415. irc_handle_summon (const struct irc_message *msg, struct client *c)
  2416. {
  2417. (void) msg;
  2418. irc_send_reply (c, IRC_ERR_SUMMONDISABLED);
  2419. }
  2420. static void
  2421. irc_handle_users (const struct irc_message *msg, struct client *c)
  2422. {
  2423. (void) msg;
  2424. irc_send_reply (c, IRC_ERR_USERSDISABLED);
  2425. }
  2426. static void
  2427. irc_handle_away (const struct irc_message *msg, struct client *c)
  2428. {
  2429. if (msg->params.len < 1)
  2430. {
  2431. free (c->away_message);
  2432. c->away_message = NULL;
  2433. irc_send_reply (c, IRC_RPL_UNAWAY);
  2434. }
  2435. else
  2436. {
  2437. free (c->away_message);
  2438. c->away_message = xstrdup (msg->params.vector[0]);
  2439. irc_send_reply (c, IRC_RPL_NOWAWAY);
  2440. }
  2441. }
  2442. static void
  2443. irc_handle_ison (const struct irc_message *msg, struct client *c)
  2444. {
  2445. if (msg->params.len < 1)
  2446. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2447. struct str result;
  2448. str_init (&result);
  2449. const char *nick;
  2450. if (str_map_find (&c->ctx->users, (nick = msg->params.vector[0])))
  2451. str_append (&result, nick);
  2452. for (size_t i = 1; i < msg->params.len; i++)
  2453. if (str_map_find (&c->ctx->users, (nick = msg->params.vector[i])))
  2454. str_append_printf (&result, " %s", nick);
  2455. irc_send_reply (c, IRC_RPL_ISON, result.str);
  2456. str_free (&result);
  2457. }
  2458. static void
  2459. irc_handle_admin (const struct irc_message *msg, struct client *c)
  2460. {
  2461. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  2462. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  2463. irc_send_reply (c, IRC_ERR_NOADMININFO, c->ctx->server_name);
  2464. }
  2465. static void
  2466. irc_handle_stats_links (struct client *c, const struct irc_message *msg)
  2467. {
  2468. // There is only an "l" query in RFC 2812 but we cannot link,
  2469. // so instead we provide the "L" query giving information for all users
  2470. const char *filter = NULL;
  2471. if (msg->params.len > 1)
  2472. filter = msg->params.vector[1];
  2473. for (struct client *iter = c->ctx->clients; iter; iter = iter->next)
  2474. {
  2475. if (filter && irc_strcmp (iter->nickname, filter))
  2476. continue;
  2477. irc_send_reply (c, IRC_RPL_STATSLINKINFO,
  2478. iter->address, // linkname
  2479. iter->write_buffer.len, // sendq
  2480. iter->n_sent_messages, iter->sent_bytes / 1024,
  2481. iter->n_received_messages, iter->received_bytes / 1024,
  2482. (long long) (time (NULL) - iter->opened));
  2483. }
  2484. }
  2485. static void
  2486. irc_handle_stats_commands (struct client *c)
  2487. {
  2488. struct str_map_iter iter;
  2489. str_map_iter_init (&iter, &c->ctx->handlers);
  2490. struct irc_command *handler;
  2491. while ((handler = str_map_iter_next (&iter)))
  2492. {
  2493. if (!handler->n_received)
  2494. continue;
  2495. irc_send_reply (c, IRC_RPL_STATSCOMMANDS, handler->name,
  2496. handler->n_received, handler->bytes_received, (size_t) 0);
  2497. }
  2498. }
  2499. static void
  2500. irc_handle_stats_uptime (struct client *c)
  2501. {
  2502. time_t uptime = time (NULL) - c->ctx->started;
  2503. int days = uptime / 60 / 60 / 24;
  2504. int hours = (uptime % (60 * 60 * 24)) / 60 / 60;
  2505. int mins = (uptime % (60 * 60)) / 60;
  2506. int secs = uptime % 60;
  2507. irc_send_reply (c, IRC_RPL_STATSUPTIME, days, hours, mins, secs);
  2508. }
  2509. static void
  2510. irc_handle_stats (const struct irc_message *msg, struct client *c)
  2511. {
  2512. char query;
  2513. if (msg->params.len < 1 || !(query = *msg->params.vector[0]))
  2514. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2515. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  2516. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  2517. if (!(c->mode & IRC_USER_MODE_OPERATOR))
  2518. RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES);
  2519. switch (query)
  2520. {
  2521. case 'L': irc_handle_stats_links (c, msg); break;
  2522. case 'm': irc_handle_stats_commands (c); break;
  2523. case 'u': irc_handle_stats_uptime (c); break;
  2524. }
  2525. irc_send_reply (c, IRC_RPL_ENDOFSTATS, query);
  2526. }
  2527. static void
  2528. irc_handle_links (const struct irc_message *msg, struct client *c)
  2529. {
  2530. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  2531. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  2532. const char *mask = "*";
  2533. if (msg->params.len > 0)
  2534. mask = msg->params.vector[msg->params.len > 1];
  2535. if (!irc_fnmatch (mask, c->ctx->server_name))
  2536. irc_send_reply (c, IRC_RPL_LINKS, mask,
  2537. c->ctx->server_name, 0 /* hop count */,
  2538. str_map_find (&c->ctx->config, "server_info"));
  2539. irc_send_reply (c, IRC_RPL_ENDOFLINKS, mask);
  2540. }
  2541. static void
  2542. irc_handle_kill (const struct irc_message *msg, struct client *c)
  2543. {
  2544. if (msg->params.len < 2)
  2545. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2546. if (!(c->mode & IRC_USER_MODE_OPERATOR))
  2547. RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES);
  2548. struct client *target;
  2549. if (!(target = str_map_find (&c->ctx->users, msg->params.vector[0])))
  2550. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHNICK, msg->params.vector[0]);
  2551. char *reason = xstrdup_printf ("Killed by %s: %s",
  2552. c->nickname, msg->params.vector[1]);
  2553. client_close_link (target, reason);
  2554. free (reason);
  2555. }
  2556. static void
  2557. irc_handle_die (const struct irc_message *msg, struct client *c)
  2558. {
  2559. (void) msg;
  2560. if (!(c->mode & IRC_USER_MODE_OPERATOR))
  2561. RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES);
  2562. if (!c->ctx->quitting)
  2563. irc_initiate_quit (c->ctx);
  2564. }
  2565. // -----------------------------------------------------------------------------
  2566. static void
  2567. irc_register_handlers (struct server_context *ctx)
  2568. {
  2569. // TODO: add an index for IRC_ERR_NOSUCHSERVER validation?
  2570. // TODO: add a minimal parameter count?
  2571. // TODO: add a field for oper-only commands?
  2572. static struct irc_command message_handlers[] =
  2573. {
  2574. { "CAP", false, irc_handle_cap, 0, 0 },
  2575. { "PASS", false, irc_handle_pass, 0, 0 },
  2576. { "NICK", false, irc_handle_nick, 0, 0 },
  2577. { "USER", false, irc_handle_user, 0, 0 },
  2578. { "USERHOST", true, irc_handle_userhost, 0, 0 },
  2579. { "LUSERS", true, irc_handle_lusers, 0, 0 },
  2580. { "MOTD", true, irc_handle_motd, 0, 0 },
  2581. { "PING", true, irc_handle_ping, 0, 0 },
  2582. { "PONG", false, irc_handle_pong, 0, 0 },
  2583. { "QUIT", false, irc_handle_quit, 0, 0 },
  2584. { "TIME", true, irc_handle_time, 0, 0 },
  2585. { "VERSION", true, irc_handle_version, 0, 0 },
  2586. { "USERS", true, irc_handle_users, 0, 0 },
  2587. { "SUMMON", true, irc_handle_summon, 0, 0 },
  2588. { "AWAY", true, irc_handle_away, 0, 0 },
  2589. { "ADMIN", true, irc_handle_admin, 0, 0 },
  2590. { "STATS", true, irc_handle_stats, 0, 0 },
  2591. { "LINKS", true, irc_handle_links, 0, 0 },
  2592. { "MODE", true, irc_handle_mode, 0, 0 },
  2593. { "PRIVMSG", true, irc_handle_privmsg, 0, 0 },
  2594. { "NOTICE", true, irc_handle_notice, 0, 0 },
  2595. { "JOIN", true, irc_handle_join, 0, 0 },
  2596. { "PART", true, irc_handle_part, 0, 0 },
  2597. { "KICK", true, irc_handle_kick, 0, 0 },
  2598. { "INVITE", true, irc_handle_invite, 0, 0 },
  2599. { "TOPIC", true, irc_handle_topic, 0, 0 },
  2600. { "LIST", true, irc_handle_list, 0, 0 },
  2601. { "NAMES", true, irc_handle_names, 0, 0 },
  2602. { "WHO", true, irc_handle_who, 0, 0 },
  2603. { "WHOIS", true, irc_handle_whois, 0, 0 },
  2604. { "WHOWAS", true, irc_handle_whowas, 0, 0 },
  2605. { "ISON", true, irc_handle_ison, 0, 0 },
  2606. { "KILL", true, irc_handle_kill, 0, 0 },
  2607. { "DIE", true, irc_handle_die, 0, 0 },
  2608. };
  2609. for (size_t i = 0; i < N_ELEMENTS (message_handlers); i++)
  2610. {
  2611. const struct irc_command *cmd = &message_handlers[i];
  2612. str_map_set (&ctx->handlers, cmd->name, (void *) cmd);
  2613. }
  2614. }
  2615. static void
  2616. irc_process_message (const struct irc_message *msg,
  2617. const char *raw, void *user_data)
  2618. {
  2619. (void) raw;
  2620. struct client *c = user_data;
  2621. if (c->closing_link)
  2622. return;
  2623. c->n_received_messages++;
  2624. c->received_bytes += strlen (raw) + 2;
  2625. if (!flood_detector_check (&c->antiflood))
  2626. {
  2627. client_close_link (c, "Excess flood");
  2628. return;
  2629. }
  2630. struct irc_command *cmd = str_map_find (&c->ctx->handlers, msg->command);
  2631. if (!cmd)
  2632. irc_send_reply (c, IRC_ERR_UNKNOWNCOMMAND, msg->command);
  2633. else
  2634. {
  2635. cmd->n_received++;
  2636. cmd->bytes_received += strlen (raw) + 2;
  2637. if (cmd->requires_registration && !c->registered)
  2638. irc_send_reply (c, IRC_ERR_NOTREGISTERED);
  2639. else
  2640. cmd->handler (msg, c);
  2641. }
  2642. }
  2643. // --- Network I/O -------------------------------------------------------------
  2644. static bool
  2645. irc_try_read (struct client *c)
  2646. {
  2647. struct str *buf = &c->read_buffer;
  2648. ssize_t n_read;
  2649. while (true)
  2650. {
  2651. str_ensure_space (buf, 512);
  2652. n_read = recv (c->socket_fd, buf->str + buf->len,
  2653. buf->alloc - buf->len - 1 /* null byte */, 0);
  2654. if (n_read > 0)
  2655. {
  2656. buf->str[buf->len += n_read] = '\0';
  2657. // TODO: discard characters above the 512 character limit
  2658. irc_process_buffer (buf, irc_process_message, c);
  2659. continue;
  2660. }
  2661. if (n_read == 0)
  2662. {
  2663. client_kill (c, NULL);
  2664. return false;
  2665. }
  2666. if (errno == EAGAIN)
  2667. return true;
  2668. if (errno == EINTR)
  2669. continue;
  2670. print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
  2671. client_kill (c, strerror (errno));
  2672. return false;
  2673. }
  2674. }
  2675. static bool
  2676. irc_try_read_tls (struct client *c)
  2677. {
  2678. if (c->ssl_tx_want_rx)
  2679. return true;
  2680. struct str *buf = &c->read_buffer;
  2681. c->ssl_rx_want_tx = false;
  2682. while (true)
  2683. {
  2684. str_ensure_space (buf, 512);
  2685. ERR_clear_error ();
  2686. int n_read = SSL_read (c->ssl, buf->str + buf->len,
  2687. buf->alloc - buf->len - 1 /* null byte */);
  2688. const char *error_info = NULL;
  2689. switch (xssl_get_error (c->ssl, n_read, &error_info))
  2690. {
  2691. case SSL_ERROR_NONE:
  2692. buf->str[buf->len += n_read] = '\0';
  2693. // TODO: discard characters above the 512 character limit
  2694. irc_process_buffer (buf, irc_process_message, c);
  2695. continue;
  2696. case SSL_ERROR_ZERO_RETURN:
  2697. client_kill (c, NULL);
  2698. return false;
  2699. case SSL_ERROR_WANT_READ:
  2700. return true;
  2701. case SSL_ERROR_WANT_WRITE:
  2702. c->ssl_rx_want_tx = true;
  2703. return true;
  2704. case XSSL_ERROR_TRY_AGAIN:
  2705. continue;
  2706. default:
  2707. print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
  2708. client_kill (c, error_info);
  2709. return false;
  2710. }
  2711. }
  2712. }
  2713. static bool
  2714. irc_try_write (struct client *c)
  2715. {
  2716. struct str *buf = &c->write_buffer;
  2717. ssize_t n_written;
  2718. while (buf->len)
  2719. {
  2720. n_written = send (c->socket_fd, buf->str, buf->len, 0);
  2721. if (n_written >= 0)
  2722. {
  2723. str_remove_slice (buf, 0, n_written);
  2724. continue;
  2725. }
  2726. if (errno == EAGAIN)
  2727. return true;
  2728. if (errno == EINTR)
  2729. continue;
  2730. print_debug ("%s: %s: %s", __func__, "send", strerror (errno));
  2731. client_kill (c, strerror (errno));
  2732. return false;
  2733. }
  2734. return true;
  2735. }
  2736. static bool
  2737. irc_try_write_tls (struct client *c)
  2738. {
  2739. if (c->ssl_rx_want_tx)
  2740. return true;
  2741. struct str *buf = &c->write_buffer;
  2742. c->ssl_tx_want_rx = false;
  2743. while (buf->len)
  2744. {
  2745. ERR_clear_error ();
  2746. int n_written = SSL_write (c->ssl, buf->str, buf->len);
  2747. const char *error_info = NULL;
  2748. switch (xssl_get_error (c->ssl, n_written, &error_info))
  2749. {
  2750. case SSL_ERROR_NONE:
  2751. str_remove_slice (buf, 0, n_written);
  2752. continue;
  2753. case SSL_ERROR_ZERO_RETURN:
  2754. client_kill (c, NULL);
  2755. return false;
  2756. case SSL_ERROR_WANT_WRITE:
  2757. return true;
  2758. case SSL_ERROR_WANT_READ:
  2759. c->ssl_tx_want_rx = true;
  2760. return true;
  2761. case XSSL_ERROR_TRY_AGAIN:
  2762. continue;
  2763. default:
  2764. print_debug ("%s: %s: %s", __func__, "SSL_write", error_info);
  2765. client_kill (c, error_info);
  2766. return false;
  2767. }
  2768. }
  2769. return true;
  2770. }
  2771. // -----------------------------------------------------------------------------
  2772. static bool
  2773. irc_autodetect_tls (struct client *c)
  2774. {
  2775. // Trivial SSL/TLS autodetection. The first block of data returned by
  2776. // recv() must be at least three bytes long for this to work reliably,
  2777. // but that should not pose a problem in practice.
  2778. //
  2779. // SSL2: 1xxx xxxx | xxxx xxxx | <1>
  2780. // (message length) (client hello)
  2781. // SSL3/TLS: <22> | <3> | xxxx xxxx
  2782. // (handshake)| (protocol version)
  2783. //
  2784. // Such byte sequences should never occur at the beginning of regular IRC
  2785. // communication, which usually begins with USER/NICK/PASS/SERVICE.
  2786. char buf[3];
  2787. start:
  2788. switch (recv (c->socket_fd, buf, sizeof buf, MSG_PEEK))
  2789. {
  2790. case 3:
  2791. if ((buf[0] & 0x80) && buf[2] == 1)
  2792. return true;
  2793. case 2:
  2794. if (buf[0] == 22 && buf[1] == 3)
  2795. return true;
  2796. break;
  2797. case 1:
  2798. if (buf[0] == 22)
  2799. return true;
  2800. break;
  2801. case 0:
  2802. break;
  2803. default:
  2804. if (errno == EINTR)
  2805. goto start;
  2806. }
  2807. return false;
  2808. }
  2809. static bool
  2810. client_initialize_tls (struct client *c)
  2811. {
  2812. const char *error_info = NULL;
  2813. if (!c->ctx->ssl_ctx)
  2814. {
  2815. error_info = "TLS support disabled";
  2816. goto error_ssl_1;
  2817. }
  2818. ERR_clear_error ();
  2819. c->ssl = SSL_new (c->ctx->ssl_ctx);
  2820. if (!c->ssl)
  2821. goto error_ssl_2;
  2822. if (!SSL_set_fd (c->ssl, c->socket_fd))
  2823. goto error_ssl_3;
  2824. SSL_set_accept_state (c->ssl);
  2825. return true;
  2826. error_ssl_3:
  2827. SSL_free (c->ssl);
  2828. c->ssl = NULL;
  2829. error_ssl_2:
  2830. error_info = ERR_reason_error_string (ERR_get_error ());
  2831. error_ssl_1:
  2832. print_debug ("could not initialize TLS for %s: %s", c->address, error_info);
  2833. return false;
  2834. }
  2835. // -----------------------------------------------------------------------------
  2836. static void
  2837. on_client_ready (const struct pollfd *pfd, void *user_data)
  2838. {
  2839. struct client *c = user_data;
  2840. if (!c->initialized)
  2841. {
  2842. hard_assert (pfd->events == POLLIN);
  2843. if (irc_autodetect_tls (c) && !client_initialize_tls (c))
  2844. {
  2845. client_kill (c, NULL);
  2846. return;
  2847. }
  2848. c->initialized = true;
  2849. client_set_ping_timer (c);
  2850. }
  2851. if (c->ssl)
  2852. {
  2853. // Reads may want to write, writes may want to read, poll() may
  2854. // return unexpected things in `revents'... let's try both
  2855. if (!irc_try_read_tls (c) || !irc_try_write_tls (c))
  2856. return;
  2857. }
  2858. else if (!irc_try_read (c) || !irc_try_write (c))
  2859. return;
  2860. client_update_poller (c, pfd);
  2861. // The purpose of the `closing_link' state is to transfer the `ERROR'
  2862. if (c->closing_link && !c->half_closed && !c->write_buffer.len)
  2863. {
  2864. // To make sure the client has received our ERROR message, we must
  2865. // first half-close the connection, otherwise it could happen that they
  2866. // receive a RST from our TCP stack first when we receive further data
  2867. // We only send the "close notify" alert if libssl can write to the
  2868. // socket at this moment. All the other data has been already written,
  2869. // though, and the client will receive a TCP half-close as usual, so
  2870. // it's not that important if the alert actually gets through.
  2871. if (c->ssl)
  2872. (void) SSL_shutdown (c->ssl);
  2873. // Either the shutdown succeeds, in which case we set a flag so that
  2874. // we don't retry this action and wait until we get an EOF, or it fails
  2875. // and we just kill the client straight away
  2876. if (!shutdown (c->socket_fd, SHUT_WR))
  2877. c->half_closed = true;
  2878. else
  2879. client_kill (c, NULL);
  2880. }
  2881. }
  2882. static void
  2883. client_update_poller (struct client *c, const struct pollfd *pfd)
  2884. {
  2885. // We must not poll for writing when the connection hasn't been initialized
  2886. int new_events = POLLIN;
  2887. if (c->ssl)
  2888. {
  2889. if (c->write_buffer.len || c->ssl_rx_want_tx)
  2890. new_events |= POLLOUT;
  2891. // While we're waiting for an opposite event, we ignore the original
  2892. if (c->ssl_rx_want_tx) new_events &= ~POLLIN;
  2893. if (c->ssl_tx_want_rx) new_events &= ~POLLOUT;
  2894. }
  2895. else if (c->initialized && c->write_buffer.len)
  2896. new_events |= POLLOUT;
  2897. hard_assert (new_events != 0);
  2898. if (!pfd || pfd->events != new_events)
  2899. poller_fd_set (&c->socket_event, new_events);
  2900. }
  2901. static void
  2902. client_finish_connection (struct client *c)
  2903. {
  2904. c->gni = NULL;
  2905. c->address = format_host_port_pair (c->hostname, c->port);
  2906. print_debug ("accepted connection from %s", c->address);
  2907. client_update_poller (c, NULL);
  2908. client_set_kill_timer (c);
  2909. }
  2910. static void
  2911. on_client_gni_resolved (int result, char *host, char *port, void *user_data)
  2912. {
  2913. struct client *c = user_data;
  2914. if (result)
  2915. print_debug ("%s: %s", "getnameinfo", gai_strerror (result));
  2916. else
  2917. {
  2918. free (c->hostname);
  2919. c->hostname = xstrdup (host);
  2920. (void) port;
  2921. }
  2922. poller_timer_reset (&c->gni_timer);
  2923. client_finish_connection (c);
  2924. }
  2925. static void
  2926. on_client_gni_timer (struct client *c)
  2927. {
  2928. async_cancel (&c->gni->async);
  2929. client_finish_connection (c);
  2930. }
  2931. static bool
  2932. irc_try_fetch_client (struct server_context *ctx, int listen_fd)
  2933. {
  2934. // XXX: `struct sockaddr_storage' is not the most portable thing
  2935. struct sockaddr_storage peer;
  2936. socklen_t peer_len = sizeof peer;
  2937. int fd = accept (listen_fd, (struct sockaddr *) &peer, &peer_len);
  2938. if (fd == -1)
  2939. {
  2940. if (errno == EAGAIN)
  2941. return false;
  2942. if (errno == EINTR
  2943. || errno == ECONNABORTED)
  2944. return true;
  2945. // TODO: handle resource exhaustion (EMFILE, ENFILE) specially
  2946. // (stop accepting new connections and wait until we close some;
  2947. // also set a timer in case of ENFILE).
  2948. print_fatal ("%s: %s", "accept", strerror (errno));
  2949. irc_initiate_quit (ctx);
  2950. return false;
  2951. }
  2952. set_blocking (fd, false);
  2953. // A little bit questionable once the traffic gets high enough (IMO),
  2954. // but it reduces silly latencies that we don't need because we already
  2955. // do buffer our output
  2956. int yes = 1;
  2957. soft_assert (setsockopt (fd, IPPROTO_TCP, TCP_NODELAY,
  2958. &yes, sizeof yes) != -1);
  2959. if (ctx->max_connections != 0 && ctx->n_clients >= ctx->max_connections)
  2960. {
  2961. print_debug ("connection limit reached, refusing connection");
  2962. close (fd);
  2963. return true;
  2964. }
  2965. char host[NI_MAXHOST] = "unknown", port[NI_MAXSERV] = "unknown";
  2966. int err = getnameinfo ((struct sockaddr *) &peer, peer_len,
  2967. host, sizeof host, port, sizeof port, NI_NUMERICHOST | NI_NUMERICSERV);
  2968. if (err)
  2969. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  2970. struct client *c = client_new ();
  2971. c->ctx = ctx;
  2972. c->opened = time (NULL);
  2973. c->socket_fd = fd;
  2974. c->hostname = xstrdup (host);
  2975. c->port = xstrdup (port);
  2976. c->last_active = time (NULL);
  2977. LIST_PREPEND (ctx->clients, c);
  2978. ctx->n_clients++;
  2979. poller_fd_init (&c->socket_event, &c->ctx->poller, c->socket_fd);
  2980. c->socket_event.dispatcher = (poller_fd_fn) on_client_ready;
  2981. c->socket_event.user_data = c;
  2982. poller_timer_init (&c->kill_timer, &c->ctx->poller);
  2983. c->kill_timer.dispatcher = (poller_timer_fn) on_client_kill_timer;
  2984. c->kill_timer.user_data = c;
  2985. poller_timer_init (&c->timeout_timer, &c->ctx->poller);
  2986. c->timeout_timer.dispatcher = (poller_timer_fn) on_client_timeout_timer;
  2987. c->timeout_timer.user_data = c;
  2988. poller_timer_init (&c->ping_timer, &c->ctx->poller);
  2989. c->ping_timer.dispatcher = (poller_timer_fn) on_client_ping_timer;
  2990. c->ping_timer.user_data = c;
  2991. // Resolve the client's hostname first; this is a blocking operation that
  2992. // depends on the network, so run it asynchronously with some timeout
  2993. c->gni = async_getnameinfo (&ctx->poller.common.async,
  2994. (const struct sockaddr *) &peer, peer_len, NI_NUMERICSERV);
  2995. c->gni->dispatcher = on_client_gni_resolved;
  2996. c->gni->user_data = c;
  2997. poller_timer_init (&c->gni_timer, &c->ctx->poller);
  2998. c->gni_timer.dispatcher = (poller_timer_fn) on_client_gni_timer;
  2999. c->gni_timer.user_data = c;
  3000. poller_timer_set (&c->gni_timer, 5000);
  3001. return true;
  3002. }
  3003. static void
  3004. on_irc_client_available (const struct pollfd *pfd, void *user_data)
  3005. {
  3006. struct server_context *ctx = user_data;
  3007. while (irc_try_fetch_client (ctx, pfd->fd))
  3008. ;
  3009. }
  3010. // --- Application setup -------------------------------------------------------
  3011. static int
  3012. irc_ssl_verify_callback (int verify_ok, X509_STORE_CTX *ctx)
  3013. {
  3014. (void) verify_ok;
  3015. (void) ctx;
  3016. // We only want to provide additional privileges based on the client's
  3017. // certificate, so let's not terminate the connection because of a failure.
  3018. return 1;
  3019. }
  3020. static void
  3021. irc_ssl_info_callback (const SSL *ssl, int where, int ret)
  3022. {
  3023. // For debugging only; provides us with the most important information
  3024. struct str s;
  3025. str_init (&s);
  3026. if (where & SSL_CB_LOOP)
  3027. str_append_printf (&s, "loop (%s) ",
  3028. SSL_state_string_long (ssl));
  3029. if (where & SSL_CB_EXIT)
  3030. str_append_printf (&s, "exit (%d in %s) ", ret,
  3031. SSL_state_string_long (ssl));
  3032. if (where & SSL_CB_READ) str_append (&s, "read ");
  3033. if (where & SSL_CB_WRITE) str_append (&s, "write ");
  3034. if (where & SSL_CB_ALERT)
  3035. str_append_printf (&s, "alert (%s: %s) ",
  3036. SSL_alert_type_string_long (ret),
  3037. SSL_alert_desc_string_long (ret));
  3038. if (where & SSL_CB_HANDSHAKE_START) str_append (&s, "handshake start ");
  3039. if (where & SSL_CB_HANDSHAKE_DONE) str_append (&s, "handshake done ");
  3040. print_debug ("ssl <%p> %s", ssl, s.str);
  3041. str_free (&s);
  3042. }
  3043. static bool
  3044. irc_initialize_ssl_ctx (struct server_context *ctx,
  3045. const char *cert_path, const char *key_path, struct error **e)
  3046. {
  3047. ERR_clear_error ();
  3048. ctx->ssl_ctx = SSL_CTX_new (SSLv23_server_method ());
  3049. if (!ctx->ssl_ctx)
  3050. {
  3051. error_set (e, "%s: %s", "could not initialize TLS",
  3052. ERR_reason_error_string (ERR_get_error ()));
  3053. return false;
  3054. }
  3055. SSL_CTX_set_verify (ctx->ssl_ctx,
  3056. SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, irc_ssl_verify_callback);
  3057. if (g_debug_mode)
  3058. SSL_CTX_set_info_callback (ctx->ssl_ctx, irc_ssl_info_callback);
  3059. const unsigned char session_id_context[SSL_MAX_SSL_SESSION_ID_LENGTH]
  3060. = PROGRAM_NAME;
  3061. (void) SSL_CTX_set_session_id_context (ctx->ssl_ctx,
  3062. session_id_context, sizeof session_id_context);
  3063. // Gah, spare me your awkward semantics, I just want to push data!
  3064. SSL_CTX_set_mode (ctx->ssl_ctx,
  3065. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
  3066. // Disable deprecated protocols (see RFC 7568)
  3067. SSL_CTX_set_options (ctx->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
  3068. // XXX: perhaps we should read the files ourselves for better messages
  3069. const char *ciphers = str_map_find (&ctx->config, "tls_ciphers");
  3070. if (!SSL_CTX_set_cipher_list (ctx->ssl_ctx, ciphers))
  3071. error_set (e, "failed to select any cipher from the cipher list");
  3072. else if (!SSL_CTX_use_certificate_chain_file (ctx->ssl_ctx, cert_path))
  3073. error_set (e, "%s: %s", "setting the TLS certificate failed",
  3074. ERR_reason_error_string (ERR_get_error ()));
  3075. else if (!SSL_CTX_use_PrivateKey_file
  3076. (ctx->ssl_ctx, key_path, SSL_FILETYPE_PEM))
  3077. error_set (e, "%s: %s", "setting the TLS private key failed",
  3078. ERR_reason_error_string (ERR_get_error ()));
  3079. else
  3080. // TODO: SSL_CTX_check_private_key()? It has probably already been
  3081. // checked by SSL_CTX_use_PrivateKey_file() above.
  3082. return true;
  3083. SSL_CTX_free (ctx->ssl_ctx);
  3084. ctx->ssl_ctx = NULL;
  3085. return false;
  3086. }
  3087. static bool
  3088. irc_initialize_tls (struct server_context *ctx, struct error **e)
  3089. {
  3090. const char *tls_cert = str_map_find (&ctx->config, "tls_cert");
  3091. const char *tls_key = str_map_find (&ctx->config, "tls_key");
  3092. // Only try to enable SSL support if the user configures it; it is not
  3093. // a failure if no one has requested it.
  3094. if (!tls_cert && !tls_key)
  3095. return true;
  3096. if (!tls_cert)
  3097. error_set (e, "no TLS certificate set");
  3098. else if (!tls_key)
  3099. error_set (e, "no TLS private key set");
  3100. if (!tls_cert || !tls_key)
  3101. return false;
  3102. bool result = false;
  3103. char *cert_path = resolve_filename
  3104. (tls_cert, resolve_relative_config_filename);
  3105. char *key_path = resolve_filename
  3106. (tls_key, resolve_relative_config_filename);
  3107. if (!cert_path)
  3108. error_set (e, "%s: %s", "cannot open file", tls_cert);
  3109. else if (!key_path)
  3110. error_set (e, "%s: %s", "cannot open file", tls_key);
  3111. else
  3112. result = irc_initialize_ssl_ctx (ctx, cert_path, key_path, e);
  3113. free (cert_path);
  3114. free (key_path);
  3115. return result;
  3116. }
  3117. static bool
  3118. irc_initialize_catalog (struct server_context *ctx, struct error **e)
  3119. {
  3120. hard_assert (ctx->catalog == (nl_catd) -1);
  3121. const char *catalog = str_map_find (&ctx->config, "catalog");
  3122. if (!catalog)
  3123. return true;
  3124. char *path = resolve_filename (catalog, resolve_relative_config_filename);
  3125. if (!path)
  3126. {
  3127. error_set (e, "%s: %s", "cannot open file", catalog);
  3128. return false;
  3129. }
  3130. ctx->catalog = catopen (path, NL_CAT_LOCALE);
  3131. free (path);
  3132. if (ctx->catalog == (nl_catd) -1)
  3133. {
  3134. error_set (e, "%s: %s",
  3135. "failed reading the message catalog file", strerror (errno));
  3136. return false;
  3137. }
  3138. return true;
  3139. }
  3140. static bool
  3141. irc_initialize_motd (struct server_context *ctx, struct error **e)
  3142. {
  3143. hard_assert (ctx->motd.len == 0);
  3144. const char *motd = str_map_find (&ctx->config, "motd");
  3145. if (!motd)
  3146. return true;
  3147. char *path = resolve_filename (motd, resolve_relative_config_filename);
  3148. if (!path)
  3149. {
  3150. error_set (e, "%s: %s", "cannot open file", motd);
  3151. return false;
  3152. }
  3153. FILE *fp = fopen (path, "r");
  3154. free (path);
  3155. if (!fp)
  3156. {
  3157. error_set (e, "%s: %s",
  3158. "failed reading the MOTD file", strerror (errno));
  3159. return false;
  3160. }
  3161. struct str line;
  3162. str_init (&line);
  3163. while (read_line (fp, &line))
  3164. str_vector_add_owned (&ctx->motd, str_steal (&line));
  3165. str_free (&line);
  3166. fclose (fp);
  3167. return true;
  3168. }
  3169. /// This function handles values that require validation before their first use,
  3170. /// or some kind of a transformation (such as conversion to an integer) needs
  3171. /// to be done before they can be used directly.
  3172. static bool
  3173. irc_parse_config (struct server_context *ctx, struct error **e)
  3174. {
  3175. unsigned long ul;
  3176. #define PARSE_UNSIGNED(name, min, max) \
  3177. const char *name = str_map_find (&ctx->config, #name); \
  3178. hard_assert (name != NULL); \
  3179. if (!xstrtoul (&ul, name, 10) || ul > max || ul < min) \
  3180. { \
  3181. error_set (e, "invalid configuration value for `%s': %s", \
  3182. #name, "the number is invalid or out of range"); \
  3183. return false; \
  3184. } \
  3185. ctx->name = ul
  3186. PARSE_UNSIGNED (ping_interval, 1, UINT_MAX);
  3187. PARSE_UNSIGNED (max_connections, 0, UINT_MAX);
  3188. bool result = true;
  3189. struct str_vector fingerprints;
  3190. str_vector_init (&fingerprints);
  3191. const char *operators = str_map_find (&ctx->config, "operators");
  3192. if (operators)
  3193. cstr_split_ignore_empty (operators, ',', &fingerprints);
  3194. for (size_t i = 0; i < fingerprints.len; i++)
  3195. {
  3196. const char *key = fingerprints.vector[i];
  3197. if (!irc_is_valid_fingerprint (key))
  3198. {
  3199. error_set (e, "invalid configuration value for `%s': %s",
  3200. "operators", "invalid fingerprint value");
  3201. result = false;
  3202. break;
  3203. }
  3204. str_map_set (&ctx->operators, key, (void *) 1);
  3205. }
  3206. str_vector_free (&fingerprints);
  3207. return result;
  3208. }
  3209. static bool
  3210. irc_initialize_server_name (struct server_context *ctx, struct error **e)
  3211. {
  3212. enum validation_result res;
  3213. const char *server_name = str_map_find (&ctx->config, "server_name");
  3214. if (server_name)
  3215. {
  3216. res = irc_validate_hostname (server_name);
  3217. if (res != VALIDATION_OK)
  3218. {
  3219. error_set (e, "invalid configuration value for `%s': %s",
  3220. "server_name", irc_validate_to_str (res));
  3221. return false;
  3222. }
  3223. ctx->server_name = xstrdup (server_name);
  3224. }
  3225. else
  3226. {
  3227. long host_name_max = sysconf (_SC_HOST_NAME_MAX);
  3228. if (host_name_max <= 0)
  3229. host_name_max = _POSIX_HOST_NAME_MAX;
  3230. char hostname[host_name_max + 1];
  3231. if (gethostname (hostname, sizeof hostname))
  3232. {
  3233. error_set (e, "%s: %s",
  3234. "getting the hostname failed", strerror (errno));
  3235. return false;
  3236. }
  3237. res = irc_validate_hostname (hostname);
  3238. if (res != VALIDATION_OK)
  3239. {
  3240. error_set (e,
  3241. "`%s' is not set and the hostname (`%s') cannot be used: %s",
  3242. "server_name", hostname, irc_validate_to_str (res));
  3243. return false;
  3244. }
  3245. ctx->server_name = xstrdup (hostname);
  3246. }
  3247. return true;
  3248. }
  3249. static bool
  3250. irc_lock_pid_file (struct server_context *ctx, struct error **e)
  3251. {
  3252. const char *path = str_map_find (&ctx->config, "pid_file");
  3253. if (!path)
  3254. return true;
  3255. char *resolved = resolve_filename (path, resolve_relative_runtime_filename);
  3256. bool result = lock_pid_file (resolved, e) != -1;
  3257. free (resolved);
  3258. return result;
  3259. }
  3260. static int
  3261. irc_listen (struct addrinfo *gai_iter)
  3262. {
  3263. int fd = socket (gai_iter->ai_family,
  3264. gai_iter->ai_socktype, gai_iter->ai_protocol);
  3265. if (fd == -1)
  3266. return -1;
  3267. set_cloexec (fd);
  3268. int yes = 1;
  3269. soft_assert (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
  3270. &yes, sizeof yes) != -1);
  3271. soft_assert (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
  3272. &yes, sizeof yes) != -1);
  3273. char host[NI_MAXHOST], port[NI_MAXSERV];
  3274. host[0] = port[0] = '\0';
  3275. int err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
  3276. host, sizeof host, port, sizeof port,
  3277. NI_NUMERICHOST | NI_NUMERICSERV);
  3278. if (err)
  3279. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  3280. char *address = format_host_port_pair (host, port);
  3281. if (bind (fd, gai_iter->ai_addr, gai_iter->ai_addrlen))
  3282. print_error ("bind to %s failed: %s", address, strerror (errno));
  3283. else if (listen (fd, 16 /* arbitrary number */))
  3284. print_error ("listen on %s failed: %s", address, strerror (errno));
  3285. else
  3286. {
  3287. print_status ("listening on %s", address);
  3288. free (address);
  3289. return fd;
  3290. }
  3291. free (address);
  3292. xclose (fd);
  3293. return -1;
  3294. }
  3295. static void
  3296. irc_listen_resolve (struct server_context *ctx,
  3297. const char *host, const char *port, struct addrinfo *gai_hints)
  3298. {
  3299. struct addrinfo *gai_result, *gai_iter;
  3300. int err = getaddrinfo (host, port, gai_hints, &gai_result);
  3301. if (err)
  3302. {
  3303. char *address = format_host_port_pair (host, port);
  3304. print_error ("bind to %s failed: %s: %s",
  3305. address, "getaddrinfo", gai_strerror (err));
  3306. free (address);
  3307. return;
  3308. }
  3309. int fd;
  3310. for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next)
  3311. {
  3312. if ((fd = irc_listen (gai_iter)) == -1)
  3313. continue;
  3314. set_blocking (fd, false);
  3315. struct poller_fd *event = &ctx->listen_events[ctx->n_listen_fds];
  3316. poller_fd_init (event, &ctx->poller, fd);
  3317. event->dispatcher = (poller_fd_fn) on_irc_client_available;
  3318. event->user_data = ctx;
  3319. ctx->listen_fds[ctx->n_listen_fds++] = fd;
  3320. poller_fd_set (event, POLLIN);
  3321. break;
  3322. }
  3323. freeaddrinfo (gai_result);
  3324. }
  3325. static bool
  3326. irc_setup_listen_fds (struct server_context *ctx, struct error **e)
  3327. {
  3328. const char *bind_host = str_map_find (&ctx->config, "bind_host");
  3329. const char *bind_port = str_map_find (&ctx->config, "bind_port");
  3330. hard_assert (bind_port != NULL); // We have a default value for this
  3331. struct addrinfo gai_hints;
  3332. memset (&gai_hints, 0, sizeof gai_hints);
  3333. gai_hints.ai_socktype = SOCK_STREAM;
  3334. gai_hints.ai_flags = AI_PASSIVE;
  3335. struct str_vector ports;
  3336. str_vector_init (&ports);
  3337. cstr_split_ignore_empty (bind_port, ',', &ports);
  3338. ctx->listen_fds = xcalloc (ports.len, sizeof *ctx->listen_fds);
  3339. ctx->listen_events = xcalloc (ports.len, sizeof *ctx->listen_events);
  3340. for (size_t i = 0; i < ports.len; i++)
  3341. irc_listen_resolve (ctx, bind_host, ports.vector[i], &gai_hints);
  3342. str_vector_free (&ports);
  3343. if (!ctx->n_listen_fds)
  3344. {
  3345. error_set (e, "%s: %s",
  3346. "network setup failed", "no ports to listen on");
  3347. return false;
  3348. }
  3349. return true;
  3350. }
  3351. // --- Main --------------------------------------------------------------------
  3352. static void
  3353. on_signal_pipe_readable (const struct pollfd *fd, struct server_context *ctx)
  3354. {
  3355. char dummy;
  3356. (void) read (fd->fd, &dummy, 1);
  3357. if (g_termination_requested && !ctx->quitting)
  3358. irc_initiate_quit (ctx);
  3359. }
  3360. static void
  3361. daemonize (struct server_context *ctx)
  3362. {
  3363. print_status ("daemonizing...");
  3364. if (chdir ("/"))
  3365. exit_fatal ("%s: %s", "chdir", strerror (errno));
  3366. // Because of systemd, we need to exit the parent process _after_ writing
  3367. // a PID file, otherwise our grandchild would receive a SIGTERM
  3368. int sync_pipe[2];
  3369. if (pipe (sync_pipe))
  3370. exit_fatal ("%s: %s", "pipe", strerror (errno));
  3371. pid_t pid;
  3372. if ((pid = fork ()) < 0)
  3373. exit_fatal ("%s: %s", "fork", strerror (errno));
  3374. else if (pid)
  3375. {
  3376. // Wait until all write ends of the pipe are closed, which can mean
  3377. // either success or failure, we don't need to care
  3378. xclose (sync_pipe[PIPE_WRITE]);
  3379. char dummy;
  3380. if (read (sync_pipe[PIPE_READ], &dummy, 1) < 0)
  3381. exit_fatal ("%s: %s", "read", strerror (errno));
  3382. exit (EXIT_SUCCESS);
  3383. }
  3384. setsid ();
  3385. signal (SIGHUP, SIG_IGN);
  3386. if ((pid = fork ()) < 0)
  3387. exit_fatal ("%s: %s", "fork", strerror (errno));
  3388. else if (pid)
  3389. exit (EXIT_SUCCESS);
  3390. openlog (PROGRAM_NAME, LOG_NDELAY | LOG_NOWAIT | LOG_PID, 0);
  3391. g_log_message_real = log_message_syslog;
  3392. // Write the PID file (if so configured) and get rid of the pipe, so that
  3393. // the read() in our grandparent finally returns zero (no write ends)
  3394. struct error *e = NULL;
  3395. if (!irc_lock_pid_file (ctx, &e))
  3396. exit_fatal ("%s", e->message);
  3397. xclose (sync_pipe[PIPE_READ]);
  3398. xclose (sync_pipe[PIPE_WRITE]);
  3399. // XXX: we may close our own descriptors this way, crippling ourselves;
  3400. // there is no real guarantee that we will start with all three
  3401. // descriptors open. In theory we could try to enumerate the descriptors
  3402. // at the start of main().
  3403. for (int i = 0; i < 3; i++)
  3404. xclose (i);
  3405. int tty = open ("/dev/null", O_RDWR);
  3406. if (tty != 0 || dup (0) != 1 || dup (0) != 2)
  3407. exit_fatal ("failed to reopen FD's: %s", strerror (errno));
  3408. poller_post_fork (&ctx->poller);
  3409. }
  3410. int
  3411. main (int argc, char *argv[])
  3412. {
  3413. // Need to call this first as all string maps depend on it
  3414. siphash_wrapper_randomize ();
  3415. static const struct opt opts[] =
  3416. {
  3417. { 'd', "debug", NULL, 0, "run in debug mode (do not daemonize)" },
  3418. { 'h', "help", NULL, 0, "display this help and exit" },
  3419. { 'V', "version", NULL, 0, "output version information and exit" },
  3420. { 'w', "write-default-cfg", "FILENAME",
  3421. OPT_OPTIONAL_ARG | OPT_LONG_ONLY,
  3422. "write a default configuration file and exit" },
  3423. { 0, NULL, NULL, 0, NULL }
  3424. };
  3425. struct opt_handler oh;
  3426. opt_handler_init (&oh, argc, argv, opts, NULL, "Experimental IRC daemon.");
  3427. int c;
  3428. while ((c = opt_handler_get (&oh)) != -1)
  3429. switch (c)
  3430. {
  3431. case 'd':
  3432. g_debug_mode = true;
  3433. break;
  3434. case 'h':
  3435. opt_handler_usage (&oh, stdout);
  3436. exit (EXIT_SUCCESS);
  3437. case 'V':
  3438. printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
  3439. exit (EXIT_SUCCESS);
  3440. case 'w':
  3441. call_simple_config_write_default (optarg, g_config_table);
  3442. exit (EXIT_SUCCESS);
  3443. default:
  3444. print_error ("wrong options");
  3445. opt_handler_usage (&oh, stderr);
  3446. exit (EXIT_FAILURE);
  3447. }
  3448. opt_handler_free (&oh);
  3449. print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting");
  3450. setup_signal_handlers ();
  3451. SSL_library_init ();
  3452. atexit (EVP_cleanup);
  3453. SSL_load_error_strings ();
  3454. atexit (ERR_free_strings);
  3455. struct server_context ctx;
  3456. server_context_init (&ctx);
  3457. ctx.started = time (NULL);
  3458. irc_register_handlers (&ctx);
  3459. irc_register_cap_handlers (&ctx);
  3460. struct error *e = NULL;
  3461. if (!simple_config_update_from_file (&ctx.config, &e))
  3462. {
  3463. print_error ("error loading configuration: %s", e->message);
  3464. error_free (e);
  3465. exit (EXIT_FAILURE);
  3466. }
  3467. poller_fd_init (&ctx.signal_event, &ctx.poller, g_signal_pipe[0]);
  3468. ctx.signal_event.dispatcher = (poller_fd_fn) on_signal_pipe_readable;
  3469. ctx.signal_event.user_data = &ctx;
  3470. poller_fd_set (&ctx.signal_event, POLLIN);
  3471. if (!irc_initialize_tls (&ctx, &e)
  3472. || !irc_initialize_server_name (&ctx, &e)
  3473. || !irc_initialize_motd (&ctx, &e)
  3474. || !irc_initialize_catalog (&ctx, &e)
  3475. || !irc_parse_config (&ctx, &e)
  3476. || !irc_setup_listen_fds (&ctx, &e))
  3477. exit_fatal ("%s", e->message);
  3478. if (!g_debug_mode)
  3479. daemonize (&ctx);
  3480. else if (!irc_lock_pid_file (&ctx, &e))
  3481. exit_fatal ("%s", e->message);
  3482. #if OpenBSD >= 201605
  3483. // This won't be as simple once we decide to implement REHASH
  3484. if (pledge ("stdio inet dns", NULL))
  3485. exit_fatal ("%s: %s", "pledge", strerror (errno));
  3486. #endif
  3487. ctx.polling = true;
  3488. while (ctx.polling)
  3489. poller_run (&ctx.poller);
  3490. server_context_free (&ctx);
  3491. return EXIT_SUCCESS;
  3492. }