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
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
|
/*
Copyright 2001-2018 John Wiseman G8BPQ
This file is part of LinBPQ/BPQ32.
LinBPQ/BPQ32 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LinBPQ/BPQ32 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LinBPQ/BPQ32. If not, see http://www.gnu.org/licenses
*/
#define _CRT_SECURE_NO_DEPRECATE
#pragma data_seg("_BPQDATA")
#define LIBCONFIG_STATIC
#include "libconfig.h"
#ifdef LINBPQ
#include "cheaders.h"
#endif
#include "bpqchat.h"
#ifndef WIN32
iconv_t link_toUTF8 = NULL;
BOOL RunEventProgram(char * Program, char * Param);
#endif
BOOL ProcessChatConnectScript(ChatCIRCUIT * conn, char * Buffer, int len);
VOID ChatClearQueue(ChatCIRCUIT * conn);
VOID ChatFlush(ChatCIRCUIT * conn);
VOID APIENTRY SendChatReport(SOCKET ChatReportSocket, char * buff, int txlen);
unsigned short int compute_crc(unsigned char *buf,int len);
char * ReadInfoFile(char * File);
void ChatWriteLogLine(ChatCIRCUIT * conn, int Flag, char * Msg, int MsgLen, int Flags);
extern struct SEM ChatSemaphore;
UCHAR * APIENTRY GetLogDirectory();
char * APIENTRY GetBPQDirectory();
VOID WriteMiniDump();
extern SOCKADDR_IN Chatreportdest;
char OurNode[10];
char OurAlias[10];
#define MaxSockets 64
int MaxChatStreams=0;
ChatCIRCUIT ChatConnections[MaxSockets+1];
ULONG ChatApplMask;
int NumberofChatStreams=0;
char ChatSignoffMsg[100];
char OtherNodesList[1000];
char ChatWelcomeMsg[1000];
char Position[81] = "";
char PopupText[260] = "";
int PopupMode = 0;
int chatPaclen = 236;
int reportChatEvents = 0;
char RtKnown[MAX_PATH] = "RTKnown.txt";
char RtUsr[MAX_PATH] = "STUsers.txt";
char RtUsrTemp[MAX_PATH] = "STUsers.tmp";
int AXIPPort = 0;
ChatCIRCUIT *circuit_hd = NULL; // This is a chain of RT circuits. There may be others
CHATNODE *node_hd = NULL; // Nodes
LINK *link_hd = NULL; // Nodes we link to
TOPIC *topic_hd = NULL;
USER *user_hd = NULL;
KNOWNNODE * known_hd = NULL;
int ChatTmr = 0;
BOOL NeedStatus = FALSE;
char Verstring[80];
static void node_dec(CHATNODE *node);
static KNOWNNODE *knownnode_add(char *call);
VOID SendChatLinkStatus();
char * lookupuser(char * call);
VOID ChatSendWelcomeMsg(int Stream, ChatCIRCUIT * conn, struct UserInfo * user);
static int AutoColours[20] = {0, 4, 9, 11, 13, 16, 17, 42, 45, 50, 61, 64, 66, 72, 81, 84, 85, 86, 87, 89};
#define MaxSockets 64
extern struct SEM OutputSEM;
int NeedINFO = 1; // Send INFO Msg after 10 Secs
time_t RunningConnectScript = 0;
//#undef free
//#define free(p)
struct HistoryRec * History = NULL;
int HistoryCount = 0;
typedef int (WINAPI FAR *FARPROCX)();
extern FARPROCX pRunEventProgram;
int AddtoHistory(struct user_t * user, char * text)
{
struct HistoryRec * Rec;
struct HistoryRec * ptr;
int n = 1;
char buf[2048];
char Stamp[16];
struct tm * tm;
time_t Now = time(NULL);
// Don't want to grow indefinitely and fill memory. We only allow display up to 24 hours back, so if first record is older that that
// remove and reuse it
if (History && History->Time < Now - 86400)
{
Rec = History;
History = Rec->next; // Remove from front of chain
}
else
Rec = malloc(sizeof (struct HistoryRec));
memset(Rec, 0, sizeof (struct HistoryRec));
tm = gmtime(&Now);
if (strlen(text) + strlen(user->name) + strlen(user->call) > 2000)
return 0; // Shouldn't be that long, but protect buffer
sprintf(Stamp,"%02d:%02d ", tm->tm_hour, tm->tm_min);
sprintf(buf, "%s%-6.6s %s %c %s\r", Stamp, user->call, user->name, ':', text);
Rec->Time = Now;
Rec->Topic = _strdup(user->topic->name);
Rec->Message = _strdup(buf);
if (History == NULL)
History = Rec;
else
{
ptr = History;
while (ptr && ptr->next)
{
n++;
ptr = ptr->next;
}
n++;
ptr->next = Rec;
}
return n;
}
int ChatIsUTF8(unsigned char *ptr, int len)
{
int n;
unsigned char * cpt = ptr;
// This is simpler than the Term version, as it only handles complete lines of text, so cant get split sequences
cpt--;
for (n = 0; n < len; n++)
{
cpt++;
if (*cpt < 128)
continue;
if ((*cpt & 0xF8) == 0xF0)
{ // start of 4-byte sequence
if (((*(cpt + 1) & 0xC0) == 0x80)
&& ((*(cpt + 2) & 0xC0) == 0x80)
&& ((*(cpt + 3) & 0xC0) == 0x80))
{
cpt += 3;
n += 3;
continue;
}
return FALSE;
}
else if ((*cpt & 0xF0) == 0xE0)
{ // start of 3-byte sequence
if (((*(cpt + 1) & 0xC0) == 0x80)
&& ((*(cpt + 2) & 0xC0) == 0x80))
{
cpt += 2;
n += 2;
continue;
}
return FALSE;
}
else if ((*cpt & 0xE0) == 0xC0)
{ // start of 2-byte sequence
if ((*(cpt + 1) & 0xC0) == 0x80)
{
cpt++;
n++;
continue;
}
return FALSE;
}
return FALSE;
}
return TRUE;
}
#ifndef LINBPQ
char * strlop(char * buf, char delim)
{
// Terminate buf at delim, and return rest of string
char * ptr = strchr(buf, delim);
if (ptr == NULL) return NULL;
*(ptr)++=0;
return ptr;
}
VOID * _zalloc(size_t len)
{
// ?? malloc and clear
void * ptr;
ptr=malloc(len);
memset(ptr, 0, len);
return ptr;
}
VOID * _zalloc_dbg(int len, int type, char * file, int line)
{
// ?? malloc and clear
void * ptr;
ptr=_malloc_dbg(len, type, file, line);
if (ptr == NULL)
CriticalErrorHandler("malloc failed");
memset(ptr, 0, len);
return ptr;
}
#endif
VOID __cdecl nprintf(ChatCIRCUIT * conn, const char * format, ...)
{
// seems to be printf to a socket
char buff[65536];
va_list(arglist);
va_start(arglist, format);
vsnprintf(buff, sizeof(buff), format, arglist);
nputs(conn, buff);
}
VOID nputc(ChatCIRCUIT * conn, char chr)
{
// Seems to send chr to socket
ChatWriteLogLine(conn, '>',&chr, 1, LOG_CHAT);
ChatQueueMsg(conn, &chr, 1);
}
VOID nputs(ChatCIRCUIT * conn, char * buf)
{
// Seems to send buf to socket
ChatQueueMsg(conn, buf, (int)strlen(buf));
if (*buf == 0x1b)
buf += 2; // Colour Escape
ChatWriteLogLine(conn, '>',buf, (int)strlen(buf), LOG_CHAT);
}
int ChatQueueMsg(ChatCIRCUIT * conn, char * msg, int len)
{
// Add Message to queue for this connection
if (conn->rtcflags & p_linked)
conn->u.link->lastMsgReceived = time(NULL);
// UCHAR * OutputQueue; // Messages to user
// int OutputQueueLength; // Total Malloc'ed size. Also Put Pointer for next Message
// int OutputGetPointer; // Next byte to send. When Getpointer = Queue Length all is sent - free the buffer and start again.
// Create or extend buffer
GetSemaphore(&OutputSEM, 0);
while (conn->OutputQueueLength + len > conn->OutputQueueSize)
{
// Extend Queue
conn->OutputQueueSize += 4096;
conn->OutputQueue = realloc(conn->OutputQueue, conn->OutputQueueSize);
}
memcpy(&conn->OutputQueue[conn->OutputQueueLength], msg, len);
conn->OutputQueueLength += len;
FreeSemaphore(&OutputSEM);
return len;
}
VOID ChatSendWelcomeMsg(int Stream, ChatCIRCUIT * conn, struct UserInfo * user)
{
if (!rtloginu (conn, TRUE))
{
// Already connected - close
ChatFlush(conn);
Sleep(1000);
Disconnect(conn->BPQStream);
}
return;
}
VOID ChatExpandAndSendMessage(ChatCIRCUIT * conn, char * Msg, int LOG)
{
char NewMessage[10000];
char * OldP = Msg;
char * NewP = NewMessage;
char * ptr, * pptr;
int len;
char Dollar[] = "$";
char CR[] = "\r";
int Msgs = 0, Unread = 0;
ptr = strchr(OldP, '$');
while (ptr)
{
len = (int)(ptr - OldP); // Chars before $
memcpy(NewP, OldP, len);
NewP += len;
switch (*++ptr)
{
case 'I': // First name of the connected user.
pptr = conn->UserPointer->Name;
break;
case 'U': // Callsign of the connected user.
pptr = conn->UserPointer->Call;
break;
case 'W': // Inserts a carriage return.
pptr = CR;
break;
break;
default:
pptr = Dollar; // Just Copy $
}
len = (int)strlen(pptr);
memcpy(NewP, pptr, len);
NewP += len;
OldP = ++ptr;
ptr = strchr(OldP, '$');
}
strcpy(NewP, OldP);
len = RemoveLF(NewMessage, (int)strlen(NewMessage));
ChatWriteLogLine(conn, '>', NewMessage, len, LOG_CHAT);
ChatQueueMsg(conn, NewMessage, len);
}
void chat_link_out (LINK *link)
{
int n, p;
ChatCIRCUIT * conn;
char Msg[80];
for (n = NumberofChatStreams-1; n >= 0 ; n--)
{
conn = &ChatConnections[n];
if (conn->Active == FALSE)
{
p = conn->BPQStream;
memset(conn, 0, sizeof(ChatCIRCUIT)); // Clear everything
conn->BPQStream = p;
conn->Active = TRUE;
circuit_new(conn, p_linkini);
conn->u.link = link;
conn->Flags = CHATMODE | CHATLINK;
n=sprintf_s(Msg, sizeof(Msg), "Connecting to Chat Node %s", conn->u.link->alias);
strcpy(conn->Callsign, conn->u.link->alias);
ChatWriteLogLine(conn, '|',Msg, n, LOG_CHAT);
link->ScriptIndex = -1;
RunningConnectScript = time(NULL);
link->MoreLines = TRUE;
link->scriptRunning = TRUE;
link->RTLSent = 0;
ConnectUsingAppl(conn->BPQStream, ChatApplMask);
// Connected Event will trigger connect to remote system
return;
}
}
return;
}
VOID saywhat(ChatCIRCUIT *circuit)
{
nputs(circuit, "Invalid Command\r");
}
VOID saydone(ChatCIRCUIT *circuit)
{
nputs(circuit, "Ok\r");
}
VOID strnew(char ** new, char *f1)
{
// seems to allocate a new string, and copy the old one to it
// how is this different to strdup??
*new = _strdup(f1);
}
#define sl_ins_hd(link, hd) \
if (hd == NULL)\
hd=link;\
else\
{\
link->next=hd->next;\
hd->next=link;\
}
BOOL matchi(char * p1, char * p2)
{
// Return TRUE is strings match
if (_stricmp(p1, p2))
return FALSE;
else
return TRUE;
}
VOID ProcessChatLine(ChatCIRCUIT * conn, struct UserInfo * user, char* OrigBuffer, int len)
{
ChatCIRCUIT *c;
char * Buffer = OrigBuffer;
WCHAR BufferW[65536];
UCHAR BufferB[65536];
// Sanity Check
if (len > 32768)
return;
// Convert to UTF8 if not already in UTF-8
if (len == 73 && memcmp(&OrigBuffer[40], " ", 20) == 0)
{
// Chat Signon Message. If Topic is present, switch to it
char * Context;
char * Appl;
char * topic;
Appl = strtok_s(OrigBuffer, " ,\r", &Context);
topic = strtok_s(NULL, " ,\r", &Context);
if (topic == NULL)
return; // Just Chat
// Have a Topic
if (conn->Flags & GETTINGUSER)
{
// Need to log in before switching topic, so Give a dummy name here
conn->Flags &= ~GETTINGUSER;
strcpy(user->Name, "?_name");
ChatSendWelcomeMsg(conn->BPQStream, conn, user);
}
OrigBuffer[40] = 0;
sprintf(&OrigBuffer[40],"/t %s\r", topic);
strcpy(OrigBuffer, &OrigBuffer[40]);
len = (int)strlen(OrigBuffer);
}
else
{
// Normal input
if (conn->Flags & GETTINGUSER)
{
// Check not getting *RTL in response to Name prompt
if (memcmp(Buffer, "*RTL", 4) == 0)
{
// Other end thinks this is a node-node link
Logprintf(LOG_CHAT, conn, '!', "Station %s trying to start Node Protocol, but not defined as a Node",
conn->Callsign);
knownnode_add(conn->Callsign); // So it won't happen again
Disconnect(conn->BPQStream);
return;
}
conn->Flags &= ~GETTINGUSER;
memcpy(user->Name, Buffer, len-1);
ChatSendWelcomeMsg(conn->BPQStream, conn, user);
return;
}
}
if (ChatIsUTF8(OrigBuffer, len) == FALSE)
{
// With Windows it is simple - convert using current codepage
// I think the only reliable way is to convert to unicode and back
#ifdef WIN32
int wlen;
wlen = MultiByteToWideChar(CP_ACP, 0, Buffer, len, BufferW, 65536);
len = WideCharToMultiByte(CP_UTF8, 0, BufferW, wlen, BufferB, 63336, NULL, NULL);
Buffer = BufferB;
#else
size_t left = 65536;
size_t clen = len;
UCHAR * BufferBP = BufferB;
struct user_t * icu = conn->u.user;
if (conn->rtcflags & p_user)
{
if (icu->iconv_toUTF8 == NULL)
{
icu->iconv_toUTF8 = iconv_open("UTF-8//IGNORE", icu->Codepage);
if (icu->iconv_toUTF8 == (iconv_t)-1)
icu->iconv_toUTF8 = iconv_open("UTF-8//IGNORE", "CP1252");
}
iconv(icu->iconv_toUTF8, NULL, NULL, NULL, NULL); // Reset State Machine
iconv(icu->iconv_toUTF8, &Buffer, &clen, (char ** __restrict__)&BufferBP, &left);
}
else
{
if (link_toUTF8 == NULL)
link_toUTF8 = iconv_open("UTF-8//IGNORE", "CP1252");
iconv(link_toUTF8, NULL, NULL, NULL, NULL); // Reset State Machine
iconv(link_toUTF8, &Buffer, &clen, (char ** __restrict__)&BufferBP, &left);
}
len = 65536 - left;
Buffer = BufferB;
#endif
}
ChatWriteLogLine(conn, '<',Buffer, len, LOG_CHAT);
Buffer[len] = 0;
strlop(Buffer, '\r');
if (conn->rtcflags == p_linkwait)
{
//waiting for *RTL
if (memcmp(Buffer, "*RTL", 4) == 0)
{
// Node - Node Connect
if (rtloginl (conn, conn->Callsign))
{
// Accepted
conn->Flags |= CHATLINK;
return;
}
else
{
// Connection refused. rtlogin1 has sent error message and closed link
return;
}
}
if (Buffer[0] == '[' && Buffer[len-2] == ']') // SID
return;
nprintf(conn, "Unexpected Message on Chat Node-Node Link - Disconnecting\r");
ChatFlush(conn);
Sleep(500);
conn->rtcflags = p_nil;
Disconnect(conn->BPQStream);
return;
}
if (conn->Flags & CHATLINK)
{
#ifndef LINBPQ
struct _EXCEPTION_POINTERS exinfo;
__try
{
chkctl(conn, Buffer, len);
}
#define EXCEPTMSG "Process Chat Line"
#include "StdExcept.c"
Debugprintf("CHAT *** Was procesing Chat Node Message %s", Buffer);
Disconnect(conn->BPQStream);
CheckProgramErrors();
}
#else
chkctl(conn, Buffer, len);
#endif
return;
}
if(conn->u.user == NULL)
{
// A node link, but not activated yet, or a chat console which has dosconnected
if (conn->BPQStream != -2)
return;
// Log console user in
if (rtloginu (conn, TRUE))
conn->Flags |= CHATMODE;
return;
}
if ((len <6) && (memcmp(Buffer, "*RTL", 4) == 0))
{
// Other end thinks this is a node-node link
Logprintf(LOG_CHAT, conn, '!', "Station %s trying to start Node Protocol, but not defined as a Node",
conn->Callsign);
knownnode_add(conn->Callsign); // So it won't happen again
Disconnect(conn->BPQStream);
return;
}
if (Buffer[0] == '/')
{
// Process Command
int cmdLen = 0;
char * param = strchr(&Buffer[1], ' ');
if (param)
cmdLen = param - &Buffer[1];
else
cmdLen = strlen(&Buffer[1]);
if (_memicmp(&Buffer[1], "Bye", 1) == 0)
{
SendUnbuffered(conn->BPQStream, ChatSignoffMsg, (int)strlen(ChatSignoffMsg));
if (conn->BPQStream < 0)
{
logout(conn);
conn->Flags = 0;
if (conn->BPQStream == -2)
CloseConsole(conn->BPQStream);
}
else
ReturntoNode(conn->BPQStream);
return;
}
if (_memicmp(&Buffer[1], "Quit", 4) == 0)
{
SendUnbuffered(conn->BPQStream, ChatSignoffMsg, (int)strlen(ChatSignoffMsg));
if (conn->BPQStream < 0)
{
logout(conn);
conn->Flags = 0;
if (conn->BPQStream == -2)
CloseConsole(conn->BPQStream);
}
else
{
Sleep(1000);
Disconnect(conn->BPQStream);
}
return;
}
if (cmdLen > 1 && _memicmp(&Buffer[1], "History", cmdLen) == 0) // Accept Hi but not H
{
// Param is number of minutes to go back (max 24 hours)
struct HistoryRec * ptr = History;
int interval = 0;
time_t start;
int n = HistoryCount;
if (param)
interval = atoi(param);
if (interval < 1)
{
nprintf(conn, "Format is /history n, where n is history time in minutes\r");
conn->u.user->lastsendtime = time(NULL);
return;
}
if (interval > 1440)
{
nprintf(conn, "History is only held for 24 Hours (1440 Minutes)\r");
interval = 1440; // Limit to 1 day
}
start = time(NULL) - (interval * 60);
// Find first record to send
while (ptr)
{
if (ptr->Time > start)
break;
n--;
ptr = ptr->next;
}
// n is records found
while (ptr)
{
nprintf(conn, ptr->Message);
ptr = ptr->next;
}
conn->u.user->lastsendtime = time(NULL);
return;
}
if (_memicmp(&Buffer[1], "Keepalive", 4) == 0)
{
conn->u.user->rtflags ^= u_keepalive;
upduser(conn->u.user);
nprintf(conn, "Keepalive is %s\r", (conn->u.user->rtflags & u_keepalive) ? "Enabled" : "Disabled");
conn->u.user->lastsendtime = time(NULL);
return;
}
if (_memicmp(&Buffer[1], "AUTOCHARSET", 4) == 0)
{
conn->u.user->rtflags ^= u_auto;
upduser(conn->u.user);
nprintf(conn, "Automatic Character set selection is %s\r", (conn->u.user->rtflags & u_auto) ? "Enabled" : "Disabled");
conn->u.user->lastsendtime = time(NULL);
return;
}
if (_memicmp(&Buffer[1], "UTF-8", 3) == 0)
{
conn->u.user->rtflags ^= u_noUTF8;
upduser(conn->u.user);
nprintf(conn, "Character set is %s\r", (conn->u.user->rtflags & u_noUTF8) ? "8 Bit" : "UTF-8");
conn->u.user->lastsendtime = time(NULL);
return;
}
if ((_memicmp(&Buffer[1], "CodePage", 3) == 0) || (_memicmp(&Buffer[1], "CP", 2) == 0))
{
char * Context;
char * CP = strtok_s(&Buffer[1], " ,\r", &Context);
#ifndef WIN32
iconv_t temp = NULL;
#else
int temp = 0;
WCHAR TempW[10];
#endif
CP = strtok_s(NULL, " ,\r", &Context);
if (CP == NULL || CP[0] == 0)
{
#ifndef WIN32
if (conn->u.user->Codepage[0])
nprintf(conn, "Codepage is %s\r", conn->u.user->Codepage);
#else
if (conn->u.user->Codepage)
nprintf(conn, "Codepage is %d\r", conn->u.user->Codepage);
#endif
else
nprintf(conn, "Codepage is not set\r");
return;
}
_strupr(CP);
#ifndef WIN32
// Validate Code Page by trying to open an iconv descriptor
temp = iconv_open("UTF-8", CP);
if (temp == (iconv_t)-1)
{
nprintf(conn, "Invalid Codepage %s\r", CP);
return;
}
iconv_close(conn->u.user->iconv_toUTF8);
iconv_close(conn->u.user->iconv_fromUTF8);
conn->u.user->iconv_toUTF8 = temp;
conn->u.user->iconv_fromUTF8 = iconv_open(CP, "UTF-8");
strcpy(conn->u.user->Codepage, CP);
nprintf(conn, "Codepage set to %s\r", conn->u.user->Codepage);
#else
if (CP[0] == 'C')
CP +=2;
// Validate by trying ot use it
temp = atoi(CP);
if (MultiByteToWideChar(temp, 0, "\r", 2, TempW, 10) == 0)
{
int err = GetLastError();
if (err == ERROR_INVALID_PARAMETER)
{
nprintf(conn, "Invalid Codepage %d\r", temp);
return;
}
}
conn->u.user->Codepage = temp;
nprintf(conn, "Codepage set to %d\r", conn->u.user->Codepage);
#endif
upduser(conn->u.user);
return;
}
if (_memicmp(&Buffer[1], "Shownames", 4) == 0)
{
conn->u.user->rtflags ^= u_shownames;
upduser(conn->u.user);
nprintf(conn, "Shownames is %s\r", (conn->u.user->rtflags & u_shownames) ? "Enabled" : "Disabled");
conn->u.user->lastsendtime = time(NULL);
return;
}
if (_memicmp(&Buffer[1], "Time", 4) == 0)
{
conn->u.user->rtflags ^= u_showtime;
upduser(conn->u.user);
nprintf(conn, "Show Time is %s\r", (conn->u.user->rtflags & u_showtime) ? "Enabled" : "Disabled");
conn->u.user->lastsendtime = time(NULL);
return;
}
if (_memicmp(&Buffer[1], "colours", 4) == 0)
{
int i =0;
while (i < 100)
{
nprintf(conn, "\x1b%c%02d XXXXX\r", i + 10, i);
i++;
if (i == 3)
i++;
}
return;
}
rt_cmd(conn, Buffer);
return;
}
// Send message to all other connected users on same channel
text_tellu(conn->u.user, Buffer, NULL, o_topic); // To local users.
HistoryCount = AddtoHistory(conn->u.user, Buffer);
conn->u.user->lastrealmsgtime = conn->u.user->lastmsgtime = time(NULL);
// Send to Linked nodes
for (c = circuit_hd; c; c = c->next)
{
if ((c->rtcflags & p_linked) && c->refcnt && ct_find(c, conn->u.user->topic))
nprintf(c, "%c%c%s %s %s\r", FORMAT, id_data, OurNode, conn->u.user->call, Buffer);
}
}
void upduser(USER *user)
{
FILE *in, *out;
char *c;
char Buffer[2048];
char *buf = Buffer;
in = fopen(RtUsr, "r");
if (!(in))
{
in = fopen(RtUsr, "w");
if (in)
fclose(in);
in = fopen(RtUsr, "r");
}
if (!(in)) return;
out = fopen(RtUsrTemp, "w");
if (!(out)) return;
while(fgets(buf, 128, in))
{
if (strstr(buf, "*RTL")) // Tidy user database
continue;
c = strchr(buf, ' ');
if (c) *c = '\0';
if (!matchi(buf, user->call))
{
if (c) *c = ' ';
fputs(buf, out);
}
}
#ifndef WIN32
fprintf(out, "%s %d %s %s¬%d¬%s\n", user->call, user->rtflags, user->name, user->qth, user->Colour, user->Codepage);
#else
fprintf(out, "%s %d %s %s¬%d¬%d\n", user->call, user->rtflags, user->name, user->qth, user->Colour, user->Codepage);
#endif
fclose(in);
fclose(out);
remove(RtUsr);
rename(RtUsrTemp, RtUsr);
}
char * lookupuser(char * call)
{
FILE *in;
char *flags;
char Buffer[2048];
char *buf = Buffer;
char * name;
in = fopen(RtUsr, "r");
if (in)
{
while(fgets(buf, 128, in))
{
strlop(buf, '\n');
flags = strlop(buf, ' ');
if (!matchi(buf, call)) continue;
if (!flags) break;
fclose(in);
name = strlop(flags, ' ');
strlop(name, ' ');
return _strdup(name);
}
fclose(in);
}
return NULL;
}
void rduser(USER *user)
{
FILE *in;
char *name, *flags, *qth;
char Buffer[2048];
char *buf = Buffer;
char * ptr;
user->name = _strdup("?_name");
user->qth = _strdup("?_qth");
in = fopen(RtUsr, "r");
if (in)
{
while(fgets(buf, 128, in))
{
strlop(buf, '\n');
flags = strlop(buf, ' ');
if (!matchi(buf, user->call)) continue;
if (!flags) break;
name = strlop(flags, ' ');
user->rtflags = atoi(flags);
qth = strlop(name, ' ');
strnew(&user->name, name);
if (!qth) break;
// Colour Code may follow QTH, and Code Page may follow Colour
ptr = strchr(qth, '¬');
if (ptr)
{
*ptr++ = 0;
user->Colour = atoi(ptr);
ptr = strchr(ptr, '¬');
if (ptr)
{
*ptr++ = 0;
#ifndef WIN32
strcpy(user->Codepage, ptr);
#else
user->Codepage = atoi(ptr);
#endif
}
}
strnew(&user->qth, qth);
break;
}
fclose(in);
#ifndef WIN32
// Open an iconv decriptor for each conversion
if (user->Codepage[0])
user->iconv_toUTF8 = iconv_open("UTF-8//IGNORE", user->Codepage);
else
user->iconv_toUTF8 = (iconv_t)-1;
if (user->iconv_toUTF8 == (iconv_t)-1)
user->iconv_toUTF8 = iconv_open("UTF-8//IGNORE", "CP1252");
if (user->Codepage[0])
user->iconv_fromUTF8 = iconv_open(user->Codepage, "UTF-8");
else
user->iconv_fromUTF8 = (iconv_t)-1;
if (user->iconv_fromUTF8 == (iconv_t)-1)
user->iconv_fromUTF8 = iconv_open("CP1252//IGNORE", "UTF-8");
#endif
}
}
void ReportBadJoin(char * ncall, char *ucall)
{
Logprintf(LOG_CHAT, NULL, '!', "User %s Join from Node %s but already connected", ucall, ncall);
}
void ReportBadLeave(char * ncall, char * ucall)
{
Logprintf(LOG_CHAT, NULL, '!', "Node %s reporting Node %s as a leaving user", ncall, ucall);
}
struct DUPINFO DupInfo[MAXDUPS];
static BOOL CheckforDups(ChatCIRCUIT * circuit, char * Call, char * Msg)
{
// Primitive duplicate suppression - see if same call and text reeived in last few secons
time_t Now = time(NULL);
time_t DupCheck = Now - DUPSECONDS;
int i, saveindex = -1;
for (i = 0; i < MAXDUPS; i++)
{
if (DupInfo[i].DupTime < DupCheck)
{
// too old - use first if we need to save it
if (saveindex == -1)
{
saveindex = i;
}
continue;
}
if ((strcmp(Call, DupInfo[i].DupUser) == 0) && (memcmp(Msg, DupInfo[i].DupText, strlen(DupInfo[i].DupText)) == 0))
{
// Duplicate, so discard, but save time
DupInfo[i].DupTime = Now;
Logprintf(LOG_CHAT, circuit, '?', "Duplicate Message From %s %s suppressed", Call, Msg);
return TRUE; // Duplicate
}
}
// Not in list
if (saveindex == -1) // List is full
saveindex = MAXDUPS - 1; // Stick on end
DupInfo[saveindex].DupTime = Now;
strcpy(DupInfo[saveindex].DupUser, Call);
if (strlen(Msg) > 99)
{
memcpy(DupInfo[saveindex].DupText, Msg, 99);
DupInfo[saveindex].DupText[99] = 0;
}
else
strcpy(DupInfo[saveindex].DupText, Msg);
return FALSE;
}
void chkctl(ChatCIRCUIT *ckt_from, char * Buffer, int Len)
{
CHATNODE * node, *ln;
ChatCIRCUIT * ckt_to;
USER * user, * su;
time_t Now = time(NULL);
LINK * Link = ckt_from->u.link;
char * ncall, * ucall, * f1, * f2, * buf;
int i;
if (Buffer[FORMAT_O] != FORMAT) return; // Not a control message.
// Check for corruption
for (i = 1; i < (Len - 1); i++)
{
if (Buffer[i] < 32 && Buffer[i] != 7) // Accept BELL
{
if (Buffer[i] == 9)
{
Buffer[i] = 32;
continue;
}
Debugprintf("Corrupt Chat Link Messages %s", Buffer);
return;
}
}
buf = _strdup(Buffer + DATA_O);
// FORMAT and TYPE bytes are followed by node and user callsigns.
ncall = buf;
ucall = strlop(buf, ' ');
if (!ucall) { free(buf); return; } // Not a control message.
// There may be at least one field after the node and user callsigns.
// Node leave (id_unlink) has no F1.
f1 = strlop(ucall, ' ');
strlop(ucall, 9); // some have tabs ??
// If the frame came from an unknown node ignore it.
// If the frame came from us ignore it (loop breaking).
node = node_find(ncall);
if (!node || matchi(ncall, OurNode)) { free(buf); return; }
if (ckt_from->rtcflags & p_linked)
ckt_from->u.link->lastMsgReceived = Now;
switch(Buffer[TYPE_O])
{
// Data from user ucall at node ncall.
case id_data :
// Check for dups
if (CheckforDups(ckt_from, ucall, f1))
break;
user = user_find(ucall, ncall);
if (!user)
break;
user->lastrealmsgtime = user->lastmsgtime = time(NULL);
text_tellu(user, f1, NULL, o_topic);
HistoryCount = AddtoHistory(user, f1);
for (ckt_to = circuit_hd; ckt_to; ckt_to = ckt_to->next)
{
if ((ckt_to->rtcflags & p_linked) && ckt_to->refcnt &&
!cn_find(ckt_to, node) && ct_find(ckt_to, user->topic))
nprintf(ckt_to, "%s\r", Buffer);
}
break;
// User ucall at node ncall changed their Name/QTH info.
case id_user :
user = user_find(ucall, ncall);
if (!user) break;
f2 = strlop(f1, ' ');
if (!f2) break;
if ((strcmp(user->name, f1) == 0) && (strcmp(user->qth, f2) == 0)) // No Change?
break;
echo(ckt_from, node, Buffer); // Relay to other nodes.
strnew(&user->name, f1);
strnew(&user->qth, f2);
upduser(user);
break;
// User ucall logged into node ncall.
case id_join :
user = user_find(ucall, ncall);
if (user)
{
// Already Here
// If last join was less the 5 secs ago don't report - probably a "Join/Leave Storm"
if (time(NULL) - user->timeconnected > 5)
ReportBadJoin(ncall, ucall);
//if (strcmp(user->node->call, OurNode) == 0)
//{
// Locally connected, and at another node
//}
user->timeconnected = time(NULL);
break; // We have this user as an active Node
}
// update join time
echo(ckt_from, node, Buffer); // Relay to other nodes.
f2 = strlop(f1, ' ');
if (!f2) break;
user = user_join(ckt_from, ucall, ncall, NULL, FALSE);
if (!user) break;
ckt_from->refcnt++;
text_tellu_Joined(user);
strnew(&user->name, f1);
strnew(&user->qth, f2);
upduser(user);
// makelinks(); // Bring up our links if not already up
break;
// User ucall logged out of node ncall.
case id_leave :
user = user_find(ucall, ncall);
if (!user)
{
Debugprintf("CHAT: Leave for %s from %s when not on list", ucall, ncall);
break;
}
// if connected for for less than 3 seconds ignore. May give stuck nodes but should stop "Join/Leave Storm"
// we can't just silently leave as next join will propagate
if (time(NULL) - user->timeconnected < 3)
break;
echo(ckt_from, node, Buffer); // Relay to other nodes.
f2 = strlop(f1, ' ');
if (!f2) break;
text_tellu(user, rtleave, NULL, o_all);
ckt_from->refcnt--;
strnew(&user->name, f1);
strnew(&user->qth, f2);
upduser(user);
user_leave(user);
cn_dec(ckt_from, node);
node_dec(node);
break;
// Node ncall lost its link to node ucall, alias f1.
case id_unlink :
// Only relay to other nodes if we had node. Could get loop otherwise.
// ?? This could possibly cause stuck nodes
ln = node_find(ucall);
// if connected for for less than 3 seconds ignore. May give stuck nodes but should stop "Join/Leave Storm"
// we can't just silently leave as next join will propagate
if (ln)
{
if (time(NULL) - ln->timeconnected < 3)
break;
// is it on this circuit?
if (cn_find(ckt_from, ln))
{
cn_dec(ckt_from, ln);
node_dec(ln);
echo(ckt_from, node, Buffer); // Relay to other nodes if we had node. COuld get loop if
}
else
{
Debugprintf("CHAT: node %s unlink for %s when not on this link", ncall, ucall);
}
}
else
{
Debugprintf("CHAT: node %s unlink for %s when not on list", ncall, ucall);
}
break;
// Node ncall acquired a link to node ucall, alias f1.
// If we are not linked, is no problem, don't link.
// If we are linked, is a loop, do what? (Try ignore!)
case id_link :
ln = node_find(ucall);
if (!ln && !matchi(ncall, OurNode))
{
f2 = strlop(f1, ' ');
cn_inc(ckt_from, ucall, f1, f2);
echo(ckt_from, node, Buffer); // Relay to other nodes.
}
else
{
// If last join was less the 5 secs ago don't report - probably a "Join/Leave Storm"
if (time(NULL) - ln->timeconnected > 5)
Debugprintf("CHAT: node %s link for %s when already on list", ncall, ucall);
// update join time
ln->timeconnected = time(NULL);
break;
}
break;
// User ucall at node ncall sent f2 to user f1.
case id_send :
user = user_find(ucall, ncall);
if (!user) break;
f2 = strlop(f1, ' ');
if (!f2) break;
su = user_find(f1, NULL);
if (!su) break;
if (su->circuit->rtcflags & p_user)
text_tellu(user, f2, f1, o_one);
else
echo(ckt_from, node, Buffer); // Relay to other nodes.
break;
// User ucall at node ncall changed topic.
case id_topic :
user = user_find(ucall, ncall);
if (user)
{
if (_stricmp(user->topic->name, f1) != 0)
{
echo(ckt_from, node, Buffer); // Relay to other nodes.
topic_chg(user, f1);
}
}
break;
case id_keepalive :
ln = node_find(ncall);
if (ln)
{
if (ln->Version == NULL)
if (f1)
ln->Version = _strdup(f1);
}
nprintf(ckt_from, "%c%c%s %s\r", FORMAT, id_pollresp, OurNode, Link->call);
break;
case id_poll:
// Send Poll Response
Link->supportsPolls = Now;
nprintf(ckt_from, "%c%c%s %s\r", FORMAT, id_pollresp, OurNode, Link->call);
break;
case id_pollresp:
Link->supportsPolls = Now;
Link->RTT = Now - Link->timePollSent;
Link->timePollSent = 0; // Cancel Timeout
break;
default:
break;
}
free(buf);
}
// Tell another node about nodes known by this node.
// Do not tell it about this node, the other node knows who it
// linked to (or who linked to it).
// Tell another node about users known by this node.
// Done at incoming or outgoing link establishment.
void state_tell(ChatCIRCUIT *circuit, char * Version)
{
CHATNODE *node;
USER *user;
node = cn_inc(circuit, circuit->u.link->call, circuit->u.link->alias, Version);
node_tell(node, id_link); // Tell other nodes about this new link
// Tell the node that just linked here about nodes known on other links.
for (node = node_hd; node; node = node->next)
{
if (!matchi(node->call, OurNode))
node_xmit(node, id_link, circuit);
}
// Tell the node that just linked here about known users, and their topics.
for (user = user_hd; user; user = user->next)
{
user_xmit(user, id_join, circuit);
topic_xmit(user, circuit);
}
}
static void circuit_free(ChatCIRCUIT *circuit)
{
ChatCIRCUIT *c, *cp;
CN *ncn;
CHATNODE *nn;
TOPIC *tn;
cp = NULL;
for (c = circuit_hd; c; cp = c, c = c->next)
{
if (c == circuit)
{
if (cp) cp->next = c->next; else circuit_hd = c->next;
while (c->hnode)
{
ncn = c->hnode->next;
free(c->hnode);
c->hnode = ncn;
}
break;
}
}
if (circuit_hd) return;
// RT has gone inactive. Clean up.
while (node_hd)
{
nn = node_hd->next;
free(node_hd->alias);
free(node_hd->call);
free(node_hd);
node_hd = nn;
}
while (topic_hd)
{
tn = topic_hd->next;
free(topic_hd->name);
free(topic_hd);
topic_hd = tn;
}
}
// Find a node in the node list.
CHATNODE *node_find(char *call)
{
CHATNODE *node;
for (node = node_hd; node; node = node->next)
{
//if (node->refcnt && matchi(node->call, call)) I don't think this is right!!!
if (matchi(node->call, call))
break;
}
return node;
}
// Add a reference to a node.
static CHATNODE *node_inc(char *call, char *alias, char * Version)
{
CHATNODE *node;
node = node_find(call);
if (!node)
{
knownnode_add(call);
node = zalloc(sizeof(CHATNODE));
sl_ins_hd(node, node_hd);
node->call = _strdup(call);
node->alias = _strdup(alias);
if (Version)
node->Version = _strdup(Version);
node->timeconnected = time(NULL);
// Debugprintf("New Node Rec Created at %x for %s %s", node, node->call, node->alias);
}
node->refcnt++;
return node;
}
// Remove a reference to a node.
static void node_dec(CHATNODE *node)
{
CHATNODE *t, *tp;
USER *user;
ChatCIRCUIT *circuit;
CN *cn;
if (--node->refcnt) return; // Other references.
// Remove the node from the node list.
tp = NULL;
// Make sure there aren't any user or circuit records pointing to it
for (user = user_hd; user; user = user->next)
{
if (user->node == node)
{
Debugprintf("Trying to remove node %s that is linked from user %s", node->call, user->call);
node->refcnt++;
}
}
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (circuit->rtcflags & p_linked)
{
for (cn = circuit->hnode; cn; cn = cn->next)
{
if (cn->node == node)
{
Debugprintf("Trying to remove node %s that is linked from circuit %s", node->call, circuit->Callsign);
node->refcnt++;
}
}
}
}
if (node->refcnt) return; // Now have other references.
for (t = node_hd; t; tp = t, t = t->next)
{
if (t == node)
{
if (tp) tp->next = t->next; else node_hd = t->next;
free(t->alias);
t->alias = NULL;
free(t->call);
t->call = NULL;
free(t);
break;
}
}
}
// User joins a topic.
static TOPIC *topic_join(ChatCIRCUIT *circuit, char *s)
{
CT *ct;
TOPIC *topic;
// Look for an existing topic.
for (topic = topic_hd; topic; topic = topic->next)
{
if (matchi(topic->name, s))
break;
}
// Create a new topic, if needed.
if (!topic)
{
topic = zalloc(sizeof(TOPIC));
sl_ins_hd(topic, topic_hd);
topic->name = _strdup(s);
}
topic->refcnt++; // One more user in this topic.
Logprintf(LOG_CHAT, circuit, '?', "topic_join complete user %s topic %s addr %x ref %d",
circuit->u.user->call, topic->name, topic, topic->refcnt);
// Add the circuit / topic association.
for (ct = circuit->topic; ct; ct = ct->next)
{
if (ct->topic == topic)
{
ct->refcnt++;
return topic;
}
}
ct = zalloc(sizeof(CT));
sl_ins_hd(ct, circuit->topic);
ct->topic = topic;
ct->refcnt = 1;
return topic;
}
// User leaves a topic.
static void topic_leave(ChatCIRCUIT *circuit, TOPIC *topic)
{
CT *ct, *ctp;
TOPIC *t, *tp;
Logprintf(LOG_CHAT, circuit, '?', "topic_leave user %s topic %s addr %x ref %d",
circuit->u.user->call, topic->name, topic, topic->refcnt);
topic->refcnt--;
ctp = NULL;
for (ct = circuit->topic; ct; ctp = ct, ct = ct->next)
{
if (ct->topic == topic)
{
if (!--ct->refcnt)
{
if (ctp) ctp->next = ct->next; else circuit->topic = ct->next;
free(ct);
break;
}
}
}
tp = NULL;
for (t = topic_hd; t; tp = t, t = t->next)
{
if (!t->refcnt && (t == topic))
{
if (tp) tp->next = t->next; else topic_hd = t->next;
free(t->name);
free(t);
break;
}
}
}
// Find a circuit/topic association.
int ct_find(ChatCIRCUIT *circuit, TOPIC *topic)
{
CT *ct;
for (ct = circuit->topic; ct; ct = ct->next)
{
if (ct->topic == topic)
return ct->refcnt;
}
return 0;
}
// Nodes reached from each circuit. Used only if the circuit is a link.
// Remove a circuit/node association.
static void cn_dec(ChatCIRCUIT *circuit, CHATNODE *node)
{
CN *c, *cp;
// Debugprintf("CHAT: Remove c/n %s ", node->call);
cp = NULL;
for (c = circuit->hnode; c; cp = c, c = c->next)
{
if (c->node == node)
{
// CN * cn;
// int len;
// char line[1000]="";
if (--c->refcnt)
{
// Debugprintf("CHAT: Remove c/n Node %s still in use refcount %d", node->call, c->refcnt);
return; // Still in use
}
if (cp)
cp->next = c->next;
else
circuit->hnode = c->next;
free(c);
break;
}
}
if (c == NULL)
{
CN * cn;
int len;
char line[1000]="";
// not found??
Debugprintf("CHAT: !! Remove c/n Node %s addr %x not found cn chain follows", node->call, node);
line[0] = 0;
for (cn = circuit->hnode; cn; cn = cn->next)
{
if (cn->node && cn->node->call)
{
#ifndef LINBPQ
__try
{
#endif
len += sprintf(&line[len], " %p %s", cn->node, cn->node->alias);
if (len > 80)
{
Debugprintf("%s", line);
len = sprintf(line, " ");
}
#ifndef LINBPQ
}
__except(EXCEPTION_EXECUTE_HANDLER)
{len = sprintf("%s *PE* Corrupt Rec %x %x ", line, cn, cn->node);}
#endif
}
else
{
len = sprintf("%s Corrupt Rec %x %x ", line, cn, cn->node);
}
}
Debugprintf("%s", line);
}
}
// Add a circuit/node association.
static CHATNODE *cn_inc(ChatCIRCUIT *circuit, char *call, char *alias, char * Version)
{
CHATNODE *node;
CN *cn;
node = node_inc(call, alias, Version);
for (cn = circuit->hnode; cn; cn = cn->next)
{
if (cn->node == node)
{
cn->refcnt++;
// Debugprintf("cn_inc cn Refcount for %s->%s incremented to %d - adding Call %s",
// circuit->Callsign, node->call, cn->refcnt, call);
return node;
}
}
cn = zalloc(sizeof(CN));
sl_ins_hd(cn, circuit->hnode);
cn->node = node;
cn->refcnt = 1;
// Debugprintf("cn_inc New cn for %s->%s - adding Call %s",
// circuit->Callsign, node->call, call);
return node;
}
// Find a circuit/node association.
static int cn_find(ChatCIRCUIT *circuit, CHATNODE *node)
{
CN *cn;
for (cn = circuit->hnode; cn; cn = cn->next)
{
if (cn->node == node)
return cn->refcnt;
}
return 0;
}
// From a local user to a specific user at another node.
static void text_xmit(USER *user, USER *to, char *text)
{
nprintf(to->circuit, "%c%c%s %s %s %s\r",
FORMAT, id_send, OurNode, user->call, to->call, text);
}
void put_text(ChatCIRCUIT * circuit, USER * user, UCHAR * buf)
{
UCHAR BufferB[4096];
// Text is UTF-8 internally. If user doen't want UTF-8. convert to Node's locale
if (circuit->u.user->rtflags & u_noUTF8)
{
#ifdef WIN32
char * Buffer = buf;
WCHAR BufferW[4096];
int wlen, blen;
BOOL DefaultUsed = FALSE;
char Subst = '?';
wlen = MultiByteToWideChar(CP_UTF8, 0, buf, (int)strlen(buf) + 1, BufferW, 4096);
blen = WideCharToMultiByte(circuit->u.user->Codepage, 0, BufferW, wlen, BufferB + 2, 4096, &Subst, &DefaultUsed);
if (blen == 0) // Probably means invalid code page
blen = WideCharToMultiByte(CP_ACP, 0, BufferW, wlen, BufferB + 2, 4096, &Subst, &DefaultUsed);
buf = BufferB + 2;
BufferB[blen + 2] = 0;
#else
size_t left = 4096;
UCHAR * BufferBP = BufferB;
size_t len = strlen(buf) + 1;
struct user_t * icu = circuit->u.user;
if (icu->iconv_fromUTF8 == NULL)
{
icu->iconv_fromUTF8 = iconv_open(icu->Codepage, "UTF-8");
if (icu->iconv_fromUTF8 == (iconv_t)-1)
icu->iconv_fromUTF8 = iconv_open("CP1252//IGNORE", "UTF-8");
}
iconv(icu->iconv_fromUTF8, NULL, NULL, NULL, NULL); // Reset State Machine
iconv(icu->iconv_fromUTF8, (char ** __restrict__)&buf, &len, (char ** __restrict__)&BufferBP, &left);
len = 4096 - left;
buf = BufferB;
#endif
}
if (circuit->u.user->rtflags & u_colour) // Use Colour
{
// Put a colour header on message
*(--buf) = user->Colour;
*(--buf) = 0x1b;
nputs(circuit, buf);
buf +=2;
}
else
nputs(circuit, buf);
circuit->u.user->lastsendtime = time(NULL);
}
void text_tellu(USER *user, char *text, char *to, int who)
{
ChatCIRCUIT *circuit;
UCHAR Buffer[2048];
UCHAR *buf = &Buffer[4];
char * Time;
struct tm * tm;
char Stamp[20];
time_t T;
T = time(NULL);
tm = gmtime(&T);
sprintf(Stamp,"%02d:%02d ", tm->tm_hour, tm->tm_min);
// Send it to all connected users in the same topic.
// Echo to originator if requested.
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (!(circuit->rtcflags & p_user)) continue; // Circuit is a link.
if ((circuit->u.user == user) && !(user->rtflags & u_echo)) continue;
if (circuit->u.user->rtflags & u_showtime)
Time = Stamp;
else
Time = "";
if (circuit->u.user->rtflags & u_shownames)
sprintf(buf, "%s%-6.6s %s %c %s\r", Time, user->call, user->name, (who == o_one) ? '>' : ':', text);
else
sprintf(buf, "%s%-6.6s %c %s\r", Time, user->call, (who == o_one) ? '>' : ':', text);
switch(who)
{
case o_topic :
if (circuit->u.user->topic == user->topic)
put_text(circuit, user, buf); // Send adding Colour if wanted
break;
case o_all:
put_text(circuit, user, buf); // Send adding Colour if wanted
break;
case o_one :
if (matchi(circuit->u.user->call, to))
put_text(circuit, user, buf); // Send adding Colour if wanted
break;
}
}
}
extern int FlashOnConnect;
void text_tellu_Joined(USER * user)
{
ChatCIRCUIT *circuit;
UCHAR Buffer[200];
UCHAR *buf = &Buffer[4];
char * Time;
struct tm * tm;
char Stamp[20];
time_t T;
char prog[256] = "";
T = time(NULL);
tm = gmtime(&T);
sprintf(Stamp,"%02d:%02d ", tm->tm_hour, tm->tm_min);
sprintf(buf, "%s%-6.6s : %s *** Joined Chat, Topic %s", Stamp, user->call, user->name, user->topic->name);
if (reportChatEvents)
{
#ifdef WIN32
if (pRunEventProgram)
pRunEventProgram("ChatNewUser.exe", user->call);
#else
sprintf(prog, "%s/%s", BPQDirectory, "ChatNewUser");
RunEventProgram(prog, user->call);
#endif
}
// Send it to all connected users in the same topic.
// Echo to originator if requested.
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (!(circuit->rtcflags & p_user)) continue; // Circuit is a link.
if ((circuit->u.user == user) && !(user->rtflags & u_echo)) continue;
if (circuit->u.user->rtflags & u_showtime)
Time = Stamp;
else
Time = "";
sprintf(buf, "%s%-6.6s : %s *** Joined Chat, Topic %s", Time, user->call, user->name, user->topic->name);
put_text(circuit, user, buf); // Send adding Colour if wanted
if (circuit->u.user->rtflags & u_bells)
if (circuit->BPQStream < 0) // Console
{
#ifndef LINBPQ
if (FlashOnConnect) FlashWindow(ConsHeader[1]->hConsole, TRUE);
#endif
nputc(circuit, 7);
// PlaySound ("BPQCHAT_USER_LOGIN", NULL, SND_ALIAS | SND_APPLICATION | SND_ASYNC);
}
else
nputc(circuit, 7);
nputc(circuit, 13);
}
}
// Tell one link circuit about a local user change of topic.
static void topic_xmit(USER *user, ChatCIRCUIT *circuit)
{
nprintf(circuit, "%c%c%s %s %s\r",
FORMAT, id_topic, OurNode, user->call, user->topic->name);
}
// Tell another node about one known node on a link add or drop
// if that node is from some other link.
static void node_xmit(CHATNODE *node, char kind, ChatCIRCUIT *circuit)
{
#ifndef LINBPQ
struct _EXCEPTION_POINTERS exinfo;
__try
{
#endif
if (!cn_find(circuit, node))
if (node->Version && (kind == id_link))
nprintf(circuit, "%c%c%s %s %s %s\r", FORMAT, kind, OurNode, node->call, node->alias, node->Version);
else
nprintf(circuit, "%c%c%s %s %s\r", FORMAT, kind, OurNode, node->call, node->alias);
#ifndef LINBPQ
}
#define EXCEPTMSG "node_xmit"
#include "StdExcept.c"
Debugprintf("Corrupt Rec %x %x %x", node, node->call, node->alias);
}
#endif
}
// Tell all other nodes about one node known by this node.
static void node_tell(CHATNODE *node, char kind)
{
ChatCIRCUIT *circuit;
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (circuit->rtcflags & p_linked)
node_xmit(node, kind, circuit);
}
}
// Tell another node about a user login/logout at this node.
static void user_xmit(USER *user, char kind, ChatCIRCUIT *circuit)
{
CHATNODE *node;
node = user->node;
if (!cn_find(circuit, node))
nprintf(circuit, "%c%c%s %s %s %s\r", FORMAT, kind, node->call, user->call, user->name, user->qth);
}
// Tell all other nodes about a user login/logout at this node.
static void user_tell(USER *user, char kind)
{
ChatCIRCUIT *circuit;
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (circuit->rtcflags & p_linked)
user_xmit(user, kind, circuit);
}
}
// Find the user record for call@node. Node can be NULL, meaning any node
USER *user_find(char *call, char * node)
{
USER *user;
for (user = user_hd; user; user = user->next)
{
if (node)
{
if (matchi(user->call, call) && matchi(user->node->call, node))
break;
}
else
{
if (matchi(user->call, call))
break;
}
}
return user;
}
static void user_leave(USER *user)
{
USER *t, *tp;
topic_leave(user->circuit, user->topic);
tp = NULL;
for (t = user_hd; t; tp = t, t = t->next)
{
if (t == user)
{
if (tp) tp->next = t->next; else user_hd = t->next;
free(t->name);
free(t->call);
free(t->qth);
#ifndef WIN32
if (t->iconv_fromUTF8)
iconv_close(t->iconv_fromUTF8);
if (t->iconv_toUTF8)
iconv_close(t->iconv_toUTF8);
#endif
free(t);
break;
}
}
if (user_hd == NULL)
ChatTmr = 59; // If no users, disconnect links after 10-20 secs
}
// User changed to a different topic.
static BOOL topic_chg(USER *user, char *s)
{
char buf[128];
if (_stricmp(user->topic->name, s) == 0) return FALSE; // Not Changed
sprintf(buf, "*** Left Topic: %s", user->topic->name);
text_tellu(user, buf, NULL, o_topic); // Tell everyone in the old topic.
topic_leave(user->circuit, user->topic);
user->topic = topic_join(user->circuit, s);
sprintf(buf, "*** Joined Topic: %s", user->topic->name);
text_tellu(user, buf, NULL, o_topic); // Tell everyone in the new topic.
return TRUE;
}
// Create a user record for this user.
static USER *user_join(ChatCIRCUIT *circuit, char *ucall, char *ncall, char *nalias, BOOL Local)
{
CHATNODE *node;
USER *user;
if (Local)
{
node = cn_inc(circuit, ncall, nalias, Verstring);
}
else
node = cn_inc(circuit, ncall, nalias, NULL);
// Is this user already logged in at this node?
for (user = user_hd; user; user = user->next)
{
if (matchi(user->call, ucall) && (user->node == node))
return user;
}
// User is not logged in, create a user record for them.
user = zalloc(sizeof(USER));
sl_ins_hd(user, user_hd);
user->circuit = circuit;
user->call = _strdup(ucall);
_strupr(user->call);
user->node = node;
rduser(user);
if (user->Colour == 0 || user->Colour == 11) // None or default
{
// Allocate Random
int sum = 0, i;
for (i = 0; i < 9; i++)
sum += user->call[i];
sum %= 20;
user->Colour = AutoColours[sum] + 10; // Best 20 colours
}
if (circuit->rtcflags & p_user)
circuit->u.user = user;
user->timeconnected = user->lastrealmsgtime = user->lastmsgtime = time(NULL);
user->topic = topic_join(circuit, deftopic);
return user;
}
// Link went away. We dropped it, or the other node dropped it.
// Drop nodes and users connected from this link.
// Tell other (still connected) links what was dropped.
void link_drop(ChatCIRCUIT *circuit)
{
USER *user, *usernext;
CN *cn;
// So we don't try and send anything on this circuit.
if (circuit->u.link)
if (circuit->rtcflags == p_linkini)
Debugprintf("Chat link %s Link Setup Failed", circuit->u.link->call);
if (circuit->rtcflags == p_linkini)
circuit->u.link->flags = p_linkfailed;
else
circuit->u.link->flags = 0;
circuit->rtcflags = p_nil;
// Users connected on the dropped link are no longer connected.
for (user = user_hd; user; user = usernext)
{
usernext = user->next; // Save next pointer in case entry is free'd
if (user->circuit == circuit)
{
CHATNODE *node;
node = user->node;
text_tellu(user, rtleave, NULL, o_all);
user_tell(user, id_leave);
user_leave(user);
circuit->refcnt--;
if (node)
node_dec(node);
}
}
// Any node known from the dropped link is no longer known.
for (cn = circuit->hnode; cn; cn = cn->next)
{
node_tell(cn->node, id_unlink);
node_dec(cn->node);
}
// The circuit is no longer used.
circuit_free(circuit);
NeedStatus = TRUE;
}
// Handle an incoming control frame from a linked RT system.
static void echo(ChatCIRCUIT *fc, CHATNODE *node, char * Buffer)
{
ChatCIRCUIT *tc;
for (tc = circuit_hd; tc; tc = tc->next)
{
if ((tc != fc) && (tc->rtcflags & p_linked) && !cn_find(tc, node))
nprintf(tc, "%s\r", Buffer);
}
}
char ** SeparateConnectScript(char * MultiString)
{
char * ptr1 = MultiString;
char ** Value;
int Count = 0;
char * ptr;
// Convert to string array
Value = zalloc(sizeof(void *)); // always NULL entry on end even if no values
Value[0] = NULL;
ptr = MultiString;
while (ptr && strlen(ptr))
{
ptr1 = strchr(ptr, '|');
if (ptr1)
*(ptr1++) = 0;
if (strlen(ptr))
{
Value = realloc(Value, (Count + 2) * sizeof(void *));
Value[Count++] = _strdup(ptr);
}
ptr = ptr1;
}
Value[Count] = NULL;
return Value;
}
// Add an entry to list of link partners
int rtlink (char * Call)
{
LINK *link, *temp;
char *c;
char * script;
_strupr(Call);
script = strlop(Call, '|');
c = strlop(Call, ':');
if (!c) return FALSE;
link = zalloc(sizeof(LINK));
link->alias = _strdup(Call);
link->call = _strdup(c);
if (script)
{
link->ConnectScript = SeparateConnectScript(script);
link->Lines = 0;
while (link->ConnectScript[++link->Lines]);
}
else
{
// Create Script with one entry to call partner direct;
link->ConnectScript = zalloc(sizeof(void *) * 2); // always NULL entry on end
link->ConnectScript[0] = malloc(32);
sprintf(link->ConnectScript[0], "C %s", c);
link->Lines = 1;
}
if (link_hd == NULL)
link_hd = link;
else
{
temp = link_hd;
while(temp->next)
temp = temp->next;
temp->next = link;
}
return TRUE;
}
VOID removelinks()
{
LINK *link, *nextlink;
for (link = link_hd; link; link = nextlink)
{
nextlink = link->next;
if (link->ConnectScript)
{
int n = 0;
while(link->ConnectScript[n])
free(link->ConnectScript[n++]);
free(link->ConnectScript);
}
free(link->alias);
link->alias = 0;
free(link->call);
link->call = 0;
free(link);
link = 0;
}
link_hd = NULL;
}
VOID removeknown()
{
// Save Known Nodes list and free struct
KNOWNNODE *node, *nextnode;
FILE *out;
out = fopen(RtKnown, "w");
if (!out)
return;
for (node = known_hd; node; node = nextnode)
{
fprintf(out, "%s %u\n", node->call, (unsigned int)node->LastHeard);
nextnode = node->next;
free(node->call);
free(node);
}
known_hd = NULL;
fclose(out);
}
VOID LoadKnown()
{
// Reload Known Nodes list
FILE *in;
char buf[128];
char * ptr;
in = fopen(RtKnown, "r");
if (in == NULL)
return;
while(fgets(buf, 128, in))
{
ptr = strchr(buf, ' ');
if (ptr)
{
*(ptr) = 0;
knownnode_add(buf);
}
}
fclose(in);
}
// We don't allocate memory for circuit, but we do chain it
ChatCIRCUIT *circuit_new(ChatCIRCUIT *circuit, int flags)
{
// Make sure circuit isn't already on list
ChatCIRCUIT *c;
circuit->rtcflags = flags;
circuit->next = NULL;
for (c = circuit_hd; c; c = c->next)
{
if (c == circuit)
{
Debugprintf("CHAT: Attempting to add Circuit when already on list");
return circuit;
}
}
sl_ins_hd(circuit, circuit_hd);
return circuit;
}
// Handle an incoming link. We should only get here if we think the station is a node.
int rtloginl (ChatCIRCUIT *conn, char * call)
{
LINK * link;
if (node_find(call))
{
Logprintf(LOG_CHAT, conn, '|', "Refusing link from %s to %s to prevent a loop", conn->Callsign, OurNode);
nprintf(conn, "Refusing link from %s to %s to prevent a loop.\n", conn->Callsign, OurNode);
ChatFlush(conn);
Sleep(500);
conn->rtcflags = p_nil;
Disconnect(conn->BPQStream);
return FALSE; // Already linked.
}
for (link = link_hd; link; link = link->next)
{
if (matchi(call, link->call))
break;
}
if (!link)
{
// We don't link with this system. Shouldn't happen, as we checked earlier
nprintf(conn, "Node %s does not have %s defined as a node to link to - closing.\r",
OurNode, conn->Callsign);
ChatFlush(conn);
Sleep(500);
conn->rtcflags = p_nil;
Disconnect(conn->BPQStream);
return FALSE;
}
if (link->flags & (p_linked | p_linkini))
{
// Already Linked. Used to Disconnect, but that can cause sync errors
// Try closing old link and keeping new
ChatCIRCUIT *c;
int len;
char Msg[80];
for (c = circuit_hd; c; c = c->next)
{
if (c->u.link == link)
{
len=sprintf_s(Msg, sizeof(Msg), "Chat Node %s Connect when Connected - Old Connection Closed", call);
ChatWriteLogLine(conn, '|',Msg, len, LOG_CHAT);
c->Active = FALSE; // So we don't try to clear circuit again
Disconnect(c->BPQStream);
link_drop(c);
RefreshMainWindow();
break;
}
}
}
// Accept the link request.
circuit_new(conn, p_linked);
conn->u.link = link;
nputs(conn, "OK\r");
link->flags = p_linked;
link->delay = 0; // Dont delay first restart
state_tell(conn, NULL);
conn->u.link->timePollSent = time(NULL); // Keepalive is a poll
nprintf(conn, "%c%c%s %s %s\r", FORMAT, id_keepalive, OurNode, conn->u.link->call, Verstring);
NeedStatus = TRUE;
return TRUE;
}
// User connected to chat, or did chat command from BBS
int rtloginu (ChatCIRCUIT *circuit, BOOL Local)
{
USER *user;
// Is this user already logged in to RT somewhere else?
user = user_find(circuit->UserPointer->Call, NULL);
if (user)
{
// if connected at this node, kill old connection and allow new login
if (user->node == node_find(OurNode))
{
nputs(circuit, "*** Already connected at this node - old session will be closed.\r");
if (user->circuit->BPQStream < 0)
{
CloseConsole(user->circuit->BPQStream);
}
else
{
Disconnect(user->circuit->BPQStream);
}
}
else
nputs(circuit, "*** Already connected at another node.\r");
return FALSE;
}
// Create the user entry.
circuit_new(circuit, p_user);
user = user_join(circuit, circuit->UserPointer->Call, OurNode, OurAlias, Local);
circuit->u.user = user;
if (strcmp(user->name, "?_name") == 0)
{
user->name = _strdup(circuit->UserPointer->Name);
}
upduser(user);
ChatExpandAndSendMessage(circuit, ChatWelcomeMsg, LOG_CHAT);
text_tellu_Joined(user);
user_tell(user, id_join);
show_users(circuit);
user->lastsendtime = time(NULL);
// makelinks();
return TRUE;
}
void logout(ChatCIRCUIT *circuit)
{
USER *user;
CHATNODE *node;
circuit->rtcflags = p_nil;
user = circuit->u.user;
if (user) // May not have logged in if already conencted
{
node = user->node;
user_tell(user, id_leave);
text_tellu(user, rtleave, NULL, o_all);
user_leave(user);
// order changed so node_dec can check if a node that is about the be deleted has eny users
if (node)
{
cn_dec(circuit, node);
node_dec(node);
}
circuit->u.user = NULL;
}
circuit_free(circuit);
}
void show_users(ChatCIRCUIT *circuit)
{
USER *user;
char * Alias;
char * Topic;
int i = 0;
// First count them
for (user = user_hd; user; user = user->next)
{
i++;
}
nprintf(circuit, "%d Station(s) connected:\r", i);
for (user = user_hd; user; user = user->next)
{
if ((user->node == 0) || (user->node->alias == 0))
Alias = "(Corrupt Alias)";
else
Alias = user->node->alias;
if ((user->topic == 0) || (user->topic->name == 0))
Topic = "(Corrupt Topic)";
else
Topic = user->topic->name;
#ifndef LINBPQ
__try
{
#endif
if (circuit->u.user->rtflags & u_colour) // Use Colour
nprintf(circuit, "\x1b%c%-6.6s at %-9.9s %s, %s [%s] Idle for %d seconds\r",
user->Colour, user->call, Alias, user->name, user->qth, Topic, time(NULL) - user->lastrealmsgtime);
else
nprintf(circuit, "%-6.6s at %-9.9s %s, %s [%s] Idle for %d seconds\r",
user->call, Alias, user->name, user->qth, Topic, time(NULL) - user->lastrealmsgtime);
#ifndef LINBPQ
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
Debugprintf("MAILCHAT *** Program Error in show_users");
CheckProgramErrors();
}
#endif
}
}
static void show_nodes(ChatCIRCUIT *circuit)
{
CHATNODE *node;
nputs(circuit, "Known Nodes:\r");
for (node = node_hd; node; node = node->next)
{
if (node->refcnt)
if (node->Version)
nprintf(circuit, "%s:%s %s %u\r", node->alias, node->call, node->Version, node->refcnt);
else
nprintf(circuit, "%s:%s %s %u\r", node->alias, node->call, "Not Known", node->refcnt);
}
}
// /P Command: List circuits and remote RT on them.
#define xxx "\r "
static void show_circuits(ChatCIRCUIT *conn, char Flag)
{
ChatCIRCUIT *circuit;
CHATNODE *node;
LINK *link;
char line[1000];
int len = 0;
CN *cn;
int i = 0;
// First count them
for (node = node_hd; node; node = node->next)
{
i++;
}
nprintf(conn, "%d Node(s)\r", i);
if (Flag == 'c')
len = sprintf(line, "Here %-6.6s <-", OurNode);
else
len = sprintf(line, "Here %-6.6s <-", OurAlias);
for (node = node_hd; node; node = node->next) if (node->refcnt)
{
if (Flag == 'c')
len += sprintf(&line[len], " %s", node->call);
else
len += sprintf(&line[len], " %s", node->alias);
if (len > 80)
{
nprintf(conn, "%s\r", line);
len = sprintf(line, " ");
}
}
nprintf(conn, "%s\r", line);
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (circuit->rtcflags & p_linked)
{
if (Flag == 'c')
len = sprintf(line, "Nodes via %-6.6s(%d) -", circuit->u.link->call, circuit->refcnt);
else
len = sprintf(line, "Nodes via %-6.6s(%d) -", circuit->u.link->alias, circuit->refcnt);
#ifndef LINBPQ
__try{
for (cn = circuit->hnode; cn; cn = cn->next)
{
if (cn->node && cn->node->alias)
{
__try
{
if (Flag == 'c')
len += sprintf(&line[len], " %s", cn->node->call);
else
len += sprintf(&line[len], " %s", cn->node->alias);
if (len > 80)
{
nprintf(conn, "%s\r", line);
len = sprintf(line, " ");
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{len += sprintf(&line[len], " *PE* Corrupt Rec %x %x", cn, cn->node);}
}
else
len = sprintf(&line[len], " Corrupt Rec %x %x ", cn, cn->node);
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{len += sprintf(&line[len], " *PE* Corrupt Rec %x %x ", cn, cn->node);}
#else
for (cn = circuit->hnode; cn; cn = cn->next)
{
if (cn->node && cn->node->alias)
{
if (Flag == 'c')
len += sprintf(&line[len], " %s", cn->node->call);
else
len += sprintf(&line[len], " %s", cn->node->alias);
if (len > 80)
{
nprintf(conn, "%s\r", line);
len = sprintf(line, " ");
}
}
else
len += sprintf(&line[len], " Corrupt Rec %p %p ", cn, cn->node);
}
#endif
nprintf(conn, "%s\r", line);
}
else if (circuit->rtcflags & p_user)
nprintf(conn, "User %-6.6s\r", circuit->u.user->call);
else if (circuit->rtcflags & p_linkini)
{
if (circuit->u.link)
{ if (Flag == 'c')
nprintf(conn, "Link %-6.6s (setup)\r", circuit->u.link->call);
else
nprintf(conn, "Link %-6.6s (setup)\r", circuit->u.link->alias);
}
else
nprintf(conn, "Link ?? (setup)\r");
}
}
nprintf(conn, "Links Defined:\r");
for (link = link_hd; link; link = link->next)
{
if (link->flags & p_linked )
if (link->supportsPolls)
nprintf(conn, " %-10.10s Open RTT %d\r", link->call, link->RTT);
else
nprintf(conn, " %-10.10s Open\r", link->call);
else if (link->flags & (p_linked | p_linkini))
nprintf(conn, " %-10.10s Connecting\r", link->call);
else if (link->flags & p_linkfailed)
nprintf(conn, " %-10.10s Connect failed\r", link->call);
else
nprintf(conn, " %-10.10s Idle\r", link->call);
}
}
// /T Command: List topics and users in them.
static void show_topics(ChatCIRCUIT *conn)
{
TOPIC *topic;
USER *user;
nputs(conn, "Active Topics are:\r");
for (topic = topic_hd; topic; topic = topic->next)
{
nprintf(conn, "%s\r", topic->name);
if (topic->refcnt)
{
nputs(conn, " ");
for (user = user_hd; user; user = user->next)
{
if (user->topic == topic)
nprintf(conn, " %s", user->call);
}
nputc(conn, '\r');
}
}
}
static void show_users_in_topic(ChatCIRCUIT *conn)
{
TOPIC *topic;
USER *user;
nputs(conn, "Users in Topic:\r");
topic = conn->u.user->topic;
{
if (topic->refcnt)
{
for (user = user_hd; user; user = user->next)
{
if (user->topic == topic)
nprintf(conn, "%s ", user->call);
}
nputc(conn, '\r');
}
}
}
// Do a user command.
int rt_cmd(ChatCIRCUIT *circuit, char * Buffer)
{
ChatCIRCUIT *c;
USER *user, *su;
char *f1, *f2;
user = circuit->u.user;
// user->lastsendtime = time(NULL);
switch(tolower(Buffer[1]))
{
case 'a' :
user->rtflags ^= u_bells;
upduser(user);
nprintf(circuit, "Alert %s\r", (user->rtflags & u_bells) ? "Enabled" : "Disabled");
return TRUE;
case 'b' : return FALSE;
case 'c' :
user->rtflags ^= u_colour;
upduser(user);
nprintf(circuit, "Colour Mode %s\r", (user->rtflags & u_colour) ? "Enabled" : "Disabled");
return TRUE;
case 'e' :
user->rtflags ^= u_echo;
upduser(user);
nprintf(circuit, "Echo %s\r", (user->rtflags & u_echo) ? "Enabled" : "Disabled");
return TRUE;
case 'f' : makelinks(); return TRUE;
case 'h' :
case '?' :
{
char * Save;
char * MsgBytes = Save = ReadInfoFile("chathelp.txt");
if (MsgBytes)
{
int Length;
// Remove lf chars
Length = RemoveLF(MsgBytes, (int)strlen(MsgBytes));
ChatQueueMsg(circuit, MsgBytes, Length);
free(Save);
}
else
{
nputs(circuit, "Commands can be in upper or lower case.\r");
nputs(circuit, "/U - Show Users.\r/N - Enter your Name.\r/Q - Enter your QTH.\r/T - Show Topics.\r");
nputs(circuit, "/T Name - Join Topic or Create new Topic. Topic Names are not case sensitive\r/P - Show Ports and Links.\r");
nprintf(circuit, "/A - Toggle Alert on user join - %s.\r",
(user->rtflags & u_bells) ? "Enabled" : "Disabled");
nprintf(circuit, "/C - Toggle Colour Mode on or off (only works on Console or BPQTerm/TermTCP/QtTermTCP - %s.\r",
(user->rtflags & u_colour) ? "Enabled" : "Disabled");
nputs(circuit, "/Codepage CPnnnn - Set Codepage to use if UTF-8 is disabled.\r");
nprintf(circuit, "/E - Toggle Echo - %s .\r",
(user->rtflags & u_echo) ? "Enabled" : "Disabled");
nprintf(circuit, "/Keepalive - Toggle sending Keepalive messages every 10 minutes - %s.\r",
(user->rtflags & u_keepalive) ? "Enabled" : "Disabled");
nprintf(circuit, "/ShowNames - Toggle displaying name as well as call on each message - %s\r",
(user->rtflags & u_shownames) ? "Enabled" : "Disabled");
nprintf(circuit, "/Auto - Toggle Automatic character set selection - %s.\r",
(user->rtflags & u_auto) ? "Enabled" : "Disabled");
nprintf(circuit, "/UTF-8 - Character set Selection - %s.\r",
(user->rtflags & u_noUTF8) ? "8 Bit" : "UTF-8");
nprintf(circuit, "/Time - Toggle displaying timestamp on each message - %s.\r",
(user->rtflags & u_showtime) ? "Enabled" : "Disabled");
nputs(circuit, "/S CALL Text - Send Text to that station only.\r");
nputs(circuit, "/F - Force all links to be made.\r/K - Show Known nodes.\r");
nputs(circuit, "/B - Leave Chat and return to node.\r/QUIT - Leave Chat and disconnect from node.\r");
nputs(circuit, "/History nn - Display chat messages received in last nn minutes.\r");
}
}
return TRUE;
case 'k' : show_nodes(circuit); return TRUE;
case 'n' :
f1 = &Buffer[2];
while ((*f1 != 0) && (*f1 == ' '))
f1++;
if (*f1 == 0)
{
nprintf(circuit, "Name is %s\r", user->name);
return TRUE;
}
strnew(&user->name, f1);
nprintf(circuit, "Name set to %s\r", user->name);
upduser(user);
user_tell(user, id_user);
return TRUE;
case 'p' : show_circuits(circuit, Buffer[3]); return TRUE;
case 'q' :
f1 = &Buffer[2];
while ((*f1 != 0) && (*f1 == ' '))
f1++;
if (*f1 == 0)
{
nprintf(circuit, "QTH is %s\r", user->qth);
return TRUE;
}
strnew(&user->qth, f1);
nprintf(circuit, "QTH set to %s\r", user->qth);
upduser(user);
user_tell(user, id_user);
return TRUE;
case 's' :
strcat(Buffer, "\r");
f1 = strlop(Buffer, ' '); // To.
if (!f1) break;
f2 = strlop(f1, ' '); // Text to send.
if (!f2) break;
_strupr(f1);
su = user_find(f1, NULL);
if (!su)
{
nputs(circuit, "*** That user is not logged in.\r");
return TRUE;
}
// Send to the desired user only.
if (su->circuit->rtcflags & p_user)
text_tellu(user, f2, f1, o_one);
else
text_xmit(user, su, f2);
return TRUE;
case 't' :
f1 = strlop(Buffer, ' ');
if (f1)
{
if (topic_chg(user, f1))
{
nprintf(circuit, "Switched to Topic %s\r", user->topic->name);
show_users_in_topic(circuit);
// Tell all link circuits about the change of topic.
for (c = circuit_hd; c; c = c->next)
{
if (c->rtcflags & p_linked)
topic_xmit(user, c);
}
}
else
{
// Already in topic
nprintf(circuit, "You were already in Topic %s\r", user->topic->name);
}
}
else
show_topics(circuit);
return TRUE;
case 'u' : show_users(circuit); return TRUE;
default : break;
}
saywhat(circuit);
return TRUE;
}
void makelinks(void)
{
LINK *link;
ChatCIRCUIT *circuit;
// Make the links. Called every 10 seconds
// Make sure previous link has completed or failed
if (RunningConnectScript)
{
// Make sure Connect Script isn't taking too long
if (time(NULL) - RunningConnectScript < 30)
return;
// Running too long - close it
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
// Find the link
if (circuit->rtcflags & (p_linkini))
{
link = circuit->u.link;
link->flags = p_linkfailed;
RunningConnectScript = 0;
link->scriptRunning = 0; // so it doesn't get reentered
Logprintf(LOG_CHAT, circuit, '|', "Connect to %s timed out", circuit->Callsign);
Disconnect(circuit->BPQStream);
}
}
RunningConnectScript = 0;
}
for (link = link_hd; link; link = link->next)
{
// Is this link already established?
if (link->flags & (p_linked | p_linkini))
continue;
// Already linked through some other node?
// If so, making this link would create a loop.
if (node_find(link->call))
continue;
// Fire up the process to handle this link.
if (link->delay == 0)
{
link->flags = p_linkini;
link->delay = 12; // 2 mins
chat_link_out(link);
return; // One at a time
}
else
link->delay--;
}
}
VOID node_close()
{
// Close all Node-Node Links
ChatCIRCUIT *circuit;
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (circuit->rtcflags & (p_linked | p_linkini | p_linkwait))
Disconnect(circuit->BPQStream);
}
}
// Send Keepalives to all connected nodes
static void node_keepalive()
{
ChatCIRCUIT *circuit;
NeedStatus = TRUE; // Send Report to Monitor
if (user_hd) // Any Users?
{
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (circuit->rtcflags & p_linked && circuit->u.link)
{
nprintf(circuit, "%c%c%s %s %s\r", FORMAT, id_keepalive, OurNode, circuit->u.link->call, Verstring);
circuit->u.link->timePollSent = time(NULL); // Also acts as poll
}
}
}
else
{
// No users. Close links
node_close();
}
}
VOID ChatTimer()
{
// Entered every 10 seconds
int i = 0;
ChatCIRCUIT *c;
#ifndef LINBPQ
int len;
CHATNODE *node;
TOPIC *topic;
char Msg[256];
#endif
USER *user;
time_t NOW = time(NULL);
GetSemaphore(&ChatSemaphore, 0);
if (NeedStatus)
{
NeedStatus = FALSE;
SendChatLinkStatus();
}
#ifndef LINBPQ
ClearDebugWindow();
WritetoDebugWindow("Chat Nodes\r\n", 12);
for (node = node_hd; node; node = node->next)
{
len = sprintf_s(Msg, sizeof(Msg), "%s Version %s Count %d\r\n",
node->call, node->Version, node->refcnt);
WritetoDebugWindow(Msg, len);
i++;
}
SetDlgItemInt(hWnd, IDC_NODES, i, FALSE);
WritetoDebugWindow("Chat Links\r\n", 12);
i = 0;
for (c = circuit_hd; c; c = c->next)
{
if (c->rtcflags & p_linked)
{
char buff[1000];
int ptr;
CT * ct;
ptr = sprintf_s(buff, sizeof(buff), "%s Topics: ", c->u.user->call);
if (c->topic)
{
for (ct = c->topic; ct; ct = ct->next)
{
ptr+= sprintf_s(&buff[ptr], sizeof(buff) - ptr, "%s ", ct->topic->name);
}
}
WritetoDebugWindow(buff, ptr);
WritetoDebugWindow("\r\n", 2);
i++;
}
}
SetDlgItemInt(hWnd, IDC_LINKS, i, FALSE);
WritetoDebugWindow("Chat Topics\r\n", 12);
i = 0;
for (topic = topic_hd; topic; topic = topic->next)
{
len = sprintf_s(Msg, sizeof(Msg), "%s %d\r\n", topic->name, topic->refcnt);
WritetoDebugWindow(Msg, len);
i++;
}
WritetoDebugWindow("Chat Users\r\n", 12);
i = 0;
for (user = user_hd; user; user = user->next)
{
len = sprintf_s(Msg, sizeof(Msg), "%s Topic %s\r\n", user->call,
(user->topic) ? user->topic->name : "** Missing Topic **");
WritetoDebugWindow(Msg, len);
i++;
if (user->circuit && user->circuit->rtcflags & p_user) // Local User
{
time_t Idle = NOW - user->lastmsgtime;
if (Idle > 7200)
{
nprintf(user->circuit, "*** Disconnected - Idle time exceeded\r");
Sleep(1000);
if (user->circuit->BPQStream < 0)
{
CloseConsole(user->circuit->BPQStream);
break;
}
else
{
Disconnect(user->circuit->BPQStream);
break;
}
}
if ((user->rtflags & u_keepalive) && (NOW - user->lastsendtime) > 600)
{
nprintf(user->circuit, "Chat Keepalive\r");
user->lastsendtime = NOW;
}
}
}
SetDlgItemInt(hWnd, IDC_USERS, i, FALSE);
#else
for (user = user_hd; user; user = user->next)
{
if (user->circuit && user->circuit->rtcflags & p_user) // Local User
{
if ((NOW - user->lastmsgtime) > 7200)
{
nprintf(user->circuit, "*** Disconnected - Idle time exceeded\r");
Sleep(1000);
if (user->circuit->BPQStream < 0)
{
CloseConsole(user->circuit->BPQStream);
break;
}
else
{
Disconnect(user->circuit->BPQStream);
break;
}
}
if ((user->rtflags & u_keepalive) && (NOW - user->lastsendtime) > 600)
{
nprintf(user->circuit, "Chat Keepalive\r");
user->lastsendtime = NOW;
}
}
}
#endif
// if no message on a Node-Node link, send poll
for (c = circuit_hd; c; c = c->next)
{
if (c->rtcflags & p_linked && c->u.link)
{
time_t Now = time(NULL);
LINK * Link = c->u.link;
if (Now - Link->lastMsgReceived > 60)
{
// if we have a poll outstanding for ? 30 secs close link
// but check other end can handle polls
if (Link->supportsPolls && Link->timePollSent && Now - Link->timePollSent > 30)
{
Logprintf(LOG_CHAT, c, '|', "%s No Poll Response for %d Secs - Dropping Link",
c->Callsign, Now - Link->timePollSent);
Disconnect(c->BPQStream);
continue;
}
Link->timePollSent = Now;
nprintf(c, "%c%c%s %s\r", FORMAT, id_poll, OurNode, Link->call);
}
}
}
ChatTmr++;
if (user_hd) // Any Users?
makelinks();
if (ChatTmr > 60) // 10 Mins
{
ChatTmr = 1;
node_keepalive();
}
FreeSemaphore(&ChatSemaphore);
if (NeedINFO)
{
NeedINFO--;
if (NeedINFO == 0)
{
// Send INFO to Chatmap
char Msg[500];
int len;
NeedINFO = 360; // Send Every Hour
if (Position[0])
{
len = sprintf(Msg, "INFO %s|%s|%d|\r", Position, PopupText, PopupMode);
if (len < 256)
Send_MON_Datagram(Msg, len);
}
}
}
}
VOID FreeChatMemory()
{
removelinks();
removeknown();
}
// Find a call in the known node list.
KNOWNNODE *knownnode_find(char *call)
{
KNOWNNODE *node;
for (node = known_hd; node; node = node->next)
{
if (matchi(node->call, call))
break;
}
return node;
}
// Add a known node.
static KNOWNNODE *knownnode_add(char *call)
{
KNOWNNODE *node;
node = knownnode_find(call);
if (!node)
{
node = zalloc(sizeof(KNOWNNODE));
sl_ins_hd(node, known_hd);
node->call = _strdup(call);
}
node->LastHeard = time(NULL);
return node;
}
static char UIDEST[10] = "DUMMY";
static char AXDEST[7];
static char ChatMYCALL[7];
#pragma pack(1)
typedef struct _MESSAGEX
{
// BASIC LINK LEVEL MESSAGE BUFFER LAYOUT
struct _MESSAGE * CHAIN;
UCHAR PORT;
USHORT LENGTH;
UCHAR DEST[7];
UCHAR ORIGIN[7];
// MAY BE UP TO 56 BYTES OF DIGIS
UCHAR CTL;
UCHAR PID;
UCHAR DATA[256];
}MESSAGEX, *PMESSAGEX;
#pragma pack()
SOCKET ChatReportSocket = 0;
VOID SetupChat()
{
u_long param=1;
BOOL bcopt=TRUE;
ConvToAX25(OurNode, ChatMYCALL);
ConvToAX25(UIDEST, AXDEST);
sprintf(Verstring, "%d.%d.%d.%d", Ver[0], Ver[1], Ver[2], Ver[3]);
LoadKnown();
ChatReportSocket = socket(AF_INET,SOCK_DGRAM,0);
if (ChatReportSocket == INVALID_SOCKET)
{
Debugprintf("Failed to create Chat Reporting socket");
ChatReportSocket = 0;
return;
}
ioctlsocket (ChatReportSocket, FIONBIO, ¶m);
setsockopt (ChatReportSocket, SOL_SOCKET, SO_BROADCAST, (const char FAR *)&bcopt,4);
}
VOID Send_MON_Datagram(UCHAR * Msg, DWORD Len)
{
MESSAGEX AXMSG;
PMESSAGEX AXPTR = &AXMSG;
if (Len > 256)
{
Debugprintf("Send_MON_Datagram Error Msg = %s Len = %d", Msg, Len);
return;
}
// ConvToAX25("GM4OAS-5", ChatMYCALL);
// Block includes the Msg Header (7 bytes), Len Does not!
memcpy(AXPTR->DEST, AXDEST, 7);
memcpy(AXPTR->ORIGIN, ChatMYCALL, 7);
AXPTR->DEST[6] &= 0x7e; // Clear End of Call
AXPTR->DEST[6] |= 0x80; // set Command Bit
AXPTR->ORIGIN[6] |= 1; // Set End of Call
AXPTR->CTL = 3; //UI
AXPTR->PID = 0xf0;
memcpy(AXPTR->DATA, Msg, Len);
SendChatReport(ChatReportSocket, (char *)&AXMSG.DEST, Len + 16);
return;
}
VOID SendChatLinkStatus()
{
char Msg[256] = {0};
LINK * link;
int len = 0;
ChatCIRCUIT *circuit;
if (ChatApplNum == 0)
return;
// if (AXIPPort == 0)
// return;
if (ChatMYCALL[0] == 0)
return;
for (link = link_hd; link; link = link->next)
{
if (link->flags & p_linked)
{
// Verify connection
for (circuit = circuit_hd; circuit; circuit = circuit->next)
{
if (strcmp(circuit->Callsign, link->alias) == 0)
{
if (circuit->Active == 0)
{
// BPQ Session is dead - Simulate a Disconnect
circuit->Active = TRUE; // So disconnect will work
Disconnected(circuit->BPQStream);
NeedStatus = TRUE; // Reenter
return; // Link Chain has changed
}
break;
}
}
if (circuit == 0)
{
// No BPQ Session - is the only answer to restart the node?
// Logprintf(LOG_DEBUGx, NULL, '!', "Stuck Chat Sesion Detected");
// Logprintf(LOG_DEBUGx, NULL, '!', "Chat is a mess - forcing a restart");
// ProgramErrors = 26;
// CheckProgramErrors();
}
}
len += sprintf(&Msg[len], "%s %c ", link->call, '0' + link->flags);
if (len > 240)
break;
}
Msg[len++] = '\r';
Send_MON_Datagram(Msg, len);
}
VOID ClearChatLinkStatus()
{
LINK * link;
for (link = link_hd; link; link = link->next)
{
link->flags = 0;
}
}
BOOL ProcessChatConnectScript(ChatCIRCUIT * conn, char * Buffer, int len)
{
LINK * link = conn->u.link;
char ** Scripts;
ChatWriteLogLine(conn, '<', Buffer, len-1, LOG_CHAT);
Buffer[len] = 0;
_strupr(Buffer);
Scripts = link->ConnectScript;
if (strstr(Buffer, "BUSY") || strstr(Buffer, "FAILURE") ||
(strstr(Buffer, "DOWNLINK") && strstr(Buffer, "ATTEMPTING") == 0) ||
strstr(Buffer, "SORRY") || strstr(Buffer, "INVALID") || strstr(Buffer, "RETRIED") ||
strstr(Buffer, "NO CONNECTION TO") || strstr(Buffer, "ERROR - ") ||
strstr(Buffer, "UNABLE TO CONNECT") || strstr(Buffer, "DISCONNECTED") ||
strstr(Buffer, "FAILED TO CONNECT") || strstr(Buffer, "REJECTED"))
{
// Connect Failed
link->flags = p_linkfailed;
RunningConnectScript = 0;
link->scriptRunning = 0; // so it doesn't get reentered
Disconnect(conn->BPQStream);
return FALSE;
}
// The pointer is only updated when we get the connect, so we can tell when the last line is acked
// The first entry is always from Connected event, so don't have to worry about testing entry -1 below
if (link->RTLSent)
{
RunningConnectScript = 0;
link->scriptRunning = 0;
link->RTLSent = 0;
if (memcmp(Buffer, "OK", 2) == 0)
{
// Reply to *RTL
// Make sure node isn't known. There is a window here that could cause a loop
if (node_find(conn->u.link->call))
{
Logprintf(LOG_CHAT, conn, '|', "Dropping link with %s to prevent a loop", conn->Callsign);
Disconnect(conn->BPQStream);
return FALSE;
}
conn->u.link->flags = p_linked;
conn->rtcflags = p_linked;
state_tell(conn, conn->FBBReplyChars);
NeedStatus = TRUE;
return TRUE;
}
// Some other response to *RTL - disconnect
Logprintf(LOG_CHAT, conn, '|', "Unexpected Response %s to *RTL - Dropping link", Buffer);
Disconnect(conn->BPQStream);
return FALSE;
}
if (strstr(Buffer, " CONNECTED") || strstr(Buffer, "PACLEN") || strstr(Buffer, "IDLETIME") ||
strstr(Buffer, "OK") || strstr(Buffer, "###LINK MADE") || strstr(Buffer, "VIRTUAL CIRCUIT ESTABLISHED"))
{
char * Cmd;
LoopBack:
Cmd = Scripts[++link->ScriptIndex];
// Only Check until script is finished
if (Cmd == 0 || link->ScriptIndex >= link->Lines)
{
link->MoreLines = FALSE;
return TRUE;
}
if (Cmd && (strcmp(Cmd, " ") == 0 || Cmd[0] == ';' || Cmd[0] == '#'))
goto LoopBack; // Blank line
// Replace \ with # so can send commands starting with #
if (Cmd[0] == '\\')
{
Cmd[0] = '#';
nprintf(conn, "%s\r", Cmd);
Cmd[0] = '\\'; // Put \ back in script
}
else
nprintf(conn, "%s\r", Cmd);
return TRUE;
}
if (memcmp(Buffer, "[BPQCHATSERVER-", 15) == 0)
{
char * ptr = strchr(Buffer, ']');
if (ptr)
{
*ptr = 0;
strcpy(conn->FBBReplyChars, &Buffer[15]);
}
else
conn->FBBReplyChars[0] = 0;
// Connected - Send *RTL
nputs(conn, "*RTL\r"); // Log in to the remote RT system.
conn->u.link->timePollSent = time(NULL); // Keepalive is a poll
nprintf(conn, "%c%c%s %s %s\r", FORMAT, id_keepalive, OurNode, conn->u.link->call, Verstring);
link->RTLSent = 1;
conn->u.link->lastMsgSent = time(NULL);
return TRUE;
}
// Anthing else could be ctext. etc. Ignore
return TRUE;
}
#ifdef LINBPQ
// LINCHAT specific code
extern struct SEM OutputSEM;
static config_t cfg;
static config_setting_t * group;
extern char pgm[256];
char ChatSYSOPCall[50] = "";
VOID ChatSendWelcomeMsg(int Stream, ChatCIRCUIT * conn, struct UserInfo * user);
int ChatConnected(int Stream)
{
int n;
ChatCIRCUIT * conn;
struct UserInfo * user = NULL;
char callsign[10];
int port, paclen, maxframe, l4window;
char ConnectedMsg[] = "*** CONNECTED ";
char Msg[100];
LINK *link;
KNOWNNODE *node;
for (n = 0; n < NumberofChatStreams; n++)
{
conn = &ChatConnections[n];
if (Stream == conn->BPQStream)
{
if (conn->Active)
{
// Probably an outgoing connect
if (conn->rtcflags == p_linkini)
{
conn->paclen = chatPaclen;
// Run first line of connect script
ProcessChatConnectScript(conn, ConnectedMsg, 15);
// nprintf(conn, "c %s\r", conn->u.link->call);
}
return 0;
}
memset(conn, 0, sizeof(ChatCIRCUIT)); // Clear everything
conn->Active = TRUE;
conn->BPQStream = Stream;
conn->Secure_Session = GetConnectionInfo(Stream, callsign,
&port, &conn->SessType, &paclen, &maxframe, &l4window);
if (paclen == 0)
paclen = 256;
if (paclen > chatPaclen)
paclen = chatPaclen;
conn->paclen = paclen;
strlop(callsign, ' '); // Remove trailing spaces
memcpy(conn->Callsign, callsign, 10);
strlop(callsign, '-'); // Remove any SSID
user = zalloc(sizeof(struct UserInfo));
strcpy(user->Call, callsign);
conn->UserPointer = user;
n=sprintf_s(Msg, sizeof(Msg), "Incoming Connect from %s", user->Call);
// Send SID and Prompt
ChatWriteLogLine(conn, '|',Msg, n, LOG_CHAT);
conn->Flags |= CHATMODE;
nprintf(conn, ChatSID, Ver[0], Ver[1], Ver[2], Ver[3]);
// See if from a defined node
for (link = link_hd; link; link = link->next)
{
if (matchi(conn->Callsign, link->call))
{
conn->rtcflags = p_linkwait;
return 0; // Wait for *RTL
}
}
// See if from a previously known node
node = knownnode_find(conn->Callsign);
if (node)
{
// A node is trying to link, but we don't have it defined - close
Logprintf(LOG_CHAT, conn, '!', "Node %s connected, but is not defined as a Node - closing",
conn->Callsign);
nprintf(conn, "Node %s does not have %s defined as a node to link to - closing.\r",
OurNode, conn->Callsign);
ChatFlush(conn);
Sleep(500);
conn->rtcflags = p_nil;
Disconnect(conn->BPQStream);
return 0;
}
if (user->Name[0] == 0)
{
char * Name = lookupuser(user->Call);
if (Name)
{
if (strlen(Name) > 17)
Name[17] = 0;
strcpy(user->Name, Name);
free(Name);
}
else
{
conn->Flags |= GETTINGUSER;
nputs(conn, NewUserPrompt);
return TRUE;
}
}
ChatSendWelcomeMsg(Stream, conn, user);
RefreshMainWindow();
ChatFlush(conn);
return 0;
}
}
return 0;
}
int ChatDisconnected (ChatCIRCUIT * conn)
{
struct UserInfo * user = NULL;
int Stream = conn->BPQStream;
char Msg[255];
int len;
if (conn->Active == FALSE)
return 0;
ChatClearQueue(conn);
conn->Active = FALSE;
if (conn->Flags & CHATMODE)
{
if (conn->Flags & CHATLINK && conn->u.link)
{
// if running connect script, clear script active
if (conn->u.link->flags & p_linkini)
{
RunningConnectScript = 0;
conn->u.link->scriptRunning = 0;
}
len=sprintf_s(Msg, sizeof(Msg), "Chat Node %s Disconnected", conn->u.link->call);
ChatWriteLogLine(conn, '|',Msg, len, LOG_CHAT);
link_drop(conn);
}
else
{
len=sprintf_s(Msg, sizeof(Msg), "Chat User %s Disconnected", conn->Callsign);
ChatWriteLogLine(conn, '|',Msg, len, LOG_CHAT);
logout(conn);
}
conn->Flags = 0;
conn->u.link = NULL;
conn->UserPointer = NULL;
return 0;
}
return 0;
}
int ChatDoReceivedData(ChatCIRCUIT * conn)
{
int count, InputLen;
UINT MsgLen;
int Stream = conn->BPQStream;
struct UserInfo * user;
char * ptr, * ptr2;
char Buffer[10000];
// May have several messages per packet, or message split over packets
if (conn->InputLen + 1000 > 10000) // Shouldnt have lines longer than this in text mode
conn->InputLen = 0; // discard
GetMsg(Stream, &conn->InputBuffer[conn->InputLen], &InputLen, &count);
if (InputLen == 0) return 0;
conn->Watchdog = 900; // 15 Minutes
conn->InputLen += InputLen;
loop:
if (conn->InputLen == 1 && conn->InputBuffer[0] == 0) // Single Null
{
conn->InputLen = 0;
if (conn->u.user->circuit && conn->u.user->circuit->rtcflags & p_user) // Local User
conn->u.user->lastmsgtime = time(NULL);
return 0;
}
ptr = memchr(conn->InputBuffer, '\r', conn->InputLen);
if (ptr) // CR in buffer
{
user = conn->UserPointer;
ptr2 = &conn->InputBuffer[conn->InputLen];
if (++ptr == ptr2)
{
// Usual Case - single meg in buffer
if (conn->rtcflags == p_linkini) // Chat Connect
ProcessChatConnectScript(conn, conn->InputBuffer, conn->InputLen);
else
ProcessChatLine(conn, user, conn->InputBuffer, conn->InputLen);
conn->InputLen=0;
}
else
{
// buffer contains more that 1 message
MsgLen = conn->InputLen - (int)(ptr2-ptr);
memcpy(Buffer, conn->InputBuffer, MsgLen);
if (conn->rtcflags == p_linkini)
ProcessChatConnectScript(conn, Buffer, MsgLen);
else
ProcessChatLine(conn, user, Buffer, MsgLen);
if (*ptr == 0 || *ptr == '\n')
{
/// CR LF or CR Null
ptr++;
conn->InputLen--;
}
memmove(conn->InputBuffer, ptr, conn->InputLen-MsgLen);
conn->InputLen -= MsgLen;
goto loop;
}
}
return 0;
}
int ChatPollStreams()
{
int state,change;
ChatCIRCUIT * conn;
int n;
struct UserInfo * user = NULL;
char ConnectedMsg[] = "*** CONNECTED ";
for (n = 0; n < NumberofChatStreams; n++)
{
conn = &ChatConnections[n];
SessionState(conn->BPQStream, &state, &change);
if (change == 1)
{
if (state == 1) // Connected
{
GetSemaphore(&ConSemaphore, 0);
ChatConnected(conn->BPQStream);
FreeSemaphore(&ConSemaphore);
}
else
{
GetSemaphore(&ConSemaphore, 0);
ChatDisconnected(conn);
FreeSemaphore(&ConSemaphore);
}
}
ChatDoReceivedData(conn);
}
return 0;
}
BOOL GetChatConfig(char * ConfigName)
{
config_init(&cfg);
/* Read the file. If there is an error, report it and exit. */
if(! config_read_file(&cfg, ConfigName))
{
fprintf(stderr, "%d - %s\n",
config_error_line(&cfg), config_error_text(&cfg));
config_destroy(&cfg);
return(EXIT_FAILURE);
}
group = config_lookup (&cfg, "Chat");
if (group == NULL)
return EXIT_FAILURE;
ChatApplNum = GetIntValue(group, "ApplNum");
MaxChatStreams = GetIntValue(group, "MaxStreams");
reportChatEvents = GetIntValue(group, "reportChatEvents");
chatPaclen = GetIntValue(group, "chatPaclen");
GetStringValue(group, "OtherChatNodes", OtherNodesList, 1000);
GetStringValue(group, "ChatWelcomeMsg", ChatWelcomeMsg, 1000);
GetStringValue(group, "MapPosition", Position, 81);
GetStringValue(group, "MapPopup", PopupText, 260);
PopupMode = GetIntValue(group, "PopupMode");
if (chatPaclen == 0)
chatPaclen = 236;
if (chatPaclen < 60)
chatPaclen = 60;
return EXIT_SUCCESS;
}
VOID SaveChatConfigFile(char * ConfigName)
{
config_setting_t *root, *group;
// Get rid of old config before saving
config_init(&cfg);
root = config_root_setting(&cfg);
group = config_setting_add(root, "Chat", CONFIG_TYPE_GROUP);
SaveIntValue(group, "ApplNum", ChatApplNum);
SaveIntValue(group, "MaxStreams", MaxChatStreams);
SaveIntValue(group, "reportChatEvents", reportChatEvents);
SaveIntValue(group, "chatPaclen", chatPaclen);
SaveStringValue(group, "OtherChatNodes", OtherNodesList);
SaveStringValue(group, "ChatWelcomeMsg", ChatWelcomeMsg);
SaveStringValue(group, "MapPosition", Position);
SaveStringValue(group, "MapPopup", PopupText);
SaveIntValue(group, "PopupMode", PopupMode);
if(! config_write_file(&cfg, ConfigName))
{
fprintf(stderr, "Error while writing file.\n");
config_destroy(&cfg);
return;
}
config_destroy(&cfg);
}
BOOL ChatInit()
{
char * ptr1 = GetApplCall(ChatApplNum);
char * ptr2;
char * Context;
int i;
ChatCIRCUIT * conn;
if (*ptr1 < 0x21)
{
printf("No APPLCALL for Chat APPL\n");
return FALSE;
}
memcpy(OurNode, ptr1, 10);
strlop(OurNode, ' ');
ptr1 = GetApplAlias(ChatApplNum);
memcpy(OurAlias, ptr1,10);
strlop(OurAlias, ' ');
if (ChatSYSOPCall[0] == 0)
{
strcpy(ChatSYSOPCall, OurNode);
strlop(ChatSYSOPCall, '-');
}
sprintf(ChatSignoffMsg, "73 de %s\r", ChatSYSOPCall);
if (ChatWelcomeMsg[0] == 0)
sprintf(ChatWelcomeMsg, "%s's Chat Server.$WType /h for command summary.$WBringing up links to other nodes.$W"
"This may take a minute or two.$WThe /p command shows what nodes are linked.$W", ChatSYSOPCall);
ChatApplMask = 1<<(ChatApplNum-1);
// Set up other nodes list. rtlink messes with the string so pass copy
// On first run config will have spaces not newlines
if (strchr(OtherNodesList, '\r')) // Has connect script entries
{
ptr2 = ptr1 = strtok_s(_strdup(OtherNodesList), "\r\n", &Context);
while (ptr1 && ptr1[0])
{
rtlink(ptr1);
ptr1 = strtok_s(NULL, "\r\n", &Context);
}
}
else
{
ptr2 = ptr1 = strtok_s(_strdup(OtherNodesList), " ,\r", &Context);
while (ptr1)
{
rtlink(ptr1);
ptr1 = strtok_s(NULL, " ,\r", &Context);
}
}
free(ptr2);
SetupChat();
// Allocate Streams
strcpy(pgm, "CHAT");
for (i = 0; i < MaxChatStreams; i++)
{
conn = &ChatConnections[i];
conn->BPQStream = FindFreeStream();
if (conn->BPQStream == 255) break;
NumberofChatStreams++;
SetAppl(conn->BPQStream, 3, ChatApplMask);
Disconnect(conn->BPQStream);
}
strcpy(pgm, "LINBPQ");
return TRUE;
}
#endif
void ChatFlush(ChatCIRCUIT * conn)
{
int tosend, len, sent;
// Try to send data to user. May be stopped by user paging or node flow control
// UCHAR * OutputQueue; // Messages to user
// int OutputQueueLength; // Total Malloc'ed size. Also Put Pointer for next Message
// int OutputGetPointer; // Next byte to send. When Getpointer = Quele Length all is sent - free the buffer and start again.
// BOOL Paging; // Set if user wants paging
// int LinesSent; // Count when paging
// int PageLen; // Lines per page
tosend = conn->OutputQueueLength - conn->OutputGetPointer;
sent = 0;
while (tosend > 0)
{
if (TXCount(conn->BPQStream) > 4)
return; // Busy
if (tosend <= conn->paclen)
len = tosend;
else
len=conn->paclen;
GetSemaphore(&OutputSEM, 0);
SendUnbuffered(conn->BPQStream, &conn->OutputQueue[conn->OutputGetPointer], len);
conn->OutputGetPointer += len;
FreeSemaphore(&OutputSEM);
tosend -= len;
sent++;
if (sent > 4)
return;
}
// All Sent. Free buffers and reset pointers
ChatClearQueue(conn);
}
VOID ChatClearQueue(ChatCIRCUIT * conn)
{
GetSemaphore(&OutputSEM, 0);
conn->OutputGetPointer = 0;
conn->OutputQueueLength = 0;
FreeSemaphore(&OutputSEM);
}
#ifdef LINBPQ
void ChatTrytoSend()
{
// call Flush on any connected streams with queued data
ChatCIRCUIT * conn;
int n;
for (n = 0; n < NumberofChatStreams; n++)
{
conn = &ChatConnections[n];
if (conn->Active == TRUE)
ChatFlush(conn);
}
}
VOID CloseChat()
{
int BPQStream, n;
for (n = 0; n < NumberofChatStreams; n++)
{
BPQStream = ChatConnections[n].BPQStream;
if (BPQStream)
{
SetAppl(BPQStream, 0, 0);
Disconnect(BPQStream);
DeallocateStream(BPQStream);
}
}
ClearChatLinkStatus();
SendChatLinkStatus();
Sleep(1000); // A bit of time for links to close
SendChatLinkStatus(); // Send again to reduce chance of being missed
FreeChatMemory();
}
VOID SendChatReport(SOCKET ChatReportSocket, char * buff, int txlen)
{
unsigned short int crc = compute_crc(buff, txlen);
crc ^= 0xffff;
buff[txlen++] = (crc&0xff);
buff[txlen++] = (crc>>8);
sendto(ChatReportSocket, buff, txlen, 0, (LPSOCKADDR)&Chatreportdest, sizeof(Chatreportdest));
}
#endif
#ifndef WIN32
#define INVALID_HANDLE_VALUE (void *)-1
#endif
static FILE * LogHandle[4] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
static time_t LastLogTime[4] = {0, 0, 0, 0};
static char FilesNames[4][100] = {"", "", "", ""};
static char * Logs[4] = {"BBS", "CHAT", "TCP", "DEBUG"};
BOOL ChatOpenLogfile(int Flags)
{
UCHAR FN[MAX_PATH];
time_t LT;
struct tm * tm;
LT = time(NULL);
tm = gmtime(<);
sprintf(FN,"%s/logs/log_%02d%02d%02d_%s.txt", GetLogDirectory(), tm->tm_year-100, tm->tm_mon+1, tm->tm_mday, Logs[Flags]);
LogHandle[Flags] = fopen(FN, "ab");
#ifndef WIN32
if (strcmp(FN, &FilesNames[Flags][0]))
{
UCHAR SYMLINK[MAX_PATH];
sprintf(SYMLINK,"%s/logLatest_%s.txt", GetBPQDirectory(), Logs[Flags]);
unlink(SYMLINK);
strcpy(&FilesNames[Flags][0], FN);
symlink(FN, SYMLINK);
}
#endif
return (LogHandle[Flags] != NULL);
}
void ChatWriteLogLine(ChatCIRCUIT * conn, int Flag, char * Msg, int MsgLen, int Flags)
{
char CRLF[2] = {0x0d,0x0a};
struct tm * tm;
char Stamp[20];
time_t T;
#ifndef LINBPQ
if (hMonitor)
{
if (Flags == LOG_CHAT)
{
WritetoMonitorWindow((char *)&Flag, 1);
if (conn && conn->Callsign[0])
{
char call[20];
sprintf(call, "%s ", conn->Callsign);
WritetoMonitorWindow(call, 10);
}
else
WritetoMonitorWindow(" ", 10);
WritetoMonitorWindow(Msg, MsgLen);
if (Msg[MsgLen-1] != '\r')
WritetoMonitorWindow(CRLF , 1);
}
else if (Flags == LOG_DEBUGx)
{
WritetoMonitorWindow((char *)&Flag, 1);
WritetoMonitorWindow(Msg, MsgLen);
WritetoMonitorWindow(CRLF , 1);
}
}
#endif
if (Flags == LOG_CHAT && !LogCHAT)
return;
if (LogHandle[Flags] == INVALID_HANDLE_VALUE) ChatOpenLogfile(Flags);
if (LogHandle[Flags] == INVALID_HANDLE_VALUE) return;
T = time(NULL);
tm = gmtime(&T);
sprintf(Stamp,"%02d%02d%02d %02d:%02d:%02d %c",
tm->tm_year-100, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, Flag);
fwrite(Stamp, 1, strlen(Stamp), LogHandle[Flags]);
if (conn && conn->Callsign[0])
{
char call[20];
sprintf(call, "%s ", conn->Callsign);
fwrite(call, 1, 10, LogHandle[Flags]);
}
else
fwrite(" ", 1, 10, LogHandle[Flags]);
fwrite(Msg, 1, MsgLen, LogHandle[Flags]);
if (Flags == LOG_CHAT && Msg[MsgLen-1] == '\r')
fwrite(&CRLF[1], 1, 1, LogHandle[Flags]);
else
fwrite(CRLF, 1, 2, LogHandle[Flags]);
fclose(LogHandle[Flags]);
LogHandle[Flags] = INVALID_HANDLE_VALUE;
}
|