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.

4033 lines
112KB

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