summaryrefslogtreecommitdiff
path: root/src/kike.c
blob: faea7b9d9def1142912b0e62af5d3511caa47511 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
/*
 * kike.c: the experimental IRC daemon
 *
 * Copyright (c) 2014, Přemysl Janouch <p.janouch@gmail.com>
 * All rights reserved.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#define PROGRAM_NAME "kike"
#define PROGRAM_VERSION "alpha"

#include "common.c"
#include <nl_types.h>

// --- Configuration (application-specific) ------------------------------------

static struct config_item g_config_table[] =
{
	{ "server_name",     NULL,              "Server name"                    },
	{ "motd",            NULL,              "MOTD filename"                  },
	{ "catalog",         NULL,              "catgets localization catalog"   },

	{ "bind_host",       NULL,              "Address of the IRC server"      },
	{ "bind_port",       "6667",            "Port of the IRC server"         },
	{ "ssl_cert",        NULL,              "Server SSL certificate (PEM)"   },
	{ "ssl_key",         NULL,              "Server SSL private key (PEM)"   },

	{ "max_connections", NULL,              "Maximum client connections"     },
	{ NULL,              NULL,              NULL                             }
};

// --- Signals -----------------------------------------------------------------

static int g_signal_pipe[2];            ///< A pipe used to signal... signals

/// Program termination has been requested by a signal
static volatile sig_atomic_t g_termination_requested;

static void
sigterm_handler (int signum)
{
	(void) signum;

	g_termination_requested = true;

	int original_errno = errno;
	if (write (g_signal_pipe[1], "t", 1) == -1)
		soft_assert (errno == EAGAIN);
	errno = original_errno;
}

static void
setup_signal_handlers (void)
{
	if (pipe (g_signal_pipe) == -1)
	{
		print_fatal ("pipe: %s", strerror (errno));
		exit (EXIT_FAILURE);
	}

	set_cloexec (g_signal_pipe[0]);
	set_cloexec (g_signal_pipe[1]);

	// So that the pipe cannot overflow; it would make write() block within
	// the signal handler, which is something we really don't want to happen.
	// The same holds true for read().
	set_blocking (g_signal_pipe[0], false);
	set_blocking (g_signal_pipe[1], false);

	signal (SIGPIPE, SIG_IGN);

	struct sigaction sa;
	sa.sa_flags = SA_RESTART;
	sigemptyset (&sa.sa_mask);
	sa.sa_handler = sigterm_handler;
	if (sigaction (SIGINT, &sa, NULL) == -1
	 || sigaction (SIGTERM, &sa, NULL) == -1)
	{
		print_error ("sigaction: %s", strerror (errno));
		exit (EXIT_FAILURE);
	}
}

// --- IRC token validation ----------------------------------------------------

enum validation_result
{
	VALIDATION_OK,
	VALIDATION_ERROR_EMPTY,
	VALIDATION_ERROR_TOO_LONG,
	VALIDATION_ERROR_INVALID
};

// Everything as per RFC 2812
#define IRC_NICKNAME_MAX    9
#define IRC_HOSTNAME_MAX   63

static bool
irc_regex_match (const char *regex, const char *s)
{
	static struct str_map cache;
	static bool initialized;

	if (!initialized)
	{
		regex_cache_init (&cache);
		initialized = true;
	}

	struct error *e = NULL;
	bool result = regex_cache_match (&cache, regex,
		REG_EXTENDED | REG_NOSUB, s, &e);
	hard_assert (!e);
	return result;
}

static const char *
irc_validate_to_str (enum validation_result result)
{
	switch (result)
	{
	case VALIDATION_OK:              return "success";
	case VALIDATION_ERROR_EMPTY:     return "the value is empty";
	case VALIDATION_ERROR_INVALID:   return "invalid format";
	case VALIDATION_ERROR_TOO_LONG:  return "the value is too long";
	default:                         abort ();
	}
}

// Anything to keep it as short as possible
#define SN "[0-9A-Za-z][-0-9A-Za-z]*[0-9A-Za-z]*"
#define N4 "[0-9]{1,3}"
#define N6 "[0-9ABCDEFabcdef]{1,}"

#define LE "A-Za-z"
#define SP "\\[\\]\\\\`_^{|}"

static enum validation_result
irc_validate_hostname (const char *hostname)
{
	if (!*hostname)
		return VALIDATION_ERROR_EMPTY;
	if (!irc_regex_match ("^" SN "(\\." SN ")*$", hostname))
		return VALIDATION_ERROR_INVALID;
	if (strlen (hostname) > IRC_HOSTNAME_MAX)
		return VALIDATION_ERROR_TOO_LONG;
	return VALIDATION_OK;
}

static bool
irc_is_valid_hostaddr (const char *hostaddr)
{
	if (irc_regex_match ("^" N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr)
	 || irc_regex_match ("^" N6 ":" N6 ":" N6 ":" N6 ":"
		N6 ":" N6 ":" N6 ":" N6 "$", hostaddr)
	 || irc_regex_match ("^0:0:0:0:0:(0|[Ff]{4}):"
		N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr))
		return true;
	return false;
}

static bool
irc_is_valid_host (const char *host)
{
	return irc_validate_hostname (host) == VALIDATION_OK
		|| irc_is_valid_hostaddr (host);
}

static bool
irc_validate_nickname (const char *nickname)
{
	if (!*nickname)
		return VALIDATION_ERROR_EMPTY;
	if (!irc_regex_match ("^[" LE SP "][-0-9" LE SP "]*$", nickname))
		return VALIDATION_ERROR_INVALID;
	if (strlen (nickname) > IRC_NICKNAME_MAX)
		return VALIDATION_ERROR_TOO_LONG;
	return VALIDATION_OK;
}

#undef SN
#undef N4
#undef N6

#undef LE
#undef SP

// --- Application data --------------------------------------------------------

enum
{
	IRC_USER_MODE_INVISIBLE          = (1 << 0),
	IRC_USER_MODE_RX_WALLOPS         = (1 << 1),
	IRC_USER_MODE_RESTRICTED         = (1 << 2),
	IRC_USER_MODE_OPERATOR           = (1 << 3),
	IRC_USER_MODE_RX_SERVER_NOTICES  = (1 << 4)
};

struct connection
{
	struct connection *next;            ///< The next link in a chain
	struct connection *prev;            ///< The previous link in a chain

	struct server_context *ctx;         ///< Server context

	int socket_fd;                      ///< The TCP socket
	struct str read_buffer;             ///< Unprocessed input
	struct str write_buffer;            ///< Output yet to be sent out

	unsigned initialized    : 1;        ///< Has any data been received yet?
	unsigned ssl_rx_want_tx : 1;        ///< SSL_read() wants to write
	unsigned ssl_tx_want_rx : 1;        ///< SSL_write() wants to read

	SSL *ssl;                           ///< SSL connection

	char *nickname;                     ///< IRC nickname (main identifier)
	char *username;                     ///< IRC username
	char *realname;                     ///< IRC realname (e-mail)

	char *hostname;                     ///< Hostname shown to the network

	unsigned mode;                      ///< User's mode
	char *away_message;                 ///< Away message
};

static void
connection_init (struct connection *self)
{
	memset (self, 0, sizeof *self);

	self->socket_fd = -1;
	str_init (&self->read_buffer);
	str_init (&self->write_buffer);
}

static void
connection_free (struct connection *self)
{
	if (!soft_assert (self->socket_fd == -1))
		xclose (self->socket_fd);
	if (self->ssl)
		SSL_free (self->ssl);

	str_free (&self->read_buffer);
	str_free (&self->write_buffer);

	free (self->nickname);
	free (self->username);
	free (self->realname);

	free (self->hostname);
	free (self->away_message);
}

enum
{
	IRC_CHAN_MODE_INVITE_ONLY      = (1 << 0),
	IRC_CHAN_MODE_MODERATED        = (1 << 1),
	IRC_CHAN_MODE_NO_OUTSIDE_MSGS  = (1 << 2),
	IRC_CHAN_MODE_SECRET           = (1 << 3),
	IRC_CHAN_MODE_PRIVATE          = (1 << 4),
	IRC_CHAN_MODE_PROTECTED_TOPIC  = (1 << 5),
	IRC_CHAN_MODE_QUIET            = (1 << 6)
};

struct channel
{
	struct server_context *ctx;         ///< Server context

	char *name;                         ///< Channel name
	unsigned modes;                     ///< Channel modes
	char *key;                          ///< Channel key
	long user_limit;                    ///< User limit or -1

	struct str_vector ban_list;         ///< Ban list
	struct str_vector exception_list;   ///< Exceptions from bans
	struct str_vector invite_list;      ///< Exceptions from +I
};

static void
channel_init (struct channel *self)
{
	memset (self, 0, sizeof *self);

	str_vector_init (&self->ban_list);
	str_vector_init (&self->exception_list);
	str_vector_init (&self->invite_list);
}

static void
channel_free (struct channel *self)
{
	free (self->name);
	free (self->key);

	str_vector_free (&self->ban_list);
	str_vector_free (&self->exception_list);
	str_vector_free (&self->invite_list);
}

struct server_context
{
	struct str_map config;              ///< Server configuration

	int listen_fd;                      ///< Listening socket FD
	struct connection *clients;         ///< Client connections
	SSL_CTX *ssl_ctx;                   ///< SSL context

	char *server_name;                  ///< Our server name
	struct str_map users;               ///< Maps nicknames to connections
	struct str_map channels;            ///< Maps channel names to data

	struct poller poller;               ///< Manages polled description
	bool quitting;                      ///< User requested quitting
	bool polling;                       ///< The event loop is running

	struct str_vector motd;             ///< MOTD (none if empty)
	nl_catd catalog;                    ///< Message catalog for server msgs
};

static void
server_context_init (struct server_context *self)
{
	str_map_init (&self->config);
	self->config.free = free;
	load_config_defaults (&self->config, g_config_table);

	self->listen_fd = -1;
	self->clients = NULL;

	self->server_name = NULL;
	str_map_init (&self->users);
	// TODO: set channel_free() as the free function?
	str_map_init (&self->channels);

	poller_init (&self->poller);
	self->quitting = false;
	self->polling = false;

	str_vector_init (&self->motd);
	self->catalog = (nl_catd) -1;
}

static void
server_context_free (struct server_context *self)
{
	str_map_free (&self->config);

	if (self->listen_fd != -1)
		xclose (self->listen_fd);
	if (self->ssl_ctx)
		SSL_CTX_free (self->ssl_ctx);

	// TODO: terminate the connections properly before this is called
	struct connection *link, *tmp;
	for (link = self->clients; link; link = tmp)
	{
		tmp = link->next;
		connection_free (link);
		free (link);
	}

	free (self->server_name);
	str_map_free (&self->users);
	str_map_free (&self->channels);
	poller_free (&self->poller);

	str_vector_free (&self->motd);
	if (self->catalog != (nl_catd) -1)
		catclose (self->catalog);
}

// --- Main program ------------------------------------------------------------

static size_t network_error_domain_tag;
#define NETWORK_ERROR (error_resolve_domain (&network_error_domain_tag))

enum
{
	NETWORK_ERROR_INVALID_CONFIGURATION,
	NETWORK_ERROR_FAILED
};

static bool
irc_autodetect_ssl (struct connection *conn)
{
	// Trivial SSL/TLS autodetection.  The first block of data returned by
	// recv() must be at least three bytes long for this to work reliably,
	// but that should not pose a problem in practice.
	//
	// SSL2:      1xxx xxxx | xxxx xxxx |    <1>
	//               (message length)  (client hello)
	// SSL3/TLS:    <22>    |    <3>    | xxxx xxxx
	//           (handshake)|  (protocol version)
	//
	// Such byte sequences should never occur at the beginning of regular IRC
	// communication, which usually begins with USER/NICK/PASS/SERVICE.

	char buf[3];
start:
	switch (recv (conn->socket_fd, buf, sizeof buf, MSG_PEEK))
	{
	case 3:
		if ((buf[0] & 0x80) && buf[2] == 1)
			return true;
	case 2:
		if (buf[0] == 22 && buf[1] == 3)
			return true;
		break;
	case 1:
		if (buf[0] == 22)
			return true;
		break;
	case 0:
		break;
	default:
		if (errno == EINTR)
			goto start;
	}
	return false;
}

static int
irc_ssl_verify_callback (int verify_ok, X509_STORE_CTX *ctx)
{
	(void) verify_ok;
	(void) ctx;

	// We only want to provide additional privileges based on the client's
	// certificate, so let's not terminate the connection because of a failure.
	return 1;
}

static bool
connection_initialize_ssl (struct connection *conn)
{
	// SSL support not enabled
	if (!conn->ctx->ssl_ctx)
		return false;

	conn->ssl = SSL_new (conn->ctx->ssl_ctx);
	if (!conn->ssl)
		goto error_ssl_1;

	if (!SSL_set_fd (conn->ssl, conn->socket_fd))
		goto error_ssl_2;
	SSL_set_accept_state (conn->ssl);
	return true;

error_ssl_2:
	SSL_free (conn->ssl);
	conn->ssl = NULL;
error_ssl_1:
	// XXX: these error strings are really nasty; also there could be
	//   multiple errors on the OpenSSL stack.
	print_debug ("%s: %s: %s", "could not initialize SSL",
		conn->hostname, ERR_error_string (ERR_get_error (), NULL));
	return false;
}

static void
connection_kill (struct connection *conn, const char *reason)
{
	// TODO: send a QUIT message with `reason' || "Client exited"
	(void) reason;

	// TODO: do further cleanup if the client has successfully registered

	struct server_context *ctx = conn->ctx;
	ssize_t i = poller_find_by_fd (&ctx->poller, conn->socket_fd);
	if (i != -1)
		poller_remove_at_index (&ctx->poller, i);

	xclose (conn->socket_fd);
	conn->socket_fd = -1;
	connection_free (conn);
	LIST_UNLINK (ctx->clients, conn);
	free (conn);
}

static void
irc_process_message (const struct irc_message *msg,
	const char *raw, void *user_data)
{
	struct connection *conn = user_data;
	// TODO
}

static bool
irc_try_read (struct connection *conn)
{
	struct str *buf = &conn->read_buffer;
	ssize_t n_read;

	while (true)
	{
		str_ensure_space (buf, 512);
		n_read = recv (conn->socket_fd, buf->str + buf->len,
			buf->alloc - buf->len - 1 /* null byte */, 0);

		if (n_read > 0)
		{
			buf->str[buf->len += n_read] = '\0';
			// TODO: discard characters above the 512 character limit
			irc_process_buffer (buf, irc_process_message, conn);
			continue;
		}
		if (n_read == 0)
		{
			connection_kill (conn, NULL);
			return false;
		}

		if (errno == EAGAIN)
			return true;
		if (errno == EINTR)
			continue;

		print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
		connection_kill (conn, strerror (errno));
		return false;
	}
}

