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
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
|
/* +------------------------------------+
* | Inspire Internet Relay Chat Daemon |
* +------------------------------------+
*
* Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
* E-mail:
* <brain@chatspike.net>
* <Craig@chatspike.net>
*
* Written by Craig Edwards, Craig McLure, and others.
* This program is free but copyrighted software; see
* the file COPYING for details.
*
* ---------------------------------------------------
*/
/* $ModDesc: Povides a spanning tree server link protocol */
using namespace std;
#include <stdio.h>
#include <vector>
#include <deque>
#include "globals.h"
#include "inspircd_config.h"
#ifdef GCC3
#include <ext/hash_map>
#else
#include <hash_map>
#endif
#include "users.h"
#include "channels.h"
#include "modules.h"
#include "commands.h"
#include "socket.h"
#include "helperfuncs.h"
#include "inspircd.h"
#include "inspstring.h"
#include "hashcomp.h"
#include "message.h"
#include "xline.h"
#include "typedefs.h"
#include "cull_list.h"
#include "aes.h"
#ifdef GCC3
#define nspace __gnu_cxx
#else
#define nspace std
#endif
/*
* The server list in InspIRCd is maintained as two structures
* which hold the data in different ways. Most of the time, we
* want to very quicky obtain three pieces of information:
*
* (1) The information on a server
* (2) The information on the server we must send data through
* to actually REACH the server we're after
* (3) Potentially, the child/parent objects of this server
*
* The InspIRCd spanning protocol provides easy access to these
* by storing the data firstly in a recursive structure, where
* each item references its parent item, and a dynamic list
* of child items, and another structure which stores the items
* hashed, linearly. This means that if we want to find a server
* by name quickly, we can look it up in the hash, avoiding
* any O(n) lookups. If however, during a split or sync, we want
* to apply an operation to a server, and any of its child objects
* we can resort to recursion to walk the tree structure.
*/
class ModuleSpanningTree;
static ModuleSpanningTree* TreeProtocolModule;
extern std::vector<Module*> modules;
extern std::vector<ircd_module*> factory;
extern int MODCOUNT;
/* Any socket can have one of five states at any one time.
* The LISTENER state indicates a socket which is listening
* for connections. It cannot receive data itself, only incoming
* sockets.
* The CONNECTING state indicates an outbound socket which is
* waiting to be writeable.
* The WAIT_AUTH_1 state indicates the socket is outbound and
* has successfully connected, but has not yet sent and received
* SERVER strings.
* The WAIT_AUTH_2 state indicates that the socket is inbound
* (allocated by a LISTENER) but has not yet sent and received
* SERVER strings.
* The CONNECTED state represents a fully authorized, fully
* connected server.
*/
enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
/* We need to import these from the core for use in netbursts */
/*typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;*/
extern user_hash clientlist;
extern chan_hash chanlist;
/* Foward declarations */
class TreeServer;
class TreeSocket;
/* This variable represents the root of the server tree
* (for all intents and purposes, it's us)
*/
TreeServer *TreeRoot;
Server* Srv;
/* This hash_map holds the hash equivalent of the server
* tree, used for rapid linear lookups.
*/
typedef nspace::hash_map<std::string, TreeServer*> server_hash;
server_hash serverlist;
/* More forward declarations */
bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms);
void ReadConfiguration(bool rebind);
/* Imported from xline.cpp for use during netburst */
extern std::vector<KLine> klines;
extern std::vector<GLine> glines;
extern std::vector<ZLine> zlines;
extern std::vector<QLine> qlines;
extern std::vector<ELine> elines;
extern std::vector<KLine> pklines;
extern std::vector<GLine> pglines;
extern std::vector<ZLine> pzlines;
extern std::vector<QLine> pqlines;
extern std::vector<ELine> pelines;
/* Each server in the tree is represented by one class of
* type TreeServer. A locally connected TreeServer can
* have a class of type TreeSocket associated with it, for
* remote servers, the TreeSocket entry will be NULL.
* Each server also maintains a pointer to its parent
* (NULL if this server is ours, at the top of the tree)
* and a pointer to its "Route" (see the comments in the
* constructors below), and also a dynamic list of pointers
* to its children which can be iterated recursively
* if required. Creating or deleting objects of type
* TreeServer automatically maintains the hash_map of
* TreeServer items, deleting and inserting them as they
* are created and destroyed.
*/
class TreeServer
{
TreeServer* Parent; /* Parent entry */
TreeServer* Route; /* Route entry */
std::vector<TreeServer*> Children; /* List of child objects */
std::string ServerName; /* Server's name */
std::string ServerDesc; /* Server's description */
std::string VersionString; /* Version string or empty string */
int UserCount; /* Not used in this version */
int OperCount; /* Not used in this version */
TreeSocket* Socket; /* For directly connected servers this points at the socket object */
time_t NextPing; /* After this time, the server should be PINGed*/
bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
public:
/* We don't use this constructor. Its a dummy, and won't cause any insertion
* of the TreeServer into the hash_map. See below for the two we DO use.
*/
TreeServer()
{
Parent = NULL;
ServerName = "";
ServerDesc = "";
VersionString = "";
UserCount = OperCount = 0;
VersionString = Srv->GetVersion();
}
/* We use this constructor only to create the 'root' item, TreeRoot, which
* represents our own server. Therefore, it has no route, no parent, and
* no socket associated with it. Its version string is our own local version.
*/
TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
{
Parent = NULL;
VersionString = "";
UserCount = OperCount = 0;
VersionString = Srv->GetVersion();
Route = NULL;
AddHashEntry();
}
/* When we create a new server, we call this constructor to initialize it.
* This constructor initializes the server's Route and Parent, and sets up
* its ping counters so that it will be pinged one minute from now.
*/
TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
{
VersionString = "";
UserCount = OperCount = 0;
this->SetNextPingTime(time(NULL) + 60);
this->SetPingFlag();
/* find the 'route' for this server (e.g. the one directly connected
* to the local server, which we can use to reach it)
*
* In the following example, consider we have just added a TreeServer
* class for server G on our network, of which we are server A.
* To route traffic to G (marked with a *) we must send the data to
* B (marked with a +) so this algorithm initializes the 'Route'
* value to point at whichever server traffic must be routed through
* to get here. If we were to try this algorithm with server B,
* the Route pointer would point at its own object ('this').
*
* A
* / \
* + B C
* / \ \
* D E F
* / \
* * G H
*
* We only run this algorithm when a server is created, as
* the routes remain constant while ever the server exists, and
* do not need to be re-calculated.
*/
Route = Above;
if (Route == TreeRoot)
{
Route = this;
}
else
{
while (this->Route->GetParent() != TreeRoot)
{
this->Route = Route->GetParent();
}
}
/* Because recursive code is slow and takes a lot of resources,
* we store two representations of the server tree. The first
* is a recursive structure where each server references its
* children and its parent, which is used for netbursts and
* netsplits to dump the whole dataset to the other server,
* and the second is used for very fast lookups when routing
* messages and is instead a hash_map, where each item can
* be referenced by its server name. The AddHashEntry()
* call below automatically inserts each TreeServer class
* into the hash_map as it is created. There is a similar
* maintainance call in the destructor to tidy up deleted
* servers.
*/
this->AddHashEntry();
}
/* This method is used to add the structure to the
* hash_map for linear searches. It is only called
* by the constructors.
*/
void AddHashEntry()
{
server_hash::iterator iter;
iter = serverlist.find(this->ServerName);
if (iter == serverlist.end())
serverlist[this->ServerName] = this;
}
/* This method removes the reference to this object
* from the hash_map which is used for linear searches.
* It is only called by the default destructor.
*/
void DelHashEntry()
{
server_hash::iterator iter;
iter = serverlist.find(this->ServerName);
if (iter != serverlist.end())
serverlist.erase(iter);
}
/* These accessors etc should be pretty self-
* explanitory.
*/
TreeServer* GetRoute()
{
return Route;
}
std::string GetName()
{
return this->ServerName;
}
std::string GetDesc()
{
return this->ServerDesc;
}
std::string GetVersion()
{
return this->VersionString;
}
void SetNextPingTime(time_t t)
{
this->NextPing = t;
LastPingWasGood = false;
}
time_t NextPingTime()
{
return this->NextPing;
}
bool AnsweredLastPing()
{
return LastPingWasGood;
}
void SetPingFlag()
{
LastPingWasGood = true;
}
int GetUserCount()
{
return this->UserCount;
}
int GetOperCount()
{
return this->OperCount;
}
TreeSocket* GetSocket()
{
return this->Socket;
}
TreeServer* GetParent()
{
return this->Parent;
}
void SetVersion(std::string Version)
{
VersionString = Version;
}
unsigned int ChildCount()
{
return Children.size();
}
TreeServer* GetChild(unsigned int n)
{
if (n < Children.size())
{
/* Make sure they cant request
* an out-of-range object. After
* all we know what these programmer
* types are like *grin*.
*/
return Children[n];
}
else
{
return NULL;
}
}
void AddChild(TreeServer* Child)
{
Children.push_back(Child);
}
bool DelChild(TreeServer* Child)
{
for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
{
if (*a == Child)
{
Children.erase(a);
return true;
}
}
return false;
}
/* Removes child nodes of this node, and of that node, etc etc.
* This is used during netsplits to automatically tidy up the
* server tree. It is slow, we don't use it for much else.
*/
bool Tidy()
{
bool stillchildren = true;
while (stillchildren)
{
stillchildren = false;
for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
{
TreeServer* s = (TreeServer*)*a;
s->Tidy();
Children.erase(a);
delete s;
stillchildren = true;
break;
}
}
return true;
}
~TreeServer()
{
/* We'd better tidy up after ourselves, eh? */
this->DelHashEntry();
}
};
/* The Link class might as well be a struct,
* but this is C++ and we don't believe in structs (!).
* It holds the entire information of one <link>
* tag from the main config file. We maintain a list
* of them, and populate the list on rehash/load.
*/
class Link
{
public:
std::string Name;
std::string IPAddr;
int Port;
std::string SendPass;
std::string RecvPass;
unsigned long AutoConnect;
time_t NextConnectTime;
std::string EncryptionKey;
};
/* The usual stuff for inspircd modules,
* plus the vector of Link classes which we
* use to store the <link> tags from the config
* file.
*/
ConfigReader *Conf;
std::vector<Link> LinkBlocks;
/* Yay for fast searches!
* This is hundreds of times faster than recursion
* or even scanning a linked list, especially when
* there are more than a few servers to deal with.
* (read as: lots).
*/
TreeServer* FindServer(std::string ServerName)
{
server_hash::iterator iter;
iter = serverlist.find(ServerName);
if (iter != serverlist.end())
{
return iter->second;
}
else
{
return NULL;
}
}
/* Returns the locally connected server we must route a
* message through to reach server 'ServerName'. This
* only applies to one-to-one and not one-to-many routing.
* See the comments for the constructor of TreeServer
* for more details.
*/
TreeServer* BestRouteTo(std::string ServerName)
{
if (ServerName.c_str() == TreeRoot->GetName())
return NULL;
TreeServer* Found = FindServer(ServerName);
if (Found)
{
return Found->GetRoute();
}
else
{
return NULL;
}
}
/* Find the first server matching a given glob mask.
* Theres no find-using-glob method of hash_map [awwww :-(]
* so instead, we iterate over the list using an iterator
* and match each one until we get a hit. Yes its slow,
* deal with it.
*/
TreeServer* FindServerMask(std::string ServerName)
{
for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
{
if (Srv->MatchText(i->first,ServerName))
return i->second;
}
return NULL;
}
/* A convenient wrapper that returns true if a server exists */
bool IsServer(std::string ServerName)
{
return (FindServer(ServerName) != NULL);
}
/* Every SERVER connection inbound or outbound is represented by
* an object of type TreeSocket.
* TreeSockets, being inherited from InspSocket, can be tied into
* the core socket engine, and we cn therefore receive activity events
* for them, just like activex objects on speed. (yes really, that
* is a technical term!) Each of these which relates to a locally
* connected server is assocated with it, by hooking it onto a
* TreeSocket class using its constructor. In this way, we can
* maintain a list of servers, some of which are directly connected,
* some of which are not.
*/
class TreeSocket : public InspSocket
{
std::string myhost;
std::string in_buffer;
ServerState LinkState;
std::string InboundServerName;
std::string InboundDescription;
int num_lost_users;
int num_lost_servers;
time_t NextPing;
bool LastPingWasGood;
bool bursting;
AES* ctx;
unsigned int keylength;
public:
/* Because most of the I/O gubbins are encapsulated within
* InspSocket, we just call the superclass constructor for
* most of the action, and append a few of our own values
* to it.
*/
TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
: InspSocket(host, port, listening, maxtime)
{
myhost = host;
this->LinkState = LISTENER;
}
TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
: InspSocket(host, port, listening, maxtime)
{
myhost = ServerName;
this->LinkState = CONNECTING;
}
/* When a listening socket gives us a new file descriptor,
* we must associate it with a socket without creating a new
* connection. This constructor is used for this purpose.
*/
TreeSocket(int newfd, char* ip)
: InspSocket(newfd, ip)
{
this->LinkState = WAIT_AUTH_1;
}
void InitAES(std::string key,std::string SName)
{
if (key == "")
return;
ctx = new AES();
log(DEBUG,"Initialized AES key %s",key.c_str());
// key must be 16, 24, 32 etc bytes (multiple of 8)
keylength = key.length();
if (!(keylength == 16 || keylength == 24 || keylength == 32))
{
WriteOpers("\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
log(DEBUG,"Key length not 16, 24 or 32 characters!");
}
else
{
WriteOpers("\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
ctx->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
}
}
/* When an outbound connection finishes connecting, we receive
* this event, and must send our SERVER string to the other
* side. If the other side is happy, as outlined in the server
* to server docs on the inspircd.org site, the other side
* will then send back its own server string.
*/
virtual bool OnConnected()
{
if (this->LinkState == CONNECTING)
{
Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
/* we do not need to change state here. */
for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
{
if (x->Name == this->myhost)
{
if (x->EncryptionKey != "")
{
if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
{
WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
}
else
{
this->WriteLine("AES "+Srv->GetServerName());
this->InitAES(x->EncryptionKey,x->Name);
}
}
/* found who we're supposed to be connecting to, send the neccessary gubbins. */
this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
return true;
}
}
}
/* There is a (remote) chance that between the /CONNECT and the connection
* being accepted, some muppet has removed the <link> block and rehashed.
* If that happens the connection hangs here until it's closed. Unlikely
* and rather harmless.
*/
return true;
}
virtual void OnError(InspSocketError e)
{
/* We don't handle this method, because all our
* dirty work is done in OnClose() (see below)
* which is still called on error conditions too.
*/
}
virtual int OnDisconnect()
{
/* For the same reason as above, we don't
* handle OnDisconnect()
*/
return true;
}
/* Recursively send the server tree with distances as hops.
* This is used during network burst to inform the other server
* (and any of ITS servers too) of what servers we know about.
* If at any point any of these servers already exist on the other
* end, our connection may be terminated. The hopcounts given
* by this function are relative, this doesn't matter so long as
* they are all >1, as all the remote servers re-calculate them
* to be relative too, with themselves as hop 0.
*/
void SendServers(TreeServer* Current, TreeServer* s, int hops)
{
char command[1024];
for (unsigned int q = 0; q < Current->ChildCount(); q++)
{
TreeServer* recursive_server = Current->GetChild(q);
if (recursive_server != s)
{
snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
this->WriteLine(command);
this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
/* down to next level */
this->SendServers(recursive_server, s, hops+1);
}
}
}
/* This function forces this server to quit, removing this server
* and any users on it (and servers and users below that, etc etc).
* It's very slow and pretty clunky, but luckily unless your network
* is having a REAL bad hair day, this function shouldnt be called
* too many times a month ;-)
*/
void SquitServer(TreeServer* Current, CullList* Goners)
{
/* recursively squit the servers attached to 'Current'.
* We're going backwards so we don't remove users
* while we still need them ;)
*/
for (unsigned int q = 0; q < Current->ChildCount(); q++)
{
TreeServer* recursive_server = Current->GetChild(q);
this->SquitServer(recursive_server,Goners);
}
/* Now we've whacked the kids, whack self */
num_lost_servers++;
for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
{
if (!strcasecmp(u->second->server,Current->GetName().c_str()))
{
std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
Goners->AddItem(u->second,qreason);
num_lost_users++;
}
}
}
/* This is a wrapper function for SquitServer above, which
* does some validation first and passes on the SQUIT to all
* other remaining servers.
*/
void Squit(TreeServer* Current,std::string reason)
{
if (Current)
{
std::deque<std::string> params;
params.push_back(Current->GetName());
params.push_back(":"+reason);
DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
if (Current->GetParent() == TreeRoot)
{
Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
}
else
{
Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
}
num_lost_servers = 0;
num_lost_users = 0;
CullList* Goners = new CullList();
SquitServer(Current, Goners);
Goners->Apply();
Current->Tidy();
Current->GetParent()->DelChild(Current);
delete Current;
delete Goners;
WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
}
else
{
log(DEFAULT,"Squit from unknown server");
}
}
/* FMODE command */
bool ForceMode(std::string source, std::deque<std::string> params)
{
userrec* who = new userrec;
who->fd = FD_MAGIC_NUMBER;
if (params.size() < 2)
return true;
char* modelist[255];
for (unsigned int q = 0; q < params.size(); q++)
{
modelist[q] = (char*)params[q].c_str();
}
Srv->SendMode(modelist,params.size(),who);
DoOneToAllButSender(source,"FMODE",params,source);
delete who;
return true;
}
/* FTOPIC command */
bool ForceTopic(std::string source, std::deque<std::string> params)
{
if (params.size() != 4)
return true;
std::string channel = params[0];
time_t ts = atoi(params[1].c_str());
std::string setby = params[2];
std::string topic = params[3];
chanrec* c = Srv->FindChannel(channel);
if (c)
{
if ((ts >= c->topicset) || (!*c->topic))
{
std::string oldtopic = c->topic;
strlcpy(c->topic,topic.c_str(),MAXTOPIC);
strlcpy(c->setby,setby.c_str(),NICKMAX);
c->topicset = ts;
/* if the topic text is the same as the current topic,
* dont bother to send the TOPIC command out, just silently
* update the set time and set nick.
*/
if (oldtopic != topic)
WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
}
}
/* all done, send it on its way */
params[3] = ":" + params[3];
DoOneToAllButSender(source,"FTOPIC",params,source);
return true;
}
/* FJOIN, similar to unreal SJOIN */
bool ForceJoin(std::string source, std::deque<std::string> params)
{
if (params.size() < 3)
return true;
char first[MAXBUF];
char modestring[MAXBUF];
char* mode_users[127];
mode_users[0] = first;
mode_users[1] = modestring;
strcpy(mode_users[1],"+");
unsigned int modectr = 2;
userrec* who = NULL;
std::string channel = params[0];
time_t TS = atoi(params[1].c_str());
char* key = "";
chanrec* chan = Srv->FindChannel(channel);
if (chan)
{
key = chan->key;
}
strlcpy(mode_users[0],channel.c_str(),MAXBUF);
/* default is a high value, which if we dont have this
* channel will let the other side apply their modes.
*/
time_t ourTS = time(NULL)+600;
chanrec* us = Srv->FindChannel(channel);
if (us)
{
ourTS = us->age;
}
log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
/* do this first, so our mode reversals are correctly received by other servers
* if there is a TS collision.
*/
DoOneToAllButSender(source,"FJOIN",params,source);
for (unsigned int usernum = 2; usernum < params.size(); usernum++)
{
/* process one channel at a time, applying modes. */
char* usr = (char*)params[usernum].c_str();
char permissions = *usr;
switch (permissions)
{
case '@':
usr++;
mode_users[modectr++] = usr;
strlcat(modestring,"o",MAXBUF);
break;
case '%':
usr++;
mode_users[modectr++] = usr;
strlcat(modestring,"h",MAXBUF);
break;
case '+':
usr++;
mode_users[modectr++] = usr;
strlcat(modestring,"v",MAXBUF);
break;
}
who = Srv->FindNick(usr);
if (who)
{
Srv->JoinUserToChannel(who,channel,key);
if (modectr >= (MAXMODES-1))
{
/* theres a mode for this user. push them onto the mode queue, and flush it
* if there are more than MAXMODES to go.
*/
if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
{
/* We also always let u-lined clients win, no matter what the TS value */
log(DEBUG,"Our our channel newer than theirs, accepting their modes");
Srv->SendMode(mode_users,modectr,who);
}
else
{
log(DEBUG,"Their channel newer than ours, bouncing their modes");
/* bouncy bouncy! */
std::deque<std::string> params;
/* modes are now being UNSET... */
*mode_users[1] = '-';
for (unsigned int x = 0; x < modectr; x++)
{
params.push_back(mode_users[x]);
}
// tell everyone to bounce the modes. bad modes, bad!
DoOneToMany(Srv->GetServerName(),"FMODE",params);
}
strcpy(mode_users[1],"+");
modectr = 2;
}
}
}
/* there werent enough modes built up to flush it during FJOIN,
* or, there are a number left over. flush them out.
*/
if ((modectr > 2) && (who))
{
if (ourTS >= TS)
{
log(DEBUG,"Our our channel newer than theirs, accepting their modes");
Srv->SendMode(mode_users,modectr,who);
}
else
{
log(DEBUG,"Their channel newer than ours, bouncing their modes");
std::deque<std::string> params;
*mode_users[1] = '-';
for (unsigned int x = 0; x < modectr; x++)
{
params.push_back(mode_users[x]);
}
DoOneToMany(Srv->GetServerName(),"FMODE",params);
}
}
return true;
}
/* NICK command */
bool IntroduceClient(std::string source, std::deque<std::string> params)
{
if (params.size() < 8)
return true;
// NICK age nick host dhost ident +modes ip :gecos
// 0 1 2 3 4 5 6 7
std::string nick = params[1];
std::string host = params[2];
std::string dhost = params[3];
std::string ident = params[4];
time_t age = atoi(params[0].c_str());
std::string modes = params[5];
while (*(modes.c_str()) == '+')
{
char* m = (char*)modes.c_str();
m++;
modes = m;
}
std::string ip = params[6];
std::string gecos = params[7];
char* tempnick = (char*)nick.c_str();
log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
user_hash::iterator iter;
iter = clientlist.find(tempnick);
if (iter != clientlist.end())
{
// nick collision
log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,ident.c_str(),host.c_str(),(unsigned long)age,(unsigned long)iter->second->age);
this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
return true;
}
clientlist[tempnick] = new userrec();
clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
strlcpy(clientlist[tempnick]->host, host.c_str(),160);
strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
clientlist[tempnick]->registered = 7;
clientlist[tempnick]->signon = age;
strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
ucrec a;
a.channel = NULL;
a.uc_modes = 0;
for (int i = 0; i < MAXCHANS; i++)
clientlist[tempnick]->chans.push_back(a);
if (!this->bursting)
{
WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
}
params[7] = ":" + params[7];
DoOneToAllButSender(source,"NICK",params,source);
return true;
}
/* Send one or more FJOINs for a channel of users.
* If the length of a single line is more than 480-NICKMAX
* in length, it is split over multiple lines.
*/
void SendFJoins(TreeServer* Current, chanrec* c)
{
log(DEBUG,"Sending FJOINs to other server for %s",c->name);
char list[MAXBUF];
snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
std::vector<char*> *ulist = c->GetUsers();
for (unsigned int i = 0; i < ulist->size(); i++)
{
char* o = (*ulist)[i];
userrec* otheruser = (userrec*)o;
strlcat(list," ",MAXBUF);
strlcat(list,cmode(otheruser,c),MAXBUF);
strlcat(list,otheruser->nick,MAXBUF);
if (strlen(list)>(480-NICKMAX))
{
log(DEBUG,"FJOIN line wrapped");
this->WriteLine(list);
snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
}
}
if (list[strlen(list)-1] != ':')
{
log(DEBUG,"Final FJOIN line");
this->WriteLine(list);
}
}
/* Send G, Q, Z and E lines */
void SendXLines(TreeServer* Current)
{
char data[MAXBUF];
/* Yes, these arent too nice looking, but they get the job done */
for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
{
snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
this->WriteLine(data);
}
for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
{
snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
this->WriteLine(data);
}
for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
{
snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
this->WriteLine(data);
}
for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
{
snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
this->WriteLine(data);
}
for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
{
snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
this->WriteLine(data);
}
for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
{
snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
this->WriteLine(data);
}
for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
{
snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
this->WriteLine(data);
}
for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
{
snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
this->WriteLine(data);
}
}
/* Send channel modes and topics */
void SendChannelModes(TreeServer* Current)
{
char data[MAXBUF];
std::deque<std::string> list;
for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
{
SendFJoins(Current, c->second);
snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
this->WriteLine(data);
if (*c->second->topic)
{
snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",Srv->GetServerName().c_str(),c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
this->WriteLine(data);
}
for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
{
snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
this->WriteLine(data);
}
FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
list.clear();
c->second->GetExtList(list);
for (unsigned int j = 0; j < list.size(); j++)
{
FOREACH_MOD OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
}
}
}
/* send all users and their oper state/modes */
void SendUsers(TreeServer* Current)
{
char data[MAXBUF];
std::deque<std::string> list;
for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
{
if (u->second->registered == 7)
{
snprintf(data,MAXBUF,":%s NICK %lu %s %s %s %s +%s %s :%s",u->second->server,(unsigned long)u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->fullname);
this->WriteLine(data);
if (strchr(u->second->modes,'o'))
{
this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
}
FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
list.clear();
u->second->GetExtList(list);
for (unsigned int j = 0; j < list.size(); j++)
{
FOREACH_MOD OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
}
}
}
}
/* This function is called when we want to send a netburst to a local
* server. There is a set order we must do this, because for example
* users require their servers to exist, and channels require their
* users to exist. You get the idea.
*/
void DoBurst(TreeServer* s)
{
Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
this->WriteLine("BURST");
/* send our version string */
this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
/* Send server tree */
this->SendServers(TreeRoot,s,1);
/* Send users and their oper status */
this->SendUsers(s);
/* Send everything else (channel modes, xlines etc) */
this->SendChannelModes(s);
this->SendXLines(s);
this->WriteLine("ENDBURST");
Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
}
/* This function is called when we receive data from a remote
* server. We buffer the data in a std::string (it doesnt stay
* there for long), reading using InspSocket::Read() which can
* read up to 16 kilobytes in one operation.
*
* IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
* THE SOCKET OBJECT FOR US.
*/
virtual bool OnDataReady()
{
char* data = this->Read();
if (data)
{
this->in_buffer += data;
/* While there is at least one new line in the buffer,
* do something useful (we hope!) with it.
*/
while (in_buffer.find("\n") != std::string::npos)
{
char* line = (char*)in_buffer.c_str();
std::string ret = "";
while ((*line != '\n') && (strlen(line)))
{
ret = ret + *line;
line++;
}
if ((*line == '\n') || (*line == '\r'))
line++;
in_buffer = line;
/* Process this one, abort if it
* didnt return true.
*/
if (this->ctx)
{
char out[1024];
char result[1024];
log(DEBUG,"Original string '%s'",ret.c_str());
int nbytes = from64tobits(out, ret.c_str(), 1024);
log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
ctx->Decrypt(out, result, nbytes, 0);
for (int t = 0; t < nbytes; t++)
if (result[t] == '\7') result[t] = 0;
ret = result;
}
if (!this->ProcessLine(ret))
{
return false;
}
}
}
return (data != NULL);
}
int WriteLine(std::string line)
{
log(DEBUG,"OUT: %s",line.c_str());
if (this->ctx)
{
log(DEBUG,"AES context");
char result[1024];
char result64[1024];
if (this->keylength)
{
while (line.length() % this->keylength != 0)
{
// pad it to be a multiple of the key length
line = line + "\7";
}
}
ctx->Encrypt(line.c_str(), result, line.length(),0);
to64frombits((unsigned char*)result64,
(unsigned char*)result,
line.length());
line = result64;
log(DEBUG,"Encrypted: %s",line.c_str());
//int from64tobits(char *out, const char *in, int maxlen);
}
return this->Write(line + "\r\n");
}
/* Handle ERROR command */
bool Error(std::deque<std::string> params)
{
if (params.size() < 1)
return false;
std::string Errmsg = params[0];
std::string SName = myhost;
if (InboundServerName != "")
{
SName = InboundServerName;
}
Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
/* we will return false to cause the socket to close.
*/
return false;
}
/* Because the core won't let users or even SERVERS set +o,
* we use the OPERTYPE command to do this.
*/
bool OperType(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() != 1)
return true;
std::string opertype = params[0];
userrec* u = Srv->FindNick(prefix);
if (u)
{
strlcpy(u->oper,opertype.c_str(),NICKMAX);
if (!strchr(u->modes,'o'))
{
strcat(u->modes,"o");
}
DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
}
return true;
}
/* Because Andy insists that services-compatible servers must
* implement SVSNICK and SVSJOIN, that's exactly what we do :p
*/
bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 3)
return true;
userrec* u = Srv->FindNick(params[0]);
if (u)
{
Srv->ChangeUserNick(u,params[1]);
u->age = atoi(params[2].c_str());
DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
}
return true;
}
bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 2)
return true;
userrec* u = Srv->FindNick(params[0]);
if (u)
{
Srv->JoinUserToChannel(u,params[1],"");
DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
}
return true;
}
bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 1)
return false;
std::string servermask = params[0];
if (Srv->MatchText(Srv->GetServerName(),servermask))
{
Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
Srv->RehashServer();
ReadConfiguration(false);
}
DoOneToAllButSender(prefix,"REHASH",params,prefix);
return true;
}
bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() != 2)
return true;
std::string nick = params[0];
userrec* u = Srv->FindNick(prefix);
userrec* who = Srv->FindNick(nick);
if (who)
{
/* Prepend kill source, if we don't have one */
std::string sourceserv = prefix;
if (u)
{
sourceserv = u->server;
}
if (*(params[1].c_str()) != '[')
{
params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
}
std::string reason = params[1];
params[1] = ":" + params[1];
DoOneToAllButSender(prefix,"KILL",params,sourceserv);
Srv->QuitUser(who,reason);
}
return true;
}
bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 1)
return true;
TreeServer* ServerSource = FindServer(prefix);
if (ServerSource)
{
ServerSource->SetPingFlag();
}
return true;
}
bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 3)
return true;
TreeServer* ServerSource = FindServer(prefix);
if (ServerSource)
{
if (*(params[0].c_str()) == '#')
{
chanrec* c = Srv->FindChannel(params[0]);
if (c)
{
FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
}
}
else
{
userrec* u = Srv->FindNick(params[0]);
if (u)
{
FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
}
}
}
params[2] = ":" + params[2];
DoOneToAllButSender(prefix,"METADATA",params,prefix);
return true;
}
bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 1)
return true;
TreeServer* ServerSource = FindServer(prefix);
if (ServerSource)
{
ServerSource->SetVersion(params[0]);
}
params[0] = ":" + params[0];
DoOneToAllButSender(prefix,"VERSION",params,prefix);
return true;
}
bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 1)
return true;
userrec* u = Srv->FindNick(prefix);
if (u)
{
Srv->ChangeHost(u,params[0]);
DoOneToAllButSender(prefix,"FHOST",params,u->server);
}
return true;
}
bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 6)
return true;
std::string linetype = params[0]; /* Z, Q, E, G, K */
std::string mask = params[1]; /* Line type dependent */
std::string source = params[2]; /* may not be online or may be a server */
std::string settime = params[3]; /* EPOCH time set */
std::string duration = params[4]; /* Duration secs */
std::string reason = params[5];
switch (*(linetype.c_str()))
{
case 'Z':
add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
break;
case 'Q':
add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
break;
case 'E':
add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
break;
case 'G':
add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
break;
case 'K':
add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
break;
default:
/* Just in case... */
Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
break;
}
/* Send it on its way */
params[5] = ":" + params[5];
DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
return true;
}
bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 1)
return true;
userrec* u = Srv->FindNick(prefix);
if (u)
{
Srv->ChangeGECOS(u,params[0]);
params[0] = ":" + params[0];
DoOneToAllButSender(prefix,"FNAME",params,u->server);
}
return true;
}
bool Whois(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 1)
return true;
log(DEBUG,"In IDLE command");
userrec* u = Srv->FindNick(prefix);
if (u)
{
log(DEBUG,"USER EXISTS: %s",u->nick);
// an incoming request
if (params.size() == 1)
{
userrec* x = Srv->FindNick(params[0]);
if (x->fd > -1)
{
userrec* x = Srv->FindNick(params[0]);
log(DEBUG,"Got IDLE");
char signon[MAXBUF];
char idle[MAXBUF];
log(DEBUG,"Sending back IDLE 3");
snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
std::deque<std::string> par;
par.push_back(prefix);
par.push_back(signon);
par.push_back(idle);
// ours, we're done, pass it BACK
DoOneToOne(params[0],"IDLE",par,u->server);
}
else
{
// not ours pass it on
DoOneToOne(prefix,"IDLE",params,x->server);
}
}
else if (params.size() == 3)
{
std::string who_did_the_whois = params[0];
userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
if (who_to_send_to->fd > -1)
{
log(DEBUG,"Got final IDLE");
// an incoming reply to a whois we sent out
std::string nick_whoised = prefix;
unsigned long signon = atoi(params[1].c_str());
unsigned long idle = atoi(params[2].c_str());
if ((who_to_send_to) && (who_to_send_to->fd > -1))
do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
}
else
{
// not ours, pass it on
DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
}
}
}
return true;
}
bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 1)
return true;
std::string stufftobounce = params[0];
this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
return true;
}
bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
{
if (params.size() < 4)
return false;
std::string servername = params[0];
std::string password = params[1];
// hopcount is not used for a remote server, we calculate this ourselves
std::string description = params[3];
TreeServer* ParentOfThis = FindServer(prefix);
if (!ParentOfThis)
{
this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
return false;
}
TreeServer* CheckDupe = FindServer(servername);
if (CheckDupe)
{
this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
return false;
}
TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
ParentOfThis->AddChild(Node);
params[3] = ":" + params[3];
DoOneToAllButSender(prefix,"SERVER",params,prefix);
Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
return true;
}
bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
{
if (params.size() < 4)
return false;
std::string servername = params[0];
std::string password = params[1];
int hops = atoi(params[2].c_str());
if (hops)
{
this->WriteLine("ERROR :Server too far away for authentication");
return false;
}
std::string description = params[3];
for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
{
if ((x->Name == servername) && (x->RecvPass == password))
{
TreeServer* CheckDupe = FindServer(servername);
if (CheckDupe)
{
this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
return false;
}
// Begin the sync here. this kickstarts the
// other side, waiting in WAIT_AUTH_2 state,
// into starting their burst, as it shows
// that we're happy.
this->LinkState = CONNECTED;
// we should add the details of this server now
// to the servers tree, as a child of the root
// node.
TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
TreeRoot->AddChild(Node);
params[3] = ":" + params[3];
DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
this->bursting = true;
this->DoBurst(Node);
return true;
}
}
this->WriteLine("ERROR :Invalid credentials");
return false;
}
bool Inbound_Server(std::deque<std::string> ¶ms)
{
if (params.size() < 4)
return false;
std::string servername = params[0];
std::string password = params[1];
int hops = atoi(params[2].c_str());
if (hops)
{
this->WriteLine("ERROR :Server too far away for authentication");
return false;
}
std::string description = params[3];
for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
{
if ((x->Name == servername) && (x->RecvPass == password))
{
TreeServer* CheckDupe = FindServer(servername);
if (CheckDupe)
{
this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
return false;
}
Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
this->InboundServerName = servername;
this->InboundDescription = description;
// this is good. Send our details: Our server name and description and hopcount of 0,
// along with the sendpass from this block.
this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
// move to the next state, we are now waiting for THEM.
this->LinkState = WAIT_AUTH_2;
return true;
}
}
this->WriteLine("ERROR :Invalid credentials");
return false;
}
void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
{
if (!strchr(line.c_str(),' '))
{
n.push_back(line);
return;
}
std::stringstream s(line);
std::string param = "";
n.clear();
int item = 0;
while (!s.eof())
{
char c;
s.get(c);
if (c == ' ')
{
n.push_back(param);
param = "";
item++;
}
else
{
if (!s.eof())
{
param = param + c;
}
if ((param == ":") && (item > 0))
{
param = "";
while (!s.eof())
{
s.get(c);
if (!s.eof())
{
param = param + c;
}
}
n.push_back(param);
param = "";
}
}
}
if (param != "")
{
n.push_back(param);
}
return;
}
bool ProcessLine(std::string line)
{
char* l = (char*)line.c_str();
while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
l[strlen(l)-1] = '\0';
line = l;
if (line == "")
return true;
Srv->Log(DEBUG,"IN: "+line);
std::deque<std::string> params;
this->Split(line,true,params);
std::string command = "";
std::string prefix = "";
if (((params[0].c_str())[0] == ':') && (params.size() > 1))
{
prefix = params[0];
command = params[1];
char* pref = (char*)prefix.c_str();
prefix = ++pref;
params.pop_front();
params.pop_front();
}
else
{
prefix = "";
command = params[0];
params.pop_front();
}
if ((!this->ctx) && (command == "AES"))
{
std::string sserv = params[0];
for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
{
if ((x->EncryptionKey != "") && (x->Name == sserv))
{
this->InitAES(x->EncryptionKey,sserv);
}
}
return true;
}
else if ((this->ctx) && (command == "AES"))
{
WriteOpers("\2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
}
switch (this->LinkState)
{
TreeServer* Node;
case WAIT_AUTH_1:
// Waiting for SERVER command from remote server. Server initiating
// the connection sends the first SERVER command, listening server
// replies with theirs if its happy, then if the initiator is happy,
// it starts to send its net sync, which starts the merge, otherwise
// it sends an ERROR.
if (command == "SERVER")
{
return this->Inbound_Server(params);
}
else if (command == "ERROR")
{
return this->Error(params);
}
break;
case WAIT_AUTH_2:
// Waiting for start of other side's netmerge to say they liked our
// password.
if (command == "SERVER")
{
// cant do this, they sent it to us in the WAIT_AUTH_1 state!
// silently ignore.
return true;
}
else if (command == "BURST")
{
this->LinkState = CONNECTED;
Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
TreeRoot->AddChild(Node);
params.clear();
params.push_back(InboundServerName);
params.push_back("*");
params.push_back("1");
params.push_back(":"+InboundDescription);
DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
this->bursting = true;
this->DoBurst(Node);
}
else if (command == "ERROR")
{
return this->Error(params);
}
break;
case LISTENER:
this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
return false;
break;
case CONNECTING:
if (command == "SERVER")
{
// another server we connected to, which was in WAIT_AUTH_1 state,
// has just sent us their credentials. If we get this far, theyre
// happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
// if we're happy with this, we should send our netburst which
// kickstarts the merge.
return this->Outbound_Reply_Server(params);
}
else if (command == "ERROR")
{
return this->Error(params);
}
break;
case CONNECTED:
// This is the 'authenticated' state, when all passwords
// have been exchanged and anything past this point is taken
// as gospel.
if (prefix != "")
{
std::string direction = prefix;
userrec* t = Srv->FindNick(prefix);
if (t)
{
direction = t->server;
}
TreeServer* route_back_again = BestRouteTo(direction);
if ((!route_back_again) || (route_back_again->GetSocket() != this))
{
if (route_back_again)
{
WriteOpers("Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
}
else
{
WriteOpers("Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
}
return true;
}
}
if (command == "SVSMODE")
{
/* Services expects us to implement
* SVSMODE. In inspircd its the same as
* MODE anyway.
*/
command = "MODE";
}
std::string target = "";
/* Yes, know, this is a mess. Its reasonably fast though as we're
* working with std::string here.
*/
if ((command == "NICK") && (params.size() > 1))
{
return this->IntroduceClient(prefix,params);
}
else if (command == "FJOIN")
{
return this->ForceJoin(prefix,params);
}
else if (command == "SERVER")
{
return this->RemoteServer(prefix,params);
}
else if (command == "ERROR")
{
return this->Error(params);
}
else if (command == "OPERTYPE")
{
return this->OperType(prefix,params);
}
else if (command == "FMODE")
{
return this->ForceMode(prefix,params);
}
else if (command == "KILL")
{
return this->RemoteKill(prefix,params);
}
else if (command == "FTOPIC")
{
return this->ForceTopic(prefix,params);
}
else if (command == "REHASH")
{
return this->RemoteRehash(prefix,params);
}
else if (command == "METADATA")
{
return this->MetaData(prefix,params);
}
else if (command == "PING")
{
return this->LocalPing(prefix,params);
}
else if (command == "PONG")
{
return this->LocalPong(prefix,params);
}
else if (command == "VERSION")
{
return this->ServerVersion(prefix,params);
}
else if (command == "FHOST")
{
return this->ChangeHost(prefix,params);
}
else if (command == "FNAME")
{
return this->ChangeName(prefix,params);
}
else if (command == "ADDLINE")
{
return this->AddLine(prefix,params);
}
else if (command == "SVSNICK")
{
if (prefix == "")
{
prefix = this->GetName();
}
return this->ForceNick(prefix,params);
}
else if (command == "IDLE")
{
return this->Whois(prefix,params);
}
else if (command == "SVSJOIN")
{
if (prefix == "")
{
prefix = this->GetName();
}
return this->ServiceJoin(prefix,params);
}
else if (command == "SQUIT")
{
if (params.size() == 2)
{
this->Squit(FindServer(params[0]),params[1]);
}
return true;
}
else if (command == "ENDBURST")
{
this->bursting = false;
return true;
}
else
{
// not a special inter-server command.
// Emulate the actual user doing the command,
// this saves us having a huge ugly parser.
userrec* who = Srv->FindNick(prefix);
std::string sourceserv = this->myhost;
if (this->InboundServerName != "")
{
sourceserv = this->InboundServerName;
}
if (who)
{
// its a user
target = who->server;
char* strparams[127];
for (unsigned int q = 0; q < params.size(); q++)
{
strparams[q] = (char*)params[q].c_str();
}
Srv->CallCommandHandler(command, strparams, params.size(), who);
}
else
{
// its not a user. Its either a server, or somethings screwed up.
if (IsServer(prefix))
{
target = Srv->GetServerName();
}
else
{
log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
return true;
}
}
return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
}
return true;
break;
}
return true;
}
virtual std::string GetName()
{
std::string sourceserv = this->myhost;
if (this->InboundServerName != "")
{
sourceserv = this->InboundServerName;
}
return sourceserv;
}
virtual void OnTimeout()
{
if (this->LinkState == CONNECTING)
{
Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
}
}
virtual void OnClose()
{
// Connection closed.
// If the connection is fully up (state CONNECTED)
// then propogate a netsplit to all peers.
std::string quitserver = this->myhost;
if (this->InboundServerName != "")
{
quitserver = this->InboundServerName;
}
TreeServer* s = FindServer(quitserver);
if (s)
{
Squit(s,"Remote host closed the connection");
}
}
virtual int OnIncomingConnection(int newsock, char* ip)
{
TreeSocket* s = new TreeSocket(newsock, ip);
Srv->AddSocket(s);
return true;
}
};
void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
{
for (unsigned int c = 0; c < list.size(); c++)
{
if (list[c] == server)
{
return;
}
}
list.push_back(server);
}
// returns a list of DIRECT servernames for a specific channel
void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
{
std::vector<char*> *ulist = c->GetUsers();
unsigned int ucount = ulist->size();
for (unsigned int i = 0; i < ucount; i++)
{
char* o = (*ulist)[i];
userrec* otheruser = (userrec*)o;
if (otheruser->fd < 0)
{
TreeServer* best = BestRouteTo(otheruser->server);
if (best)
AddThisServer(best,list);
}
}
return;
}
bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
{
TreeServer* omitroute = BestRouteTo(omit);
if ((command == "NOTICE") || (command == "PRIVMSG"))
{
if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
{
if (*(params[0].c_str()) != '#')
{
// special routing for private messages/notices
userrec* d = Srv->FindNick(params[0]);
if (d)
{
std::deque<std::string> par;
par.push_back(params[0]);
par.push_back(":"+params[1]);
DoOneToOne(prefix,command,par,d->server);
return true;
}
}
else
{
log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
chanrec* c = Srv->FindChannel(params[0]);
if (c)
{
std::deque<TreeServer*> list;
GetListOfServersForChannel(c,list);
log(DEBUG,"Got a list of %d servers",list.size());
unsigned int lsize = list.size();
for (unsigned int i = 0; i < lsize; i++)
{
TreeSocket* Sock = list[i]->GetSocket();
if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
{
log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
Sock->WriteLine(data);
}
}
return true;
}
}
}
}
unsigned int items = TreeRoot->ChildCount();
for (unsigned int x = 0; x < items; x++)
{
TreeServer* Route = TreeRoot->GetChild(x);
if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
{
TreeSocket* Sock = Route->GetSocket();
Sock->WriteLine(data);
}
}
return true;
}
bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
{
TreeServer* omitroute = BestRouteTo(omit);
std::string FullLine = ":" + prefix + " " + command;
unsigned int words = params.size();
for (unsigned int x = 0; x < words; x++)
{
FullLine = FullLine + " " + params[x];
}
unsigned int items = TreeRoot->ChildCount();
for (unsigned int x = 0; x < items; x++)
{
TreeServer* Route = TreeRoot->GetChild(x);
// Send the line IF:
// The route has a socket (its a direct connection)
// The route isnt the one to be omitted
// The route isnt the path to the one to be omitted
if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
{
TreeSocket* Sock = Route->GetSocket();
Sock->WriteLine(FullLine);
}
}
return true;
}
bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
{
std::string FullLine = ":" + prefix + " " + command;
unsigned int words = params.size();
for (unsigned int x = 0; x < words; x++)
{
FullLine = FullLine + " " + params[x];
}
unsigned int items = TreeRoot->ChildCount();
for (unsigned int x = 0; x < items; x++)
{
TreeServer* Route = TreeRoot->GetChild(x);
if (Route->GetSocket())
{
TreeSocket* Sock = Route->GetSocket();
Sock->WriteLine(FullLine);
}
}
return true;
}
bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
{
TreeServer* Route = BestRouteTo(target);
if (Route)
{
std::string FullLine = ":" + prefix + " " + command;
unsigned int words = params.size();
for (unsigned int x = 0; x < words; x++)
{
FullLine = FullLine + " " + params[x];
}
if (Route->GetSocket())
{
TreeSocket* Sock = Route->GetSocket();
Sock->WriteLine(FullLine);
}
return true;
}
else
{
return true;
}
}
std::vector<TreeSocket*> Bindings;
void ReadConfiguration(bool rebind)
{
Conf = new ConfigReader;
if (rebind)
{
for (int j =0; j < Conf->Enumerate("bind"); j++)
{
std::string Type = Conf->ReadValue("bind","type",j);
std::string IP = Conf->ReadValue("bind","address",j);
long Port = Conf->ReadInteger("bind","port",j,true);
if (Type == "servers")
{
if (IP == "*")
{
IP = "";
}
TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
if (listener->GetState() == I_LISTENING)
{
Srv->AddSocket(listener);
Bindings.push_back(listener);
}
else
{
log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
listener->Close();
delete listener;
}
}
}
}
LinkBlocks.clear();
for (int j =0; j < Conf->Enumerate("link"); j++)
{
Link L;
L.Name = Conf->ReadValue("link","name",j);
L.IPAddr = Conf->ReadValue("link","ipaddr",j);
L.Port = Conf->ReadInteger("link","port",j,true);
L.SendPass = Conf->ReadValue("link","sendpass",j);
L.RecvPass = Conf->ReadValue("link","recvpass",j);
L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
L.NextConnectTime = time(NULL) + L.AutoConnect;
/* Bugfix by brain, do not allow people to enter bad configurations */
if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
{
LinkBlocks.push_back(L);
log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
}
else
{
log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
}
}
delete Conf;
}
class ModuleSpanningTree : public Module
{
std::vector<TreeSocket*> Bindings;
int line;
int NumServers;
public:
ModuleSpanningTree(Server* Me)
: Module::Module(Me)
{
Srv = Me;
Bindings.clear();
// Create the root of the tree
TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
ReadConfiguration(true);
}
void ShowLinks(TreeServer* Current, userrec* user, int hops)
{
std::string Parent = TreeRoot->GetName();
if (Current->GetParent())
{
Parent = Current->GetParent()->GetName();
}
for (unsigned int q = 0; q < Current->ChildCount(); q++)
{
ShowLinks(Current->GetChild(q),user,hops+1);
}
WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
}
int CountLocalServs()
{
return TreeRoot->ChildCount();
}
int CountServs()
{
return serverlist.size();
}
void HandleLinks(char** parameters, int pcnt, userrec* user)
{
ShowLinks(TreeRoot,user,0);
WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
return;
}
void HandleLusers(char** parameters, int pcnt, userrec* user)
{
WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
return;
}
// WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
{
if (line < 128)
{
for (int t = 0; t < depth; t++)
{
matrix[line][t] = ' ';
}
strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
line++;
for (unsigned int q = 0; q < Current->ChildCount(); q++)
{
ShowMap(Current->GetChild(q),user,depth+2,matrix);
}
}
}
// Ok, prepare to be confused.
// After much mulling over how to approach this, it struck me that
// the 'usual' way of doing a /MAP isnt the best way. Instead of
// keeping track of a ton of ascii characters, and line by line
// under recursion working out where to place them using multiplications
// and divisons, we instead render the map onto a backplane of characters
// (a character matrix), then draw the branches as a series of "L" shapes
// from the nodes. This is not only friendlier on CPU it uses less stack.
void HandleMap(char** parameters, int pcnt, userrec* user)
{
// This array represents a virtual screen which we will
// "scratch" draw to, as the console device of an irc
// client does not provide for a proper terminal.
char matrix[128][80];
for (unsigned int t = 0; t < 128; t++)
{
matrix[t][0] = '\0';
}
line = 0;
// The only recursive bit is called here.
ShowMap(TreeRoot,user,0,matrix);
// Process each line one by one. The algorithm has a limit of
// 128 servers (which is far more than a spanning tree should have
// anyway, so we're ok). This limit can be raised simply by making
// the character matrix deeper, 128 rows taking 10k of memory.
for (int l = 1; l < line; l++)
{
// scan across the line looking for the start of the
// servername (the recursive part of the algorithm has placed
// the servers at indented positions depending on what they
// are related to)
int first_nonspace = 0;
while (matrix[l][first_nonspace] == ' ')
{
first_nonspace++;
}
first_nonspace--;
// Draw the `- (corner) section: this may be overwritten by
// another L shape passing along the same vertical pane, becoming
// a |- (branch) section instead.
matrix[l][first_nonspace] = '-';
matrix[l][first_nonspace-1] = '`';
int l2 = l - 1;
// Draw upwards until we hit the parent server, causing possibly
// other corners (`-) to become branches (|-)
while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
{
matrix[l2][first_nonspace-1] = '|';
l2--;
}
}
// dump the whole lot to the user. This is the easy bit, honest.
for (int t = 0; t < line; t++)
{
WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
}
WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
return;
}
int HandleSquit(char** parameters, int pcnt, userrec* user)
{
TreeServer* s = FindServerMask(parameters[0]);
if (s)
{
TreeSocket* sock = s->GetSocket();
if (sock)
{
WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
sock->Close();
}
else
{
WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
}
}
else
{
WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
}
return 1;
}
int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
{
if ((user->fd > -1) && (pcnt > 1))
{
userrec* remote = Srv->FindNick(parameters[1]);
if ((remote) && (remote->fd < 0))
{
std::deque<std::string> params;
params.push_back(parameters[1]);
DoOneToOne(user->nick,"IDLE",params,remote->server);
return 1;
}
else if (!remote)
{
WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
return 1;
}
}
return 0;
}
void DoPingChecks(time_t curtime)
{
for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
{
TreeServer* serv = TreeRoot->GetChild(j);
TreeSocket* sock = serv->GetSocket();
if (sock)
{
if (curtime >= serv->NextPingTime())
{
if (serv->AnsweredLastPing())
{
sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
serv->SetNextPingTime(curtime + 60);
}
else
{
// they didnt answer, boot them
WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
sock->Squit(serv,"Ping timeout");
sock->Close();
return;
}
}
}
}
}
void AutoConnectServers(time_t curtime)
{
for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
{
if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
{
log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
x->NextConnectTime = curtime + x->AutoConnect;
TreeServer* CheckDupe = FindServer(x->Name);
if (!CheckDupe)
{
// an autoconnected server is not connected. Check if its time to connect it
WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
Srv->AddSocket(newsocket);
}
}
}
}
int HandleVersion(char** parameters, int pcnt, userrec* user)
{
// we've already checked if pcnt > 0, so this is safe
TreeServer* found = FindServerMask(parameters[0]);
if (found)
{
std::string Version = found->GetVersion();
WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
}
else
{
WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
}
return 1;
}
int HandleConnect(char** parameters, int pcnt, userrec* user)
{
for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
{
if (Srv->MatchText(x->Name.c_str(),parameters[0]))
{
TreeServer* CheckDupe = FindServer(x->Name);
if (!CheckDupe)
{
WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
Srv->AddSocket(newsocket);
return 1;
}
else
{
WriteServ(user->fd,"NOTICE %s :*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",user->nick,x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
return 1;
}
}
}
WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
return 1;
}
virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
{
if (*parameters[0] == 'c')
{
for (unsigned int i = 0; i < LinkBlocks.size(); i++)
{
WriteServ(user->fd,"213 %s C *@%s * %s %d 0 M",user->nick,LinkBlocks[i].IPAddr.c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port);
WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
}
WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
return true;
}
return false;
}
virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
{
if (command == "CONNECT")
{
return this->HandleConnect(parameters,pcnt,user);
}
else if (command == "SQUIT")
{
return this->HandleSquit(parameters,pcnt,user);
}
else if (command == "STATS")
{
return this->HandleStats(parameters,pcnt,user);
}
else if (command == "MAP")
{
this->HandleMap(parameters,pcnt,user);
return 1;
}
else if (command == "LUSERS")
{
this->HandleLusers(parameters,pcnt,user);
return 1;
}
else if (command == "LINKS")
{
this->HandleLinks(parameters,pcnt,user);
return 1;
}
else if (command == "WHOIS")
{
if (pcnt > 1)
{
// remote whois
return this->HandleRemoteWhois(parameters,pcnt,user);
}
}
else if ((command == "VERSION") && (pcnt > 0))
{
this->HandleVersion(parameters,pcnt,user);
return 1;
}
else if (Srv->IsValidModuleCommand(command, pcnt, user))
{
// this bit of code cleverly routes all module commands
// to all remote severs *automatically* so that modules
// can just handle commands locally, without having
// to have any special provision in place for remote
// commands and linking protocols.
std::deque<std::string> params;
params.clear();
for (int j = 0; j < pcnt; j++)
{
if (strchr(parameters[j],' '))
{
params.push_back(":" + std::string(parameters[j]));
}
else
{
params.push_back(std::string(parameters[j]));
}
}
DoOneToMany(user->nick,command,params);
}
return 0;
}
virtual void OnGetServerDescription(std::string servername,std::string &description)
{
TreeServer* s = FindServer(servername);
if (s)
{
description = s->GetDesc();
}
}
virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
{
if (source->fd > -1)
{
std::deque<std::string> params;
params.push_back(dest->nick);
params.push_back(channel->name);
DoOneToMany(source->nick,"INVITE",params);
}
}
virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
{
std::deque<std::string> params;
params.push_back(chan->name);
params.push_back(":"+topic);
DoOneToMany(user->nick,"TOPIC",params);
}
virtual void OnWallops(userrec* user, std::string text)
{
if (user->fd > -1)
{
std::deque<std::string> params;
params.push_back(":"+text);
DoOneToMany(user->nick,"WALLOPS",params);
}
}
virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
{
if (target_type == TYPE_USER)
{
userrec* d = (userrec*)dest;
if ((d->fd < 0) && (user->fd > -1))
{
std::deque<std::string> params;
params.clear();
params.push_back(d->nick);
params.push_back(":"+text);
DoOneToOne(user->nick,"NOTICE",params,d->server);
}
}
else
{
if (user->fd > -1)
{
chanrec *c = (chanrec*)dest;
std::deque<TreeServer*> list;
GetListOfServersForChannel(c,list);
unsigned int ucount = list.size();
for (unsigned int i = 0; i < ucount; i++)
{
TreeSocket* Sock = list[i]->GetSocket();
if (Sock)
Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
}
}
}
}
virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
{
if (target_type == TYPE_USER)
{
// route private messages which are targetted at clients only to the server
// which needs to receive them
userrec* d = (userrec*)dest;
if ((d->fd < 0) && (user->fd > -1))
{
std::deque<std::string> params;
params.clear();
params.push_back(d->nick);
params.push_back(":"+text);
DoOneToOne(user->nick,"PRIVMSG",params,d->server);
}
}
else
{
if (user->fd > -1)
{
chanrec *c = (chanrec*)dest;
std::deque<TreeServer*> list;
GetListOfServersForChannel(c,list);
unsigned int ucount = list.size();
for (unsigned int i = 0; i < ucount; i++)
{
TreeSocket* Sock = list[i]->GetSocket();
if (Sock)
Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
}
}
}
}
virtual void OnBackgroundTimer(time_t curtime)
{
AutoConnectServers(curtime);
DoPingChecks(curtime);
}
virtual void OnUserJoin(userrec* user, chanrec* channel)
{
// Only do this for local users
if (user->fd > -1)
{
std::deque<std::string> params;
params.clear();
params.push_back(channel->name);
if (*channel->key)
{
// if the channel has a key, force the join by emulating the key.
params.push_back(channel->key);
}
if (channel->GetUserCounter() > 1)
{
// not the first in the channel
DoOneToMany(user->nick,"JOIN",params);
}
else
{
// first in the channel, set up their permissions
// and the channel TS with FJOIN.
char ts[24];
snprintf(ts,24,"%lu",(unsigned long)channel->age);
params.clear();
params.push_back(channel->name);
params.push_back(ts);
params.push_back("@"+std::string(user->nick));
DoOneToMany(Srv->GetServerName(),"FJOIN",params);
}
}
}
virtual void OnChangeHost(userrec* user, std::string newhost)
{
// only occurs for local clients
if (user->registered != 7)
return;
std::deque<std::string> params;
params.push_back(newhost);
DoOneToMany(user->nick,"FHOST",params);
}
virtual void OnChangeName(userrec* user, std::string gecos)
{
// only occurs for local clients
if (user->registered != 7)
return;
std::deque<std::string> params;
params.push_back(gecos);
DoOneToMany(user->nick,"FNAME",params);
}
virtual void OnUserPart(userrec* user, chanrec* channel)
{
if (user->fd > -1)
{
std::deque<std::string> params;
params.push_back(channel->name);
DoOneToMany(user->nick,"PART",params);
}
}
virtual void OnUserConnect(userrec* user)
{
char agestr[MAXBUF];
if (user->fd > -1)
{
std::deque<std::string> params;
snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
params.push_back(agestr);
params.push_back(user->nick);
params.push_back(user->host);
params.push_back(user->dhost);
params.push_back(user->ident);
params.push_back("+"+std::string(user->modes));
params.push_back(user->ip);
params.push_back(":"+std::string(user->fullname));
DoOneToMany(Srv->GetServerName(),"NICK",params);
}
}
virtual void OnUserQuit(userrec* user, std::string reason)
{
if ((user->fd > -1) && (user->registered == 7))
{
std::deque<std::string> params;
params.push_back(":"+reason);
DoOneToMany(user->nick,"QUIT",params);
}
}
virtual void OnUserPostNick(userrec* user, std::string oldnick)
{
if (user->fd > -1)
{
std::deque<std::string> params;
params.push_back(user->nick);
DoOneToMany(oldnick,"NICK",params);
}
}
virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
{
if (source->fd > -1)
{
std::deque<std::string> params;
params.push_back(chan->name);
params.push_back(user->nick);
params.push_back(":"+reason);
DoOneToMany(source->nick,"KICK",params);
}
}
virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
{
std::deque<std::string> params;
params.push_back(dest->nick);
params.push_back(":"+reason);
DoOneToMany(source->nick,"KILL",params);
}
virtual void OnRehash(std::string parameter)
{
if (parameter != "")
{
std::deque<std::string> params;
params.push_back(parameter);
DoOneToMany(Srv->GetServerName(),"REHASH",params);
// check for self
if (Srv->MatchText(Srv->GetServerName(),parameter))
{
Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
Srv->RehashServer();
}
}
ReadConfiguration(false);
}
// note: the protocol does not allow direct umode +o except
// via NICK with 8 params. sending OPERTYPE infers +o modechange
// locally.
virtual void OnOper(userrec* user, std::string opertype)
{
if (user->fd > -1)
{
std::deque<std::string> params;
params.push_back(opertype);
DoOneToMany(user->nick,"OPERTYPE",params);
}
}
void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
{
if (source->fd > -1)
{
char type[8];
snprintf(type,8,"%cLINE",linetype);
std::string stype = type;
if (adding)
{
char sduration[MAXBUF];
snprintf(sduration,MAXBUF,"%ld",duration);
std::deque<std::string> params;
params.push_back(host);
params.push_back(sduration);
params.push_back(":"+reason);
DoOneToMany(source->nick,stype,params);
}
else
{
std::deque<std::string> params;
params.push_back(host);
DoOneToMany(source->nick,stype,params);
}
}
}
virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
{
OnLine(source,hostmask,true,'G',duration,reason);
}
virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
{
OnLine(source,ipmask,true,'Z',duration,reason);
}
virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
{
OnLine(source,nickmask,true,'Q',duration,reason);
}
virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
{
OnLine(source,hostmask,true,'E',duration,reason);
}
virtual void OnDelGLine(userrec* source, std::string hostmask)
{
OnLine(source,hostmask,false,'G',0,"");
}
virtual void OnDelZLine(userrec* source, std::string ipmask)
{
OnLine(source,ipmask,false,'Z',0,"");
}
virtual void OnDelQLine(userrec* source, std::string nickmask)
{
OnLine(source,nickmask,false,'Q',0,"");
}
virtual void OnDelELine(userrec* source, std::string hostmask)
{
OnLine(source,hostmask,false,'E',0,"");
}
virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
{
if ((user->fd > -1) && (user->registered == 7))
{
if (target_type == TYPE_USER)
{
userrec* u = (userrec*)dest;
std::deque<std::string> params;
params.push_back(u->nick);
params.push_back(text);
DoOneToMany(user->nick,"MODE",params);
}
else
{
chanrec* c = (chanrec*)dest;
std::deque<std::string> params;
params.push_back(c->name);
params.push_back(text);
DoOneToMany(user->nick,"MODE",params);
}
}
}
virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
{
TreeSocket* s = (TreeSocket*)opaque;
if (target)
{
if (target_type == TYPE_USER)
{
userrec* u = (userrec*)target;
s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
}
else
{
chanrec* c = (chanrec*)target;
s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
}
}
}
virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
{
TreeSocket* s = (TreeSocket*)opaque;
if (target)
{
if (target_type == TYPE_USER)
{
userrec* u = (userrec*)target;
s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
}
else
{
chanrec* c = (chanrec*)target;
s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
}
}
}
virtual ~ModuleSpanningTree()
{
}
virtual Version GetVersion()
{
return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
}
};
class ModuleSpanningTreeFactory : public ModuleFactory
{
public:
ModuleSpanningTreeFactory()
{
}
~ModuleSpanningTreeFactory()
{
}
virtual Module * CreateModule(Server* Me)
{
TreeProtocolModule = new ModuleSpanningTree(Me);
return TreeProtocolModule;
}
};
extern "C" void * init_module( void )
{
return new ModuleSpanningTreeFactory;
}
|