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.

4042 lines
111KB

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