static bool
irc_try_read_ssl (struct connection *conn)
{
	if (conn->ssl_tx_want_rx)
		return true;

	struct str *buf = &conn->read_buffer;
	conn->ssl_rx_want_tx = false;
	while (true)
	{
		str_ensure_space (buf, 512);
		int n_read = SSL_read (conn->ssl, buf->str + buf->len,
			buf->alloc - buf->len - 1 /* null byte */);

		const char *error_info = NULL;
		switch (xssl_get_error (conn->ssl, n_read, &error_info))
		{
		case SSL_ERROR_NONE:
			buf->str[buf->len += n_read] = '\0';
			// TODO: discard characters above the 512 character limit
			irc_process_buffer (buf, irc_process_message, conn);
			continue;
		case SSL_ERROR_ZERO_RETURN:
			connection_kill (conn, NULL);
			return false;
		case SSL_ERROR_WANT_READ:
			return true;
		case SSL_ERROR_WANT_WRITE:
			conn->ssl_rx_want_tx = true;
			return true;
		case XSSL_ERROR_TRY_AGAIN:
			continue;
		default:
			print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
			connection_kill (conn, error_info);
			return false;
		}
	}
}

static bool
irc_try_write (struct connection *conn)
{
	struct str *buf = &conn->write_buffer;
	ssize_t n_written;

	while (buf->len)
	{
		n_written = send (conn->socket_fd, buf->str, buf->len, 0);
		if (n_written >= 0)
		{
			str_remove_slice (buf, 0, n_written);
			continue;
		}

		if (errno == EAGAIN)
			return true;
		if (errno == EINTR)
			continue;

		print_debug ("%s: %s: %s", __func__, "send", strerror (errno));
		connection_kill (conn, strerror (errno));
		return false;
	}
	return true;
}

