summaryrefslogtreecommitdiff
path: root/xS/main.go
blob: 98a8b3b18d30ec92cc347fefe8943ada850aeeea (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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
//
// Copyright (c) 2014 - 2018, Přemysl Janouch <p@janouch.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.
//
// 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.
//

// hid is a straight-forward port of kike IRCd from C.
package main

import (
	"bufio"
	"crypto/sha256"
	"crypto/tls"
	"encoding/hex"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"os/signal"
	"os/user"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"syscall"
	"time"
)

var debugMode = false

const (
	projectName = "hid"
	// TODO: Consider using the same version number for all subprojects.
	projectVersion = "0"
)

// --- Utilities ---------------------------------------------------------------

// Split a string by a set of UTF-8 delimiters, optionally ignoring empty items.
func splitString(s, delims string, ignoreEmpty bool) (result []string) {
	for {
		end := strings.IndexAny(s, delims)
		if end < 0 {
			break
		}
		if !ignoreEmpty || end != 0 {
			result = append(result, s[:end])
		}
		s = s[end+1:]
	}
	if !ignoreEmpty || s != "" {
		result = append(result, s)
	}
	return
}

func findTildeHome(username string) string {
	if username != "" {
		if u, _ := user.Lookup(username); u != nil {
			return u.HomeDir
		}
	} else if u, _ := user.Current(); u != nil {
		return u.HomeDir
	} else if v, ok := os.LookupEnv("HOME"); ok {
		return v
	}
	return "~" + username
}

// Tries to expand the tilde in paths, leaving it as-is on error.
func expandTilde(path string) string {
	if path[0] != '~' {
		return path
	}

	var n int
	for n = 0; n < len(path); n++ {
		if path[n] == '/' {
			break
		}
	}
	return findTildeHome(path[1:n]) + path[n:]
}

func getXDGHomeDir(name, def string) string {
	env := os.Getenv(name)
	if env != "" && env[0] == '/' {
		return env
	}

	home := ""
	if v, ok := os.LookupEnv("HOME"); ok {
		home = v
	} else if u, _ := user.Current(); u != nil {
		home = u.HomeDir
	}
	return filepath.Join(home, def)
}

// Retrieve all XDG base directories for configuration files.
func getXDGConfigDirs() (result []string) {
	home := getXDGHomeDir("XDG_CONFIG_HOME", ".config")
	if home != "" {
		result = append(result, home)
	}
	dirs := os.Getenv("XDG_CONFIG_DIRS")
	if dirs == "" {
		dirs = "/etc/xdg"
	}
	for _, path := range strings.Split(dirs, ":") {
		if path != "" {
			result = append(result, path)
		}
	}
	return
}

//
// Trivial SSL/TLS autodetection. The first block of data returned by Recvfrom
// must be at least three octets long for this to work reliably, but that should
// not pose a problem in practice. We might try waiting for them.
//
//  SSL2:      1xxx xxxx | xxxx xxxx |    <1>
//                (message length)  (client hello)
//  SSL3/TLS:    <22>    |    <3>    | xxxx xxxx
//            (handshake)|  (protocol version)
//
func detectTLS(sysconn syscall.RawConn) (isTLS bool) {
	sysconn.Read(func(fd uintptr) (done bool) {
		var buf [3]byte
		n, _, err := syscall.Recvfrom(int(fd), buf[:], syscall.MSG_PEEK)
		switch {
		case n == 3:
			isTLS = buf[0]&0x80 != 0 && buf[2] == 1
			fallthrough
		case n == 2:
			isTLS = buf[0] == 22 && buf[1] == 3
		case n == 1:
			isTLS = buf[0] == 22
		case err == syscall.EAGAIN:
			return false
		}
		return true
	})
	return isTLS
}

// --- Configuration -----------------------------------------------------------

// XXX: Do we really want to support default nil values?
var config = []struct {
	key         string // INI key
	def         []rune // default value, may be nil
	description string // documentation
}{
	// XXX: I'm not sure if Go will cooperate here.
	{"pid_file", nil, "Path or name of the PID file"},
	{"bind", []rune(":6667"), "Address of the IRC server"},
}

/*

// Read a configuration file with the given basename w/o extension.
func readConfigFile(name string, output interface{}) error {
	var suffix = filepath.Join(projectName, name+".json")
	for _, path := range getXDGConfigDirs() {
		full := filepath.Join(path, suffix)
		file, err := os.Open(full)
		if err != nil {
			if !os.IsNotExist(err) {
				return err
			}
			continue
		}
		defer file.Close()

		// TODO: We don't want to use JSON.
		decoder := json.NewDecoder(file)
		err = decoder.Decode(output)
		if err != nil {
			return fmt.Errorf("%s: %s", full, err)
		}
		return nil
	}
	return errors.New("configuration file not found")
}

*/

// --- Rate limiter ------------------------------------------------------------

type floodDetector struct {
	interval   uint    // interval for the limit
	limit      uint    // maximum number of events allowed
	timestamps []int64 // timestamps of last events
	pos        uint    // index of the oldest event
}

func newFloodDetector(interval, limit uint) *floodDetector {
	return &floodDetector{
		interval:   interval,
		limit:      limit,
		timestamps: make([]int64, limit+1),
		pos:        0,
	}
}

func (fd *floodDetector) check() bool {
	now := time.Now().Unix()
	fd.timestamps[fd.pos] = now

	fd.pos++
	if fd.pos > fd.limit {
		fd.pos = 0
	}

	var count uint
	begin := now - int64(fd.interval)
	for _, ts := range fd.timestamps {
		if ts >= begin {
			count++
		}
	}
	return count <= fd.limit
}

// --- IRC protocol ------------------------------------------------------------

//go:generate sh -c "./hid-gen-replies.sh > hid-replies.go < hid-replies"

func ircToLower(c byte) byte {
	switch c {
	case '[':
		return '{'
	case ']':
		return '}'
	case '\\':
		return '|'
	case '~':
		return '^'
	}
	if c >= 'A' && c <= 'Z' {
		return c + ('a' - 'A')
	}
	return c
}

func ircToUpper(c byte) byte {
	switch c {
	case '{':
		return '['
	case '}':
		return ']'
	case '|':
		return '\\'
	case '^':
		return '~'
	}
	if c >= 'a' && c <= 'z' {
		return c - ('a' - 'A')
	}
	return c
}

// Convert identifier to a canonical form for case-insensitive comparisons.
// ircToUpper is used so that statically initialized maps can be in uppercase.
func ircToCanon(ident string) string {
	var canon []byte
	for _, c := range []byte(ident) {
		canon = append(canon, ircToUpper(c))
	}
	return string(canon)
}

func ircEqual(s1, s2 string) bool {
	return ircToCanon(s1) == ircToCanon(s2)
}

func ircFnmatch(pattern string, s string) bool {
	pattern, s = ircToCanon(pattern), ircToCanon(s)
	// FIXME: This should not support [] ranges and handle '/' specially.
	// We could translate the pattern to a regular expression.
	matched, _ := filepath.Match(pattern, s)
	return matched
}

// TODO: We will need to add support for IRCv3 tags.
var reMsg = regexp.MustCompile(
	`^(?::([^! ]*)(?:!([^@]*)@([^ ]*))? +)?([^ ]+)(.*)?$`)
var reArgs = regexp.MustCompile(`:.*| [^: ][^ ]*`)

type message struct {
	nick    string   // optional nickname
	user    string   // optional username
	host    string   // optional hostname or IP address
	command string   // command name
	params  []string // arguments
}

// Everything as per RFC 2812
const (
	ircMaxNickname      = 9
	ircMaxHostname      = 63
	ircMaxChannelName   = 50
	ircMaxMessageLength = 510
)

// TODO: Port the IRC token validation part as needed.

const reClassSpecial = "\\[\\]\\\\`_^{|}"

var (
	// Extending ASCII to the whole range of Unicode letters.
	reNickname = regexp.MustCompile(
		`^[\pL` + reClassSpecial + `][\pL` + reClassSpecial + `0-9-]*$`)

	// Notably, this won't match invalid UTF-8 characters, although the
	// behaviour seems to be unstated in the documentation.
	reUsername = regexp.MustCompile(`^[^\0\r\n @]+$`)

	reChannelName = regexp.MustCompile(`^[^\0\7\r\n ,:]+$`)
)

func ircIsValidNickname(nickname string) bool {
	return len(nickname) <= ircMaxNickname && reNickname.MatchString(nickname)
}

func ircIsValidUsername(username string) bool {
	// XXX: We really should put a limit on this
	// despite the RFC not mentioning one.
	return reUsername.MatchString(username)
}

func ircIsValidChannelName(name string) bool {
	return len(name) <= ircMaxChannelName && reChannelName.MatchString(name)
}

// --- Clients (equals users) --------------------------------------------------

type connCloseWrite interface {
	net.Conn
	CloseWrite() error
}

const ircSupportedUserModes = "aiwros"

const (
	ircUserModeInvisible = 1 << iota
	ircUserModeRxWallops
	ircUserModeRestricted
	ircUserModeOperator
	ircUserModeRxServerNotices
)

const (
	ircCapMultiPrefix = 1 << iota
	ircCapInviteNotify
	ircCapEchoMessage
	ircCapUserhostInNames
	ircCapServerTime
)

type client struct {
	transport net.Conn       // underlying connection
	tls       *tls.Conn      // TLS, if detected
	conn      connCloseWrite // high-level connection
	recvQ     []byte         // unprocessed input
	sendQ     []byte         // unprocessed output
	reading   bool           // whether a reading goroutine is running
	writing   bool           // whether a writing goroutine is running
	closing   bool           // whether we're closing the connection
	killTimer *time.Timer    // hard kill timeout

	opened            int64 // when the connection was opened
	nSentMessages     uint  // number of sent messages total
	sentBytes         int   // number of sent bytes total
	nReceivedMessages uint  // number of received messages total
	receivedBytes     int   // number of received bytes total

	hostname string // hostname or IP shown to the network
	port     string // port of the peer as a string
	address  string // full network address

	pingTimer      *time.Timer // we should send a PING
	timeoutTimer   *time.Timer // connection seems to be dead
	registered     bool        // the user has registered
	capNegotiating bool        // negotiating capabilities
	capsEnabled    uint        // enabled capabilities
	capVersion     uint        // CAP protocol version

	tlsCertFingerprint string // client certificate fingerprint

	nickname string // IRC nickname (main identifier)
	username string // IRC username
	realname string // IRC realname (or e-mail)

	mode        uint            // user's mode
	awayMessage string          // away message
	lastActive  int64           // last PRIVMSG, to get idle time
	invites     map[string]bool // channel invitations by operators
	antiflood   floodDetector   // flood detector
}

// --- Channels ----------------------------------------------------------------

const ircSupportedChanModes = "ov" + "beI" + "imnqpst" + "kl"

const (
	ircChanModeInviteOnly = 1 << iota
	ircChanModeModerated
	ircChanModeNoOutsideMsgs
	ircChanModeQuiet
	ircChanModePrivate
	ircChanModeSecret
	ircChanModeProtectedTopic

	ircChanModeOperator
	ircChanModeVoice
)

type channel struct {
	name      string // channel name
	modes     uint   // channel modes
	key       string // channel key
	userLimit int    // user limit or -1
	created   int64  // creation time

	topic     string // channel topic
	topicWho  string // who set the topic
	topicTime int64  // when the topic was set

	userModes map[*client]uint // modes for all channel users

	banList       []string // ban list
	exceptionList []string // exceptions from bans
	inviteList    []string // exceptions from +I
}

func newChannel() *channel {
	return &channel{userLimit: -1}
}

// TODO: Port struct channel methods.

// --- IRC server context ------------------------------------------------------

type whowasInfo struct {
	nickname, username, realname, hostname string
}

func newWhowasInfo(c *client) *whowasInfo {
	return &whowasInfo{
		nickname: c.nickname,
		username: c.username,
		realname: c.realname,
		hostname: c.hostname,
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

type ircCommand struct {
	name                 string
	requiresRegistration bool
	handler              func(*message, *client)

	nReceived     uint // number of commands received
	bytesReceived uint // number of bytes received total
}

type preparedEvent struct {
	client *client
	host   string // client's hostname or literal IP address
	isTLS  bool   // the client seems to use TLS
}

type readEvent struct {
	client *client
	data   []byte // new data from the client
	err    error  // read error
}

type writeEvent struct {
	client  *client
	written int   // amount of bytes written
	err     error // write error
}

// TODO: Port server_context. Maybe we want to keep it in a struct?
// XXX: Beware that maps with identifier keys need to be indexed correctly.
// We might want to enforce accessor functions for users and channels.
var (
	started int64 // when has the server been started

	users    map[string]*client  // maps nicknames to clients
	channels map[string]*channel // maps channel names to data

	whowas map[string]*whowasInfo // WHOWAS registry

	serverName     string          // our server name
	pingInterval   uint            // ping interval in seconds
	maxConnections int             // max connections allowed or 0
	motd           []string        // MOTD (none if empty)
	operators      map[string]bool // TLS certificate fingerprints for IRCops
)

var (
	sigs     = make(chan os.Signal, 1)
	conns    = make(chan net.Conn)
	prepared = make(chan preparedEvent)
	reads    = make(chan readEvent)
	writes   = make(chan writeEvent)
	timeouts = make(chan *client)

	tlsConf   *tls.Config
	clients   = make(map[*client]bool)
	listener  net.Listener
	quitting  bool
	quitTimer <-chan time.Time
)

// Forcefully tear down all connections.
func forceQuit(reason string) {
	if !quitting {
		log.Fatalln("forceQuit called without initiateQuit")
	}

	log.Printf("forced shutdown (%s)\n", reason)
	for c := range clients {
		// initiateQuit has already unregistered the client.
		c.kill("Shutting down")
	}
}

// Initiate a clean shutdown of the whole daemon.
func initiateQuit() {
	log.Println("shutting down")
	if err := listener.Close(); err != nil {
		log.Println(err)
	}
	for c := range clients {
		c.closeLink("Shutting down")
	}

	quitTimer = time.After(5 * time.Second)
	quitting = true
}

// TODO: ircChannelCreate

func ircChannelDestroyIfEmpty(ch *channel) {
	// TODO
}

// TODO: ircSendToRoommates
// Broadcast to all /other/ clients (telnet-friendly, also in accordance to
// the plan of extending this to an IRCd).
func broadcast(line string, except *client) {
	for c := range clients {
		if c != except {
			c.send(line)
		}
	}
}

func ircSendToRoommates(c *client, message string) {
	// TODO
}

// --- Clients (continued) -----------------------------------------------------

func clientModeToString(m uint, mode *[]byte) {
	if 0 != m&ircUserModeInvisible {
		*mode = append(*mode, 'i')
	}
	if 0 != m&ircUserModeRxWallops {
		*mode = append(*mode, 'w')
	}
	if 0 != m&ircUserModeRestricted {
		*mode = append(*mode, 'r')
	}
	if 0 != m&ircUserModeOperator {
		*mode = append(*mode, 'o')
	}
	if 0 != m&ircUserModeRxServerNotices {
		*mode = append(*mode, 's')
	}
}

func (c *client) getMode() string {
	var mode []byte
	if c.awayMessage != "" {
		mode = append(mode, 'a')
	}
	clientModeToString(c.mode, &mode)
	return string(mode)
}

func (c *client) send(line string) {
	if c.conn == nil || c.closing {
		return
	}

	oldSendQLen := len(c.sendQ)

	// So far there's only one message tag we use, so we can do it simple;
	// note that a 1024-character limit applies to messages with tags on.
	if 0 != c.capsEnabled&ircCapServerTime {
		c.sendQ = time.Now().UTC().
			AppendFormat(c.sendQ, "@time=2006-01-02T15:04:05.000Z ")
	}

	bytes := []byte(line)
	if len(bytes) > ircMaxMessageLength {
		bytes = bytes[:ircMaxMessageLength]
	}

	// TODO: Kill the connection above some "SendQ" threshold (careful!)
	c.sendQ = append(c.sendQ, bytes...)
	c.sendQ = append(c.sendQ, "\r\n"...)
	c.flushSendQ()

	// Technically we haven't sent it yet but that's a minor detail
	c.nSentMessages++
	c.sentBytes += len(c.sendQ) - oldSendQLen
}

func (c *client) sendf(format string, a ...interface{}) {
	c.send(fmt.Sprintf(format, a...))
}

func (c *client) addToWhowas() {
	// Only keeping one entry for each nickname.
	// TODO: Make sure this list doesn't get too long, for example by
	// putting them in a linked list ordered by time.
	whowas[ircToCanon(c.nickname)] = newWhowasInfo(c)
}

func (c *client) nicknameOrStar() string {
	if c.nickname == "" {
		return "*"
	}
	return c.nickname
}

func (c *client) unregister(reason string) {
	if !c.registered {
		return
	}

	ircSendToRoommates(c, fmt.Sprintf(":%s!%s@%s QUIT :%s",
		c.nickname, c.username, c.hostname, reason))

	// The eventual QUIT message will take care of state at clients.
	for _, ch := range channels {
		delete(ch.userModes, c)
		ircChannelDestroyIfEmpty(ch)
	}

	c.addToWhowas()
	delete(users, ircToCanon(c.nickname))
	c.nickname = ""
	c.registered = false
}

// Close the connection and forget about the client.
func (c *client) kill(reason string) {
	if reason == "" {
		reason = "Client exited"
	}
	c.unregister(reason)

	// TODO: Log the address; seems like we always have c.address.
	log.Println("client destroyed")

	// Try to send a "close notify" alert if the TLS object is ready,
	// otherwise just tear down the transport.
	if c.conn != nil {
		_ = c.conn.Close()
	} else {
		_ = c.transport.Close()
	}

	// Clean up the goroutine, although a spurious event may still be sent.
	// TODO: Other timers if needed.
	if c.killTimer != nil {
		c.killTimer.Stop()
	}

	delete(clients, c)
}

// Tear down the client connection, trying to do so in a graceful manner.
func (c *client) closeLink(reason string) {
	// Let's just cut the connection, the client can try again later.
	// We also want to avoid accidentally writing to the socket before
	// address resolution has finished.
	if c.conn == nil {
		c.kill(reason)
		return
	}
	if c.closing {
		return
	}

	// We push an "ERROR" message to the write buffer and let the writer send
	// it, with some arbitrary timeout. The "closing" state makes sure
	// that a/ we ignore any successive messages, and b/ that the connection
	// is killed after the write buffer is transferred and emptied.
	// (Since we send this message, we don't need to call CloseWrite here.)
	c.sendf("ERROR :Closing link: %s[%s] (%s)",
		c.nicknameOrStar(), c.hostname /* TODO host IP? */, reason)
	c.closing = true

	c.unregister(reason)
	c.killTimer = time.AfterFunc(3*time.Second, func() {
		timeouts <- c
	})
}

func (c *client) inMaskList(masks []string) bool {
	client := fmt.Sprintf("%s!%s@%s", c.nickname, c.username, c.hostname)
	for _, mask := range masks {
		if ircFnmatch(mask, client) {
			return true
		}
	}
	return false
}

func (c *client) getTLSCertFingerprint() string {
	if c.tls == nil {
		return ""
	}

	peerCerts := c.tls.ConnectionState().PeerCertificates
	if len(peerCerts) == 0 {
		return ""
	}

	hash := sha256.Sum256(peerCerts[0].Raw)
	return hex.EncodeToString(hash[:])
}

// --- Timers ------------------------------------------------------------------

// TODO

// --- IRC command handling ----------------------------------------------------

// XXX: ap doesn't really need to be a slice.
func (c *client) makeReply(id int, ap []interface{}) string {
	s := fmt.Sprintf(":%s %03d %s ", serverName, id, c.nicknameOrStar())
	a := fmt.Sprintf(defaultReplies[id], ap...)
	return s + a
}

// XXX: This way we cannot typecheck the arguments, so we must be careful.
func (c *client) sendReply(id int, args ...interface{}) {
	c.send(c.makeReply(id, args))
}

/// Send a space-separated list of words across as many replies as needed.
func (c *client) sendReplyVector(id int, items []string, args ...interface{}) {
	common := c.makeReply(id, args)

	// We always send at least one message (there might be a client that
	// expects us to send this message at least once).
	for len(items) > 0 {
		// If not even a single item fits in the limit (which may happen,
		// in theory) it just gets cropped. We could also skip it.
		reply := append([]byte(common), items[0]...)

		// Append as many items as fits in a single message.
		for len(items) > 0 &&
			len(reply)+1+len(items[0]) <= ircMaxMessageLength {
			reply = append(reply, ' ')
			reply = append(reply, items[0]...)
			items = items[1:]
		}

		c.send(string(reply))
	}
}

func (c *client) sendMOTD() {
	if len(motd) == 0 {
		c.sendReply(ERR_NOMOTD)
		return
	}

	c.sendReply(RPL_MOTDSTART, serverName)
	for _, line := range motd {
		c.sendReply(RPL_MOTD, line)
	}
	c.sendReply(RPL_ENDOFMOTD)
}

func (c *client) sendLUSERS() {
	nUsers, nServices, nOpers, nUnknown := 0, 0, 0, 0
	for c := range clients {
		if c.registered {
			nUsers++
		} else {
			nUnknown++
		}
		if 0 != c.mode&ircUserModeOperator {
			nOpers++
		}
	}

	nChannels := 0
	for _, ch := range channels {
		if 0 != ch.modes&ircChanModeSecret {
			nChannels++
		}
	}

	c.sendReply(RPL_LUSERCLIENT, nUsers, nServices, 1 /* servers total */)
	if nOpers != 0 {
		c.sendReply(RPL_LUSEROP, nOpers)
	}
	if nUnknown != 0 {
		c.sendReply(RPL_LUSERUNKNOWN, nUnknown)
	}
	if nChannels != 0 {
		c.sendReply(RPL_LUSERCHANNELS, nChannels)
	}
	c.sendReply(RPL_LUSERME, nUsers+nServices+nUnknown, 0 /* peer servers */)
}

func isThisMe(target string) bool {
	// Target servers can also be matched by their users
	if ircFnmatch(target, serverName) {
		return true
	}
	_, ok := users[ircToCanon(target)]
	return ok
}

func (c *client) sendISUPPORT() {
	// Only # channels, +e supported, +I supported, unlimited arguments to MODE
	c.sendReply(RPL_ISUPPORT, "CHANTYPES=# EXCEPTS INVEX MODES"+
		" TARGMAX=WHOIS:,LIST:,NAMES:,PRIVMSG:1,NOTICE:1,KICK:"+
		" NICKLEN=%d CHANNELLEN=%d", ircMaxNickname, ircMaxChannelName)
}

func (c *client) tryFinishRegistration() {
	if c.registered || c.capNegotiating {
		return
	}
	if c.nickname == "" || c.username == "" {
		return
	}

	c.registered = true
	c.sendReply(RPL_WELCOME, c.nickname, c.username, c.hostname)

	c.sendReply(RPL_YOURHOST, serverName, projectVersion)
	// The purpose of this message eludes me.
	c.sendReply(RPL_CREATED, time.Unix(started, 0).Format("Mon, 02 Jan 2006"))
	c.sendReply(RPL_MYINFO, serverName, projectVersion,
		ircSupportedUserModes, ircSupportedChanModes)

	c.sendISUPPORT()
	c.sendLUSERS()
	c.sendMOTD()

	if mode := c.getMode(); mode != "" {
		c.sendf(":%s MODE %s :+%s", c.nickname, c.nickname, mode)
	}

	c.tlsCertFingerprint = c.getTLSCertFingerprint()
	if c.tlsCertFingerprint != "" {
		c.sendf(":%s NOTICE %s :Your TLS client certificate fingerprint is %s",
			serverName, c.nickname, c.tlsCertFingerprint)
	}

	delete(whowas, ircToCanon(c.nickname))
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// IRCv3 capability negotiation. See http://ircv3.org for details.

type ircCapArgs struct {
	subcommand string   // the subcommand being processed
	fullParams string   // whole parameter string
	params     []string // split parameters
	target     string   // target parameter for replies
}

var ircCapTable = []struct {
	flag uint   // flag
	name string // name of the capability
}{
	{ircCapMultiPrefix, "multi-prefix"},
	{ircCapInviteNotify, "invite-notify"},
	{ircCapEchoMessage, "echo-message"},
	{ircCapUserhostInNames, "userhost-in-names"},
	{ircCapServerTime, "server-time"},
}

func (c *client) handleCAPLS(a *ircCapArgs) {
	if len(a.params) == 1 {
		if ver, err := strconv.ParseUint(a.params[0], 10, 32); err != nil {
			c.sendReply(ERR_INVALIDCAPCMD, a.subcommand,
				"Ignoring invalid protocol version number")
		} else {
			c.capVersion = uint(ver)
		}
	}

	c.capNegotiating = true
	c.sendf(":%s CAP %s LS :multi-prefix invite-notify echo-message"+
		" userhost-in-names server-time", serverName, a.target)
}

func (c *client) handleCAPLIST(a *ircCapArgs) {
	caps := []string{}
	for _, cap := range ircCapTable {
		if 0 != c.capsEnabled&cap.flag {
			caps = append(caps, cap.name)
		}
	}

	c.sendf(":%s CAP %s LIST :%s", serverName, a.target,
		strings.Join(caps, " "))
}

func ircDecodeCapability(name string) uint {
	for _, cap := range ircCapTable {
		if cap.name == name {
			return cap.flag
		}
	}
	return 0
}

func (c *client) handleCAPREQ(a *ircCapArgs) {
	c.capNegotiating = true

	newCaps := c.capsEnabled
	ok := true
	for _, param := range a.params {
		removing := false
		name := param
		if name[:1] == "-" {
			removing = true
			name = name[1:]
		}

		if cap := ircDecodeCapability(name); cap == 0 {
			ok = false
		} else if removing {
			newCaps &= ^cap
		} else {
			newCaps |= cap
		}
	}

	if ok {
		c.capsEnabled = newCaps
		c.sendf(":%s CAP %s ACK :%s", serverName, a.target, a.fullParams)
	} else {
		c.sendf(":%s CAP %s NAK :%s", serverName, a.target, a.fullParams)
	}
}

func (c *client) handleCAPACK(a *ircCapArgs) {
	if len(a.params) > 0 {
		c.sendReply(ERR_INVALIDCAPCMD, a.subcommand,
			"No acknowledgable capabilities supported")
	}
}

func (c *client) handleCAPEND(a *ircCapArgs) {
	c.capNegotiating = false
	c.tryFinishRegistration()
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

var ircCapHandlers = map[string]func(*client, *ircCapArgs){
	"LS":   (*client).handleCAPLS,
	"LIST": (*client).handleCAPLIST,
	"REQ":  (*client).handleCAPREQ,
	"ACK":  (*client).handleCAPACK,
	"END":  (*client).handleCAPEND,
}

// XXX: Maybe these also deserve to be methods for client?  They operato on
// global state, though.

func ircHandleCAP(msg *message, c *client) {
	if len(msg.params) < 1 {
		c.sendReply(ERR_NEEDMOREPARAMS, msg.command)
		return
	}

	args := &ircCapArgs{
		target:     c.nicknameOrStar(),
		subcommand: msg.params[0],
		fullParams: "",
		params:     []string{},
	}

	if len(msg.params) > 1 {
		args.fullParams = msg.params[1]
		args.params = splitString(args.fullParams, " ", true)
	}

	if fn, ok := ircCapHandlers[ircToCanon(args.subcommand)]; !ok {
		c.sendReply(ERR_INVALIDCAPCMD, args.subcommand,
			"Invalid CAP subcommand")
	} else {
		fn(c, args)
	}
}

func ircHandlePASS(msg *message, c *client) {
	if c.registered {
		c.sendReply(ERR_ALREADYREGISTERED)
	} else if len(msg.params) < 1 {
		c.sendReply(ERR_NEEDMOREPARAMS, msg.command)
	}

	// We have TLS client certificates for this purpose; ignoring.
}

func ircHandleNICK(msg *message, c *client) {
	if len(msg.params) < 1 {
		c.sendReply(ERR_NONICKNAMEGIVEN)
		return
	}

	nickname := msg.params[0]
	if !ircIsValidNickname(nickname) {
		c.sendReply(ERR_ERRONEOUSNICKNAME, nickname)
		return
	}

	nicknameCanon := ircToCanon(nickname)
	if client, ok := users[nicknameCanon]; ok && client != c {
		c.sendReply(ERR_NICKNAMEINUSE, nickname)
		return
	}

	if c.registered {
		c.addToWhowas()

		message := fmt.Sprintf(":%s!%s@%s NICK :%s",
			c.nickname, c.username, c.hostname, nickname)
		ircSendToRoommates(c, message)
		c.send(message)
	}

	// Release the old nickname and allocate a new one.
	if c.nickname != "" {
		delete(users, ircToCanon(c.nickname))
	}

	c.nickname = nickname
	users[nicknameCanon] = c

	c.tryFinishRegistration()
}

func ircHandleUSER(msg *message, c *client) {
	if c.registered {
		c.sendReply(ERR_ALREADYREGISTERED)
		return
	}
	if len(msg.params) < 4 {
		c.sendReply(ERR_NEEDMOREPARAMS, msg.command)
		return
	}

	username, mode, realname := msg.params[0], msg.params[1], msg.params[3]

	// Unfortunately, the protocol doesn't give us any means of rejecting it.
	if !ircIsValidUsername(username) {
		username = "*"
	}

	c.username = username
	c.realname = realname

	c.mode = 0
	if m, err := strconv.ParseUint(mode, 10, 32); err != nil {
		if 0 != m&4 {
			c.mode |= ircUserModeRxWallops
		}
		if 0 != m&8 {
			c.mode |= ircUserModeInvisible
		}
	}

	c.tryFinishRegistration()
}

func ircHandleUSERHOST(msg *message, c *client) {
	if len(msg.params) < 1 {
		c.sendReply(ERR_NEEDMOREPARAMS, msg.command)
		return
	}

	var reply []byte
	for i := 0; i < 5 && i < len(msg.params); i++ {
		nick := msg.params[i]
		target := users[ircToCanon(nick)]
		if target == nil {
			continue
		}
		if i != 0 {
			reply = append(reply, ' ')
		}

		reply = append(reply, nick...)
		if 0 != target.mode&ircUserModeOperator {
			reply = append(reply, '*')
		}

		if target.awayMessage != "" {
			reply = append(reply, "=-"...)
		} else {
			reply = append(reply, "=+"...)
		}
		reply = append(reply, (target.username + "@" + target.hostname)...)
	}
	c.sendReply(RPL_USERHOST, string(reply))
}

func ircHandleLUSERS(msg *message, c *client) {
	if len(msg.params) > 1 && !isThisMe(msg.params[1]) {
		c.sendReply(ERR_NOSUCHSERVER, msg.params[1])
		return
	}
	c.sendLUSERS()
}

func ircHandleMOTD(msg *message, c *client) {
	if len(msg.params) > 0 && !isThisMe(msg.params[0]) {
		c.sendReply(ERR_NOSUCHSERVER, msg.params[1])
		return
	}
	c.sendMOTD()
}

func ircHandlePING(msg *message, c *client) {
	// XXX: The RFC is pretty incomprehensible about the exact usage.
	if len(msg.params) > 1 && !isThisMe(msg.params[1]) {
		c.sendReply(ERR_NOSUCHSERVER, msg.params[1])
	} else if len(msg.params) < 1 {
		c.sendReply(ERR_NOORIGIN)
	} else {
		c.sendf(":%s PONG :%s", serverName, msg.params[0])
	}
}

func ircHandlePONG(msg *message, c *client) {
	// We are the only server, so we don't have to care too much.
	if len(msg.params) < 1 {
		c.sendReply(ERR_NOORIGIN)
		return
	}

	// Set a new timer to send another PING
	// TODO
}

func ircHandleQUIT(msg *message, c *client) {
	reason := c.nickname
	if len(msg.params) > 0 {
		reason = msg.params[0]
	}

	c.closeLink("Quit: " + reason)
}

func ircHandleTIME(msg *message, c *client) {
	if len(msg.params) > 0 && !isThisMe(msg.params[0]) {
		c.sendReply(ERR_NOSUCHSERVER, msg.params[0])
		return
	}

	c.sendReply(RPL_TIME, serverName,
		time.Now().Format("Mon Jan _2 2006 15:04:05"))
}

func ircHandleVERSION(msg *message, c *client) {
	if len(msg.params) > 0 && !isThisMe(msg.params[0]) {
		c.sendReply(ERR_NOSUCHSERVER, msg.params[0])
		return
	}

	postVersion := 0
	if debugMode {
		postVersion = 1
	}

	c.sendReply(RPL_VERSION, projectVersion, postVersion, serverName,
		projectName+" "+projectVersion)
	c.sendISUPPORT()
}

/*
func ircChannelMulticast(ch *channel, msg string, except *client) {
	for c, m := range ch.userModes {
		if c != except {
			c.send(msg)
		}
	}
}

func ircModifyMode(mask *uint, mode uint, add bool) bool {
	orig := *mask
	if add {
		*mask |= mode
	} else {
		*mask &= ^mode
	}
	return *mask != orig
}

func ircUpdateUserMode(c *client, newMode uint) {
	// TODO: Port, as well as all the other kike functions.
}
*/

func ircHandleMODE(msg *message, c *client) {
	if len(msg.params) < 1 {
		c.sendReply(ERR_NEEDMOREPARAMS, msg.command)
		return
	}

	// TODO
	target := msg.params[0]
	client := users[ircToCanon(target)]
	ch := users[ircToCanon(target)]

	if client != nil {
		// TODO
		if ircEqual(target, c.nickname) {
		}
	} else if ch != nil {
		// TODO
	}
}

func ircHandleUserMessage(msg *message, c *client,
	command string, allowAwayReply bool) {
	if len(msg.params) < 1 {
		c.sendReply(ERR_NORECIPIENT, msg.command)
		return
	}
	if len(msg.params) < 2 || msg.params[1] == "" {
		c.sendReply(ERR_NOTEXTTOSEND)
		return
	}

	target, text := msg.params[0], msg.params[1]
	if client, ok := users[ircToCanon(target)]; ok {
		// TODO
		_ = client
		_ = text
	} else if ch, ok := channels[ircToCanon(target)]; ok {
		// TODO
		_ = ch
	} else {
		c.sendReply(ERR_NOSUCHNICK, target)
	}
}

// TODO: All the various real command handlers.

func ircHandleX(msg *message, c *client) {
}

// --- ? -----------------------------------------------------------------------

// Handle the results from initializing the client's connection.
func (c *client) onPrepared(host string, isTLS bool) {
	if isTLS {
		c.tls = tls.Server(c.transport, tlsConf)
		c.conn = c.tls
	} else {
		c.conn = c.transport.(connCloseWrite)
	}

	c.hostname = host
	c.address = net.JoinHostPort(host, c.port)

	// TODO: If we've tried to send any data before now, we need to flushSendQ.
	go read(c)
	c.reading = true
}

// Handle the results from trying to read from the client connection.
func (c *client) onRead(data []byte, readErr error) {
	if !c.reading {
		// Abusing the flag to emulate CloseRead and skip over data, see below.
		return
	}

	c.recvQ = append(c.recvQ, data...)
	for {
		// XXX: This accepts even simple LF newlines, even though they're not
		// really allowed by the protocol.
		advance, token, _ := bufio.ScanLines(c.recvQ, false /* atEOF */)
		if advance == 0 {
			break
		}

		c.recvQ = c.recvQ[advance:]
		line := string(token)
		log.Printf("-> %s\n", line)

		m := reMsg.FindStringSubmatch(line)
		if m == nil {
			log.Println("error: invalid line")
			continue
		}

		msg := message{m[1], m[2], m[3], m[4], nil}
		for _, x := range reArgs.FindAllString(m[5], -1) {
			msg.params = append(msg.params, x[1:])
		}

		broadcast(line, c)
	}

	if readErr != nil {
		c.reading = false

		if readErr != io.EOF {
			log.Println(readErr)
			c.kill(readErr.Error())
		} else if c.closing {
			// Disregarding whether a clean shutdown has happened or not.
			log.Println("client finished shutdown")
			c.kill("TODO")
		} else {
			log.Println("client EOF")
			c.closeLink("")
		}
	} else if len(c.recvQ) > 8192 {
		log.Println("client recvQ overrun")
		c.closeLink("recvQ overrun")

		// tls.Conn doesn't have the CloseRead method (and it needs to be able
		// to read from the TCP connection even for writes, so there isn't much
		// sense in expecting the implementation to do anything useful),
		// otherwise we'd use it to block incoming packet data.
		c.reading = false
	}
}

// Spawn a goroutine to flush the sendQ if possible and necessary.
func (c *client) flushSendQ() {
	if !c.writing && c.conn != nil {
		go write(c, c.sendQ)
		c.writing = true
	}
}

// Handle the results from trying to write to the client connection.
func (c *client) onWrite(written int, writeErr error) {
	c.sendQ = c.sendQ[written:]
	c.writing = false

	if writeErr != nil {
		log.Println(writeErr)
		c.kill(writeErr.Error())
	} else if len(c.sendQ) > 0 {
		c.flushSendQ()
	} else if c.closing {
		if c.reading {
			c.conn.CloseWrite()
		} else {
			c.kill("TODO")
		}
	}
}

// --- Worker goroutines -------------------------------------------------------

func accept(ln net.Listener) {
	for {
		if conn, err := ln.Accept(); err != nil {
			// TODO: Consider specific cases in error handling, some errors
			// are transitional while others are fatal.
			log.Println(err)
			break
		} else {
			conns <- conn
		}
	}
}

func prepare(client *client) {
	conn := client.transport
	host, _, err := net.SplitHostPort(conn.RemoteAddr().String())
	if err != nil {
		// In effect, we require TCP/UDP, as they have port numbers.
		log.Fatalln(err)
	}

	// The Cgo resolver doesn't pthread_cancel getnameinfo threads, so not
	// bothering with pointless contexts.
	ch := make(chan string, 1)
	go func() {
		defer close(ch)
		if names, err := net.LookupAddr(host); err != nil {
			log.Println(err)
		} else {
			ch <- names[0]
		}
	}()

	// While we can't cancel it, we still want to set a timeout on it.
	select {
	case <-time.After(5 * time.Second):
	case resolved, ok := <-ch:
		if ok {
			host = resolved
		}
	}

	// Note that in this demo application the autodetection prevents non-TLS
	// clients from receiving any messages until they send something.
	isTLS := false
	if sysconn, err := conn.(syscall.Conn).SyscallConn(); err != nil {
		// This is just for the TLS detection and doesn't need to be fatal.
		log.Println(err)
	} else {
		isTLS = detectTLS(sysconn)
	}

	// FIXME: When the client sends no data, we still initialize its conn.
	prepared <- preparedEvent{client, host, isTLS}
}

func read(client *client) {
	// A new buffer is allocated each time we receive some bytes, because of
	// thread-safety. Therefore the buffer shouldn't be too large, or we'd
	// need to copy it each time into a precisely sized new buffer.
	var err error
	for err == nil {
		var (
			buf [512]byte
			n   int
		)
		n, err = client.conn.Read(buf[:])
		reads <- readEvent{client, buf[:n], err}
	}
}

// Flush sendQ, which is passed by parameter so that there are no data races.
func write(client *client, data []byte) {
	// We just write as much as we can, the main goroutine does the looping.
	n, err := client.conn.Write(data)
	writes <- writeEvent{client, n, err}
}

// --- Main --------------------------------------------------------------------

func processOneEvent() {
	select {
	case <-sigs:
		if quitting {
			forceQuit("requested by user")
		} else {
			initiateQuit()
		}

	case <-quitTimer:
		forceQuit("timeout")

	case conn := <-conns:
		log.Println("accepted client connection")

		// In effect, we require TCP/UDP, as they have port numbers.
		address := conn.RemoteAddr().String()
		host, port, err := net.SplitHostPort(address)
		if err != nil {
			log.Fatalln(err)
		}

		c := &client{
			transport: conn,
			address:   address,
			hostname:  host,
			port:      port,
		}
		clients[c] = true
		go prepare(c)

	case ev := <-prepared:
		log.Println("client is ready:", ev.host)
		if _, ok := clients[ev.client]; ok {
			ev.client.onPrepared(ev.host, ev.isTLS)
		}

	case ev := <-reads:
		log.Println("received data from client")
		if _, ok := clients[ev.client]; ok {
			ev.client.onRead(ev.data, ev.err)
		}

	case ev := <-writes:
		log.Println("sent data to client")
		if _, ok := clients[ev.client]; ok {
			ev.client.onWrite(ev.written, ev.err)
		}

	case c := <-timeouts:
		if _, ok := clients[c]; ok {
			log.Println("client timeouted")
			c.kill("TODO")
		}
	}
}

func main() {
	flag.BoolVar(&debugMode, "debug", false, "debug mode")
	version := flag.Bool("version", false, "show version and exit")
	flag.Parse()

	if *version {
		fmt.Printf("%s %s\n", projectName, projectVersion)
		return
	}

	// TODO: Configuration--create an INI parser, probably.
	if len(flag.Args()) != 3 {
		log.Fatalf("usage: %s KEY CERT ADDRESS\n", os.Args[0])
	}

	cert, err := tls.LoadX509KeyPair(flag.Arg(1), flag.Arg(0))
	if err != nil {
		log.Fatalln(err)
	}

	tlsConf = &tls.Config{
		Certificates:           []tls.Certificate{cert},
		ClientAuth:             tls.RequestClientCert,
		SessionTicketsDisabled: true,
	}
	listener, err = net.Listen("tcp", flag.Arg(2))
	if err != nil {
		log.Fatalln(err)
	}

	go accept(listener)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	for !quitting || len(clients) > 0 {
		processOneEvent()
	}
}