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.

3996 lines
110KB

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