static bool
irc_try_write_ssl (struct connection *conn)
{
	if (conn->ssl_rx_want_tx)
		return true;

	struct str *buf = &conn->write_buffer;
	conn->ssl_tx_want_rx = false;
	while (buf->len)
	{
		int n_written = SSL_write (conn->ssl, buf->str, buf->len);

		const char *error_info = NULL;
		switch (xssl_get_error (conn->ssl, n_written, &error_info))
		{
		case SSL_ERROR_NONE:
			str_remove_slice (buf, 0, n_written);
			continue;
		case SSL_ERROR_ZERO_RETURN:
			connection_kill (conn, NULL);
			return false;
		case SSL_ERROR_WANT_WRITE:
			return true;
		case SSL_ERROR_WANT_READ:
			conn->ssl_tx_want_rx = true;
			return true;
		case XSSL_ERROR_TRY_AGAIN:
			continue;
		default:
			print_debug ("%s: %s: %s", __func__, "SSL_write", error_info);
			connection_kill (conn, error_info);
			return false;
		}
	}
	return true;
}

static void
on_irc_client_ready (const struct pollfd *pfd, void *user_data)
{
	struct connection *conn = user_data;
	if (!conn->initialized)
	{
		hard_assert (pfd->events == POLLIN);
		if (irc_autodetect_ssl (conn) && !connection_initialize_ssl (conn))
		{
			connection_kill (conn, NULL);
			return;
		}
		conn->initialized = true;
	}

	int new_events = 0;
	if (conn->ssl)
	{
		// Reads may want to write, writes may want to read, poll() may
		// return unexpected things in `revents'... let's try both
		if (!irc_try_read_ssl (conn) || !irc_try_write_ssl (conn))
			return;

		new_events |= POLLIN;
		if (conn->write_buffer.len || conn->ssl_rx_want_tx)
			new_events |= POLLOUT;

		// While we're waiting for an opposite event, we ignore the original
		if (conn->ssl_rx_want_tx)  new_events &= ~POLLIN;
		if (conn->ssl_tx_want_rx)  new_events &= ~POLLOUT;
	}
	else
	{
		if (!irc_try_read (conn) || !irc_try_write (conn))
			return;

		new_events |= POLLIN;
		if (conn->write_buffer.len)
			new_events |= POLLOUT;
	}

	hard_assert (new_events != 0);
	if (pfd->events != new_events)
		poller_set (&conn->ctx->poller, conn->socket_fd, new_events,
			(poller_dispatcher_func) on_irc_client_ready, conn);
}

