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
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const JSIRC_ERR_NO_SOCKET = "JSIRCE:NS";
const JSIRC_ERR_EXHAUSTED = "JSIRCE:E";
const JSIRC_ERR_CANCELLED = "JSIRCE:C";
const JSIRC_ERR_NO_SECURE = "JSIRCE:NO_SECURE";
const JSIRC_ERR_OFFLINE = "JSIRCE:OFFLINE";
const JSIRC_ERR_PAC_LOADING = "JSIRCE:PAC_LOADING";
const JSIRCV3_SUPPORTED_CAPS = [
"account-notify",
"account-tag",
"away-notify",
"batch",
"cap-notify",
"chghost",
"echo-message",
"extended-join",
"invite-notify",
//"labeled-response",
"message-tags",
//"metadata",
"multi-prefix",
"sasl",
"server-time",
"tls",
"userhost-in-names",
];
function userIsMe (user)
{
switch (user.TYPE)
{
case "IRCUser":
return (user == user.parent.me);
break;
case "IRCChanUser":
return (user.__proto__ == user.parent.parent.me);
break;
default:
return false;
}
return false;
}
/*
* Attached to event objects in onRawData
*/
function decodeParam(number, charsetOrObject)
{
if (!charsetOrObject)
charsetOrObject = this.currentObject;
var rv = toUnicode(this.params[number], charsetOrObject);
return rv;
}
// JavaScript won't let you delete things declared with "var", workaround:
window.i = 1;
const NET_OFFLINE = i++; // Initial, disconected.
const NET_WAITING = i++; // Waiting before trying.
const NET_CONNECTING = i++; // Trying a connect...
const NET_CANCELLING = i++; // Cancelling connect.
const NET_ONLINE = i++; // Connected ok.
const NET_DISCONNECTING = i++; // Disconnecting.
delete window.i;
function CIRCNetwork (name, serverList, eventPump, temporary)
{
this.unicodeName = name;
this.viewName = name;
this.canonicalName = name;
this.collectionKey = ":" + name;
this.encodedName = name;
this.servers = new Object();
this.serverList = new Array();
this.ignoreList = new Object();
this.ignoreMaskCache = new Object();
this.state = NET_OFFLINE;
this.temporary = Boolean(temporary);
for (var i = 0; i < serverList.length; ++i)
{
var server = serverList[i];
var password = ("password" in server) ? server.password : null;
var isSecure = ("isSecure" in server) ? server.isSecure : false;
this.serverList.push(new CIRCServer(this, server.name, server.port, isSecure,
password));
}
this.eventPump = eventPump;
if ("onInit" in this)
this.onInit();
}
/** Clients should override this stuff themselves **/
CIRCNetwork.prototype.INITIAL_NICK = "js-irc";
CIRCNetwork.prototype.INITIAL_NAME = "INITIAL_NAME";
CIRCNetwork.prototype.INITIAL_DESC = "INITIAL_DESC";
CIRCNetwork.prototype.USE_SASL = false;
CIRCNetwork.prototype.UPGRADE_INSECURE = false;
CIRCNetwork.prototype.STS_MODULE = null;
/* set INITIAL_CHANNEL to "" if you don't want a primary channel */
CIRCNetwork.prototype.INITIAL_CHANNEL = "#jsbot";
CIRCNetwork.prototype.INITIAL_UMODE = "+iw";
CIRCNetwork.prototype.MAX_CONNECT_ATTEMPTS = 5;
CIRCNetwork.prototype.PAC_RECONNECT_DELAY = 5 * 1000;
CIRCNetwork.prototype.getReconnectDelayMs = function() { return 15000; }
CIRCNetwork.prototype.stayingPower = false;
// "http" = use HTTP proxy, "none" = none, anything else = auto.
CIRCNetwork.prototype.PROXY_TYPE_OVERRIDE = "";
CIRCNetwork.prototype.TYPE = "IRCNetwork";
/**
* Returns the IRC URL representation of this network.
*
* @param target A network-specific object to target the URL at. Instead of
* passing it in here, call the target's |getURL| method.
* @param flags An |Object| with flags (as properties) to be applied to the URL.
*/
CIRCNetwork.prototype.getURL =
function net_geturl(target, flags)
{
if (this.temporary)
return this.serverList[0].getURL(target, flags);
/* Determine whether to use the irc:// or ircs:// scheme */
var scheme = "irc";
if ((("primServ" in this) && this.primServ.isConnected &&
this.primServ.isSecure) ||
this.hasOnlySecureServers())
{
scheme = "ircs"
}
var obj = {host: this.unicodeName, scheme: scheme};
if (target)
obj.target = target;
if (flags)
{
for (var i = 0; i < flags.length; i++)
obj[flags[i]] = true;
}
return constructIRCURL(obj);
}
CIRCNetwork.prototype.getUser =
function net_getuser (nick)
{
if ("primServ" in this && this.primServ)
return this.primServ.getUser(nick);
return null;
}
CIRCNetwork.prototype.addServer =
function net_addsrv(host, port, isSecure, password)
{
this.serverList.push(new CIRCServer(this, host, port, isSecure, password));
}
/**
* Returns |true| iif a network has a secure server in its list.
*/
CIRCNetwork.prototype.hasSecureServer =
function net_hasSecure()
{
for (var i = 0; i < this.serverList.length; i++)
{
if (this.serverList[i].isSecure)
return true;
}
return false;
}
/**
* Returns |true| iif a network only has secure servers in its list.
*/
CIRCNetwork.prototype.hasOnlySecureServers =
function net_hasOnlySecure()
{
for (var i = 0; i < this.serverList.length; i++)
{
if (!this.serverList[i].isSecure)
return false;
}
return true;
}
CIRCNetwork.prototype.clearServerList =
function net_clearserverlist()
{
/* Note: we don't have to worry about being connected, since primServ
* keeps the currently connected server alive if we still need it.
*/
this.servers = new Object();
this.serverList = new Array();
}
/**
* Trigger an |onDoConnect| event after a delay.
*/
CIRCNetwork.prototype.delayedConnect =
function net_delayedConnect(eventProperties)
{
function reconnectFn(network, eventProperties)
{
network.immediateConnect(eventProperties);
};
if ((-1 != this.MAX_CONNECT_ATTEMPTS) &&
(this.connectAttempt >= this.MAX_CONNECT_ATTEMPTS))
{
this.state = NET_OFFLINE;
var ev = new CEvent("network", "error", this, "onError");
ev.debug = "Connection attempts exhausted, giving up.";
ev.errorCode = JSIRC_ERR_EXHAUSTED;
this.eventPump.addEvent(ev);
return;
}
this.state = NET_WAITING;
this.reconnectTimer = setTimeout(reconnectFn,
this.getReconnectDelayMs(),
this,
eventProperties);
}
/**
* Immediately trigger an |onDoConnect| event. Use |delayedConnect| for automatic
* repeat attempts, instead, to throttle the attempts to a reasonable pace.
*/
CIRCNetwork.prototype.immediateConnect =
function net_immediateConnect(eventProperties)
{
var ev = new CEvent("network", "do-connect", this, "onDoConnect");
if (typeof eventProperties != "undefined")
for (var key in eventProperties)
ev[key] = eventProperties[key];
this.eventPump.addEvent(ev);
}
CIRCNetwork.prototype.connect =
function net_connect(requireSecurity)
{
if ("primServ" in this && this.primServ.isConnected)
return true;
// We need to test for secure servers in the network object here,
// because without them all connection attempts will fail anyway.
if (requireSecurity && !this.hasSecureServer())
{
// No secure server, cope.
ev = new CEvent ("network", "error", this, "onError");
ev.server = this;
ev.debug = "No connection attempted: no secure servers in list";
ev.errorCode = JSIRC_ERR_NO_SECURE;
this.eventPump.addEvent(ev);
return false;
}
this.state = NET_CONNECTING;
this.connectAttempt = 0; // actual connection attempts
this.connectCandidate = 0; // incl. requireSecurity non-attempts
this.nextHost = 0;
this.requireSecurity = requireSecurity || false;
this.immediateConnect({"password": null});
return true;
}
/**
* Disconnects the network with a given reason.
*/
CIRCNetwork.prototype.quit =
function net_quit (reason)
{
if (this.isConnected())
this.primServ.logout(reason);
}
/**
* Cancels the network's connection (whatever its current state).
*/
CIRCNetwork.prototype.cancel =
function net_cancel()
{
// We're online, pull the plug on the current connection, or...
if (this.state == NET_ONLINE)
{
this.quit();
}
// We're waiting for the 001, too late to throw a reconnect, or...
else if (this.state == NET_CONNECTING)
{
this.state = NET_CANCELLING;
if ("primServ" in this && this.primServ.isConnected)
{
this.primServ.connection.disconnect();
var ev = new CEvent("network", "error", this, "onError");
ev.server = this.primServ;
ev.debug = "Connect sequence was canceled.";
ev.errorCode = JSIRC_ERR_CANCELLED;
this.eventPump.addEvent(ev);
}
}
// We're waiting for onDoConnect, so try a reconnect (which will fail us)
else if (this.state == NET_WAITING)
{
this.state = NET_CANCELLING;
// onDoConnect will throw the error events for us, as it will fail
this.immediateConnect();
}
else
{
dd("Network cancel in odd state: " + this.state);
}
}
CIRCNetwork.prototype.onDoConnect =
function net_doconnect(e)
{
const NS_ERROR_OFFLINE = 0x804b0010;
var c;
// Clear the timer, if there is one.
if ("reconnectTimer" in this)
{
clearTimeout(this.reconnectTimer);
delete this.reconnectTimer;
}
var ev;
if (this.state == NET_CANCELLING)
{
if ("primServ" in this && this.primServ.isConnected)
this.primServ.connection.disconnect();
else
this.state = NET_OFFLINE;
ev = new CEvent("network", "error", this, "onError");
ev.server = this.primServ;
ev.debug = "Connect sequence was canceled.";
ev.errorCode = JSIRC_ERR_CANCELLED;
this.eventPump.addEvent(ev);
return false;
}
if ("primServ" in this && this.primServ.isConnected)
return true;
this.connectAttempt++;
this.connectCandidate++;
this.state = NET_CONNECTING; /* connection is considered "made" when server
* sends a 001 message (see server.on001) */
var host = this.nextHost++;
if (host >= this.serverList.length)
{
this.nextHost = 1;
host = 0;
}
// If STS is enabled, check the cache for a secure port to connect to.
if (this.STS_MODULE.ENABLED && !this.serverList[host].isSecure)
{
var newPort = this.STS_MODULE.getUpgradePolicy(this.serverList[host].hostname);
if (newPort)
{
// If we're a temporary network, just change the server prior to connecting.
if (this.temporary)
{
this.serverList[host].port = newPort;
this.serverList[host].isSecure = true;
}
// Otherwise, find or create a server with the specified host and port.
else
{
var hostname = this.serverList[host].hostname;
var matches = this.serverList.filter(function(s) {
return s.hostname == hostname && s.port == newPort;
});
if (matches.length > 0)
{
host = arrayIndexOf(this.serverList, matches[0]);
}
else
{
this.addServer(hostname, newPort, true,
this.serverList[host].password);
host = this.serverList.length - 1;
}
}
}
}
if (this.serverList[host].isSecure || !this.requireSecurity)
{
ev = new CEvent ("network", "startconnect", this, "onStartConnect");
ev.debug = "Connecting to " + this.serverList[host].unicodeName + ":" +
this.serverList[host].port + ", attempt " + this.connectAttempt +
" of " + this.MAX_CONNECT_ATTEMPTS + "...";
ev.host = this.serverList[host].hostname;
ev.port = this.serverList[host].port;
ev.server = this.serverList[host];
ev.connectAttempt = this.connectAttempt;
ev.reconnectDelayMs = this.getReconnectDelayMs();
this.eventPump.addEvent (ev);
try
{
this.serverList[host].connect();
}
catch(ex)
{
this.state = NET_OFFLINE;
ev = new CEvent("network", "error", this, "onError");
ev.server = this;
ev.debug = "Exception opening socket: " + ex;
ev.errorCode = JSIRC_ERR_NO_SOCKET;
if ((typeof ex == "object") && (ex.result == NS_ERROR_OFFLINE))
ev.errorCode = JSIRC_ERR_OFFLINE;
if ((typeof ex == "string") && (ex == JSIRC_ERR_PAC_LOADING))
{
ev.errorCode = JSIRC_ERR_PAC_LOADING;
ev.retryDelay = CIRCNetwork.prototype.PAC_RECONNECT_DELAY;
/* PAC loading is not a problem with any specific server. We'll
* retry the connection in 5 seconds.
*/
this.nextHost--;
this.state = NET_WAITING;
setTimeout(function(n) { n.immediateConnect() },
ev.retryDelay, this);
}
this.eventPump.addEvent(ev);
}
}
else
{
/* Server doesn't use SSL as requested, try next one.
* In the meantime, correct the connection attempt counter */
this.connectAttempt--;
this.immediateConnect();
}
return true;
}
/**
* Returns |true| iff this network has a socket-level connection.
*/
CIRCNetwork.prototype.isConnected =
function net_connected (e)
{
return ("primServ" in this && this.primServ.isConnected);
}
CIRCNetwork.prototype.ignore =
function net_ignore (hostmask)
{
var input = getHostmaskParts(hostmask);
if (input.mask in this.ignoreList)
return false;
this.ignoreList[input.mask] = input;
this.ignoreMaskCache = new Object();
return true;
}
CIRCNetwork.prototype.unignore =
function net_ignore (hostmask)
{
var input = getHostmaskParts(hostmask);
if (!(input.mask in this.ignoreList))
return false;
delete this.ignoreList[input.mask];
this.ignoreMaskCache = new Object();
return true;
}
function CIRCServer (parent, hostname, port, isSecure, password)
{
var serverName = hostname + ":" + port;
var s;
if (serverName in parent.servers)
{
s = parent.servers[serverName];
}
else
{
s = this;
s.channels = new Object();
s.users = new Object();
}
s.unicodeName = serverName;
s.viewName = serverName;
s.canonicalName = serverName;
s.collectionKey = ":" + serverName;
s.encodedName = serverName;
s.hostname = hostname;
s.port = port;
s.parent = parent;
s.isSecure = isSecure;
s.password = password;
s.connection = null;
s.isConnected = false;
s.sendQueue = new Array();
s.lastSend = new Date("1/1/1980");
s.lastPingSent = null;
s.lastPing = null;
s.savedLine = "";
s.lag = -1;
s.usersStable = true;
s.supports = null;
s.channelTypes = null;
s.channelModes = null;
s.channelCount = -1;
s.userModes = null;
s.maxLineLength = 400;
s.caps = new Object();
s.capvals = new Object();
parent.servers[s.collectionKey] = s;
if ("onInit" in s)
s.onInit();
return s;
}
CIRCServer.prototype.MS_BETWEEN_SENDS = 1500;
CIRCServer.prototype.READ_TIMEOUT = 100;
CIRCServer.prototype.VERSION_RPLY = "JS-IRC Library v0.01, " +
"Copyright (C) 1999 Robert Ginda; rginda@ndcico.com";
CIRCServer.prototype.OS_RPLY = "Unknown";
CIRCServer.prototype.HOST_RPLY = "Unknown";
CIRCServer.prototype.DEFAULT_REASON = "no reason";
/* true means WHO command doesn't collect hostmask, username, etc. */
CIRCServer.prototype.LIGHTWEIGHT_WHO = false;
/* Unique identifier for WHOX commands. */
CIRCServer.prototype.WHOX_TYPE = "314";
/* -1 == never, 0 == prune onQuit, >0 == prune when >X ms old */
CIRCServer.prototype.PRUNE_OLD_USERS = -1;
CIRCServer.prototype.TYPE = "IRCServer";
// Define functions to set modes so they're easily readable.
// name is the name used on the CIRCChanMode object
// getValue is a function returning the value the canonicalmode should be set to
// given a certain modifier and appropriate data.
CIRCServer.prototype.canonicalChanModes = {
i: {
name: "invite",
getValue: function (modifier) { return (modifier == "+"); }
},
m: {
name: "moderated",
getValue: function (modifier) { return (modifier == "+"); }
},
n: {
name: "publicMessages",
getValue: function (modifier) { return (modifier == "-"); }
},
t: {
name: "publicTopic",
getValue: function (modifier) { return (modifier == "-"); }
},
s: {
name: "secret",
getValue: function (modifier) { return (modifier == "+"); }
},
p: {
name: "pvt",
getValue: function (modifier) { return (modifier == "+"); }
},
k: {
name: "key",
getValue: function (modifier, data)
{
if (modifier == "+")
return data;
else
return "";
}
},
l: {
name: "limit",
getValue: function (modifier, data)
{
// limit is special - we return -1 if there is no limit.
if (modifier == "-")
return -1;
else
return data;
}
}
};
CIRCServer.prototype.toLowerCase =
function serv_tolowercase(str)
{
/* This is an implementation that lower-cases strings according to the
* prevailing CASEMAPPING setting for the server. Values for this are:
*
* o "ascii": The ASCII characters 97 to 122 (decimal) are defined as
* the lower-case characters of ASCII 65 to 90 (decimal). No other
* character equivalency is defined.
* o "strict-rfc1459": The ASCII characters 97 to 125 (decimal) are
* defined as the lower-case characters of ASCII 65 to 93 (decimal).
* No other character equivalency is defined.
* o "rfc1459": The ASCII characters 97 to 126 (decimal) are defined as
* the lower-case characters of ASCII 65 to 94 (decimal). No other
* character equivalency is defined.
*
*/
function replaceFunction(chr)
{
return String.fromCharCode(chr.charCodeAt(0) + 32);
}
var mapping = "rfc1459";
if (this.supports)
mapping = this.supports.casemapping;
/* NOTE: There are NO breaks in this switch. This is CORRECT.
* Each mapping listed is a super-set of those below, thus we only
* transform the extra characters, and then fall through.
*/
switch (mapping)
{
case "rfc1459":
str = str.replace(/\^/g, replaceFunction);
case "strict-rfc1459":
str = str.replace(/[\[\\\]]/g, replaceFunction);
case "ascii":
str = str.replace(/[A-Z]/g, replaceFunction);
}
return str;
}
// Iterates through the keys in an object and, if specified, the keys of
// child objects.
CIRCServer.prototype.renameProperties =
function serv_renameproperties(obj, child)
{
for (let key in obj)
{
let item = obj[key];
item.canonicalName = this.toLowerCase(item.encodedName);
item.collectionKey = ":" + item.canonicalName;
renameProperty(obj, key, item.collectionKey);
if (child && (child in item))
this.renameProperties(item[child], null);
}
}
// Encodes tag data to send.
CIRCServer.prototype.encodeTagData =
function serv_encodetagdata(obj)
{
var dict = new Object();
dict[";"] = ":";
dict[" "] = "s";
dict["\\"] = "\\";
dict["\r"] = "r";
dict["\n"] = "n";
// Function for escaping key values.
function escapeTagValue(data)
{
var rv = "";
for (var i = 0; i < data.length; i++)
{
var ci = data[i];
var co = dict[data[i]];
if (co)
rv += "\\" + co;
else
rv += ci;
}
return rv;
}
var str = "";
for(var key in obj)
{
var val = obj[key];
str += key;
if (val)
{
str += "=";
str += escapeTagValue(val);
}
str += ";";
}
// Remove any trailing semicolons.
if (str[str.length - 1] == ";")
str = str.substring(0, str.length - 1);
return str;
}
// Decodes received tag data.
CIRCServer.prototype.decodeTagData =
function serv_decodetagdata(str)
{
// Remove the leading '@' if we have one.
if (str[0] == "@")
str = str.substring(1);
var dict = new Object();
dict[":"] = ";";
dict["s"] = " ";
dict["\\"] = "\\";
dict["r"] = "\r";
dict["n"] = "\n";
// Function for unescaping key values.
function unescapeTagValue(data)
{
var rv = "";
for (let j = 0; j < data.length; j++)
{
let currentItem = data[j];
if (currentItem == "\\" && j < data.length - 1)
{
let nextItem = data[j + 1];
if (nextItem in dict)
rv += dict[nextItem];
else
rv += nextItem;
j++
}
else if (currentItem != "\\")
rv += currentItem;
}
return rv;
}
var obj = Object();
var tags = str.split(";");
for (var i = 0; i < tags.length; i++)
{
var [key, val] = tags[i].split("=");
val = unescapeTagValue(val);
obj[key] = val;
}
return obj;
}
// Returns the IRC URL representation of this server.
CIRCServer.prototype.getURL =
function serv_geturl(target, flags)
{
var scheme = (this.isSecure ? "ircs" : "irc");
var obj = {host: this.hostname, scheme: scheme, isserver: true,
port: this.port, needpass: Boolean(this.password)};
if (target)
obj.target = target;
if (flags)
{
for (var i = 0; i < flags.length; i++)
obj[flags[i]] = true;
}
return constructIRCURL(obj);
}
CIRCServer.prototype.getUser =
function chan_getuser(nick)
{
var tnick = ":" + this.toLowerCase(nick);
if (tnick in this.users)
return this.users[tnick];
tnick = ":" + this.toLowerCase(fromUnicode(nick, this));
if (tnick in this.users)
return this.users[tnick];
return null;
}
CIRCServer.prototype.getChannel =
function chan_getchannel(name)
{
var tname = ":" + this.toLowerCase(name);
if (tname in this.channels)
return this.channels[tname];
tname = ":" + this.toLowerCase(fromUnicode(name, this));
if (tname in this.channels)
return this.channels[tname];
return null;
}
CIRCServer.prototype.connect =
function serv_connect()
{
if (this.connection != null)
throw "Server already has a connection pending or established";
var config = { isSecure: this.isSecure };
if (this.parent.PROXY_TYPE_OVERRIDE)
config.proxy = this.parent.PROXY_TYPE_OVERRIDE;
this.connection = new CBSConnection();
this.connection.connect(this.hostname, this.port, config, this);
}
// This may be called synchronously or asynchronously by CBSConnection.connect.
CIRCServer.prototype.onSocketConnection =
function serv_onsocketconnection(host, port, config, exception)
{
if (this.parent.state == NET_CANCELLING)
{
this.connection.disconnect();
this.connection = null;
this.parent.state = NET_OFFLINE;
var ev = new CEvent("network", "error", this.parent, "onError");
ev.server = this;
ev.debug = "Connect sequence was canceled.";
ev.errorCode = JSIRC_ERR_CANCELLED;
this.parent.eventPump.addEvent(ev);
}
else if (!exception)
{
var ev = new CEvent("server", "connect", this, "onConnect");
ev.server = this;
this.parent.eventPump.addEvent(ev);
this.isConnected = true;
this.connection.startAsyncRead(this);
}
else
{
var ev = new CEvent("server", "disconnect", this, "onDisconnect");
ev.server = this;
ev.reason = "error";
ev.exception = exception;
ev.disconnectStatus = NS_ERROR_ABORT;
this.parent.eventPump.addEvent(ev);
}
}
/*
* What to do when the client connects to it's primary server
*/
CIRCServer.prototype.onConnect =
function serv_onconnect (e)
{
this.parent.primServ = e.server;
this.sendData("CAP LS 302\n");
this.pendingCapNegotiation = true;
this.caps = new Object();
this.capvals = new Object();
this.login(this.parent.INITIAL_NICK, this.parent.INITIAL_NAME,
this.parent.INITIAL_DESC);
return true;
}
CIRCServer.prototype.onStreamDataAvailable =
function serv_sda (request, inStream, sourceOffset, count)
{
var ev = new CEvent ("server", "data-available", this,
"onDataAvailable");
ev.line = this.connection.readData(0, count);
/* route data-available as we get it. the data-available handler does
* not do much, so we can probably get away with this without starving
* the UI even under heavy input traffic.
*/
this.parent.eventPump.routeEvent(ev);
}
CIRCServer.prototype.onStreamClose =
function serv_sockdiscon(status)
{
var ev = new CEvent ("server", "disconnect", this, "onDisconnect");
ev.server = this;
ev.disconnectStatus = status;
if (ev.disconnectStatus == NS_ERROR_BINDING_ABORTED)
ev.disconnectStatus = NS_ERROR_ABORT;
this.parent.eventPump.addEvent (ev);
}
CIRCServer.prototype.flushSendQueue =
function serv_flush()
{
this.sendQueue.length = 0;
dd("sendQueue flushed.");
return true;
}
CIRCServer.prototype.login =
function serv_login(nick, name, desc)
{
nick = nick.replace(/ /g, "_");
name = name.replace(/ /g, "_");
if (!nick)
nick = "nick";
if (!name)
name = nick;
if (!desc)
desc = nick;
this.me = new CIRCUser(this, nick, null, name);
if (this.password)
this.sendData("PASS " + this.password + "\n");
this.changeNick(this.me.unicodeName);
this.sendData("USER " + name + " * * :" +
fromUnicode(desc, this) + "\n");
}
CIRCServer.prototype.logout =
function serv_logout(reason)
{
if (reason == null || typeof reason == "undefined")
reason = this.DEFAULT_REASON;
this.quitting = true;
this.connection.sendData("QUIT :" +
fromUnicode(reason, this.parent) + "\n");
this.connection.disconnect();
}
CIRCServer.prototype.sendAuthResponse =
function serv_authresponse(resp)
{
// Encode the response and break into 400-byte parts.
var resp = btoa(resp);
var part = null;
var n = 0;
do
{
part = resp.substring(0, 400);
n = part.length;
resp = resp.substring(400);
this.sendData("AUTHENTICATE " + part + '\n');
}
while (resp.length > 0);
// Send empty auth response if last part was exactly 400 bytes long.
if (n == 400)
{
this.sendData("AUTHENTICATE +\n");
}
}
CIRCServer.prototype.sendAuthAbort =
function serv_authabort()
{
// Abort an in-progress SASL authentication.
this.sendData("AUTHENTICATE *\n");
}
CIRCServer.prototype.sendMonitorList =
function serv_monitorlist(nicks, isAdd)
{
if (!nicks.length)
return;
var prefix;
if (isAdd)
prefix = "MONITOR + ";
else
prefix = "MONITOR - ";
/* Send monitor list updates in chunks less than
maxLineLength in size. */
var nicks_string = nicks.join(",");
while (nicks_string.length > this.maxLineLength)
{
var nicks_part = nicks_string.substring(0, this.maxLineLength);
var i = nicks_part.lastIndexOf(",");
nicks_part = nicks_string.substring(0, i);
nicks_string = nicks_string.substring(i + 1);
this.sendData(prefix + nicks_part + "\n");
}
this.sendData(prefix + nicks_string + "\n");
}
CIRCServer.prototype.addTarget =
function serv_addtarget(name)
{
if (arrayIndexOf(this.channelTypes, name[0]) != -1) {
return this.addChannel(name);
} else {
return this.addUser(name);
}
}
CIRCServer.prototype.addChannel =
function serv_addchan(unicodeName, charset)
{
return new CIRCChannel(this, unicodeName, fromUnicode(unicodeName, charset));
}
CIRCServer.prototype.addUser =
function serv_addusr(unicodeName, name, host)
{
return new CIRCUser(this, unicodeName, null, name, host);
}
CIRCServer.prototype.getChannelsLength =
function serv_chanlen()
{
var i = 0;
for (var p in this.channels)
i++;
return i;
}
CIRCServer.prototype.getUsersLength =
function serv_chanlen()
{
var i = 0;
for (var p in this.users)
i++;
return i;
}
CIRCServer.prototype.sendData =
function serv_senddata (msg)
{
this.queuedSendData (msg);
}
CIRCServer.prototype.queuedSendData =
function serv_senddata (msg)
{
if (this.sendQueue.length == 0)
this.parent.eventPump.addEvent (new CEvent ("server", "senddata",
this, "onSendData"));
arrayInsertAt (this.sendQueue, 0, new String(msg));
}
// Utility method for splitting large lines prior to sending.
CIRCServer.prototype.splitLinesForSending =
function serv_splitlines(line, prettyWrap)
{
let lines = String(line).split("\n");
let realLines = [];
for (let i = 0; i < lines.length; i++)
{
if (lines[i])
{
while (lines[i].length > this.maxLineLength)
{
var extraLine = lines[i].substr(0, this.maxLineLength - 5);
var pos = extraLine.lastIndexOf(" ");
if ((pos >= 0) && (pos >= this.maxLineLength - 15))
{
// Smart-split.
extraLine = lines[i].substr(0, pos);
lines[i] = lines[i].substr(extraLine.length + 1);
if (prettyWrap)
{
extraLine += "...";
lines[i] = "..." + lines[i];
}
}
else
{
// Dumb-split.
extraLine = lines[i].substr(0, this.maxLineLength);
lines[i] = lines[i].substr(extraLine.length);
}
realLines.push(extraLine);
}
realLines.push(lines[i]);
}
}
return realLines;
}
CIRCServer.prototype.messageTo =
function serv_messto(code, target, msg, ctcpCode)
{
let lines = this.splitLinesForSending(msg, true);
let i = 0;
let pfx = "";
let sfx = "";
if (ctcpCode)
{
pfx = "\01" + ctcpCode;
sfx = "\01";
}
// We may have no message at all with CTCP commands.
if (!lines.length && ctcpCode)
lines.push("");
for (i in lines)
{
if ((lines[i] != "") || ctcpCode)
{
var line = code + " " + target + " :" + pfx;
if (lines[i] != "")
{
if (ctcpCode)
line += " ";
line += lines[i] + sfx;
}
else
line += sfx;
//dd ("-*- irc sending '" + line + "'");
this.sendData(line + "\n");
}
}
}
CIRCServer.prototype.sayTo =
function serv_sayto (target, msg)
{
this.messageTo("PRIVMSG", target, msg);
}
CIRCServer.prototype.noticeTo =
function serv_noticeto (target, msg)
{
this.messageTo("NOTICE", target, msg);
}
CIRCServer.prototype.actTo =
function serv_actto (target, msg)
{
this.messageTo("PRIVMSG", target, msg, "ACTION");
}
CIRCServer.prototype.ctcpTo =
function serv_ctcpto (target, code, msg, method)
{
msg = msg || "";
method = method || "PRIVMSG";
code = code.toUpperCase();
if (code == "PING" && !msg)
msg = Number(new Date());
this.messageTo(method, target, msg, code);
}
CIRCServer.prototype.changeNick =
function serv_changenick(newNick)
{
this.sendData("NICK " + fromUnicode(newNick, this) + "\n");
}
CIRCServer.prototype.updateLagTimer =
function serv_uptimer()
{
this.connection.sendData("PING :LAGTIMER\n");
this.lastPing = this.lastPingSent = new Date();
}
CIRCServer.prototype.userhost =
function serv_userhost(target)
{
this.sendData("USERHOST " + fromUnicode(target, this) + "\n");
}
CIRCServer.prototype.userip =
function serv_userip(target)
{
this.sendData("USERIP " + fromUnicode(target, this) + "\n");
}
CIRCServer.prototype.who =
function serv_who(target)
{
this.sendData("WHO " + fromUnicode(target, this) + "\n");
}
/**
* Abstracts the whois command.
*
* @param target intended user(s).
*/
CIRCServer.prototype.whois =
function serv_whois (target)
{
this.sendData("WHOIS " + fromUnicode(target, this) + "\n");
}
CIRCServer.prototype.whowas =
function serv_whowas(target, limit)
{
if (typeof limit == "undefined")
limit = 1;
else if (limit == 0)
limit = "";
this.sendData("WHOWAS " + fromUnicode(target, this) + " " + limit + "\n");
}
CIRCServer.prototype.onDisconnect =
function serv_disconnect(e)
{
function stateChangeFn(network, state) {
network.state = state;
};
function delayedConnectFn(network) {
network.delayedConnect();
};
/* If we're not connected and get this, it means we have almost certainly
* encountered a read or write error on the socket post-disconnect. There's
* no point propagating this any further, as we've already notified the
* user of the disconnect (with the right error).
*/
if (!this.isConnected)
return;
// Don't reconnect from a certificate error.
var certError = (getNSSErrorClass(e.disconnectStatus) == ERROR_CLASS_BAD_CERT);
// Don't reconnect if our connection was aborted.
var wasAborted = (e.disconnectStatus == NS_ERROR_ABORT);
var dontReconnect = certError || wasAborted;
if (((this.parent.state == NET_CONNECTING) && !dontReconnect) ||
/* fell off while connecting, try again */
(this.parent.primServ == this) && (this.parent.state == NET_ONLINE) &&
(!("quitting" in this) && this.parent.stayingPower && !dontReconnect))
{ /* fell off primary server, reconnect to any host in the serverList */
setTimeout(delayedConnectFn, 0, this.parent);
}
else
{
setTimeout(stateChangeFn, 0, this.parent, NET_OFFLINE);
}
e.server = this;
e.set = "network";
e.destObject = this.parent;
e.quitting = this.quitting;
for (var c in this.channels)
{
this.channels[c].users = new Object();
this.channels[c].active = false;
}
if (this.isStartTLS)
{
this.isSecure = false;
delete this.isStartTLS;
}
delete this.batches;
this.connection = null;
this.isConnected = false;
delete this.quitting;
}
CIRCServer.prototype.onSendData =
function serv_onsenddata (e)
{
if (!this.isConnected || (this.parent.state == NET_CANCELLING))
{
dd ("Can't send to disconnected socket");
this.flushSendQueue();
return false;
}
var d = new Date();
// Wheee, some sanity checking! (there's been at least one case of lastSend
// ending up in the *future* at this point, which kinda busts things)
if (this.lastSend > d)
this.lastSend = 0;
if (((d - this.lastSend) >= this.MS_BETWEEN_SENDS) &&
this.sendQueue.length > 0)
{
var s = this.sendQueue.pop();
if (s)
{
try
{
this.connection.sendData(s);
}
catch(ex)
{
dd("Exception in queued send: " + ex);
this.flushSendQueue();
var ev = new CEvent("server", "disconnect",
this, "onDisconnect");
ev.server = this;
ev.reason = "error";
ev.exception = ex;
ev.disconnectStatus = NS_ERROR_ABORT;
this.parent.eventPump.addEvent(ev);
return false;
}
this.lastSend = d;
}
}
else
{
this.parent.eventPump.addEvent(new CEvent("event-pump", "yield",
null, ""));
}
if (this.sendQueue.length > 0)
this.parent.eventPump.addEvent(new CEvent("server", "senddata",
this, "onSendData"));
return true;
}
CIRCServer.prototype.onPoll =
function serv_poll(e)
{
var lines;
var ex;
var ev;
try
{
if (this.parent.state != NET_CANCELLING)
line = this.connection.readData(this.READ_TIMEOUT);
}
catch (ex)
{
dd ("*** Caught exception " + ex + " reading from server " +
this.hostname);
ev = new CEvent ("server", "disconnect", this, "onDisconnect");
ev.server = this;
ev.reason = "error";
ev.exception = ex;
ev.disconnectStatus = NS_ERROR_ABORT;
this.parent.eventPump.addEvent (ev);
return false;
}
this.parent.eventPump.addEvent (new CEvent ("server", "poll", this,
"onPoll"));
if (line)
{
ev = new CEvent ("server", "data-available", this, "onDataAvailable");
ev.line = line;
this.parent.eventPump.routeEvent(ev);
}
return true;
}
CIRCServer.prototype.onDataAvailable =
function serv_ppline(e)
{
var line = e.line;
if (line == "")
return false;
var incomplete = (line[line.length - 1] != '\n');
var lines = line.split("\n");
if (this.savedLine)
{
lines[0] = this.savedLine + lines[0];
this.savedLine = "";
}
if (incomplete)
this.savedLine = lines.pop();
for (var i in lines)
{
var ev = new CEvent("server", "rawdata", this, "onRawData");
ev.data = lines[i].replace(/\r/g, "");
if (ev.data)
{
if (ev.data.match(/^(?::[^ ]+ )?(?:32[123]|352|354|315) /i))
this.parent.eventPump.addBulkEvent(ev);
else
this.parent.eventPump.addEvent(ev);
}
}
return true;
}
/*
* onRawData begins shaping the event by parsing the IRC message at it's
* simplest level. After onRawData, the event will have the following
* properties:
* name value
*
* set............"server"
* type..........."parsedata"
* destMethod....."onParsedData"
* destObject.....server (this)
* server.........server (this)
* connection.....CBSConnection (this.connection)
* source.........the <prefix> of the message (if it exists)
* user...........user object initialized with data from the message <prefix>
* params.........array containing the parameters of the message
* code...........the first parameter (most messages have this)
*
* See Section 2.3.1 of RFC 1459 for details on <prefix>, <middle> and
* <trailing> tokens.
*/
CIRCServer.prototype.onRawData =
function serv_onRawData(e)
{
var ary;
var l = e.data;
if (l.length == 0)
{
dd ("empty line on onRawData?");
return false;
}
if (l[0] == "@")
{
e.tagdata = l.substring(0, l.indexOf(" "));
e.tags = this.decodeTagData(e.tagdata);
l = l.substring(l.indexOf(" ") + 1);
}
else
{
e.tagdata = new Object();
e.tags = new Object();
}
if (l[0] == ":")
{
// Must split only on REAL spaces here, not just any old whitespace.
ary = l.match(/:([^ ]+) +(.*)/);
e.source = ary[1];
l = ary[2];
ary = e.source.match(/([^ ]+)!([^ ]+)@(.*)/);
if (ary)
{
e.user = new CIRCUser(this, null, ary[1], ary[2], ary[3]);
}
else
{
ary = e.source.match(/([^ ]+)@(.*)/);
if (ary)
{
e.user = new CIRCUser(this, null, ary[1], null, ary[2]);
}
else
{
ary = e.source.match(/([^ ]+)!(.*)/);
if (ary)
e.user = new CIRCUser(this, null, ary[1], ary[2], null);
}
}
}
if (("user" in e) && e.user && e.tags.account)
{
e.user.account = e.tags.account;
}
e.ignored = false;
if (("user" in e) && e.user && ("ignoreList" in this.parent))
{
// Assumption: if "ignoreList" is in this.parent, we assume that:
// a) it's an array.
// b) ignoreMaskCache also exists, and
// c) it's an array too.
if (!(e.source in this.parent.ignoreMaskCache))
{
for (var m in this.parent.ignoreList)
{
if (hostmaskMatches(e.user, this.parent.ignoreList[m]))
{
e.ignored = true;
break;
}
}
/* Save this exact source in the cache, with results of tests. */
this.parent.ignoreMaskCache[e.source] = e.ignored;
}
else
{
e.ignored = this.parent.ignoreMaskCache[e.source];
}
}
e.server = this;
var sep = l.indexOf(" :");
if (sep != -1) /* <trailing> param, if there is one */
{
var trail = l.substr (sep + 2, l.length);
e.params = l.substr(0, sep).split(/ +/);
e.params[e.params.length] = trail;
}
else
{
e.params = l.split(/ +/);
}
e.decodeParam = decodeParam;
e.code = e.params[0].toUpperCase();
// Ignore all private (inc. channel) messages, notices and invites here.
if (e.ignored && ((e.code == "PRIVMSG") || (e.code == "NOTICE") ||
(e.code == "INVITE") || (e.code == "TAGMSG")))
return true;
// If the message is part of a batch, store it for later.
if (this.batches && e.tags["batch"] && e.code != "BATCH")
{
var reftag = e.tags["batch"];
// Check if the batch is already open.
// If not, ignore the incoming message.
if (this.batches[reftag])
this.batches[reftag].messages.push(e);
return false;
}
e.type = "parseddata";
e.destObject = this;
e.destMethod = "onParsedData";
return true;
}
/*
* onParsedData forwards to next event, based on |e.code|
*/
CIRCServer.prototype.onParsedData =
function serv_onParsedData(e)
{
e.type = this.toLowerCase(e.code);
if (!e.code[0])
{
dd (dumpObjectTree (e));
return false;
}
e.destMethod = "on" + e.code[0].toUpperCase() +
e.code.substr (1, e.code.length).toLowerCase();
if (typeof this[e.destMethod] == "function")
e.destObject = this;
else if (typeof this["onUnknown"] == "function")
e.destMethod = "onUnknown";
else if (typeof this.parent[e.destMethod] == "function")
{
e.set = "network";
e.destObject = this.parent;
}
else
{
e.set = "network";
e.destObject = this.parent;
e.destMethod = "onUnknown";
}
return true;
}
/* User changed topic */
CIRCServer.prototype.onTopic =
function serv_topic (e)
{
e.channel = new CIRCChannel(this, null, e.params[1]);
e.channel.topicBy = e.user.unicodeName;
e.channel.topicDate = new Date();
e.channel.topic = toUnicode(e.params[2], e.channel);
e.destObject = e.channel;
e.set = "channel";
return true;
}
/* Successful login */
CIRCServer.prototype.on001 =
function serv_001 (e)
{
this.parent.connectAttempt = 0;
this.parent.connectCandidate = 0;
//Mark capability negotiation as finished, if we haven't already.
delete this.parent.pendingCapNegotiation;
this.parent.state = NET_ONLINE;
// nextHost is incremented after picking a server. Push it back here.
this.parent.nextHost--;
/* servers won't send a nick change notification if user was forced
* to change nick while logging in (eg. nick already in use.) We need
* to verify here that what the server thinks our name is, matches what
* we think it is. If not, the server wins.
*/
if (e.params[1] != e.server.me.encodedName)
{
renameProperty(e.server.users, e.server.me.collectionKey,
":" + this.toLowerCase(e.params[1]));
e.server.me.changeNick(toUnicode(e.params[1], this));
}
/* Set up supports defaults here.
* This is so that we don't waste /huge/ amounts of RAM for the network's
* servers just because we know about them. Until we connect, that is.
* These defaults are taken from the draft 005 RPL_ISUPPORTS here:
* http://www.ietf.org/internet-drafts/draft-brocklesby-irc-isupport-02.txt
*/
this.supports = new Object();
this.supports.modes = 3;
this.supports.maxchannels = 10;
this.supports.nicklen = 9;
this.supports.casemapping = "rfc1459";
this.supports.channellen = 200;
this.supports.chidlen = 5;
/* Make sure it's possible to tell if we've actually got a 005 message. */
this.supports.rpl_isupport = false;
this.channelTypes = [ '#', '&' ];
/* This next one isn't in the isupport draft, but instead is defaulting to
* the codes we understand. It should be noted, some servers include the
* mode characters (o, h, v) in the 'a' list, although the draft spec says
* they should be treated as type 'b'. Luckly, in practise this doesn't
* matter, since both 'a' and 'b' types always take a parameter in the
* MODE message, and parsing is not affected. */
this.channelModes = {
a: ['b'],
b: ['k'],
c: ['l'],
d: ['i', 'm', 'n', 'p', 's', 't']
};
// Default to support of v/+ and o/@ only.
this.userModes = [
{ mode: 'o', symbol: '@' },
{ mode: 'v', symbol: '+' }
];
// Assume the server supports no extra interesting commands.
this.servCmds = {};
if (this.parent.INITIAL_UMODE)
{
e.server.sendData("MODE " + e.server.me.encodedName + " :" +
this.parent.INITIAL_UMODE + "\n");
}
this.parent.users = this.users;
e.destObject = this.parent;
e.set = "network";
}
/* server features */
CIRCServer.prototype.on005 =
function serv_005 (e)
{
var oldCaseMapping = this.supports["casemapping"];
/* Drop params 0 and 1. */
for (var i = 2; i < e.params.length; i++) {
var itemStr = e.params[i];
/* Items may be of the forms:
* NAME
* -NAME
* NAME=value
* Value may be empty on occasion.
* No value allowed for -NAME items.
*/
var item = itemStr.match(/^(-?)([A-Z]+)(=(.*))?$/i);
if (! item)
continue;
var name = item[2].toLowerCase();
if (("3" in item) && item[3])
{
// And other items are stored as-is, though numeric items
// get special treatment to make our life easier later.
if (("4" in item) && item[4].match(/^\d+$/))
this.supports[name] = Number(item[4]);
else
this.supports[name] = item[4];
}
else
{
// Boolean-type items stored as 'true'.
this.supports[name] = !(("1" in item) && item[1] == "-");
}
}
// Update all users and channels if the casemapping changed.
if (this.supports["casemapping"] != oldCaseMapping)
{
this.renameProperties(this.users, null);
this.renameProperties(this.channels, "users");
}
// Supported 'special' items:
// CHANTYPES (--> channelTypes{}),
// PREFIX (--> userModes[{mode,symbol}]),
// CHANMODES (--> channelModes{a:[], b:[], c:[], d:[]}).
var m;
if ("chantypes" in this.supports)
{
this.channelTypes = [];
for (m = 0; m < this.supports.chantypes.length; m++)
this.channelTypes.push( this.supports.chantypes[m] );
}
if ("prefix" in this.supports)
{
var mlist = this.supports.prefix.match(/^\((.*)\)(.*)$/i);
if ((! mlist) || (mlist[1].length != mlist[2].length))
{
dd ("** Malformed PREFIX entry in 005 SUPPORTS message **");
}
else
{
this.userModes = [];
for (m = 0; m < mlist[1].length; m++)
this.userModes.push( { mode: mlist[1][m],
symbol: mlist[2][m] } );
}
}
if ("chanmodes" in this.supports)
{
var cmlist = this.supports.chanmodes.split(/,/);
if ((!cmlist) || (cmlist.length < 4))
{
dd ("** Malformed CHANMODES entry in 005 SUPPORTS message **");
}
else
{
// 4 types - list, set-unset-param, set-only-param, flag.
this.channelModes = {
a: cmlist[0].split(''),
b: cmlist[1].split(''),
c: cmlist[2].split(''),
d: cmlist[3].split('')
};
}
}
if ("cmds" in this.supports)
{
// Map this.supports.cmds [comma-list] into this.servCmds [props].
var cmdlist = this.supports.cmds.split(/,/);
for (var i = 0; i < cmdlist.length; i++)
this.servCmds[cmdlist[i].toLowerCase()] = true;
}
this.supports.rpl_isupport = true;
e.destObject = this.parent;
e.set = "network";
return true;
}
/* users */
CIRCServer.prototype.on251 =
function serv_251(e)
{
// 251 is the first message we get after 005, so it's now safe to do
// things that might depend upon server features.
if (("namesx" in this.supports) && this.supports.namesx)
{
// "multi-prefix" is the same as "namesx" but PROTOCTL doesn't reply.
this.caps["multi-prefix"] = true;
this.sendData("PROTOCTL NAMESX\n");
}
if (this.parent.INITIAL_CHANNEL)
{
this.parent.primChan = this.addChannel(this.parent.INITIAL_CHANNEL);
this.parent.primChan.join();
}
e.destObject = this.parent;
e.set = "network";
}
/* channels */
CIRCServer.prototype.on254 =
function serv_254(e)
{
this.channelCount = e.params[2];
e.destObject = this.parent;
e.set = "network";
}
/* user away message */
CIRCServer.prototype.on301 =
function serv_301(e)
{
e.user = new CIRCUser(this, null, e.params[2]);
e.user.awayMessage = e.decodeParam(3, e.user);
e.destObject = this.parent;
e.set = "network";
}
/* whois name */
CIRCServer.prototype.on311 =
function serv_311 (e)
{
e.user = new CIRCUser(this, null, e.params[2], e.params[3], e.params[4]);
e.user.desc = e.decodeParam(6, e.user);
e.destObject = this.parent;
e.set = "network";
this.pendingWhoisLines = e.user;
}
/* whois server */
CIRCServer.prototype.on312 =
function serv_312 (e)
{
e.user = new CIRCUser(this, null, e.params[2]);
e.user.connectionHost = e.params[3];
e.destObject = this.parent;
e.set = "network";
}
/* whois idle time */
CIRCServer.prototype.on317 =
function serv_317 (e)
{
e.user = new CIRCUser(this, null, e.params[2]);
e.user.idleSeconds = e.params[3];
e.destObject = this.parent;
e.set = "network";
}
/* whois channel list */
CIRCServer.prototype.on319 =
function serv_319(e)
{
e.user = new CIRCUser(this, null, e.params[2]);
e.destObject = this.parent;
e.set = "network";
}
/* end of whois */
CIRCServer.prototype.on318 =
function serv_318(e)
{
e.user = new CIRCUser(this, null, e.params[2]);
if ("pendingWhoisLines" in this)
delete this.pendingWhoisLines;
e.destObject = this.parent;
e.set = "network";
}
/* ircu's 330 numeric ("X is logged in as Y") */
CIRCServer.prototype.on330 =
function serv_330(e)
{
e.user = new CIRCUser(this, null, e.params[2]);
var account = (e.params[3] == "*" ? null : e.params[3]);
this.users[e.user.collectionKey].account = account;
e.destObject = this.parent;
e.set = "network";
}
/* TOPIC reply - no topic set */
CIRCServer.prototype.on331 =
function serv_331 (e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.channel.topic = "";
e.destObject = e.channel;
e.set = "channel";
return true;
}
/* TOPIC reply - topic set */
CIRCServer.prototype.on332 =
function serv_332 (e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.channel.topic = toUnicode(e.params[3], e.channel);
e.destObject = e.channel;
e.set = "channel";
return true;
}
/* topic information */
CIRCServer.prototype.on333 =
function serv_333 (e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.channel.topicBy = toUnicode(e.params[3], this);
e.channel.topicDate = new Date(Number(e.params[4]) * 1000);
e.destObject = e.channel;
e.set = "channel";
return true;
}
/* who reply */
CIRCServer.prototype.on352 =
function serv_352 (e)
{
e.userHasChanges = false;
if (this.LIGHTWEIGHT_WHO)
{
e.user = new CIRCUser(this, null, e.params[6]);
}
else
{
e.user = new CIRCUser(this, null, e.params[6], e.params[3], e.params[4]);
e.user.connectionHost = e.params[5];
if (8 in e.params)
{
var ary = e.params[8].match(/(?:(\d+)\s)?(.*)/);
e.user.hops = ary[1];
var desc = fromUnicode(ary[2], e.user);
if (e.user.desc != desc)
{
e.userHasChanges = true;
e.user.desc = desc;
}
}
}
var away = (e.params[7][0] == "G");
if (e.user.isAway != away)
{
e.userHasChanges = true;
e.user.isAway = away;
}
e.destObject = this.parent;
e.set = "network";
return true;
}
/* extended who reply */
CIRCServer.prototype.on354 =
function serv_354(e)
{
// Discard if the type is not ours.
if (e.params[2] != this.WHOX_TYPE)
return;
e.userHasChanges = false;
if (this.LIGHTWEIGHT_WHO)
{
e.user = new CIRCUser(this, null, e.params[7]);
}
else
{
e.user = new CIRCUser(this, null, e.params[7], e.params[4], e.params[5]);
e.user.connectionHost = e.params[6];
// Hops is a separate parameter in WHOX.
e.user.hops = e.params[9];
var account = (e.params[10] == "0" ? null : e.params[10]);
e.user.account = account;
if (11 in e.params)
{
var desc = e.decodeParam(11, e.user);
if (e.user.desc != desc)
{
e.userHasChanges = true;
e.user.desc = desc;
}
}
}
var away = (e.params[8][0] == "G");
if (e.user.isAway != away)
{
e.userHasChanges = true;
e.user.isAway = away;
}
e.destObject = this.parent;
e.set = "network";
return true;
}
/* end of who */
CIRCServer.prototype.on315 =
function serv_315 (e)
{
e.user = new CIRCUser(this, null, e.params[1]);
e.destObject = this.parent;
e.set = "network";
return true;
}
/* names reply */
CIRCServer.prototype.on353 =
function serv_353 (e)
{
e.channel = new CIRCChannel(this, null, e.params[3]);
if (e.channel.usersStable)
{
e.channel.users = new Object();
e.channel.usersStable = false;
}
e.destObject = e.channel;
e.set = "channel";
var nicks = e.params[4].split (" ");
var mList = this.userModes;
for (var n in nicks)
{
var nick = nicks[n];
if (nick == "")
break;
var modes = new Array();
var multiPrefix = (("namesx" in this.supports) && this.supports.namesx)
|| (("multi-prefix" in this.caps)
&& this.caps["multi-prefix"]);
do
{
var found = false;
for (var m in mList)
{
if (nick[0] == mList[m].symbol)
{
nick = nick.substr(1);
modes.push(mList[m].mode);
found = true;
break;
}
}
} while (found && multiPrefix);
var ary = nick.match(/([^ ]+)!([^ ]+)@(.*)/);
var user = null;
var host = null;
if (this.caps["userhost-in-names"] && ary)
{
nick = ary[1];
user = ary[2];
host = ary[3];
}
new CIRCChanUser(e.channel, null, nick, modes, true, user, host);
}
return true;
}
/* end of names */
CIRCServer.prototype.on366 =
function serv_366 (e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = e.channel;
e.set = "channel";
e.channel.usersStable = true;
return true;
}
/* channel time stamp? */
CIRCServer.prototype.on329 =
function serv_329 (e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = e.channel;
e.set = "channel";
e.channel.timeStamp = new Date (Number(e.params[3]) * 1000);
return true;
}
/* channel mode reply */
CIRCServer.prototype.on324 =
function serv_324 (e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = this;
e.type = "chanmode";
e.destMethod = "onChanMode";
return true;
}
/* channel ban entry */
CIRCServer.prototype.on367 =
function serv_367(e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = e.channel;
e.set = "channel";
e.ban = e.params[3];
e.user = new CIRCUser(this, null, e.params[4]);
e.banTime = new Date (Number(e.params[5]) * 1000);
if (typeof e.channel.bans[e.ban] == "undefined")
{
e.channel.bans[e.ban] = {host: e.ban, user: e.user, time: e.banTime };
var ban_evt = new CEvent("channel", "ban", e.channel, "onBan");
ban_evt.tags = e.tags;
ban_evt.channel = e.channel;
ban_evt.ban = e.ban;
ban_evt.source = e.user;
this.parent.eventPump.addEvent(ban_evt);
}
return true;
}
/* channel ban list end */
CIRCServer.prototype.on368 =
function serv_368(e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = e.channel;
e.set = "channel";
/* This flag is cleared in a timeout (which occurs right after the current
* message has been processed) so that the new event target (the channel)
* will still have the flag set when it executes.
*/
if ("pendingBanList" in e.channel)
setTimeout(function() { delete e.channel.pendingBanList; }, 0);
return true;
}
/* channel except entry */
CIRCServer.prototype.on348 =
function serv_348(e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = e.channel;
e.set = "channel";
e.except = e.params[3];
e.user = new CIRCUser(this, null, e.params[4]);
e.exceptTime = new Date (Number(e.params[5]) * 1000);
if (typeof e.channel.excepts[e.except] == "undefined")
{
e.channel.excepts[e.except] = {host: e.except, user: e.user,
time: e.exceptTime };
}
return true;
}
/* channel except list end */
CIRCServer.prototype.on349 =
function serv_349(e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = e.channel;
e.set = "channel";
if ("pendingExceptList" in e.channel)
setTimeout(function (){ delete e.channel.pendingExceptList; }, 0);
return true;
}
/* don't have operator perms */
CIRCServer.prototype.on482 =
function serv_482(e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = e.channel;
e.set = "channel";
/* Some servers (e.g. Hybrid) don't let you get the except list without ops,
* so we might be waiting for this list forever otherwise.
*/
if ("pendingExceptList" in e.channel)
setTimeout(function (){ delete e.channel.pendingExceptList; }, 0);
return true;
}
/* userhost reply */
CIRCServer.prototype.on302 =
function serv_302(e)
{
var list = e.params[2].split(/\s+/);
for (var i = 0; i < list.length; i++)
{
// <reply> ::= <nick>['*'] '=' <'+'|'-'><hostname>
// '*' == IRCop. '+' == here, '-' == away.
var data = list[i].match(/^(.*)(\*?)=([-+])(.*)@(.*)$/);
if (data)
this.addUser(data[1], data[4], data[5]);
}
e.destObject = this.parent;
e.set = "network";
return true;
}
/* CAP response */
CIRCServer.prototype.onCap =
function my_cap (e)
{
// We expect some sort of identifier.
if (e.params.length < 2)
return;
if (e.params[2] == "LS")
{
/* We're getting a list of all server capabilities. Set them all to
* null (if they don't exist) to indicate we don't know if they're
* enabled or not (but this will evaluate to false which matches that
* capabilities are only enabled on request).
*/
var caps = e.params[3].split(/\s+/);
var multiline = (e.params[3] == "*");
if (multiline)
caps = e.params[4].split(/\s+/);
for (var i = 0; i < caps.length; i++)
{
var [cap, value] = caps[i].split(/=(.+)/);
cap = cap.replace(/^-/, "").trim();
if (!(cap in this.caps))
this.caps[cap] = null;
if (value)
this.capvals[cap] = value;
}
// Don't do anything until the end of the response.
if (multiline)
return true;
//Only request capabilities we support if we are connecting.
if (this.pendingCapNegotiation)
{
// If we have an STS upgrade policy, immediately disconnect
// and reconnect on the secure port.
if (this.parent.STS_MODULE.ENABLED && ("sts" in this.caps) && !this.isSecure)
{
var policy = this.parent.STS_MODULE.parseParameters(this.capvals["sts"]);
if (policy && policy.port)
{
e.stsUpgradePort = policy.port;
e.destObject = this.parent;
e.set = "network";
return false;
}
}
// Request STARTTLS if we are configured to do so.
if (!this.isSecure && ("tls" in this.caps) && this.parent.UPGRADE_INSECURE)
this.sendData("STARTTLS\n");
var caps_req = JSIRCV3_SUPPORTED_CAPS.filter(i => (i in this.caps));
// Don't send requests for these caps.
let caps_noreq = ["tls", "sts", "echo-message"];
if (!this.parent.USE_SASL)
caps_noreq.push("sasl");
caps_req = caps_req.filter(i => caps_noreq.indexOf(i) === -1);
if (caps_req.length > 0)
{
caps_req = caps_req.join(" ");
e.server.sendData("CAP REQ :" + caps_req + "\n");
}
else
{
e.server.sendData("CAP END\n");
delete this.pendingCapNegotiation;
}
}
}
else if (e.params[2] == "LIST")
{
/* Received list of enabled capabilities. Just use this as a sanity
* check. */
var caps = e.params[3].trim().split(/\s+/);
var multiline = (e.params[3] == "*");
if (multiline)
caps = e.params[4].trim().split(/\s+/);
for (var i = 0; i < caps.length; i++)
{
this.caps[caps[i]] = true;
}
// Don't do anything until the end of the response.
if (multiline)
return true;
}
else if (e.params[2] == "ACK")
{
/* One or more capability changes have been successfully applied. An enabled
* capability is just "cap" whilst a disabled capability is "-cap".
*/
var caps = e.params[3].trim().split(/\s+/);
e.capsOn = new Array();
e.capsOff = new Array();
for (var i = 0; i < caps.length; i++)
{
var cap = caps[i].replace(/^-/,"").trim();
var enabled = caps[i][0] != "-";
if (enabled)
e.capsOn.push(cap);
else
e.capsOff.push(cap);
this.caps[cap] = enabled;
}
// Try SASL authentication if we are configured to do so.
if (caps.indexOf("sasl") != -1)
{
var ev = new CEvent("server", "sasl-start", this, "onSASLStart");
ev.server = this;
if (this.capvals["sasl"])
ev.mechs = this.capvals["sasl"].toLowerCase().split(/,/);
ev.destObject = this.parent;
this.parent.eventPump.routeEvent(ev);
if (this.pendingCapNegotiation)
return true;
}
if (this.pendingCapNegotiation)
{
e.server.sendData("CAP END\n");
delete this.pendingCapNegotiation;
//Don't show the raw message while connecting.
return true;
}
}
else if (e.params[2] == "NAK")
{
// A capability change has failed.
var caps = e.params[3].trim().split(/\s+/);
e.caps = new Array();
for (var i = 0; i < caps.length; i++)
{
var cap = caps[i].replace(/^-/, "").trim();
e.caps.push(cap);
}
if (this.pendingCapNegotiation)
{
e.server.sendData("CAP END\n");
delete this.pendingCapNegotiation;
//Don't show the raw message while connecting.
return true;
}
}
else if (e.params[2] == "NEW")
{
// A capability is now available, so request it if we can.
var caps = e.params[3].split(/\s+/);
e.newcaps = [];
for (var i = 0; i < caps.length; i++)
{
var [cap, value] = caps[i].split(/=(.+)/);
cap = cap.trim();
this.caps[cap] = null;
e.newcaps.push(cap);
if (value)
this.capvals[cap] = value;
}
var caps_req = JSIRCV3_SUPPORTED_CAPS.filter(i => (i in e.newcaps));
// Don't send requests for these caps.
caps_noreq = ["tls", "sts", "sasl", "echo-message"];
caps_req = caps_req.filter(i => caps_noreq.indexOf(i) === -1);
if (caps_req.length > 0)
{
caps_req = caps_req.join(" ");
e.server.sendData("CAP REQ :" + caps_req + "\n");
}
}
else if (e.params[2] == "DEL")
{
// A capability is no longer available.
var caps = e.params[3].split(/\s+/);
var caps_nodel = ["sts"];
for (var i = 0; i < caps.length; i++)
{
var cap = caps[i].split(/=(.+)/)[0];
cap = cap.trim();
if (arrayContains(caps_nodel, cap))
continue;
this.caps[cap] = null;
}
}
else
{
dd("Unknown CAP reply " + e.params[2]);
}
e.destObject = this.parent;
e.set = "network";
}
/* BATCH start or end */
CIRCServer.prototype.onBatch =
function serv_batch(e)
{
// We should at least get a ref tag.
if (e.params.length < 2)
return false;
e.reftag = e.params[1].substring(1);
switch (e.params[1][0])
{
case "+":
e.starting = true;
break;
case "-":
e.starting = false;
break;
default:
// Invalid reference tag.
return false;
}
var isPlayback = (this.batches && this.batches[e.reftag] &&
this.batches[e.reftag].playback);
if (!isPlayback)
{
if (e.starting)
{
// We're starting a batch, so we also need a type.
if (e.params.length < 3)
return false;
if (!this.batches)
this.batches = new Object();
// The batch object holds the messages queued up as part
// of this batch, and a boolean value indicating whether
// it is being played back.
var newBatch = new Object();
newBatch.messages = [e];
newBatch.type = e.params[2].toUpperCase();
if (e.params[3] && (e.params[3] in this.channels))
{
newBatch.destObject = this.channels[e.params[3]];
}
else if (e.params[3] && (e.params[3] in this.users))
{
newBatch.destObject = this.users[e.params[3]];
}
else
{
newBatch.destObject = this.parent;
}
newBatch.playback = false;
this.batches[e.reftag] = newBatch;
}
else
{
if (!this.batches[e.reftag])
{
// Got a close tag without an open tag, so ignore it.
return false;
}
var batch = this.batches[e.reftag];
// Closing the batch, prepare for playback.
batch.messages.push(e);
batch.playback = true;
if (e.tags["batch"])
{
// We are an inner batch. Append the message queue
// to the outer batch's message queue.
var parentRef = e.tags["batch"];
var parentMsgs = this.batches[parentRef].messages;
parentMsgs = parentMsgs.concat(batch.messages);
}
else
{
// We are an outer batch. Playback!
for (var i = 0; i < batch.messages.length; i++)
{
var ev = batch.messages[i];
ev.type = "parseddata";
ev.destObject = this;
ev.destMethod = "onParsedData";
this.parent.eventPump.routeEvent(ev);
}
}
}
return false;
}
else
{
// Batch command is ready for handling.
e.batchtype = this.batches[e.reftag].type;
e.destObject = this.batches[e.reftag].destObject;
if (e.destObject.TYPE == "CIRCChannel")
{
e.set = "channel";
}
else
{
e.set = "network";
}
if (!e.starting)
{
// If we've reached the end of a batch in playback,
// do some cleanup.
delete this.batches[e.reftag];
if (Object.entries(this.batches).length == 0)
delete this.batches;
}
// Massage the batchtype into a method name for handlers:
// netsplit - onNetsplitBatch
// some-batch-type - onSomeBatchTypeBatch
// example.com/example - onExampleComExampleBatch
var batchCode = e.batchtype.split(/[\.\/-]/).map(function(s)
{
return s[0].toUpperCase() + s.substr(1).toLowerCase();
}).join("");
e.destMethod = "on" + batchCode + "Batch";
if (!e.destObject[e.destMethod])
e.destMethod = "onUnknownBatch";
}
}
/* SASL authentication responses */
CIRCServer.prototype.on902 = /* Nick locked */
CIRCServer.prototype.on903 = /* Auth success */
CIRCServer.prototype.on904 = /* Auth failed */
CIRCServer.prototype.on905 = /* Command too long */
CIRCServer.prototype.on906 = /* Aborted */
CIRCServer.prototype.on907 = /* Already authenticated */
CIRCServer.prototype.on908 = /* Mechanisms */
function cap_on900(e)
{
if (this.pendingCapNegotiation)
{
delete this.pendingCapNegotiation;
this.sendData("CAP END\n");
}
if (e.code == "908")
{
// Update our list of SASL mechanics.
this.capvals["sasl"] = e.params[2];
}
e.destObject = this.parent;
e.set = "network";
}
/* STARTTLS responses */
CIRCServer.prototype.on670 = /* Success */
function cap_on670(e)
{
this.caps["tls"] = true;
e.server.connection.startTLS();
e.server.isSecure = true;
e.server.isStartTLS = true;
e.destObject = this.parent;
e.set = "network";
}
CIRCServer.prototype.on691 = /* Failure */
function cap_on691(e)
{
this.caps["tls"] = false;
e.destObject = this.parent;
e.set = "network";
}
/* User away status changed */
CIRCServer.prototype.onAway =
function serv_away(e)
{
e.user.isAway = e.params[1] ? true : false;
e.destObject = this.parent;
e.set = "network";
}
/* User host changed */
CIRCServer.prototype.onChghost =
function serv_chghost(e)
{
this.users[e.user.collectionKey].name = e.params[1];
this.users[e.user.collectionKey].host = e.params[2];
e.destObject = this.parent;
e.set = "network";
}
/* user changed the mode */
CIRCServer.prototype.onMode =
function serv_mode (e)
{
e.destObject = this;
/* modes are not allowed in +channels -> no need to test that here.. */
if (arrayIndexOf(this.channelTypes, e.params[1][0]) != -1)
{
e.channel = new CIRCChannel(this, null, e.params[1]);
if ("user" in e && e.user)
e.user = new CIRCChanUser(e.channel, e.user.unicodeName);
e.type = "chanmode";
e.destMethod = "onChanMode";
}
else
{
e.type = "usermode";
e.destMethod = "onUserMode";
}
return true;
}
CIRCServer.prototype.onUserMode =
function serv_usermode (e)
{
e.user = new CIRCUser(this, null, e.params[1])
e.user.modestr = e.params[2];
e.destObject = this.parent;
e.set = "network";
// usermode usually happens on connect, after the MOTD, so it's a good
// place to kick off the lag timer.
this.updateLagTimer();
return true;
}
CIRCServer.prototype.onChanMode =
function serv_chanmode (e)
{
var modifier = "";
var params_eaten = 0;
var BASE_PARAM;
if (e.code.toUpperCase() == "MODE")
BASE_PARAM = 2;
else
if (e.code == "324")
BASE_PARAM = 3;
else
{
dd ("** INVALID CODE in ChanMode event **");
return false;
}
var mode_str = e.params[BASE_PARAM];
params_eaten++;
e.modeStr = mode_str;
e.usersAffected = new Array();
var nick;
var user;
var umList = this.userModes;
var cmList = this.channelModes;
var modeMap = this.canonicalChanModes;
var canonicalModeValue;
for (var i = 0; i < mode_str.length ; i++)
{
/* Take care of modifier first. */
if ((mode_str[i] == '+') || (mode_str[i] == '-'))
{
modifier = mode_str[i];
continue;
}
var done = false;
for (var m in umList)
{
if ((mode_str[i] == umList[m].mode) && (modifier != ""))
{
nick = e.params[BASE_PARAM + params_eaten];
user = new CIRCChanUser(e.channel, null, nick,
[ modifier + umList[m].mode ]);
params_eaten++;
e.usersAffected.push (user);
done = true;
break;
}
}
if (done)
continue;
// Update legacy canonical modes if necessary.
if (mode_str[i] in modeMap)
{
// Get the data in case we need it, but don't increment the counter.
var datacounter = BASE_PARAM + params_eaten;
var data = (datacounter in e.params) ? e.params[datacounter] : null;
canonicalModeValue = modeMap[mode_str[i]].getValue(modifier, data);
e.channel.mode[modeMap[mode_str[i]].name] = canonicalModeValue;
}
if (arrayContains(cmList.a, mode_str[i]))
{
var data = e.params[BASE_PARAM + params_eaten++];
if (modifier == "+")
{
e.channel.mode.modeA[data] = true;
}
else
{
if (data in e.channel.mode.modeA)
{
delete e.channel.mode.modeA[data];
}
else
{
dd("** Trying to remove channel mode '" + mode_str[i] +
"'/'" + data + "' which does not exist in list.");
}
}
}
else if (arrayContains(cmList.b, mode_str[i]))
{
var data = e.params[BASE_PARAM + params_eaten++];
if (modifier == "+")
{
e.channel.mode.modeB[mode_str[i]] = data;
}
else
{
// Save 'null' even though we have some data.
e.channel.mode.modeB[mode_str[i]] = null;
}
}
else if (arrayContains(cmList.c, mode_str[i]))
{
if (modifier == "+")
{
var data = e.params[BASE_PARAM + params_eaten++];
e.channel.mode.modeC[mode_str[i]] = data;
}
else
{
e.channel.mode.modeC[mode_str[i]] = null;
}
}
else if (arrayContains(cmList.d, mode_str[i]))
{
e.channel.mode.modeD[mode_str[i]] = (modifier == "+");
}
else
{
dd("** UNKNOWN mode symbol '" + mode_str[i] + "' in ChanMode event **");
}
}
e.destObject = e.channel;
e.set = "channel";
return true;
}
CIRCServer.prototype.onNick =
function serv_nick (e)
{
var newNick = e.params[1];
var newKey = ":" + this.toLowerCase(newNick);
var oldKey = e.user.collectionKey;
var ev;
renameProperty (this.users, oldKey, newKey);
e.oldNick = e.user.unicodeName;
e.user.changeNick(toUnicode(newNick, this));
for (var c in this.channels)
{
if (this.channels[c].active &&
((oldKey in this.channels[c].users) || e.user == this.me))
{
var cuser = this.channels[c].users[oldKey];
renameProperty (this.channels[c].users, oldKey, newKey);
// User must be a channel user, update sort name for userlist,
// before we route the event further:
cuser.updateSortName();
ev = new CEvent ("channel", "nick", this.channels[c], "onNick");
ev.tags = e.tags;
ev.channel = this.channels[c];
ev.user = cuser;
ev.server = this;
ev.oldNick = e.oldNick;
this.parent.eventPump.routeEvent(ev);
}
}
if (e.user == this.me)
{
/* if it was me, tell the network about the nick change as well */
ev = new CEvent ("network", "nick", this.parent, "onNick");
ev.tags = e.tags;
ev.user = e.user;
ev.server = this;
ev.oldNick = e.oldNick;
this.parent.eventPump.routeEvent(ev);
}
e.destObject = e.user;
e.set = "user";
return true;
}
CIRCServer.prototype.onQuit =
function serv_quit (e)
{
var reason = e.decodeParam(1);
for (var c in e.server.channels)
{
if (e.server.channels[c].active &&
e.user.collectionKey in e.server.channels[c].users)
{
var ev = new CEvent ("channel", "quit", e.server.channels[c],
"onQuit");
ev.tags = e.tags;
ev.user = e.server.channels[c].users[e.user.collectionKey];
ev.channel = e.server.channels[c];
ev.server = ev.channel.parent;
ev.reason = reason;
this.parent.eventPump.routeEvent(ev);
delete e.server.channels[c].users[e.user.collectionKey];
}
}
this.users[e.user.collectionKey].lastQuitMessage = reason;
this.users[e.user.collectionKey].lastQuitDate = new Date();
// 0 == prune onQuit.
if (this.PRUNE_OLD_USERS == 0)
delete this.users[e.user.collectionKey];
e.reason = reason;
e.destObject = e.user;
e.set = "user";
return true;
}
CIRCServer.prototype.onPart =
function serv_part (e)
{
e.channel = new CIRCChannel(this, null, e.params[1]);
e.reason = (e.params.length > 2) ? e.decodeParam(2, e.channel) : "";
e.user = new CIRCChanUser(e.channel, e.user.unicodeName);
if (userIsMe(e.user))
{
e.channel.active = false;
e.channel.joined = false;
}
e.channel.removeUser(e.user.encodedName);
e.destObject = e.channel;
e.set = "channel";
return true;
}
CIRCServer.prototype.onKick =
function serv_kick (e)
{
e.channel = new CIRCChannel(this, null, e.params[1]);
e.lamer = new CIRCChanUser(e.channel, null, e.params[2]);
delete e.channel.users[e.lamer.collectionKey];
if (userIsMe(e.lamer))
{
e.channel.active = false;
e.channel.joined = false;
}
e.reason = e.decodeParam(3, e.channel);
e.destObject = e.channel;
e.set = "channel";
return true;
}
CIRCServer.prototype.onJoin =
function serv_join(e)
{
e.channel = new CIRCChannel(this, null, e.params[1]);
// Passing undefined here because CIRCChanUser doesn't like "null"
e.user = new CIRCChanUser(e.channel, e.user.unicodeName, null,
undefined, true);
if (e.params[2] && e.params[3])
{
var account = (e.params[2] == "*" ? null : e.params[2]);
var desc = e.decodeParam([3], e.user);
this.users[e.user.collectionKey].account = account;
this.users[e.user.collectionKey].desc = desc;
}
if (userIsMe(e.user))
{
var delayFn1 = function(t) {
if (!e.channel.active)
return;
// Give us the channel mode!
e.server.sendData("MODE " + e.channel.encodedName + "\n");
};
// Between 1s - 3s.
setTimeout(delayFn1, 1000 + 2000 * Math.random(), this);
var delayFn2 = function(t) {
if (!e.channel.active)
return;
// Get a full list of bans and exceptions, if supported.
if (arrayContains(t.channelModes.a, "b"))
{
e.server.sendData("MODE " + e.channel.encodedName + " +b\n");
e.channel.pendingBanList = true;
}
if (arrayContains(t.channelModes.a, "e"))
{
e.server.sendData("MODE " + e.channel.encodedName + " +e\n");
e.channel.pendingExceptList = true;
}
//If away-notify is active, query the list of users for away status.
if (e.server.caps["away-notify"])
{
// If the server supports extended who, use it.
// This lets us initialize the account property.
if (e.server.supports["whox"])
e.server.who(e.channel.unicodeName + " %acdfhnrstu," + e.server.WHOX_TYPE);
else
e.server.who(e.channel.unicodeName);
}
};
// Between 10s - 20s.
setTimeout(delayFn2, 10000 + 10000 * Math.random(), this);
/* Clean up the topic, since servers don't always send RPL_NOTOPIC
* (no topic set) when joining a channel without a topic. In fact,
* the RFC even fails to mention sending a RPL_NOTOPIC after a join!
*/
e.channel.topic = "";
e.channel.topicBy = null;
e.channel.topicDate = null;
// And we're in!
e.channel.active = true;
e.channel.joined = true;
}
e.destObject = e.channel;
e.set = "channel";
return true;
}
CIRCServer.prototype.onAccount =
function serv_acct(e)
{
var account = (e.params[1] == "*" ? null : e.params[1]);
this.users[e.user.collectionKey].account = account;
return true;
}
CIRCServer.prototype.onPing =
function serv_ping (e)
{
/* non-queued send, so we can calcualte lag */
this.connection.sendData("PONG :" + e.params[1] + "\n");
this.updateLagTimer();
e.destObject = this.parent;
e.set = "network";
return true;
}
CIRCServer.prototype.onPong =
function serv_pong (e)
{
if (e.params[2] != "LAGTIMER")
return true;
if (this.lastPingSent)
this.lag = (new Date() - this.lastPingSent) / 1000;
this.lastPingSent = null;
e.destObject = this.parent;
e.set = "network";
return true;
}
CIRCServer.prototype.onInvite =
function serv_invite(e)
{
e.channel = new CIRCChannel(this, null, e.params[2]);
e.destObject = this.parent;
e.set = "network";
}
CIRCServer.prototype.onNotice =
CIRCServer.prototype.onPrivmsg =
CIRCServer.prototype.onTagmsg =
function serv_notice_privmsg (e)
{
var targetName = e.params[1];
if (this.userModes)
{
// Strip off one (and only one) user mode prefix.
for (var i = 0; i < this.userModes.length; i++)
{
if (targetName[0] == this.userModes[i].symbol)
{
e.msgPrefix = this.userModes[i];
targetName = targetName.substr(1);
break;
}
}
}
/* setting replyTo provides a standard place to find the target for */
/* replies associated with this event. */
if (arrayIndexOf(this.channelTypes, targetName[0]) != -1)
{
e.channel = new CIRCChannel(this, null, targetName);
if ("user" in e)
e.user = new CIRCChanUser(e.channel, e.user.unicodeName);
e.replyTo = e.channel;
e.set = "channel";
}
else if (!("user" in e))
{
e.set = "network";
e.destObject = this.parent;
return true;
}
else
{
e.set = "user";
e.replyTo = e.user; /* send replies to the user who sent the message */
}
/* The capability identify-msg adds a + or - in front the message to
* indicate their network registration status.
*/
if (("identify-msg" in this.caps) && this.caps["identify-msg"])
{
e.identifyMsg = false;
var flag = e.params[2].substring(0,1);
if (flag == "+")
{
e.identifyMsg = true;
e.params[2] = e.params[2].substring(1);
}
else if (flag == "-")
{
e.params[2] = e.params[2].substring(1);
}
else
{
// Just print to console on failure - or we'd spam the user
dd("Warning: IDENTIFY-MSG is on, but there's no message flags");
}
}
// TAGMSG doesn't have a message parameter, so just pass it on.
if (e.code == "TAGMSG")
{
e.destObject = e.replyTo;
return true;
}
if (e.params[2].search (/^\x01[^ ]+.*\x01$/) != -1)
{
if (e.code == "NOTICE")
{
e.type = "ctcp-reply";
e.destMethod = "onCTCPReply";
}
else // e.code == "PRIVMSG"
{
e.type = "ctcp";
e.destMethod = "onCTCP";
}
e.set = "server";
e.destObject = this;
}
else
{
e.msg = e.decodeParam(2, e.replyTo);
e.destObject = e.replyTo;
}
return true;
}
CIRCServer.prototype.onWallops =
function serv_wallops(e)
{
if (("user" in e) && e.user)
{
e.msg = e.decodeParam(1, e.user);
e.replyTo = e.user;
}
else
{
e.msg = e.decodeParam(1);
e.replyTo = this;
}
e.destObject = this.parent;
e.set = "network";
return true;
}
CIRCServer.prototype.onCTCPReply =
function serv_ctcpr (e)
{
var ary = e.params[2].match (/^\x01([^ ]+) ?(.*)\x01$/i);
if (ary == null)
return false;
e.CTCPData = ary[2] ? ary[2] : "";
e.CTCPCode = ary[1].toLowerCase();
e.type = "ctcp-reply-" + e.CTCPCode;
e.destMethod = "onCTCPReply" + ary[1][0].toUpperCase() +
ary[1].substr (1, ary[1].length).toLowerCase();
if (typeof this[e.destMethod] != "function")
{ /* if there's no place to land the event here, try to forward it */
e.destObject = this.parent;
e.set = "network";
if (typeof e.destObject[e.destMethod] != "function")
{ /* if there's no place to forward it, send it to unknownCTCP */
e.type = "unk-ctcp-reply";
e.destMethod = "onUnknownCTCPReply";
if (e.destMethod in this)
{
e.set = "server";
e.destObject = this;
}
else
{
e.set = "network";
e.destObject = this.parent;
}
}
}
else
e.destObject = this;
return true;
}
CIRCServer.prototype.onCTCP =
function serv_ctcp (e)
{
var ary = e.params[2].match (/^\x01([^ ]+) ?(.*)\x01$/i);
if (ary == null)
return false;
e.CTCPData = ary[2] ? ary[2] : "";
e.CTCPCode = ary[1].toLowerCase();
if (e.CTCPCode.search (/^reply/i) == 0)
{
dd ("dropping spoofed reply.");
return false;
}
e.CTCPCode = toUnicode(e.CTCPCode, e.replyTo);
e.CTCPData = toUnicode(e.CTCPData, e.replyTo);
e.type = "ctcp-" + e.CTCPCode;
e.destMethod = "onCTCP" + ary[1][0].toUpperCase() +
ary[1].substr (1, ary[1].length).toLowerCase();
if (typeof this[e.destMethod] != "function")
{ /* if there's no place to land the event here, try to forward it */
e.destObject = e.replyTo;
e.set = (e.replyTo == e.user) ? "user" : "channel";
if (typeof e.replyTo[e.destMethod] != "function")
{ /* if there's no place to forward it, send it to unknownCTCP */
e.type = "unk-ctcp";
e.destMethod = "onUnknownCTCP";
}
}
else
e.destObject = this;
var ev = new CEvent("server", "ctcp-receive", this, "onReceiveCTCP");
ev.tags = e.tags;
ev.server = this;
ev.CTCPCode = e.CTCPCode;
ev.CTCPData = e.CTCPData;
ev.type = e.type;
ev.user = e.user;
ev.destObject = this.parent;
this.parent.eventPump.addEvent(ev);
return true;
}
CIRCServer.prototype.onCTCPClientinfo =
function serv_ccinfo (e)
{
var clientinfo = new Array();
if (e.CTCPData)
{
var cmdName = "onCTCP" + e.CTCPData[0].toUpperCase() +
e.CTCPData.substr (1, e.CTCPData.length).toLowerCase();
var helpName = cmdName.replace(/^onCTCP/, "CTCPHelp");
// Check we support the command.
if (cmdName in this)
{
// Do we have help for it?
if (helpName in this)
{
var msg;
if (typeof this[helpName] == "function")
msg = this[helpName]();
else
msg = this[helpName];
e.user.ctcp("CLIENTINFO", msg, "NOTICE");
}
else
{
e.user.ctcp("CLIENTINFO",
getMsg(MSG_ERR_NO_CTCP_HELP, e.CTCPData), "NOTICE");
}
}
else
{
e.user.ctcp("CLIENTINFO",
getMsg(MSG_ERR_NO_CTCP_CMD, e.CTCPData), "NOTICE");
}
return true;
}
for (var fname in this)
{
var ary = fname.match(/^onCTCP(.+)/);
if (ary && ary[1].search(/^Reply/) == -1)
clientinfo.push (ary[1].toUpperCase());
}
e.user.ctcp("CLIENTINFO", clientinfo.join(" "), "NOTICE");
return true;
}
CIRCServer.prototype.onCTCPAction =
function serv_cact (e)
{
e.destObject = e.replyTo;
e.set = (e.replyTo == e.user) ? "user" : "channel";
}
CIRCServer.prototype.onCTCPFinger =
function serv_cfinger (e)
{
e.user.ctcp("FINGER", this.parent.INITIAL_DESC, "NOTICE");
return true;
}
CIRCServer.prototype.onCTCPTime =
function serv_cping (e)
{
e.user.ctcp("TIME", new Date(), "NOTICE");
return true;
}
CIRCServer.prototype.onCTCPVersion =
function serv_cver (e)
{
var lines = e.server.VERSION_RPLY.split ("\n");
for (var i in lines)
e.user.ctcp("VERSION", lines[i], "NOTICE");
e.destObject = e.replyTo;
e.set = (e.replyTo == e.user) ? "user" : "channel";
return true;
}
CIRCServer.prototype.onCTCPSource =
function serv_csrc (e)
{
e.user.ctcp("SOURCE", this.SOURCE_RPLY, "NOTICE");
return true;
}
CIRCServer.prototype.onCTCPOs =
function serv_os(e)
{
e.user.ctcp("OS", this.OS_RPLY, "NOTICE");
return true;
}
CIRCServer.prototype.onCTCPHost =
function serv_host(e)
{
e.user.ctcp("HOST", this.HOST_RPLY, "NOTICE");
return true;
}
CIRCServer.prototype.onCTCPPing =
function serv_cping (e)
{
/* non-queued send */
this.connection.sendData("NOTICE " + e.user.encodedName + " :\01PING " +
e.CTCPData + "\01\n");
e.destObject = e.replyTo;
e.set = (e.replyTo == e.user) ? "user" : "channel";
return true;
}
CIRCServer.prototype.onCTCPDcc =
function serv_dcc (e)
{
var ary = e.CTCPData.match (/([^ ]+)? ?(.*)/);
e.DCCData = ary[2];
e.type = "dcc-" + ary[1].toLowerCase();
e.destMethod = "onDCC" + ary[1][0].toUpperCase() +
ary[1].substr (1, ary[1].length).toLowerCase();
if (typeof this[e.destMethod] != "function")
{ /* if there's no place to land the event here, try to forward it */
e.destObject = e.replyTo;
e.set = (e.replyTo == e.user) ? "user" : "channel";
}
else
e.destObject = this;
return true;
}
CIRCServer.prototype.onDCCChat =
function serv_dccchat (e)
{
var ary = e.DCCData.match (/(chat) (\d+) (\d+)/i);
if (ary == null)
return false;
e.id = ary[2];
// Longword --> dotted IP conversion.
var host = Number(e.id);
e.host = ((host >> 24) & 0xFF) + "." +
((host >> 16) & 0xFF) + "." +
((host >> 8) & 0xFF) + "." +
(host & 0xFF);
e.port = Number(ary[3]);
e.destObject = e.replyTo;
e.set = (e.replyTo == e.user) ? "user" : "channel";
return true;
}
CIRCServer.prototype.onDCCSend =
function serv_dccsend (e)
{
var ary = e.DCCData.match(/([^ ]+) (\d+) (\d+) (\d+)/);
/* Just for mIRC: filenames with spaces may be enclosed in double-quotes.
* (though by default it replaces spaces with underscores, but we might as
* well cope). */
if ((ary[1][0] == '"') || (ary[1][ary[1].length - 1] == '"'))
ary = e.DCCData.match(/"(.+)" (\d+) (\d+) (\d+)/);
if (ary == null)
return false;
e.file = ary[1];
e.id = ary[2];
// Longword --> dotted IP conversion.
var host = Number(e.id);
e.host = ((host >> 24) & 0xFF) + "." +
((host >> 16) & 0xFF) + "." +
((host >> 8) & 0xFF) + "." +
(host & 0xFF);
e.port = Number(ary[3]);
e.size = Number(ary[4]);
e.destObject = e.replyTo;
e.set = (e.replyTo == e.user) ? "user" : "channel";
return true;
}
function CIRCChannel(parent, unicodeName, encodedName)
{
// Both unicodeName and encodedName are optional, but at least one must be
// present.
if (!encodedName && !unicodeName)
throw "Hey! Come on, I need either an encoded or a Unicode name.";
if (!encodedName)
encodedName = fromUnicode(unicodeName, parent);
let collectionKey = ":" + parent.toLowerCase(encodedName);
if (collectionKey in parent.channels)
return parent.channels[collectionKey];
this.parent = parent;
this.encodedName = encodedName;
this.canonicalName = collectionKey.substr(1);
this.collectionKey = collectionKey;
this.unicodeName = unicodeName || toUnicode(encodedName, this);
this.viewName = this.unicodeName;
this.users = new Object();
this.bans = new Object();
this.excepts = new Object();
this.mode = new CIRCChanMode(this);
this.usersStable = true;
/* These next two flags represent a subtle difference in state:
* active - in the channel, from the server's point of view.
* joined - in the channel, from the user's point of view.
* e.g. parting the channel clears both, but being disconnected only
* clears |active| - the user still wants to be in the channel, even
* though they aren't physically able to until we've reconnected.
*/
this.active = false;
this.joined = false;
this.parent.channels[this.collectionKey] = this;
if ("onInit" in this)
this.onInit();
return this;
}
CIRCChannel.prototype.TYPE = "IRCChannel";
CIRCChannel.prototype.topic = "";
// Returns the IRC URL representation of this channel.
CIRCChannel.prototype.getURL =
function chan_geturl()
{
var target = this.encodedName;
var flags = this.mode.key ? ["needkey"] : [];
if ((target[0] == "#") && (target.length > 1) &&
arrayIndexOf(this.parent.channelTypes, target[1]) == -1)
{
/* First character is "#" (which we're allowed to omit), and the
* following character is NOT a valid prefix, so it's safe to remove.
*/
target = target.substr(1);
}
return this.parent.parent.getURL(target, flags);
}
CIRCChannel.prototype.rehome =
function chan_rehome(newParent)
{
delete this.parent.channels[this.collectionKey];
this.parent = newParent;
this.parent.channels[this.collectionKey] = this;
}
CIRCChannel.prototype.addUser =
function chan_adduser (unicodeName, modes)
{
return new CIRCChanUser(this, unicodeName, null, modes);
}
CIRCChannel.prototype.getUser =
function chan_getuser(nick)
{
// Try assuming it's an encodedName first.
let tnick = ":" + this.parent.toLowerCase(nick);
if (tnick in this.users)
return this.users[tnick];
// Ok, failed, so try assuming it's a unicodeName.
tnick = ":" + this.parent.toLowerCase(fromUnicode(nick, this.parent));
if (tnick in this.users)
return this.users[tnick];
return null;
}
CIRCChannel.prototype.removeUser =
function chan_removeuser(nick)
{
// Try assuming it's an encodedName first.
let key = ":" + this.parent.toLowerCase(nick);
if (key in this.users)
delete this.users[key]; // see ya
// Ok, failed, so try assuming it's a unicodeName.
key = ":" + this.parent.toLowerCase(fromUnicode(nick, this.parent));
if (key in this.users)
delete this.users[key];
}
CIRCChannel.prototype.getUsersLength =
function chan_userslen (mode)
{
var i = 0;
var p;
this.opCount = 0;
this.halfopCount = 0;
this.voiceCount = 0;
if (typeof mode == "undefined")
{
for (p in this.users)
{
if (this.users[p].isOp)
this.opCount++;
if (this.users[p].isHalfOp)
this.halfopCount++;
if (this.users[p].isVoice)
this.voiceCount++;
i++;
}
}
else
{
for (p in this.users)
if (arrayContains(this.users[p].modes, mode))
i++;
}
return i;
}
CIRCChannel.prototype.iAmOp =
function chan_amop()
{
return this.active && this.users[this.parent.me.collectionKey].isOp;
}
CIRCChannel.prototype.iAmHalfOp =
function chan_amhalfop()
{
return this.active && this.users[this.parent.me.collectionKey].isHalfOp;
}
CIRCChannel.prototype.iAmVoice =
function chan_amvoice()
{
return this.active && this.users[this.parent.me.collectionKey].isVoice;
}
CIRCChannel.prototype.setTopic =
function chan_topic (str)
{
this.parent.sendData ("TOPIC " + this.encodedName + " :" +
fromUnicode(str, this) + "\n");
}
CIRCChannel.prototype.say =
function chan_say (msg)
{
this.parent.sayTo(this.encodedName, fromUnicode(msg, this));
}
CIRCChannel.prototype.act =
function chan_say (msg)
{
this.parent.actTo(this.encodedName, fromUnicode(msg, this));
}
CIRCChannel.prototype.notice =
function chan_notice (msg)
{
this.parent.noticeTo(this.encodedName, fromUnicode(msg, this));
}
CIRCChannel.prototype.ctcp =
function chan_ctcpto (code, msg, type)
{
msg = msg || "";
type = type || "PRIVMSG";
this.parent.ctcpTo(this.encodedName, fromUnicode(code, this),
fromUnicode(msg, this), type);
}
CIRCChannel.prototype.join =
function chan_join (key)
{
if (!key)
key = "";
this.parent.sendData ("JOIN " + this.encodedName + " " + key + "\n");
return true;
}
CIRCChannel.prototype.part =
function chan_part (reason)
{
if (!reason)
reason = "";
this.parent.sendData ("PART " + this.encodedName + " :" +
fromUnicode(reason, this) + "\n");
this.users = new Object();
return true;
}
/**
* Invites a user to a channel.
*
* @param nick the user name to invite.
*/
CIRCChannel.prototype.invite =
function chan_inviteuser (nick)
{
var rawNick = fromUnicode(nick, this.parent);
this.parent.sendData("INVITE " + rawNick + " " + this.encodedName + "\n");
return true;
}
CIRCChannel.prototype.findUsers =
function chan_findUsers(mask)
{
var ary = [];
var unchecked = 0;
mask = getHostmaskParts(mask);
for (var nick in this.users)
{
var user = this.users[nick];
if (!user.host || !user.name)
unchecked++;
else if (hostmaskMatches(user, mask))
ary.push(user);
}
return { users: ary, unchecked: unchecked };
}
/**
* Stores a channel's current mode settings.
*
* You should never need to create an instance of this prototype; access the
* channel mode information through the |CIRCChannel.mode| property.
*
* @param parent The |CIRCChannel| to which this mode belongs.
*/
function CIRCChanMode (parent)
{
this.parent = parent;
this.modeA = new Object();
this.modeB = new Object();
this.modeC = new Object();
this.modeD = new Object();
this.invite = false;
this.moderated = false;
this.publicMessages = true;
this.publicTopic = true;
this.secret = false;
this.pvt = false;
this.key = "";
this.limit = -1;
}
CIRCChanMode.prototype.TYPE = "IRCChanMode";
// Returns the complete mode string, as constructed from its component parts.
CIRCChanMode.prototype.getModeStr =
function chan_modestr (f)
{
var str = "";
var modeCparams = "";
/* modeA are 'list' ones, and so should not be shown.
* modeB are 'param' ones, like +k key, so we wont show them either.
* modeC are 'on-param' ones, like +l limit, which we will show.
* modeD are 'boolean' ones, which we will definitely show.
*/
// Add modeD:
for (var m in this.modeD)
{
if (this.modeD[m])
str += m;
}
// Add modeC, save parameters for adding all the way at the end:
for (var m in this.modeC)
{
if (this.modeC[m])
{
str += m;
modeCparams += " " + this.modeC[m];
}
}
// Add parameters:
if (str)
str = "+" + str + modeCparams;
return str;
}
// Sends the given mode string to the server with the channel pre-filled.
CIRCChanMode.prototype.setMode =
function chanm_mode (modestr)
{
this.parent.parent.sendData ("MODE " + this.parent.encodedName + " " +
modestr + "\n");
return true;
}
// Sets (|n| > 0) or clears (|n| <= 0) the user count limit.
CIRCChanMode.prototype.setLimit =
function chanm_limit (n)
{
if ((typeof n == "undefined") || (n <= 0))
{
this.parent.parent.sendData("MODE " + this.parent.encodedName +
" -l\n");
}
else
{
this.parent.parent.sendData("MODE " + this.parent.encodedName + " +l " +
Number(n) + "\n");
}
return true;
}
// Locks the channel with a given key.
CIRCChanMode.prototype.lock =
function chanm_lock (k)
{
this.parent.parent.sendData("MODE " + this.parent.encodedName + " +k " +
k + "\n");
return true;
}
// Unlocks the channel with a given key.
CIRCChanMode.prototype.unlock =
function chan_unlock (k)
{
this.parent.parent.sendData("MODE " + this.parent.encodedName + " -k " +
k + "\n");
return true;
}
// Sets or clears the moderation mode.
CIRCChanMode.prototype.setModerated =
function chan_moderate (f)
{
var modifier = (f) ? "+" : "-";
this.parent.parent.sendData("MODE " + this.parent.encodedName + " " +
modifier + "m\n");
return true;
}
// Sets or clears the allow public messages mode.
CIRCChanMode.prototype.setPublicMessages =
function chan_pmessages (f)
{
var modifier = (f) ? "-" : "+";
this.parent.parent.sendData("MODE " + this.parent.encodedName + " " +
modifier + "n\n");
return true;
}
// Sets or clears the public topic mode.
CIRCChanMode.prototype.setPublicTopic =
function chan_ptopic (f)
{
var modifier = (f) ? "-" : "+";
this.parent.parent.sendData("MODE " + this.parent.encodedName + " " +
modifier + "t\n");
return true;
}
// Sets or clears the invite-only mode.
CIRCChanMode.prototype.setInvite =
function chan_invite (f)
{
var modifier = (f) ? "+" : "-";
this.parent.parent.sendData("MODE " + this.parent.encodedName + " " +
modifier + "i\n");
return true;
}
// Sets or clears the private channel mode.
CIRCChanMode.prototype.setPvt =
function chan_pvt (f)
{
var modifier = (f) ? "+" : "-";
this.parent.parent.sendData("MODE " + this.parent.encodedName + " " +
modifier + "p\n");
return true;
}
// Sets or clears the secret channel mode.
CIRCChanMode.prototype.setSecret =
function chan_secret (f)
{
var modifier = (f) ? "+" : "-";
this.parent.parent.sendData("MODE " + this.parent.encodedName + " " +
modifier + "s\n");
return true;
}
function CIRCUser(parent, unicodeName, encodedName, name, host)
{
// Both unicodeName and encodedName are optional, but at least one must be
// present.
if (!encodedName && !unicodeName)
throw "Hey! Come on, I need either an encoded or a Unicode name.";
if (!encodedName)
encodedName = fromUnicode(unicodeName, parent);
let collectionKey = ":" + parent.toLowerCase(encodedName);
if (collectionKey in parent.users)
{
let existingUser = parent.users[collectionKey];
if (name)
existingUser.name = name;
if (host)
existingUser.host = host;
return existingUser;
}
this.parent = parent;
this.encodedName = encodedName;
this.canonicalName = collectionKey.substr(1);
this.collectionKey = collectionKey;
this.unicodeName = unicodeName || toUnicode(encodedName, this.parent);
this.viewName = this.unicodeName;
this.name = name;
this.host = host;
this.desc = "";
this.account = null;
this.connectionHost = null;
this.isAway = false;
this.modestr = this.parent.parent.INITIAL_UMODE;
this.parent.users[this.collectionKey] = this;
if ("onInit" in this)
this.onInit();
return this;
}
CIRCUser.prototype.TYPE = "IRCUser";
// Returns the IRC URL representation of this user.
CIRCUser.prototype.getURL =
function usr_geturl()
{
return this.parent.parent.getURL(this.encodedName, ["isnick"]);
}
CIRCUser.prototype.rehome =
function usr_rehome(newParent)
{
delete this.parent.users[this.collectionKey];
this.parent = newParent;
this.parent.users[this.collectionKey] = this;
}
CIRCUser.prototype.changeNick =
function usr_changenick(unicodeName)
{
this.unicodeName = unicodeName;
this.viewName = this.unicodeName;
this.encodedName = fromUnicode(this.unicodeName, this.parent);
this.canonicalName = this.parent.toLowerCase(this.encodedName);
this.collectionKey = ":" + this.canonicalName;
}
CIRCUser.prototype.getHostMask =
function usr_hostmask (pfx)
{
pfx = (typeof pfx != "undefined") ? pfx : "*!" + this.name + "@*.";
var idx = this.host.indexOf(".");
if (idx == -1)
return pfx + this.host;
return (pfx + this.host.substr(idx + 1, this.host.length));
}
CIRCUser.prototype.getBanMask =
function usr_banmask()
{
if (!this.host)
return this.unicodeName + "!*@*";
return "*!*@" + this.host;
}
CIRCUser.prototype.say =
function usr_say (msg)
{
this.parent.sayTo(this.encodedName, fromUnicode(msg, this));
}
CIRCUser.prototype.notice =
function usr_notice (msg)
{
this.parent.noticeTo(this.encodedName, fromUnicode(msg, this));
}
CIRCUser.prototype.act =
function usr_act (msg)
{
this.parent.actTo(this.encodedName, fromUnicode(msg, this));
}
CIRCUser.prototype.ctcp =
function usr_ctcp (code, msg, type)
{
msg = msg || "";
type = type || "PRIVMSG";
this.parent.ctcpTo(this.encodedName, fromUnicode(code, this),
fromUnicode(msg, this), type);
}
CIRCUser.prototype.whois =
function usr_whois ()
{
this.parent.whois(this.unicodeName);
}
/*
* channel user
*/
function CIRCChanUser(parent, unicodeName, encodedName, modes, userInChannel, name, host)
{
// Both unicodeName and encodedName are optional, but at least one must be
// present.
if (!encodedName && !unicodeName)
throw "Hey! Come on, I need either an encoded or a Unicode name.";
else if (encodedName && !unicodeName)
unicodeName = toUnicode(encodedName, parent);
else if (!encodedName && unicodeName)
encodedName = fromUnicode(unicodeName, parent);
// We should have both unicode and encoded names by now.
let collectionKey = ":" + parent.parent.toLowerCase(encodedName);
if (collectionKey in parent.users)
{
let existingUser = parent.users[collectionKey];
if (modes)
{
// If we start with a single character mode, assume we're replacing
// the list. (i.e. the list is either all +/- modes, or all normal)
if ((modes.length >= 1) && (modes[0].search(/^[-+]/) == -1))
{
// Modes, but no +/- prefixes, so *replace* mode list.
existingUser.modes = modes;
}
else
{
// We have a +/- mode list, so carefully update the mode list.
for (var m in modes)
{
// This will remove '-' modes, and all other modes will be
// added.
var mode = modes[m][1];
if (modes[m][0] == "-")
{
if (arrayContains(existingUser.modes, mode))
{
var i = arrayIndexOf(existingUser.modes, mode);
arrayRemoveAt(existingUser.modes, i);
}
}
else
{
if (!arrayContains(existingUser.modes, mode))
existingUser.modes.push(mode);
}
}
}
}
existingUser.isFounder = (arrayContains(existingUser.modes, "q")) ?
true : false;
existingUser.isAdmin = (arrayContains(existingUser.modes, "a")) ?
true : false;
existingUser.isOp = (arrayContains(existingUser.modes, "o")) ?
true : false;
existingUser.isHalfOp = (arrayContains(existingUser.modes, "h")) ?
true : false;
existingUser.isVoice = (arrayContains(existingUser.modes, "v")) ?
true : false;
existingUser.updateSortName();
return existingUser;
}
var protoUser = new CIRCUser(parent.parent, unicodeName, encodedName, name, host);
this.__proto__ = protoUser;
this.getURL = cusr_geturl;
this.setOp = cusr_setop;
this.setHalfOp = cusr_sethalfop;
this.setVoice = cusr_setvoice;
this.setBan = cusr_setban;
this.kick = cusr_kick;
this.kickBan = cusr_kban;
this.say = cusr_say;
this.notice = cusr_notice;
this.act = cusr_act;
this.whois = cusr_whois;
this.updateSortName = cusr_updatesortname;
this.parent = parent;
this.TYPE = "IRCChanUser";
this.modes = new Array();
if (typeof modes != "undefined")
this.modes = modes;
this.isFounder = (arrayContains(this.modes, "q")) ? true : false;
this.isAdmin = (arrayContains(this.modes, "a")) ? true : false;
this.isOp = (arrayContains(this.modes, "o")) ? true : false;
this.isHalfOp = (arrayContains(this.modes, "h")) ? true : false;
this.isVoice = (arrayContains(this.modes, "v")) ? true : false;
this.updateSortName();
if (userInChannel)
parent.users[this.collectionKey] = this;
return this;
}
function cusr_updatesortname()
{
// Check for the highest mode the user has (for sorting the userlist)
const userModes = this.parent.parent.userModes;
var modeLevel = 0;
var mode;
for (var i = 0; i < this.modes.length; i++)
{
for (var j = 0; j < userModes.length; j++)
{
if (userModes[j].mode == this.modes[i])
{
if (userModes.length - j > modeLevel)
{
modeLevel = userModes.length - j;
mode = userModes[j];
}
break;
}
}
}
// Counts numerically down from 9.
this.sortName = (9 - modeLevel) + "-" + this.unicodeName;
}
function cusr_geturl()
{
// Don't ask.
return this.parent.parent.parent.getURL(this.encodedName, ["isnick"]);
}
function cusr_setop(f)
{
var server = this.parent.parent;
var me = server.me;
var modifier = (f) ? " +o " : " -o ";
server.sendData("MODE " + this.parent.encodedName + modifier + this.encodedName + "\n");
return true;
}
function cusr_sethalfop (f)
{
var server = this.parent.parent;
var me = server.me;
var modifier = (f) ? " +h " : " -h ";
server.sendData("MODE " + this.parent.encodedName + modifier + this.encodedName + "\n");
return true;
}
function cusr_setvoice (f)
{
var server = this.parent.parent;
var me = server.me;
var modifier = (f) ? " +v " : " -v ";
server.sendData("MODE " + this.parent.encodedName + modifier + this.encodedName + "\n");
return true;
}
function cusr_kick (reason)
{
var server = this.parent.parent;
var me = server.me;
reason = typeof reason == "string" ? reason : "";
server.sendData("KICK " + this.parent.encodedName + " " + this.encodedName + " :" +
fromUnicode(reason, this) + "\n");
return true;
}
function cusr_setban (f)
{
var server = this.parent.parent;
var me = server.me;
if (!this.host)
return false;
var modifier = (f) ? " +b " : " -b ";
modifier += fromUnicode(this.getBanMask(), server) + " ";
server.sendData("MODE " + this.parent.encodedName + modifier + "\n");
return true;
}
function cusr_kban (reason)
{
var server = this.parent.parent;
var me = server.me;
if (!this.host)
return false;
reason = (typeof reason != "undefined") ? reason : this.encodedName;
var modifier = " -o+b " + this.encodedName + " " +
fromUnicode(this.getBanMask(), server) + " ";
server.sendData("MODE " + this.parent.encodedName + modifier + "\n" +
"KICK " + this.parent.encodedName + " " +
this.encodedName + " :" + reason + "\n");
return true;
}
function cusr_say (msg)
{
this.__proto__.say (msg);
}
function cusr_notice (msg)
{
this.__proto__.notice (msg);
}
function cusr_act (msg)
{
this.__proto__.act (msg);
}
function cusr_whois ()
{
this.__proto__.whois ();
}
// IRC URL parsing and generating
function parseIRCURL(url)
{
var specifiedHost = "";
var rv = new Object();
rv.spec = url;
rv.scheme = url.split(":")[0];
rv.host = null;
rv.target = "";
rv.port = (rv.scheme == "ircs" ? 6697 : 6667);
rv.msg = "";
rv.pass = null;
rv.key = null;
rv.charset = null;
rv.needpass = false;
rv.needkey = false;
rv.isnick = false;
rv.isserver = false;
if (url.search(/^(ircs?:\/?\/?)$/i) != -1)
return rv;
/* split url into <host>/<everything-else> pieces */
var ary = url.match(/^ircs?:\/\/([^\/\s]+)?(\/[^\s]*)?$/i);
if (!ary || !ary[1])
{
dd("parseIRCURL: initial split failed");
return null;
}
var host = ary[1];
var rest = arrayHasElementAt(ary, 2) ? ary[2] : "";
/* split <host> into server (or network) / port */
ary = host.match(/^([^\:]+|\[[^\]]+\])(\:\d+)?$/i);
if (!ary)
{
dd("parseIRCURL: host/port split failed");
return null;
}
// 1 = hostname or IPv4 address, 2 = port.
specifiedHost = rv.host = ary[1].toLowerCase();
rv.isserver = arrayHasElementAt(ary, 2) || /\.|:/.test(specifiedHost);
if (arrayHasElementAt(ary, 2))
rv.port = parseInt(ary[2].substr(1));
if (rest)
{
ary = rest.match(/^\/([^\?\s\/,]*)?\/?(,[^\?]*)?(\?.*)?$/);
if (!ary)
{
dd("parseIRCURL: rest split failed ``" + rest + "''");
return null;
}
rv.target = arrayHasElementAt(ary, 1) ? ecmaUnescape(ary[1]) : "";
if (rv.target.search(/[\x07,\s]/) != -1)
{
dd("parseIRCURL: invalid characters in channel name");
return null;
}
var params = arrayHasElementAt(ary, 2) ? ary[2].toLowerCase() : "";
var query = arrayHasElementAt(ary, 3) ? ary[3] : "";
if (params)
{
params = params.split(",");
while (params.length)
{
var param = params.pop();
// split doesn't take out empty bits:
if (param == "")
continue;
switch (param)
{
case "isnick":
rv.isnick = true;
if (!rv.target)
{
dd("parseIRCURL: isnick w/o target");
/* isnick w/o a target is bogus */
return null;
}
break;
case "isserver":
rv.isserver = true;
if (!specifiedHost)
{
dd("parseIRCURL: isserver w/o host");
/* isserver w/o a host is bogus */
return null;
}
break;
case "needpass":
case "needkey":
rv[param] = true;
break;
default:
/* If we didn't understand it, ignore but warn: */
dd("parseIRCURL: Unrecognized param '" + param +
"' in URL!");
}
}
}
if (query)
{
ary = query.substr(1).split("&");
while (ary.length)
{
var arg = ary.pop().split("=");
/*
* we don't want to accept *any* query, or folks could
* say things like "target=foo", and overwrite what we've
* already parsed, so we only use query args we know about.
*/
switch (arg[0].toLowerCase())
{
case "msg":
rv.msg = ecmaUnescape(arg[1]).replace("\n", "\\n");
break;
case "pass":
rv.needpass = true;
rv.pass = ecmaUnescape(arg[1]).replace("\n", "\\n");
break;
case "key":
rv.needkey = true;
rv.key = ecmaUnescape(arg[1]).replace("\n", "\\n");
break;
case "charset":
rv.charset = ecmaUnescape(arg[1]).replace("\n", "\\n");
break;
}
}
}
}
return rv;
}
function constructIRCURL(obj)
{
function parseQuery(obj)
{
var rv = new Array();
if ("msg" in obj)
rv.push("msg=" + ecmaEscape(obj.msg.replace("\\n", "\n")));
if ("pass" in obj)
rv.push("pass=" + ecmaEscape(obj.pass.replace("\\n", "\n")));
if ("key" in obj)
rv.push("key=" + ecmaEscape(obj.key.replace("\\n", "\n")));
if ("charset" in obj)
rv.push("charset=" + ecmaEscape(obj.charset.replace("\\n", "\n")));
return rv.length ? "?" + rv.join("&") : "";
};
function parseFlags(obj)
{
var rv = new Array();
var haveTarget = ("target" in obj) && obj.target;
if (("needpass" in obj) && obj.needpass)
rv.push(",needpass");
if (("needkey" in obj) && obj.needkey && haveTarget)
rv.push(",needkey");
if (("isnick" in obj) && obj.isnick && haveTarget)
rv.push(",isnick");
return rv.join("");
};
var flags = "";
var scheme = ("scheme" in obj) ? obj.scheme : "irc";
if (!("host" in obj) || !obj.host)
return scheme + "://";
var url = scheme + "://" + obj.host;
// Add port if non-standard:
if (("port" in obj) && (((scheme == "ircs") && (obj.port != 6697)) ||
((scheme == "irc") && (obj.port != 6667))))
{
url += ":" + obj.port;
}
// Need to add ",isserver" if there's no port and no dots in the hostname:
else if (("isserver" in obj) && obj.isserver &&
(obj.host.indexOf(".") == -1))
{
flags += ",isserver";
}
url += "/";
if (("target" in obj) && obj.target)
{
if (obj.target.search(/[\x07,\s]/) != -1)
{
dd("parseIRCObject: invalid characters in channel/nick name");
return null;
}
url += ecmaEscape(obj.target).replace(/\//g, "%2f");
}
return url + flags + parseFlags(obj) + parseQuery(obj);
}
/* Canonicalizing an IRC URL removes all items which aren't necessary to
* identify the target. For example, an IRC URL with ?pass=password and one
* without (but otherwise identical) are refering to the same target, so
* ?pass= is removed.
*/
function makeCanonicalIRCURL(url)
{
var canonicalProps = { scheme: true, host: true, port: true,
target: true, isserver: true, isnick: true };
var urlObject = parseIRCURL(url);
if (!urlObject)
return ""; // Input wasn't a valid IRC URL.
for (var prop in urlObject)
{
if (!(prop in canonicalProps))
delete urlObject[prop];
}
return constructIRCURL(urlObject);
}
|