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
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
|
/*
* 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", "0", "Global connection limit" },
{ "ping_interval", "180", "Interval between PING's (sec)" },
{ 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)
exit_fatal ("%s: %s", "pipe", strerror (errno));
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)
exit_fatal ("%s: %s", "sigaction", strerror (errno));
}
// --- IRC token validation ----------------------------------------------------
// Use the enum only if applicable and a simple boolean isn't sufficient.
enum validation_result
{
VALIDATION_OK,
VALIDATION_ERROR_EMPTY,
VALIDATION_ERROR_TOO_LONG,
VALIDATION_ERROR_INVALID
};
// Everything as per RFC 2812
#define IRC_MAX_NICKNAME 9
#define IRC_MAX_HOSTNAME 63
#define IRC_MAX_CHANNEL_NAME 50
#define IRC_MAX_MESSAGE_LENGTH 510
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_MAX_HOSTNAME)
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_is_valid_user (const char *user)
{
return irc_regex_match ("^[^\r\n @]+$", user);
}
static bool
irc_validate_nickname (const char *nickname)
{
if (!*nickname)
return VALIDATION_ERROR_EMPTY;
if (!irc_regex_match ("^[" SP LE "][" SP LE "0-9-]*$", nickname))
return VALIDATION_ERROR_INVALID;
if (strlen (nickname) > IRC_MAX_NICKNAME)
return VALIDATION_ERROR_TOO_LONG;
return VALIDATION_OK;
}
static enum validation_result
irc_validate_channel_name (const char *channel_name)
{
if (!*channel_name)
return VALIDATION_ERROR_EMPTY;
if (*channel_name != '#' || strpbrk (channel_name, "\7\r\n ,:"))
return VALIDATION_ERROR_INVALID;
if (strlen (channel_name) > IRC_MAX_CHANNEL_NAME)
return VALIDATION_ERROR_TOO_LONG;
return VALIDATION_OK;
}
static bool
irc_is_valid_key (const char *key)
{
// XXX: should be 7-bit as well but whatever
return irc_regex_match ("^[^\r\n\f\t\v ]{1,23}$", key);
}
#undef SN
#undef N4
#undef N6
#undef LE
#undef SP
// --- Application data --------------------------------------------------------
#define IRC_SUPPORTED_USER_MODES "aiwros"
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 client
{
LIST_HEADER (client)
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
bool initialized; ///< Has any data been received yet?
bool registered; ///< The user has registered
bool closing_link; ///< Closing link
bool ssl_rx_want_tx; ///< SSL_read() wants to write
bool ssl_tx_want_rx; ///< 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
client_init (struct client *self)
{
memset (self, 0, sizeof *self);
self->socket_fd = -1;
str_init (&self->read_buffer);
str_init (&self->write_buffer);
}
static void
client_free (struct client *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);
}
static char *
client_get_mode (struct client *self)
{
struct str mode;
str_init (&mode);
if (self->away_message) str_append_c (&mode, 'a');
unsigned m = self->mode;
if (m & IRC_USER_MODE_INVISIBLE) str_append_c (&mode, 'i');
if (m & IRC_USER_MODE_RX_WALLOPS) str_append_c (&mode, 'w');
if (m & IRC_USER_MODE_RESTRICTED) str_append_c (&mode, 'r');
if (m & IRC_USER_MODE_OPERATOR) str_append_c (&mode, 'o');
if (m & IRC_USER_MODE_RX_SERVER_NOTICES) str_append_c (&mode, 's');
return str_steal (&mode);
}
#define IRC_SUPPORTED_CHAN_MODES "ov" "imnqpst" "kl"
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_QUIET = (1 << 3),
IRC_CHAN_MODE_PRIVATE = (1 << 4),
IRC_CHAN_MODE_SECRET = (1 << 5),
IRC_CHAN_MODE_PROTECTED_TOPIC = (1 << 6),
IRC_CHAN_MODE_OPERATOR = (1 << 7),
IRC_CHAN_MODE_VOICE = (1 << 8)
};
struct channel_user
{
LIST_HEADER (channel_user)
unsigned modes;
char nickname[];
};
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
char *topic; ///< Channel topic
struct channel_user *users; ///< Channel users
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);
self->user_limit = -1;
self->topic = xstrdup ("");
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);
free (self->topic);
struct channel_user *link, *tmp;
for (link = self->users; link; link = tmp)
{
tmp = link->next;
free (link);
}
str_vector_free (&self->ban_list);
str_vector_free (&self->exception_list);
str_vector_free (&self->invite_list);
}
static char *
channel_get_mode (struct channel *self, bool disclose_secrets)
{
struct str mode;
str_init (&mode);
unsigned m = self->modes;
if (m & IRC_CHAN_MODE_INVITE_ONLY) str_append_c (&mode, 'i');
if (m & IRC_CHAN_MODE_MODERATED) str_append_c (&mode, 'm');
if (m & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) str_append_c (&mode, 'n');
if (m & IRC_CHAN_MODE_QUIET) str_append_c (&mode, 'q');
if (m & IRC_CHAN_MODE_PRIVATE) str_append_c (&mode, 'p');
if (m & IRC_CHAN_MODE_SECRET) str_append_c (&mode, 's');
if (m & IRC_CHAN_MODE_PROTECTED_TOPIC) str_append_c (&mode, 't');
if (self->user_limit != -1) str_append_c (&mode, 'l');
if (self->key) str_append_c (&mode, 'k');
if (self->user_limit != -1)
str_append_printf (&mode, " %ld", self->user_limit);
// XXX: is this correct? Try it on an existing implementation.
if (self->key && disclose_secrets)
str_append_printf (&mode, " %s", self->key);
return str_steal (&mode);
}
struct server_context
{
int listen_fd; ///< Listening socket FD
struct client *clients; ///< Clients
SSL_CTX *ssl_ctx; ///< SSL context
unsigned n_clients; ///< Current number of connections
struct str_map users; ///< Maps nicknames to clients
struct str_map channels; ///< Maps channel names to data
struct str_map handlers; ///< Message handlers
struct poller poller; ///< Manages polled description
bool quitting; ///< User requested quitting
bool polling; ///< The event loop is running
struct str_map config; ///< Server configuration
char *server_name; ///< Our server name
unsigned ping_interval; ///< Ping interval in seconds
unsigned max_connections; ///< Max. connections allowed or 0
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)
{
self->listen_fd = -1;
self->clients = NULL;
self->n_clients = 0;
str_map_init (&self->users);
self->users.key_xfrm = irc_strxfrm;
// TODO: set channel_free() as the free function?
str_map_init (&self->channels);
self->channels.key_xfrm = irc_strxfrm;
str_map_init (&self->handlers);
self->handlers.key_xfrm = irc_strxfrm;
poller_init (&self->poller);
self->quitting = false;
self->polling = false;
str_map_init (&self->config);
self->config.free = free;
load_config_defaults (&self->config, g_config_table);
self->server_name = NULL;
self->ping_interval = 0;
self->max_connections = 0;
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);
struct client *link, *tmp;
for (link = self->clients; link; link = tmp)
{
tmp = link->next;
client_free (link);
free (link);
}
free (self->server_name);
str_map_free (&self->users);
str_map_free (&self->channels);
str_map_free (&self->handlers);
poller_free (&self->poller);
str_vector_free (&self->motd);
if (self->catalog != (nl_catd) -1)
catclose (self->catalog);
}
// --- Main program ------------------------------------------------------------
static void client_cancel_timers (struct client *);
static void client_set_kill_timer (struct client *);
static void client_update_poller (struct client *, const struct pollfd *);
static void client_unregister (struct client *, const char *);
static void
irc_try_finish_quit (struct server_context *ctx)
{
if (!ctx->n_clients && ctx->quitting)
ctx->polling = false;
}
static void
client_kill (struct client *c, const char *reason)
{
client_unregister (c, reason ? reason : "Client exited");
struct server_context *ctx = c->ctx;
ssize_t i = poller_find_by_fd (&ctx->poller, c->socket_fd);
if (i != -1)
poller_remove_at_index (&ctx->poller, i);
client_cancel_timers (c);
if (c->ssl)
(void) SSL_shutdown (c->ssl);
xclose (c->socket_fd);
c->socket_fd = -1;
client_free (c);
LIST_UNLINK (ctx->clients, c);
ctx->n_clients--;
free (c);
irc_try_finish_quit (ctx);
}
static void
irc_send_str (struct client *c, const struct str *s)
{
hard_assert (c->initialized && !c->closing_link);
// TODO: kill the connection above some "SendQ" threshold (careful!)
str_append_data (&c->write_buffer, s->str,
s->len > IRC_MAX_MESSAGE_LENGTH ? IRC_MAX_MESSAGE_LENGTH : s->len);
str_append (&c->write_buffer, "\r\n");
// XXX: we might want to move this elsewhere, so that it doesn't get called
// as often; it's going to cause a lot of syscalls with epoll.
client_update_poller (c, NULL);
}
static void irc_send (struct client *c,
const char *format, ...) ATTRIBUTE_PRINTF (2, 3);
static void
irc_send (struct client *c, const char *format, ...)
{
struct str tmp;
str_init (&tmp);
va_list ap;
va_start (ap, format);
str_append_vprintf (&tmp, format, ap);
va_end (ap);
irc_send_str (c, &tmp);
str_free (&tmp);
}
static const char *
irc_get_text (struct server_context *ctx, int id, const char *def)
{
if (!soft_assert (def != NULL))
def = "";
if (ctx->catalog == (nl_catd) -1)
return def;
return catgets (ctx->catalog, 1, id, def);
}
static void
irc_close_link (struct client *c, const char *reason)
{
if (!soft_assert (!c->closing_link))
return;
// We push an `ERROR' message to the write buffer and let the poller send
// it, with some arbitrary timeout. The `closing_link' 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.
irc_send (c, "ERROR :Closing Link: %s[%s] (%s)", c->nickname,
c->hostname /* TODO host IP? */, reason);
c->closing_link = true;
client_unregister (c, reason);
client_set_kill_timer (c);
}
// --- Timers ------------------------------------------------------------------
static void
client_cancel_timers (struct client *c)
{
ssize_t i;
struct poller_timers *timers = &c->ctx->poller.timers;
while ((i = poller_timers_find_by_data (timers, c)) != -1)
poller_timers_remove_at_index (timers, i);
}
static void
client_set_timer (struct client *c, poller_timer_func fn, unsigned interval)
{
client_cancel_timers (c);
poller_timers_add (&c->ctx->poller.timers, fn, c, interval * 1000);
}
static void
on_irc_client_kill_timer (void *user_data)
{
struct client *c = user_data;
hard_assert (!c->initialized || c->closing_link);
client_kill (c, NULL);
}
static void
client_set_kill_timer (struct client *c)
{
client_set_timer (c, on_irc_client_kill_timer, c->ctx->ping_interval);
}
static void
on_irc_client_timeout_timer (void *user_data)
{
struct client *c = user_data;
char *reason = xstrdup_printf
("Ping timeout: >%u seconds", c->ctx->ping_interval);
irc_close_link (c, reason);
free (reason);
}
static void
on_irc_client_ping_timer (void *user_data)
{
struct client *c = user_data;
hard_assert (!c->closing_link);
irc_send (c, "PING :%s", c->ctx->server_name);
client_set_timer (c, on_irc_client_timeout_timer, c->ctx->ping_interval);
}
static void
client_set_ping_timer (struct client *c)
{
client_set_timer (c, on_irc_client_ping_timer, c->ctx->ping_interval);
}
// --- IRC command handling ----------------------------------------------------
enum
{
IRC_RPL_WELCOME = 1,
IRC_RPL_YOURHOST = 2,
IRC_RPL_CREATED = 3,
IRC_RPL_MYINFO = 4,
IRC_RPL_UMODEIS = 221,
IRC_RPL_LUSERCLIENT = 251,
IRC_RPL_LUSEROP = 252,
IRC_RPL_LUSERUNKNOWN = 253,
IRC_RPL_LUSERCHANNELS = 254,
IRC_RPL_LUSERME = 255,
IRC_RPL_AWAY = 301,
IRC_RPL_USERHOST = 302,
IRC_RPL_UNAWAY = 305,
IRC_RPL_NOWAWAY = 306,
IRC_RPL_LIST = 322,
IRC_RPL_LISTEND = 323,
IRC_RPL_CHANNELMODEIS = 324,
IRC_RPL_NOTOPIC = 331,
IRC_RPL_TOPIC = 332,
IRC_RPL_INVITELIST = 346,
IRC_RPL_ENDOFINVITELIST = 347,
IRC_RPL_EXCEPTLIST = 348,
IRC_RPL_ENDOFEXCEPTLIST = 349,
IRC_RPL_VERSION = 351,
IRC_RPL_NAMREPLY = 353,
IRC_RPL_ENDOFNAMES = 366,
IRC_RPL_BANLIST = 367,
IRC_RPL_ENDOFBANLIST = 368,
IRC_RPL_MOTD = 372,
IRC_RPL_MOTDSTART = 375,
IRC_RPL_ENDOFMOTD = 376,
IRC_RPL_TIME = 391,
IRC_ERR_NOSUCHNICK = 401,
IRC_ERR_NOSUCHSERVER = 402,
IRC_ERR_NOSUCHCHANNEL = 403,
IRC_ERR_CANNOTSENDTOCHAN = 404,
IRC_ERR_NOORIGIN = 409,
IRC_ERR_NORECIPIENT = 411,
IRC_ERR_NOTEXTTOSEND = 412,
IRC_ERR_UNKNOWNCOMMAND = 421,
IRC_ERR_NOMOTD = 422,
IRC_ERR_NONICKNAMEGIVEN = 431,
IRC_ERR_ERRONEOUSNICKNAME = 432,
IRC_ERR_NICKNAMEINUSE = 433,
IRC_ERR_NOTONCHANNEL = 442,
IRC_ERR_SUMMONDISABLED = 445,
IRC_ERR_USERSDISABLED = 446,
IRC_ERR_NOTREGISTERED = 451,
IRC_ERR_NEEDMOREPARAMS = 461,
IRC_ERR_ALREADYREGISTERED = 462,
IRC_ERR_CHANNELISFULL = 471,
IRC_ERR_INVITEONLYCHAN = 473,
IRC_ERR_BANNEDFROMCHAN = 474,
IRC_ERR_BADCHANNELKEY = 475,
IRC_ERR_BADCHANMASK = 476,
IRC_ERR_CHANOPRIVSNEEDED = 482,
IRC_ERR_USERSDONTMATCH = 502
};
static const char *g_default_replies[] =
{
[IRC_RPL_WELCOME] = ":Welcome to the Internet Relay Network %s!%s@%s",
[IRC_RPL_YOURHOST] = ":Your host is %s, running version %s",
[IRC_RPL_CREATED] = ":This server was created %s",
[IRC_RPL_MYINFO] = "%s %s %s %s",
[IRC_RPL_UMODEIS] = "+%s",
[IRC_RPL_LUSERCLIENT] = ":There are %d users and %d services on %d servers",
[IRC_RPL_LUSEROP] = "%d :operator(s) online",
[IRC_RPL_LUSERUNKNOWN] = "%d :unknown connection(s)",
[IRC_RPL_LUSERCHANNELS] = "%d :channels formed",
[IRC_RPL_LUSERME] = ":I have %d clients and %d servers",
[IRC_RPL_AWAY] = "%s :%s",
[IRC_RPL_USERHOST] = ":%s",
[IRC_RPL_UNAWAY] = ":You are no longer marked as being away",
[IRC_RPL_NOWAWAY] = ":You have been marked as being away",
[IRC_RPL_LIST] = "%s %d :%s",
[IRC_RPL_LISTEND] = ":End of LIST",
[IRC_RPL_CHANNELMODEIS] = "%s +%s",
[IRC_RPL_NOTOPIC] = "%s :No topic is set",
[IRC_RPL_TOPIC] = "%s :%s",
[IRC_RPL_INVITELIST] = "%s %s",
[IRC_RPL_ENDOFINVITELIST] = "%s :End of channel invite list",
[IRC_RPL_EXCEPTLIST] = "%s %s",
[IRC_RPL_ENDOFEXCEPTLIST] = "%s :End of channel exception list",
[IRC_RPL_VERSION] = "%s.%d %s :%s",
[IRC_RPL_NAMREPLY] = "%c %s :%s",
[IRC_RPL_ENDOFNAMES] = "%s :End of NAMES list",
[IRC_RPL_BANLIST] = "%s %s",
[IRC_RPL_ENDOFBANLIST] = "%s :End of channel ban list",
[IRC_RPL_MOTD] = ":- %s",
[IRC_RPL_MOTDSTART] = ":- %s Message of the day - ",
[IRC_RPL_ENDOFMOTD] = ":End of MOTD command",
[IRC_RPL_TIME] = "%s :%s",
[IRC_ERR_NOSUCHNICK] = "%s :No such nick/channel",
[IRC_ERR_NOSUCHSERVER] = "%s :No such server",
[IRC_ERR_NOSUCHCHANNEL] = "%s :No such channel",
[IRC_ERR_CANNOTSENDTOCHAN] = "%s :Cannot send to channel",
[IRC_ERR_NOORIGIN] = ":No origin specified",
[IRC_ERR_NORECIPIENT] = ":No recipient given (%s)",
[IRC_ERR_NOTEXTTOSEND] = ":No text to send",
[IRC_ERR_UNKNOWNCOMMAND] = "%s: Unknown command",
[IRC_ERR_NOMOTD] = ":MOTD File is missing",
[IRC_ERR_NONICKNAMEGIVEN] = ":No nickname given",
[IRC_ERR_ERRONEOUSNICKNAME] = "%s :Erroneous nickname",
[IRC_ERR_NICKNAMEINUSE] = "%s :Nickname is already in use",
[IRC_ERR_NOTONCHANNEL] = "%s :You're not on that channel",
[IRC_ERR_SUMMONDISABLED] = ":SUMMON has been disabled",
[IRC_ERR_USERSDISABLED] = ":USERS has been disabled",
[IRC_ERR_NOTREGISTERED] = ":You have not registered",
[IRC_ERR_NEEDMOREPARAMS] = "%s :Not enough parameters",
[IRC_ERR_ALREADYREGISTERED] = ":Unauthorized command (already registered)",
[IRC_ERR_CHANNELISFULL] = "%s :Cannot join channel (+l)",
[IRC_ERR_INVITEONLYCHAN] = "%s :Cannot join channel (+i)",
[IRC_ERR_BANNEDFROMCHAN] = "%s :Cannot join channel (+b)",
[IRC_ERR_BADCHANNELKEY] = "%s :Cannot join channel (+k)",
[IRC_ERR_BADCHANMASK] = "%s :Bad Channel Mask",
[IRC_ERR_CHANOPRIVSNEEDED] = "%s :You're not channel operator",
[IRC_ERR_USERSDONTMATCH] = ":Cannot change mode for other users",
};
// XXX: this way we cannot typecheck the arguments, so we must be careful
static void
irc_send_reply (struct client *c, int id, ...)
{
struct str tmp;
str_init (&tmp);
va_list ap;
va_start (ap, id);
str_append_printf (&tmp, ":%s %03d %s ",
c->ctx->server_name, id, c->nickname ? c->nickname : "");
str_append_vprintf (&tmp,
irc_get_text (c->ctx, id, g_default_replies[id]), ap);
va_end (ap);
irc_send_str (c, &tmp);
str_free (&tmp);
}
#define RETURN_WITH_REPLY(c, ...) \
BLOCK_START \
irc_send_reply ((c), __VA_ARGS__); \
return; \
BLOCK_END
static void
irc_send_motd (struct client *c)
{
struct server_context *ctx = c->ctx;
if (!ctx->motd.len)
RETURN_WITH_REPLY (c, IRC_ERR_NOMOTD);
irc_send_reply (c, IRC_RPL_MOTDSTART, ctx->server_name);
for (size_t i = 0; i < ctx->motd.len; i++)
irc_send_reply (c, IRC_RPL_MOTD, ctx->motd.vector[i]);
irc_send_reply (c, IRC_RPL_ENDOFMOTD);
}
static struct channel_user *
channel_get_user (const struct channel *chan, const struct client *c)
{
for (struct channel_user *iter = chan->users; iter; iter = iter->next)
if (!irc_strcmp (iter->nickname, c->nickname))
return iter;
return NULL;
}
static struct channel_user *
channel_add_user (struct channel *chan, const struct client *c)
{
size_t nick_len = strlen (c->nickname);
struct channel_user *link = xcalloc (1, sizeof *link + nick_len + 1);
memcpy (link->nickname, c->nickname, nick_len + 1);
LIST_PREPEND (chan->users, link);
return link;
}
static void
channel_remove_user (struct channel *chan, struct channel_user *user)
{
LIST_UNLINK (chan->users, user);
free (user);
}
static size_t
channel_user_count (const struct channel *chan)
{
size_t result = 0;
for (struct channel_user *iter = chan->users; iter; iter = iter->next)
result++;
return result;
}
static void
channel_destroy_if_empty (struct server_context *ctx, struct channel *chan)
{
if (!chan->users)
{
str_map_set (&ctx->channels, chan->name, NULL);
channel_free (chan);
free (chan);
}
}
static bool
client_in_mask_list (const struct client *c, const struct str_vector *mask)
{
struct str client;
str_init (&client);
str_append_printf (&client, "%s!%s@%s",
c->nickname, c->username, c->hostname);
irc_strxfrm (client.str, client.str, client.len);
bool result = false;
for (size_t i = 0; i < mask->len; i++)
// FIXME: irc_strxfrm() for the mask (save in canonical format?)
if (!fnmatch (client.str, mask->vector[i], 0))
{
result = true;
break;
}
str_free (&client);
return result;
}
static void
client_send_to_roommates (struct client *c, const char *message)
{
struct str_map targets;
str_map_init (&targets);
targets.key_xfrm = irc_strxfrm;
struct str_map_iter iter;
str_map_iter_init (&iter, &c->ctx->channels);
struct channel *chan;
while ((chan = str_map_iter_next (&iter)))
{
if (chan->modes & IRC_CHAN_MODE_QUIET
|| !channel_get_user (chan, c))
continue;
// When we're unregistering, the str_map_find() will return zero,
// which will prevent sending the QUIT message to ourselves.
for (struct channel_user *iter = chan->users; iter; iter = iter->next)
str_map_set (&targets, iter->nickname,
str_map_find (&c->ctx->users, iter->nickname));
}
str_map_iter_init (&iter, &targets);
struct client *target;
while ((target = str_map_iter_next (&iter)))
irc_send (target, "%s", message);
}
static void
client_unregister (struct client *c, const char *reason)
{
if (!c->registered)
return;
// Make the user effectively non-existent
str_map_set (&c->ctx->users, c->nickname, NULL);
char *message = xstrdup_printf (":%s!%s@%s QUIT :%s",
c->nickname, c->username, c->hostname, reason);
client_send_to_roommates (c, message);
free (message);
struct str_map_iter iter;
str_map_iter_init (&iter, &c->ctx->channels);
struct channel *chan;
while ((chan = str_map_iter_next (&iter)))
{
struct channel_user *user;
if (!(user = channel_get_user (chan, c)))
continue;
channel_remove_user (chan, user);
channel_destroy_if_empty (c->ctx, chan);
}
free (c->nickname);
c->nickname = NULL;
c->registered = false;
}
static void
irc_send_lusers (struct client *c)
{
int n_users = 0, n_services = 0, n_opers = 0, n_unknown = 0;
for (struct client *link = c->ctx->clients; link; link = link->next)
{
if (link->registered)
n_users++;
else
n_unknown++;
if (link->mode & IRC_USER_MODE_OPERATOR)
n_opers++;
}
int n_channels = 0;
struct str_map_iter iter;
str_map_iter_init (&iter, &c->ctx->channels);
struct channel *chan;
while ((chan = str_map_iter_next (&iter)))
if (!(chan->modes & IRC_CHAN_MODE_SECRET)
|| channel_get_user (chan, c))
n_channels++;
irc_send_reply (c, IRC_RPL_LUSERCLIENT,
n_users, n_services, 1 /* servers total */);
if (n_opers)
irc_send_reply (c, IRC_RPL_LUSEROP, n_opers);
if (n_unknown)
irc_send_reply (c, IRC_RPL_LUSERUNKNOWN, n_unknown);
if (n_channels)
irc_send_reply (c, IRC_RPL_LUSERCHANNELS, n_channels);
irc_send_reply (c, IRC_RPL_LUSERME,
n_users + n_services + n_unknown, 0 /* peer servers */);
}
static bool
irc_is_this_me (struct server_context *ctx, const char *target)
{
return !fnmatch (target, ctx->server_name, 0);
}
static void
irc_try_finish_registration (struct client *c)
{
struct server_context *ctx = c->ctx;
if (!c->nickname || !c->username || !c->realname)
return;
c->registered = true;
irc_send_reply (c, IRC_RPL_WELCOME, c->nickname, c->username, c->hostname);
irc_send_reply (c, IRC_RPL_YOURHOST, ctx->server_name, PROGRAM_VERSION);
// The purpose of this message eludes me
irc_send_reply (c, IRC_RPL_CREATED, __DATE__);
irc_send_reply (c, IRC_RPL_MYINFO, ctx->server_name, PROGRAM_VERSION,
IRC_SUPPORTED_USER_MODES, IRC_SUPPORTED_CHAN_MODES);
irc_send_lusers (c);
irc_send_motd (c);
char *mode = client_get_mode (c);
if (*mode)
irc_send (c, ":%s MODE %s :+%s", c->nickname, c->nickname, mode);
free (mode);
}
static void
irc_handle_pass (const struct irc_message *msg, struct client *c)
{
if (c->registered)
irc_send_reply (c, IRC_ERR_ALREADYREGISTERED);
else if (msg->params.len < 1)
irc_send_reply (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
// We have SSL client certificates for this purpose; ignoring
}
static void
irc_handle_nick (const struct irc_message *msg, struct client *c)
{
struct server_context *ctx = c->ctx;
if (msg->params.len < 1)
RETURN_WITH_REPLY (c, IRC_ERR_NONICKNAMEGIVEN);
const char *nickname = msg->params.vector[0];
if (irc_validate_nickname (nickname) != VALIDATION_OK)
RETURN_WITH_REPLY (c, IRC_ERR_ERRONEOUSNICKNAME, nickname);
struct client *client = str_map_find (&ctx->users, nickname);
if (client && client != c)
RETURN_WITH_REPLY (c, IRC_ERR_NICKNAMEINUSE, nickname);
if (c->registered)
{
char *message = xstrdup_printf (":%s!%s@%s NICK :%s",
c->nickname, c->username, c->hostname, nickname);
client_send_to_roommates (c, message);
free (message);
}
// Release the old nickname and allocate a new one
if (c->nickname)
{
str_map_set (&ctx->users, c->nickname, NULL);
free (c->nickname);
}
c->nickname = xstrdup (nickname);
str_map_set (&ctx->users, nickname, c);
if (!c->registered)
irc_try_finish_registration (c);
}
static void
irc_handle_user (const struct irc_message *msg, struct client *c)
{
if (c->registered)
RETURN_WITH_REPLY (c, IRC_ERR_ALREADYREGISTERED);
if (msg->params.len < 4)
RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
const char *username = msg->params.vector[0];
const char *mode = msg->params.vector[1];
const char *realname = msg->params.vector[3];
// Unfortunately the protocol doesn't give us any means of rejecting it
if (!irc_is_valid_user (username))
username = "xxx";
free (c->username);
c->username = xstrdup (username);
free (c->realname);
c->realname = xstrdup (realname);
unsigned long m;
if (xstrtoul (&m, mode, 10))
{
if (m & 4) c->mode |= IRC_USER_MODE_RX_WALLOPS;
if (m & 8) c->mode |= IRC_USER_MODE_INVISIBLE;
}
irc_try_finish_registration (c);
}
static void
irc_handle_userhost (const struct irc_message *msg, struct client *c)
{
if (msg->params.len < 1)
RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
struct str reply;
str_init (&reply);
for (size_t i = 0; i < 5 && i < msg->params.len; i++)
{
const char *nick = msg->params.vector[i];
struct client *target = str_map_find (&c->ctx->users, nick);
if (!target)
continue;
if (i)
str_append_c (&reply, ' ');
str_append (&reply, nick);
if (target->mode & IRC_USER_MODE_OPERATOR)
str_append_c (&reply, '*');
str_append_printf (&reply, "=%c%s@%s",
target->away_message ? '-' : '+',
target->username, target->hostname);
}
irc_send_reply (c, IRC_RPL_USERHOST, reply.str);
str_free (&reply);
}
static void
irc_handle_lusers (const struct irc_message *msg, struct client *c)
{
if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
else
irc_send_lusers (c);
}
static void
irc_handle_motd (const struct irc_message *msg, struct client *c)
{
if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
else
irc_send_motd (c);
}
static void
irc_handle_ping (const struct irc_message *msg, struct client *c)
{
// XXX: the RFC is pretty incomprehensible about the exact usage
if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
else if (msg->params.len < 1)
irc_send_reply (c, IRC_ERR_NOORIGIN);
else
irc_send (c, ":%s PONG :%s",
c->ctx->server_name, msg->params.vector[0]);
}
static void
irc_handle_pong (const struct irc_message *msg, struct client *c)
{
// We are the only server, so we don't have to care too much
if (msg->params.len < 1)
irc_send_reply (c, IRC_ERR_NOORIGIN);
else
// Set a new timer to send another PING
client_set_ping_timer (c);
}
static void
irc_handle_quit (const struct irc_message *msg, struct client *c)
{
char *reason = xstrdup_printf ("Quit: %s",
msg->params.len > 0 ? msg->params.vector[0] : c->nickname);
irc_close_link (c, reason);
free (reason);
}
static void
irc_handle_time (const struct irc_message *msg, struct client *c)
{
if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
char buf[32];
time_t now = time (NULL);
struct tm tm;
strftime (buf, sizeof buf, "%a %b %d %Y %T", localtime_r (&now, &tm));
irc_send_reply (c, IRC_RPL_TIME, c->ctx->server_name, buf);
}
static void
irc_handle_version (const struct irc_message *msg, struct client *c)
{
if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
else
irc_send_reply (c, IRC_RPL_VERSION, PROGRAM_VERSION, g_debug_mode,
c->ctx->server_name, PROGRAM_NAME " " PROGRAM_VERSION);
}
static void
irc_channel_multicast (struct channel *chan, const char *message)
{
for (struct channel_user *iter = chan->users; iter; iter = iter->next)
{
struct client *c = str_map_find (&chan->ctx->users, iter->nickname);
irc_send (c, "%s", message);
}
}
static void
irc_send_channel_list (struct client *c, const char *channel_name,
const struct str_vector *list, int reply, int end_reply)
{
for (size_t i = 0; i < list->len; i++)
irc_send_reply (c, reply, channel_name, list->vector[i]);
irc_send_reply (c, end_reply);
}
static bool
irc_maybe_send_channel_list (struct client *c, struct channel *chan,
const char *mode_string)
{
if (*mode_string == '+')
mode_string++;
if (!strcmp (mode_string, "b"))
irc_send_channel_list (c, chan->name, &chan->ban_list,
IRC_RPL_BANLIST, IRC_RPL_ENDOFBANLIST);
else if (!strcmp (mode_string, "e"))
irc_send_channel_list (c, chan->name, &chan->exception_list,
IRC_RPL_EXCEPTLIST, IRC_RPL_ENDOFEXCEPTLIST);
else if (!strcmp (mode_string, "I"))
irc_send_channel_list (c, chan->name, &chan->invite_list,
IRC_RPL_INVITELIST, IRC_RPL_ENDOFINVITELIST);
else
return false;
return true;
}
static void
irc_handle_mode (const struct irc_message *msg, struct client *c)
{
if (msg->params.len < 1)
RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
const char *target = msg->params.vector[0];
struct client *client = str_map_find (&c->ctx->users, target);
if (client)
{
if (irc_strcmp (target, c->nickname))
RETURN_WITH_REPLY (c, IRC_ERR_USERSDONTMATCH);
char *mode = client_get_mode (client);
irc_send_reply (c, IRC_RPL_UMODEIS, mode);
free (mode);
// TODO: mode modification
return;
}
struct channel *chan = str_map_find (&c->ctx->channels, target);
if (chan)
{
if (msg->params.len < 2)
{
char *mode = channel_get_mode (chan, channel_get_user (chan, c));
irc_send_reply (c, IRC_RPL_CHANNELMODEIS, target, mode);
free (mode);
return;
}
if (msg->params.len < 3
&& irc_maybe_send_channel_list (c, chan, msg->params.vector[1]))
return;
// TODO: mode modification
return;
}
irc_send_reply (c, IRC_ERR_NOSUCHNICK, target);
}
static void
irc_handle_privmsg (const struct irc_message *msg, struct client *c)
{
if (msg->params.len < 1)
RETURN_WITH_REPLY (c, IRC_ERR_NORECIPIENT, msg->command);
if (msg->params.len < 2 || !*msg->params.vector[1])
RETURN_WITH_REPLY (c, IRC_ERR_NOTEXTTOSEND);
const char *target = msg->params.vector[0];
const char *text = msg->params.vector[1];
struct client *client = str_map_find (&c->ctx->users, target);
if (client)
{
irc_send (client, ":%s!%s@%s PRIVMSG %s :%s",
c->nickname, c->username, c->hostname, target, text);
return;
}
struct channel *chan = str_map_find (&c->ctx->channels, target);
if (chan)
{
struct channel_user *user = channel_get_user (chan, c);
if ((chan->modes & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) && !user)
RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
if ((chan->modes & IRC_CHAN_MODE_MODERATED) && (!user ||
!(user->modes & (IRC_CHAN_MODE_VOICE | IRC_CHAN_MODE_OPERATOR))))
RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
if (client_in_mask_list (c, &chan->ban_list)
&& !client_in_mask_list (c, &chan->exception_list))
RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
char *message = xstrdup_printf (":%s!%s@%s PRIVMSG %s :%s",
c->nickname, c->username, c->hostname, target, text);
irc_channel_multicast (chan, message);
free (message);
return;
}
irc_send_reply (c, IRC_ERR_NOSUCHNICK, target);
}
static void
irc_send_rpl_list (struct client *c, const struct channel *chan)
{
int visible = 0;
for (struct channel_user *user = chan->users;
user; user = user->next)
visible++;
irc_send_reply (c, IRC_RPL_LIST, chan->name, visible, chan->topic);
}
static void
irc_handle_list (const struct irc_message *msg, struct client *c)
{
if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
struct channel *chan;
if (msg->params.len == 0)
{
struct str_map_iter iter;
str_map_iter_init (&iter, &c->ctx->channels);
while ((chan = str_map_iter_next (&iter)))
if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
|| channel_get_user (chan, c))
irc_send_rpl_list (c, chan);
}
else
{
struct str_vector channels;
str_vector_init (&channels);
split_str_ignore_empty (msg->params.vector[0], ',', &channels);
for (size_t i = 0; i < channels.len; i++)
if ((chan = str_map_find (&c->ctx->channels, channels.vector[i]))
&& (!(chan->modes & IRC_CHAN_MODE_SECRET)
|| channel_get_user (chan, c)))
irc_send_rpl_list (c, chan);
str_vector_free (&channels);
}
irc_send_reply (c, IRC_RPL_LISTEND);
}
static void
irc_send_rpl_namreply (struct client *c, const struct channel *chan)
{
struct str_vector nicks;
str_vector_init (&nicks);
char type = '=';
if (chan->modes & IRC_CHAN_MODE_SECRET)
type = '@';
else if (chan->modes & IRC_CHAN_MODE_PRIVATE)
type = '*';
bool on_channel = channel_get_user (chan, c);
for (struct channel_user *iter = chan->users; iter; iter = iter->next)
{
struct client *target = str_map_find (&c->ctx->users, iter->nickname);
if (!on_channel && (target->mode & IRC_USER_MODE_INVISIBLE))
continue;
struct str result;
str_init (&result);
if (iter->modes & IRC_CHAN_MODE_OPERATOR)
str_append_c (&result, '@');
else if (iter->modes & IRC_CHAN_MODE_VOICE)
str_append_c (&result, '+');
str_append (&result, target->nickname);
str_vector_add_owned (&nicks, str_steal (&result));
}
if (nicks.len)
{
char *reply = join_str_vector (&nicks, ' ');
irc_send_reply (c, IRC_RPL_NAMREPLY, type, chan->name, reply);
free (reply);
}
str_vector_free (&nicks);
}
static void
irc_handle_names (const struct irc_message *msg, struct client *c)
{
if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
struct channel *chan;
if (msg->params.len == 0)
{
struct str_map_iter iter;
str_map_iter_init (&iter, &c->ctx->channels);
while ((chan = str_map_iter_next (&iter)))
if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
|| channel_get_user (chan, c))
irc_send_rpl_namreply (c, chan);
// TODO
// If no <channel> parameter is given, a list of all channels and their
// occupants is returned. At the end of this list, a list of users who
// are visible but either not on any channel or not on a visible channel
// are listed as being on `channel' "*".
irc_send_reply (c, IRC_RPL_ENDOFNAMES, "*");
}
else
{
struct str_vector channels;
str_vector_init (&channels);
split_str_ignore_empty (msg->params.vector[0], ',', &channels);
for (size_t i = 0; i < channels.len; i++)
if ((chan = str_map_find (&c->ctx->channels, channels.vector[i]))
&& (!(chan->modes & IRC_CHAN_MODE_SECRET)
|| channel_get_user (chan, c)))
{
irc_send_rpl_namreply (c, chan);
irc_send_reply (c, IRC_RPL_ENDOFNAMES, channels.vector[i]);
}
str_vector_free (&channels);
}
}
static void
irc_send_rpl_topic (struct client *c, struct channel *chan)
{
if (!*chan->topic)
irc_send_reply (c, IRC_RPL_NOTOPIC, chan->name);
else
irc_send_reply (c, IRC_RPL_TOPIC, chan->name, chan->topic);
}
static void
irc_handle_topic (const struct irc_message *msg, struct client *c)
{
if (msg->params.len < 1)
RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
const char *target = msg->params.vector[0];
struct channel *chan = str_map_find (&c->ctx->channels, target);
if (!chan)
RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, target);
if (msg->params.len < 2)
{
irc_send_rpl_topic (c, chan);
return;
}
struct channel_user *user = channel_get_user (chan, c);
if (!user)
RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, target);
if ((chan->modes & IRC_CHAN_MODE_PROTECTED_TOPIC)
&& !(user->modes & IRC_CHAN_MODE_OPERATOR))
RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED);
free (chan->topic);
chan->topic = xstrdup (msg->params.vector[1]);
char *message = xstrdup_printf (":%s!%s@%s TOPIC %s :%s",
c->nickname, c->username, c->hostname, target, chan->topic);
irc_channel_multicast (chan, message);
free (message);
}
static void
irc_try_part (struct client *c, const char *channel_name, const char *reason)
{
if (!reason)
reason = c->nickname;
struct channel *chan;
if (!(chan = str_map_find (&c->ctx->channels, channel_name)))
RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name);
struct channel_user *user;
if (!(user = channel_get_user (chan, c)))
RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
char *message = xstrdup_printf (":%s!%s@%s PART %s :%s",
c->nickname, c->username, c->hostname, channel_name, reason);
if (!(chan->modes & IRC_CHAN_MODE_QUIET))
irc_channel_multicast (chan, message);
else
irc_send (c, "%s", message);
free (message);
channel_remove_user (chan, user);
channel_destroy_if_empty (c->ctx, chan);
}
static void
irc_part_all_channels (struct client *c)
{
struct str_map_iter iter;
str_map_iter_init (&iter, &c->ctx->channels);
struct channel *chan = str_map_iter_next (&iter), *next;
while (chan)
{
// We have to be careful here, the channel might get destroyed
next = str_map_iter_next (&iter);
if (channel_get_user (chan, c))
irc_try_part (c, chan->name, NULL);
chan = next;
}
}
static void
irc_handle_part (const struct irc_message *msg, struct client *c)
{
if (msg->params.len < 1)
RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
const char *reason = msg->params.len > 1 ? msg->params.vector[1] : NULL;
struct str_vector channels;
str_vector_init (&channels);
split_str_ignore_empty (msg->params.vector[0], ',', &channels);
for (size_t i = 0; i < channels.len; i++)
irc_try_part (c, channels.vector[i], reason);
str_vector_free (&channels);
}
static void
irc_try_join (struct client *c, const char *channel_name, const char *key)
{
struct channel *chan = str_map_find (&c->ctx->channels, channel_name);
unsigned user_mode = 0;
if (!chan)
{
if (irc_validate_channel_name (channel_name) != VALIDATION_OK)
RETURN_WITH_REPLY (c, IRC_ERR_BADCHANMASK, channel_name);
user_mode = IRC_CHAN_MODE_OPERATOR;
chan = xcalloc (1, sizeof *chan);
channel_init (chan);
str_map_set (&c->ctx->channels, channel_name, chan);
chan->ctx = c->ctx;
chan->name = xstrdup (channel_name);
}
else if (channel_get_user (chan, c))
return;
if ((chan->modes & IRC_CHAN_MODE_INVITE_ONLY)
&& !client_in_mask_list (c, &chan->invite_list))
// TODO: exceptions caused by INVITE
RETURN_WITH_REPLY (c, IRC_ERR_INVITEONLYCHAN, channel_name);
if (chan->key && (!key || strcmp (key, chan->key)))
RETURN_WITH_REPLY (c, IRC_ERR_BADCHANNELKEY, channel_name);
if (chan->user_limit != -1
&& channel_user_count (chan) >= (size_t) chan->user_limit)
RETURN_WITH_REPLY (c, IRC_ERR_CHANNELISFULL, channel_name);
if (client_in_mask_list (c, &chan->ban_list)
&& !client_in_mask_list (c, &chan->exception_list))
RETURN_WITH_REPLY (c, IRC_ERR_BANNEDFROMCHAN, channel_name);
channel_add_user (chan, c)->modes = user_mode;
char *message = xstrdup_printf (":%s!%s@%s JOIN %s",
c->nickname, c->username, c->hostname, channel_name);
if (!(chan->modes & IRC_CHAN_MODE_QUIET))
irc_channel_multicast (chan, message);
else
irc_send (c, "%s", message);
free (message);
irc_send_rpl_topic (c, chan);
irc_send_rpl_namreply (c, chan);
}
static void
irc_handle_join (const struct irc_message *msg, struct client *c)
{
if (msg->params.len < 1)
RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
if (!strcmp (msg->params.vector[0], "0"))
{
irc_part_all_channels (c);
return;
}
struct str_vector channels;
struct str_vector keys;
str_vector_init (&channels);
str_vector_init (&keys);
split_str_ignore_empty (msg->params.vector[0], ',', &channels);
if (msg->params.len > 1)
split_str_ignore_empty (msg->params.vector[1], ',', &keys);
for (size_t i = 0; i < channels.len; i++)
irc_try_join (c, channels.vector[i],
i < keys.len ? keys.vector[i] : NULL);
str_vector_free (&channels);
str_vector_free (&keys);
}
static void
irc_handle_summon (const struct irc_message *msg, struct client *c)
{
(void) msg;
irc_send_reply (c, IRC_ERR_SUMMONDISABLED);
}
static void
irc_handle_users (const struct irc_message *msg, struct client *c)
{
(void) msg;
irc_send_reply (c, IRC_ERR_USERSDISABLED);
}
static void
irc_handle_away (const struct irc_message *msg, struct client *c)
{
if (msg->params.len < 1)
{
free (c->away_message);
c->away_message = NULL;
irc_send_reply (c, IRC_RPL_UNAWAY);
}
else
{
free (c->away_message);
c->away_message = xstrdup (msg->params.vector[0]);
irc_send_reply (c, IRC_RPL_NOWAWAY);
}
}
// -----------------------------------------------------------------------------
struct irc_command
{
const char *name;
bool requires_registration;
void (*handler) (const struct irc_message *, struct client *);
};
static void
irc_register_handlers (struct server_context *ctx)
{
// TODO: add an index for IRC_ERR_NOSUCHSERVER validation?
// TODO: add a minimal parameter count?
// TODO: more commands, see RFC 2812 :!
static const struct irc_command message_handlers[] =
{
{ "PASS", false, irc_handle_pass },
{ "NICK", false, irc_handle_nick },
{ "USER", false, irc_handle_user },
{ "USERHOST", true, irc_handle_userhost },
{ "LUSERS", true, irc_handle_lusers },
{ "MOTD", true, irc_handle_motd },
{ "PING", true, irc_handle_ping },
{ "PONG", false, irc_handle_pong },
{ "QUIT", false, irc_handle_quit },
{ "TIME", true, irc_handle_time },
{ "VERSION", true, irc_handle_version },
{ "USERS", true, irc_handle_users },
{ "SUMMON", true, irc_handle_summon },
{ "AWAY", true, irc_handle_away },
{ "MODE", true, irc_handle_mode },
{ "PRIVMSG", true, irc_handle_privmsg },
{ "JOIN", true, irc_handle_join },
{ "PART", true, irc_handle_part },
{ "TOPIC", true, irc_handle_topic },
{ "LIST", true, irc_handle_list },
{ "NAMES", true, irc_handle_names },
};
for (size_t i = 0; i < N_ELEMENTS (message_handlers); i++)
{
const struct irc_command *cmd = &message_handlers[i];
str_map_set (&ctx->handlers, cmd->name, (void *) cmd);
}
}
static void
irc_process_message (const struct irc_message *msg,
const char *raw, void *user_data)
{
(void) raw;
struct client *c = user_data;
if (c->closing_link)
return;
struct irc_command *cmd = str_map_find (&c->ctx->handlers, msg->command);
if (!cmd)
irc_send_reply (c, IRC_ERR_UNKNOWNCOMMAND, msg->command);
else if (cmd->requires_registration && !c->registered)
irc_send_reply (c, IRC_ERR_NOTREGISTERED);
else
cmd->handler (msg, c);
}
// --- Network I/O -------------------------------------------------------------
static bool
irc_try_read (struct client *c)
{
struct str *buf = &c->read_buffer;
ssize_t n_read;
while (true)
{
str_ensure_space (buf, 512);
n_read = recv (c->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, c);
continue;
}
if (n_read == 0)
{
client_kill (c, NULL);
return false;
}
if (errno == EAGAIN)
return true;
if (errno == EINTR)
continue;
print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
client_kill (c, strerror (errno));
return false;
}
}
static bool
irc_try_read_ssl (struct client *c)
{
if (c->ssl_tx_want_rx)
return true;
struct str *buf = &c->read_buffer;
c->ssl_rx_want_tx = false;
while (true)
{
str_ensure_space (buf, 512);
int n_read = SSL_read (c->ssl, buf->str + buf->len,
buf->alloc - buf->len - 1 /* null byte */);
const char *error_info = NULL;
switch (xssl_get_error (c->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, c);
continue;
case SSL_ERROR_ZERO_RETURN:
client_kill (c, NULL);
return false;
case SSL_ERROR_WANT_READ:
return true;
case SSL_ERROR_WANT_WRITE:
c->ssl_rx_want_tx = true;
return true;
case XSSL_ERROR_TRY_AGAIN:
continue;
default:
print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
client_kill (c, error_info);
return false;
}
}
}
static bool
irc_try_write (struct client *c)
{
struct str *buf = &c->write_buffer;
ssize_t n_written;
while (buf->len)
{
n_written = send (c->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));
client_kill (c, strerror (errno));
return false;
}
return true;
}
static bool
irc_try_write_ssl (struct client *c)
{
if (c->ssl_rx_want_tx)
return true;
struct str *buf = &c->write_buffer;
c->ssl_tx_want_rx = false;
while (buf->len)
{
int n_written = SSL_write (c->ssl, buf->str, buf->len);
const char *error_info = NULL;
switch (xssl_get_error (c->ssl, n_written, &error_info))
{
case SSL_ERROR_NONE:
str_remove_slice (buf, 0, n_written);
continue;
case SSL_ERROR_ZERO_RETURN:
client_kill (c, NULL);
return false;
case SSL_ERROR_WANT_WRITE:
return true;
case SSL_ERROR_WANT_READ:
c->ssl_tx_want_rx = true;
return true;
case XSSL_ERROR_TRY_AGAIN:
continue;
default:
print_debug ("%s: %s: %s", __func__, "SSL_write", error_info);
client_kill (c, error_info);
return false;
}
}
return true;
}
static bool
irc_autodetect_ssl (struct client *c)
{
// 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 (c->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 bool
client_initialize_ssl (struct client *c)
{
// SSL support not enabled
if (!c->ctx->ssl_ctx)
return false;
c->ssl = SSL_new (c->ctx->ssl_ctx);
if (!c->ssl)
goto error_ssl_1;
if (!SSL_set_fd (c->ssl, c->socket_fd))
goto error_ssl_2;
SSL_set_accept_state (c->ssl);
return true;
error_ssl_2:
SSL_free (c->ssl);
c->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",
c->hostname, ERR_error_string (ERR_get_error (), NULL));
return false;
}
static void
on_irc_client_ready (const struct pollfd *pfd, void *user_data)
{
struct client *c = user_data;
if (!c->initialized)
{
hard_assert (pfd->events == POLLIN);
if (irc_autodetect_ssl (c) && !client_initialize_ssl (c))
{
client_kill (c, NULL);
return;
}
c->initialized = true;
client_set_ping_timer (c);
}
if (c->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 (c) || !irc_try_write_ssl (c))
return;
}
else if (!irc_try_read (c) || !irc_try_write (c))
return;
client_update_poller (c, pfd);
// The purpose of the `closing_link' state is to transfer the `ERROR'
if (c->closing_link && !c->write_buffer.len)
client_kill (c, NULL);
}
static void
client_update_poller (struct client *c, const struct pollfd *pfd)
{
int new_events = POLLIN;
if (c->ssl)
{
if (c->write_buffer.len || c->ssl_rx_want_tx)
new_events |= POLLOUT;
// While we're waiting for an opposite event, we ignore the original
if (c->ssl_rx_want_tx) new_events &= ~POLLIN;
if (c->ssl_tx_want_rx) new_events &= ~POLLOUT;
}
else if (c->write_buffer.len)
new_events |= POLLOUT;
hard_assert (new_events != 0);
if (!pfd || pfd->events != new_events)
poller_set (&c->ctx->poller, c->socket_fd, new_events,
(poller_dispatcher_func) on_irc_client_ready, c);
}
static void
on_irc_client_available (const struct pollfd *pfd, void *user_data)
{
(void) pfd;
struct server_context *ctx = user_data;
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
|| errno == ECONNABORTED)
continue;
// TODO: handle resource exhaustion (EMFILE, ENFILE) specially
// (stop accepting new connections and wait until we close some).
// FIXME: handle this better, bring the server down cleanly.
exit_fatal ("%s: %s", "accept", strerror (errno));
}
if (ctx->max_connections != 0 && ctx->n_clients >= ctx->max_connections)
{
print_debug ("connection limit reached, refusing connection");
close (fd);
continue;
}
char host[NI_MAXHOST] = "unknown", port[NI_MAXSERV] = "unknown";
int err = getnameinfo ((struct sockaddr *) &peer, peer_len,
host, sizeof host, port, sizeof port, NI_NUMERICSERV);
if (err)
print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
print_debug ("accepted connection from %s:%s", host, port);
struct client *c = xmalloc (sizeof *c);
client_init (c);
c->ctx = ctx;
c->socket_fd = fd;
c->hostname = xstrdup (host);
LIST_PREPEND (ctx->clients, c);
ctx->n_clients++;
set_blocking (fd, false);
client_update_poller (c, NULL);
client_set_kill_timer (c);
}
}
// -----------------------------------------------------------------------------
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
irc_initialize_ssl (struct server_context *ctx, struct error **e)
{
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)
error_set (e, "no SSL certificate set");
else if (!ssl_key)
error_set (e, "no SSL private key set");
if (!ssl_cert || !ssl_key)
return false;
char *cert_path = resolve_config_filename (ssl_cert);
char *key_path = resolve_config_filename (ssl_key);
if (!cert_path)
error_set (e, "%s: %s", "cannot open file", ssl_cert);
else if (!key_path)
error_set (e, "%s: %s", "cannot open file", ssl_key);
if (!cert_path || !key_path)
return false;
ctx->ssl_ctx = SSL_CTX_new (SSLv23_server_method ());
if (!ctx->ssl_ctx)
{
// XXX: these error strings are really nasty; also there could be
// multiple errors on the OpenSSL stack.
error_set (e, "%s: %s", "could not initialize SSL",
ERR_error_string (ERR_get_error (), NULL));
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, cert_path))
{
error_set (e, "%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, key_path, SSL_FILETYPE_PEM))
{
error_set (e, "%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:
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;
char *path = resolve_config_filename (catalog);
if (!path)
{
error_set (e, "%s: %s", "cannot open file", catalog);
return false;
}
ctx->catalog = catopen (path, NL_CAT_LOCALE);
free (path);
if (ctx->catalog == (nl_catd) -1)
{
error_set (e, "%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;
char *path = resolve_config_filename (motd);
if (!path)
{
error_set (e, "%s: %s", "cannot open file", motd);
return false;
}
FILE *fp = fopen (path, "r");
free (path);
if (!fp)
{
error_set (e, "%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;
}
/// This function handles values that require validation before their first use,
/// or some kind of a transformation (such as conversion to an integer) needs
/// to be done before they can be used directly.
static bool
irc_parse_config (struct server_context *ctx, struct error **e)
{
unsigned long ul;
#define PARSE_UNSIGNED(name, min, max) \
const char *name = str_map_find (&ctx->config, #name); \
hard_assert (name != NULL); \
if (!xstrtoul (&ul, name, 10) || ul > max || ul < min) \
{ \
error_set (e, "invalid configuration value for `%s': %s", \
#name, "the number is invalid or out of range"); \
return false; \
} \
ctx->name = ul
PARSE_UNSIGNED (ping_interval, 1, UINT_MAX);
PARSE_UNSIGNED (max_connections, 0, UINT_MAX);
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, "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, "%s: %s",
"getting the hostname failed", strerror (errno));
return false;
}
res = irc_validate_hostname (hostname);
if (res != VALIDATION_OK)
{
error_set (e,
"`%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
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, "%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 setup failed");
return false;
}
set_blocking (sockfd, false);
ctx->listen_fd = sockfd;
poller_set (&ctx->poller, ctx->listen_fd, POLLIN,
(poller_dispatcher_func) on_irc_client_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);
if (g_termination_requested && !ctx->quitting)
{
print_status ("shutting down");
for (struct client *iter = ctx->clients; iter; iter = iter->next)
if (!iter->closing_link)
irc_close_link (iter, "Shutting down");
ssize_t i = poller_find_by_fd (&ctx->poller, ctx->listen_fd);
if (soft_assert (i != -1))
poller_remove_at_index (&ctx->poller, i);
if (ctx->listen_fd != -1)
xclose (ctx->listen_fd);
ctx->listen_fd = -1;
ctx->quitting = true;
irc_try_finish_quit (ctx);
}
}
static void
daemonize (void)
{
// TODO: create and lock a PID file?
print_status ("daemonizing...");
if (chdir ("/"))
exit_fatal ("%s: %s", "chdir", strerror (errno));
pid_t pid;
if ((pid = fork ()) < 0)
exit_fatal ("%s: %s", "fork", strerror (errno));
else if (pid)
exit (EXIT_SUCCESS);
setsid ();
signal (SIGHUP, SIG_IGN);
if ((pid = fork ()) < 0)
exit_fatal ("%s: %s", "fork", strerror (errno));
else if (pid)
exit (EXIT_SUCCESS);
openlog (PROGRAM_NAME, LOG_NDELAY | LOG_NOWAIT | LOG_PID, 0);
g_log_message_real = log_message_syslog;
// XXX: we may close our own descriptors this way, crippling ourselves
for (int i = 0; i < 3; i++)
xclose (i);
int tty = open ("/dev/null", O_RDWR);
if (tty != 0 || dup (0) != 1 || dup (0) != 2)
exit_fatal ("failed to reopen FD's: %s", strerror (errno));
}
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];
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':
call_write_default_config (optarg, g_config_table);
exit (EXIT_SUCCESS);
default:
print_error ("wrong 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);
irc_register_handlers (&ctx);
struct error *e = NULL;
if (!read_config_file (&ctx.config, &e))
{
print_error ("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, &e)
|| !irc_initialize_server_name (&ctx, &e)
|| !irc_initialize_motd (&ctx, &e)
|| !irc_initialize_catalog (&ctx, &e)
|| !irc_parse_config (&ctx, &e)
|| !irc_listen (&ctx, &e))
{
print_error ("%s", e->message);
error_free (e);
exit (EXIT_FAILURE);
}
if (!g_debug_mode)
daemonize ();
ctx.polling = true;
while (ctx.polling)
poller_run (&ctx.poller);
server_context_free (&ctx);
return EXIT_SUCCESS;
}
|