static void
on_irc_connection_available (const struct pollfd *pfd, void *user_data)
{
	(void) pfd;
	struct server_context *ctx = user_data;

	// TODO: stop accepting new connections when `max_connections' is reached

	while (true)
	{
		// XXX: `struct sockaddr_storage' is not the most portable thing
		struct sockaddr_storage peer;
		socklen_t peer_len = sizeof peer;

		int fd = accept (ctx->listen_fd, (struct sockaddr *) &peer, &peer_len);
		if (fd == -1)
		{
			if (errno == EAGAIN)
				break;
			if (errno == EINTR)
				continue;
			if (errno == ECONNABORTED)
				continue;

			// TODO: handle resource exhaustion (EMFILE, ENFILE) specially
			//   (stop accepting new connections and wait until we close some).
			print_fatal ("%s: %s", "accept", strerror (errno));

			// FIXME: handle this better, bring the server down cleanly.
			exit (EXIT_FAILURE);
		}

		char host[NI_MAXHOST] = "unknown", port[NI_MAXSERV] = "unknown";
		int err = getnameinfo ((struct sockaddr *) &peer, peer_len,
			host, sizeof host, port, sizeof port, AI_NUMERICSERV);
		if (err)
			print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
		print_debug ("accepted connection from %s:%s", host, port);

		struct connection *conn = xmalloc (sizeof *conn);
		connection_init (conn);
		conn->socket_fd = fd;
		conn->hostname = xstrdup (host);
		LIST_PREPEND (ctx->clients, conn);

		// TODO: set a timeout on the socket, something like 3 minutes, then we
		//   should terminate the connection.
		poller_set (&ctx->poller, conn->socket_fd, POLLIN,
			(poller_dispatcher_func) on_irc_client_ready, conn);
	}
}

static bool
irc_initialize_ssl (struct server_context *ctx)
{
	const char *ssl_cert = str_map_find (&ctx->config, "ssl_cert");
	const char *ssl_key = str_map_find (&ctx->config, "ssl_key");

	// Only try to enable SSL support if the user configures it; it is not
	// a failure if no one has requested it.
	if (!ssl_cert && !ssl_key)
		return true;

	if (!ssl_cert)
	{
		print_error ("no SSL certificate set");
		return false;
	}
	if (!ssl_key)
	{
		print_error ("no SSL private key set");
		return false;
	}

	ctx->ssl_ctx = SSL_CTX_new (SSLv23_server_method ());
	if (!ctx->ssl_ctx)
		goto error_ssl_1;
	SSL_CTX_set_verify (ctx->ssl_ctx,
		SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, irc_ssl_verify_callback);
	// XXX: maybe we should call SSL_CTX_set_options() for some workarounds

	// XXX: perhaps we should read the files ourselves for better messages
	if (!SSL_CTX_use_certificate_chain_file (ctx->ssl_ctx, ssl_cert))
	{
		print_error ("%s: %s", "setting the SSL client certificate failed",
			ERR_error_string (ERR_get_error (), NULL));
		goto error_ssl_2;
	}
	if (!SSL_CTX_use_PrivateKey_file (ctx->ssl_ctx, ssl_key, SSL_FILETYPE_PEM))
	{
		print_error ("%s: %s", "setting the SSL private key failed",
			ERR_error_string (ERR_get_error (), NULL));
		goto error_ssl_2;
	}

	// TODO: SSL_CTX_check_private_key()?  It has probably already been checked
	//   by SSL_CTX_use_PrivateKey_file() above.

	// Gah, spare me your awkward semantics, I just want to push data!
	// XXX: do we want SSL_MODE_AUTO_RETRY as well?  I guess not.
	SSL_CTX_set_mode (ctx->ssl_ctx,
		SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
	return true;

error_ssl_2:
	SSL_CTX_free (ctx->ssl_ctx);
	ctx->ssl_ctx = NULL;
error_ssl_1:
	// XXX: these error strings are really nasty; also there could be
	//   multiple errors on the OpenSSL stack.
	print_error ("%s: %s", "could not initialize SSL",
		ERR_error_string (ERR_get_error (), NULL));
	return false;
}

static bool
irc_initialize_catalog (struct server_context *ctx, struct error **e)
{
	hard_assert (ctx->catalog == (nl_catd) -1);
	const char *catalog = str_map_find (&ctx->config, "catalog");
	if (!catalog)
		return true;

	ctx->catalog = catopen (catalog, NL_CAT_LOCALE);
	if (ctx->catalog == (nl_catd) -1)
	{
		error_set (e, IO_ERROR, IO_ERROR_FAILED, "%s: %s",
			"failed reading the message catalog file", strerror (errno));
		return false;
	}
	return true;
}

static bool
irc_initialize_motd (struct server_context *ctx, struct error **e)
{
	hard_assert (ctx->motd.len == 0);
	const char *motd = str_map_find (&ctx->config, "motd");
	if (!motd)
		return true;

	FILE *fp = fopen (motd, "r");
	if (!fp)
	{
		error_set (e, IO_ERROR, IO_ERROR_FAILED,
			"%s: %s", "failed reading the MOTD file", strerror (errno));
		return false;
	}

	struct str line;
	str_init (&line);
	while (read_line (fp, &line))
		str_vector_add_owned (&ctx->motd, str_steal (&line));
	str_free (&line);

	fclose (fp);
	return true;
}

static bool
irc_initialize_server_name (struct server_context *ctx, struct error **e)
{
	enum validation_result res;
	const char *server_name = str_map_find (&ctx->config, "server_name");
	if (server_name)
	{
		res = irc_validate_hostname (server_name);
		if (res != VALIDATION_OK)
		{
			error_set (e, NETWORK_ERROR, NETWORK_ERROR_INVALID_CONFIGURATION,
				"invalid configuration value for `%s': %s", "server_name",
				irc_validate_to_str (res));
			return false;
		}
		ctx->server_name = xstrdup (server_name);
	}
	else
	{
		char hostname[HOST_NAME_MAX];
		if (gethostname (hostname, sizeof hostname))
		{
			error_set (e, NETWORK_ERROR, NETWORK_ERROR_INVALID_CONFIGURATION,
				"%s: %s", "getting the hostname failed", strerror (errno));
			return false;
		}
		res = irc_validate_hostname (hostname);
		if (res != VALIDATION_OK)
		{
			error_set (e, NETWORK_ERROR, NETWORK_ERROR_INVALID_CONFIGURATION,
				"`%s' is not set and the hostname (`%s') cannot be used: %s",
				"server_name", hostname, irc_validate_to_str (res));
			return false;
		}
		ctx->server_name = xstrdup (hostname);
	}
	return true;
}

static bool
irc_listen (struct server_context *ctx, struct error **e)
{
	const char *bind_host = str_map_find (&ctx->config, "bind_host");
	const char *bind_port = str_map_find (&ctx->config, "bind_port");
	hard_assert (bind_port != NULL);  // We have a default value for this

	if (!irc_initialize_server_name (ctx, e))
		return false;
	if (!irc_initialize_motd (ctx, e))
		return false;

	struct addrinfo gai_hints, *gai_result, *gai_iter;
	memset (&gai_hints, 0, sizeof gai_hints);

	gai_hints.ai_socktype = SOCK_STREAM;
	gai_hints.ai_flags = AI_PASSIVE;

	int err = getaddrinfo (bind_host, bind_port, &gai_hints, &gai_result);
	if (err)
	{
		error_set (e, NETWORK_ERROR, NETWORK_ERROR_FAILED, "%s: %s: %s",
			"network setup failed", "getaddrinfo", gai_strerror (err));
		return false;
	}

	int sockfd;
	char real_host[NI_MAXHOST], real_port[NI_MAXSERV];

	for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next)
	{
		sockfd = socket (gai_iter->ai_family,
			gai_iter->ai_socktype, gai_iter->ai_protocol);
		if (sockfd == -1)
			continue;
		set_cloexec (sockfd);

		int yes = 1;
		soft_assert (setsockopt (sockfd, SOL_SOCKET, SO_KEEPALIVE,
			&yes, sizeof yes) != -1);
		soft_assert (setsockopt (sockfd, SOL_SOCKET, SO_REUSEADDR,
			&yes, sizeof yes) != -1);

		real_host[0] = real_port[0] = '\0';
		err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
			real_host, sizeof real_host, real_port, sizeof real_port,
			NI_NUMERICHOST | NI_NUMERICSERV);
		if (err)
			print_debug ("%s: %s", "getnameinfo", gai_strerror (err));

		if (bind (sockfd, gai_iter->ai_addr, gai_iter->ai_addrlen))
			print_error ("bind() to %s:%s failed: %s",
				real_host, real_port, strerror (errno));
		else if (listen (sockfd, 16 /* arbitrary number */))
			print_error ("listen() at %s:%s failed: %s",
				real_host, real_port, strerror (errno));
		else
			break;

		xclose (sockfd);
	}

	freeaddrinfo (gai_result);

	if (!gai_iter)
	{
		error_set (e, NETWORK_ERROR, NETWORK_ERROR_FAILED,
			"network setup failed");
		return false;
	}

	ctx->listen_fd = sockfd;
	poller_set (&ctx->poller, ctx->listen_fd, POLLIN,
		(poller_dispatcher_func) on_irc_connection_available, ctx);

	print_status ("listening at %s:%s", real_host, real_port);
	return true;
}

static void
on_signal_pipe_readable (const struct pollfd *fd, struct server_context *ctx)
{
	char *dummy;
	(void) read (fd->fd, &dummy, 1);

	// TODO: send ERROR messages to anyone, wait for the messages to get
	//   dispatched for a few seconds, RST the rest and quit.
	if (g_termination_requested && !ctx->quitting)
	{
#if 0
		initiate_quit (ctx);
#endif
	}
}

static void
print_usage (const char *program_name)
{
	fprintf (stderr,
		"Usage: %s [OPTION]...\n"
		"Experimental IRC server.\n"
		"\n"
		"  -d, --debug     run in debug mode (do not daemonize)\n"
		"  -h, --help      display this help and exit\n"
		"  -V, --version   output version information and exit\n"
		"  --write-default-cfg [filename]\n"
		"                  write a default configuration file and exit\n",
		program_name);
}

int
main (int argc, char *argv[])
{
	const char *invocation_name = argv[0];

	struct error *e = NULL;
	static struct option opts[] =
	{
		{ "debug",             no_argument,       NULL, 'd' },
		{ "help",              no_argument,       NULL, 'h' },
		{ "version",           no_argument,       NULL, 'V' },
		{ "write-default-cfg", optional_argument, NULL, 'w' },
		{ NULL,                0,                 NULL,  0  }
	};

	while (1)
	{
		int c, opt_index;

		c = getopt_long (argc, argv, "dhV", opts, &opt_index);
		if (c == -1)
			break;

		switch (c)
		{
		case 'd':
			g_debug_mode = true;
			break;
		case 'h':
			print_usage (invocation_name);
			exit (EXIT_SUCCESS);
		case 'V':
			printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
			exit (EXIT_SUCCESS);
		case 'w':
		{
			char *filename = write_default_config (optarg, g_config_table, &e);
			if (!filename)
			{
				print_fatal ("%s", e->message);
				error_free (e);
				exit (EXIT_FAILURE);
			}
			print_status ("configuration written to `%s'", filename);
			free (filename);
			exit (EXIT_SUCCESS);
		}
		default:
			print_fatal ("error in options");
			exit (EXIT_FAILURE);
		}
	}

	print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting");
	setup_signal_handlers ();

	SSL_library_init ();
	atexit (EVP_cleanup);
	SSL_load_error_strings ();
	// XXX: ERR_load_BIO_strings()?  Anything else?
	atexit (ERR_free_strings);

	struct server_context ctx;
	server_context_init (&ctx);

	if (!read_config_file (&ctx.config, &e))
	{
		print_fatal ("error loading configuration: %s", e->message);
		error_free (e);
		exit (EXIT_FAILURE);
	}

	poller_set (&ctx.poller, g_signal_pipe[0], POLLIN,
		(poller_dispatcher_func) on_signal_pipe_readable, &ctx);

	if (!irc_initialize_ssl (&ctx))
		exit (EXIT_FAILURE);
	if (!irc_initialize_catalog (&ctx, &e)
	 || !irc_listen (&ctx, &e))
	{
		print_error ("%s", e->message);
		error_free (e);
		exit (EXIT_FAILURE);
	}

	// TODO: daemonize

	ctx.polling = true;
	while (ctx.polling)
		poller_run (&ctx.poller);

	server_context_free (&ctx);
	return EXIT_SUCCESS;
}