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
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
|
/* sledjchisl.c - opensim-SC management system.
*
* Copyright 2020 David Seikel <sledjchisl@sledjhamr.org>
* Not in SUSv4. An entirely new invention, thus no web site either.
USE_SLEDJCHISL(NEWTOY(sledjchisl, "?vqma", TOYFLAG_USR|TOYFLAG_BIN))
config SLEDJCHISL
bool "sledjchisl"
default y
help
usage: sledjchisl [-vqma] [mode [name]]
opensim-SC management system.
-v verbose mode.
Mode selects what sledjchisl will do -
start
start -q
start Welcome
start Welcome.ini
start Welcome.shini
start "Welcome sim"
Will start a sim or everything.
-q when starting everything wont show the tmux console.
backup
backup -m
backup -m "Joan Smith"
backup Welcome
backup Welcome.ini
backup Welcome.shini
backup "Welcome sim"
Will backup sim or everything.
-m for a members inventory.
gitar m "Joan Smith"
gitar Welcome
gitar Welcome.ini
gitar Welcome.shini
gitar o "Welcome sim"
restart
restart Welcome
restart Welcome.ini
restart Welcome.shini
restart "Welcome sim"
Will stop then start a sim, or everything.
status
status Welcome
status Welcome.ini
status Welcome.shini
status "Welcome sim"
Will show status of a sim, or everything.
stop
stop -a
stop Welcome
stop Welcome.ini
stop Welcome.shini
stop "Welcome sim"
Will stop a sim, or everything.
-a when stopping everything will close down all tmux windows and panes.
*/
// TODO - remember to rebuild all of toybox if any of the above changes.
// Toybox's strend overrides another strend that causes MariaDB library to crash. Renaming it to tb_strend helps.
// I deal with that by using a sed invokation when building toybox.
#define FOR_sledjchisl
#include "toys.h"
GLOBALS(
)
/*
configs/sim01 -
backup-sim
start-sim
stop-sim
Currently they are all links to ../../current/scripts/start-sim,
they should be links to ../../current/bin/sledjchisl,
which itself is a link to ../src/build/toybox/generated/unstripped/toybox or ../src/build/toybox/toybox
They are obsolete now, should remove them.
*/
// TODO - figure out how to automate testing of this.
// Being all interactive and involving external web servers / viewers makes it hard.
// TODO - do all the setup on first run, and check if needed on each start up, to be self healing.
// TODO - pepper could be entered on the console on startup if it's not defined, as a master password sort of thing.
// I'd go as far as protecting the database credentials that way, but legacy OpenSim needs it unprotected.
// Also keep in mind, people want autostart of their services without having to enter passwords on each boot.
// TODO - once it is event driven, periodically run things like session clean ups, self healing, and the secure.sh thing.
// And backups off course.
// As well as regular database pings to keep the connection open.
#include <fcgi_config.h>
#ifdef _WIN32
#include <process.h>
#else
extern char **environ;
#endif
// Don't overide standard stdio stuff.
#define NO_FCGI_DEFINES
#include <fcgi_stdio.h>
#undef NO_FCGI_DEFINES
//#include "fcgiapp.h"
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <luajit.h>
// lua.h has LUA_T* NONE, NIL, BOOLEAN, LIGHTUSERDATA, NUMBER, STRING, TABLE, FUNCTION, USERDATA, THREAD as defines, -1 - 8.
// These are the missing ones. Then later we will have prim, mesh, script, sound, terrain, ...
#define LUA_TGROUP 42
#define LUA_TINTEGER 43
#define LUA_TEMAIL 44
#define LUA_TPASSWORD 45
#define LUA_TFILE 46
#define LUA_TIMAGE 47
#include "lib/fcgi_SC.h"
#include "lib/handlekeys.h"
// Both my_config.h and fcgi_config.h define the same PACKAGE* variables, which we don't use anyway,
// I deal with that by using a sed invokation when building fcgi2.
// https://mariadb.com/kb/en/about-mariadb-connector-c/ Official docs.
// http://dev.mysql.com/doc/refman/5.5/en/c-api-function-overview.html MySQL docs.
// http://zetcode.com/db/mysqlc/ MySQL tutorial.
//#include <my_global.h>
#include <mysql.h>
#include <qlibc.h>
#include <extensions/qconfig.h>
// TODO - I should probably replace openSSL with something else. Only using it for the hash functions, and apparently it's got a bit of a bad rep.
// only sha 512 I think. Which qLibc doesn't have. It has MD5 128 bit, Mummur3 32 and 128 bit, and FNV1 32 and 64 bit.
// qLibc optionally uses openSSL for it's HTTP client stuff.
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include "openssl/hmac.h"
#include <uuid/uuid.h>
typedef enum
{
START = 0,
BACKUP = 1,
GITAR = 2,
RESTART = 3,
STATUS = 4,
STOP = 9
} modes;
modes currentMode = START;
char *modeStrings[] =
{
"start",
"backup",
"gitAR",
"restart",
"status",
"Huh?",
"WTF?",
"mumblefuck",
"dontDoThis"
"stop"
};
// Duplicate some small amount of code from qLibc, coz /, + and, = are not good choices, and the standard says we can pick those.
/**
* Encode data using BASE64 algorithm.
*
* @param bin a pointer of input data.
* @param size the length of input data.
*
* @return a malloced string pointer of BASE64 encoded string in case of
* successful, otherwise returns NULL
*
* @code
* const char *text = "hello world";
*
* char *encstr = qB64_encode(text, strlen(text));
* if(encstr == NULL) return -1;
*
* printf("Original: %s\n", text);
* printf("Encoded : %s\n", encstr);
*
* size_t decsize = qB64_decode(encstr);
*
* printf("Decoded : %s (%zu bytes)\n", encstr, decsize);
* free(encstr);
*
* --[output]--
* Original: hello world
* Encoded: aGVsbG8gd29ybGQ=
* Decoded: hello world (11 bytes)
* @endcode
*/
char *qB64_encode(const void *bin, size_t size) {
const char B64CHARTBL[64] = {
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', // 00-0F
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', // 10-1F
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', // 20-2F
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' // 30-3F
};
if (size == 0) {
return strdup("");
}
// malloc for encoded string
char *pszB64 = (char *) malloc(
4 * ((size / 3) + ((size % 3 == 0) ? 0 : 1)) + 1);
if (pszB64 == NULL) {
return NULL;
}
char *pszB64Pt = pszB64;
unsigned char *pBinPt, *pBinEnd = (unsigned char *) (bin + size - 1);
unsigned char szIn[3] = { 0, 0, 0 };
int nOffset;
for (pBinPt = (unsigned char *) bin, nOffset = 0; pBinPt <= pBinEnd;
pBinPt++, nOffset++) {
int nIdxOfThree = nOffset % 3;
szIn[nIdxOfThree] = *pBinPt;
if (nIdxOfThree < 2 && pBinPt < pBinEnd)
continue;
*pszB64Pt++ = B64CHARTBL[((szIn[0] & 0xFC) >> 2)];
*pszB64Pt++ = B64CHARTBL[(((szIn[0] & 0x03) << 4)
| ((szIn[1] & 0xF0) >> 4))];
*pszB64Pt++ =
(nIdxOfThree >= 1) ?
B64CHARTBL[(((szIn[1] & 0x0F) << 2)
| ((szIn[2] & 0xC0) >> 6))] :
'=';
*pszB64Pt++ = (nIdxOfThree >= 2) ? B64CHARTBL[(szIn[2] & 0x3F)] : '=';
memset((void *) szIn, 0, sizeof(szIn));
}
*pszB64Pt = '\0';
pszB64 = qstrreplace("tr", pszB64, "+", "~");
pszB64 = qstrreplace("tr", pszB64, "/", "_");
pszB64 = qstrreplace("tr", pszB64, "=", "^");
return pszB64;
}
/**
* Decode BASE64 encoded string.
*
* @param str a pointer of Base64 encoded string.
*
* @return the length of bytes stored in the str memory in case of successful,
* otherwise returns NULL
*
* @note
* This modify str directly. And the 'str' is always terminated by NULL
* character.
*/
size_t qB64_decode(char *str) {
const char B64MAPTBL[16 * 16] = {
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 00-0F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 10-1F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, // 20-2F
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, // 30-3F
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40-4F
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, // 50-5F
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60-6F
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, // 70-7F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 80-8F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 90-9F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // A0-AF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // B0-BF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // C0-CF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // D0-DF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // E0-EF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 // F0-FF
};
str = qstrreplace("tr", str, "~", "+");
str = qstrreplace("tr", str, "_", "/");
str = qstrreplace("tr", str, "^", "=");
char *pEncPt, *pBinPt = str;
int nIdxOfFour = 0;
char cLastByte = 0;
for (pEncPt = str; *pEncPt != '\0'; pEncPt++) {
char cByte = B64MAPTBL[(unsigned char) (*pEncPt)];
if (cByte == 64)
continue;
if (nIdxOfFour == 0) {
nIdxOfFour++;
} else if (nIdxOfFour == 1) {
// 00876543 0021????
//*pBinPt++ = ( ((cLastByte << 2) & 0xFC) | ((cByte >> 4) & 0x03) );
*pBinPt++ = ((cLastByte << 2) | (cByte >> 4));
nIdxOfFour++;
} else if (nIdxOfFour == 2) {
// 00??8765 004321??
//*pBinPt++ = ( ((cLastByte << 4) & 0xF0) | ((cByte >> 2) & 0x0F) );
*pBinPt++ = ((cLastByte << 4) | (cByte >> 2));
nIdxOfFour++;
} else {
// 00????87 00654321
//*pBinPt++ = ( ((cLastByte << 6) & 0xC0) | (cByte & 0x3F) );
*pBinPt++ = ((cLastByte << 6) | cByte);
nIdxOfFour = 0;
}
cLastByte = cByte;
}
*pBinPt = '\0';
return (pBinPt - str);
}
// Duplicate some small amount of code from toys/pending/sh.c
// TODO - to be really useful I need to return the output.
int runToy(char *argv[])
{
int ret = 0;
struct toy_list *tl;
struct toy_context temp;
sigjmp_buf rebound;
if ((tl = toy_find(argv[0])) )//&& (tl->flags & (TOYFLAG_NOFORK|TOYFLAG_MAYFORK)))
{
// This fakes lots of what toybox_main() does.
memcpy(&temp, &toys, sizeof(struct toy_context));
memset(&toys, 0, sizeof(struct toy_context));
if (!sigsetjmp(rebound, 1))
{
toys.rebound = &rebound;
toy_init(tl, argv); // argv must be null terminated
tl->toy_main();
xflush(0);
}
ret = toys.exitval;
if (toys.optargs != toys.argv+1) free(toys.optargs);
if (toys.old_umask) umask(toys.old_umask);
memcpy(&toys, &temp, sizeof(struct toy_context));
}
return ret;
}
#undef FALSE
#undef TRUE
#ifndef FALSE
// NEVER change this, true and false work to.
typedef enum
{
FALSE = 0,
TRUE = 1
} boolean;
#endif
// Silly "man getrandom" is bullshitting.
// Note - this is Linux specific, it's calling a Linux kernel function.
// Remove this when we have a real getrandom(), and replace it with -
//#include <sys/random.h>
#include <sys/syscall.h>
#include <linux/random.h>
ssize_t getrandom(void *b, size_t l, unsigned int f)
{
return (int) syscall(SYS_getrandom, b, l, f);
}
typedef struct _gridStats gridStats;
struct _gridStats
{
float next;
struct timeval last;
qhashtbl_t *stats;
};
typedef struct _HTMLfile HTMLfile;
struct _HTMLfile
{
struct timespec last;
qlist_t *fragments;
};
qhashtbl_t *HTMLfileCache = NULL;
typedef struct _reqData reqData;
typedef void *(*pageFunction) (char *file, reqData *Rd, HTMLfile *thisFile);
typedef struct _dynPage dynPage;
struct _dynPage
{
char *name;
pageFunction func;
};
qhashtbl_t *dynPages;
static void newDynPage(char *name, pageFunction func)
{
dynPage *dp = xmalloc(sizeof(dynPage));
dp->name = name; dp->func = func;
dynPages->put(dynPages, dp->name, dp, sizeof(dynPage));
free(dp);
}
#define HMACSIZE EVP_MAX_MD_SIZE * 2
#define HMACSIZE64 88
// Session details about the logged in web user. A sorta state machine. Ish.
enum reqSessionStatus // Status of the session. Refresh and wipe / nuke -> delete the old session file first.
{
SHS_UNKNOWN = 0, // Haven't looked at the session yet. -> validate it
SHS_NONE, // No session at all. -> logout
SHS_BOGUS, // Looked at the session, it's bogus. -> nuke and logout
SHS_PROBLEM, // Some other problem with the session. -> nuke and logout
SHS_VALID, // Session is valid. -> continue
SHS_LOGIN, // User has just logged in, add UUID to session. -> wipe, add UUID
SHS_RENEW, // Refresh the session based on timer. -> continue
SHS_REFRESH, // Refresh the session for other reason. -> continue
SHS_IDLE, // Session has been idle too long. -> relogin
SHS_ANCIENT, // Session is way too old. -> nuke and logout
SHS_SECURITY, // High security task needs users name & password. ->
SHS_RELOGIN, // Ask user to login again. ->
SHS_KEEP, // Keep the session. -> continue
SHS_WIPE, // Wipe the session, use users UUID. -> continue
SHS_NUKE // Wipe the session, no UUID. -> logout
};
typedef struct _sesh sesh;
struct _sesh
{
char salt[256 + 1], seshID[256 + 1],
sesh[256 + 16 + 10 + 1], munchie[HMACSIZE + 16 + 10 + 1], toke_n_munchie[HMACSIZE + 1], hashish[HMACSIZE + 1],
leaf[HMACSIZE64 + 6 + 1], *UUID, *name;
struct timespec timeStamp[2];
short level;
enum reqSessionStatus status;
boolean isLinky;
};
// Details about the current web request.
struct _reqData
{
lua_State *L;
qhashtbl_t *configs, *queries, *body, *cookies, *headers, *valid, *stuff, *database, *Rcookies, *Rheaders;
char *Scheme, *Host, *Method, *Script, *Path, *RUri, *doit, *form, *output, *outQuery;
sesh shs, *lnk;
gridStats *stats;
qlist_t *errors, *messages;
qgrow_t *reply;
struct timespec then;
boolean fromDb;
};
static void showSesh(qgrow_t *reply, sesh *shs)
{
if (shs->isLinky)
reply->addstrf(reply, "Linky:<br>\n<pre>\n");
else
reply->addstrf(reply, "Session:<br>\n<pre>\n");
if (NULL != shs->name)
reply->addstrf(reply, " name = %s\n", shs->name);
if (NULL != shs->UUID)
reply->addstrf(reply, " UUID = %s\n", shs->UUID);
reply->addstrf(reply, " salt = %s\n", shs->salt);
reply->addstrf(reply, " seshID = %s\n", shs->seshID);
reply->addstrf(reply, " timeStamp = %ld.%ld\n", shs->timeStamp[1].tv_sec, shs->timeStamp[1].tv_nsec);
reply->addstrf(reply, " sesh = %s\n", shs->sesh);
reply->addstrf(reply, " munchie = %s\n", shs->munchie);
reply->addstrf(reply, " toke_n_munchie = %s\n", shs->toke_n_munchie);
reply->addstrf(reply, " hashish = %s\n", shs->hashish);
reply->addstrf(reply, " leaf = %s\n", shs->leaf);
reply->addstrf(reply, " level = %d\n", (int) shs->level);
reply->addstr(reply, "</pre>\n");
}
char toybuf[4096];
lua_State *L;
qhashtbl_t *configs;
MYSQL *database, *dbconn;
unsigned int dbTimeout;
struct timespec dbLast;
my_bool dbReconnect;
gridStats *stats;
boolean isTmux = 0;
boolean isWeb = 0;
char *pwd = "";
char *scRoot = "/opt/opensim_SC";
char *scUser = "opensimsc";
char *scBin = "";
char *scEtc = "";
char *scLib = "";
char *scRun = "";
char *scBackup = "";
char *scCache = "";
char *scData = "";
char *scLog = "";
char *scTemp = "";
char *Tconsole = "SledjChisl";
char *Tsocket = "opensim-tmux.socket";
char *Ttab = "SC";
char *Tcmd = "tmux -S";
char *backupIARsim = "Sandbox";
char *rSync = "";
int rSyncPort = 0;
char *webRoot = "/var/www/html";
char *URL = "fcgi-bin/sledjchisl.fcgi";
char *ToS = "Be good.";
char *webIframers = "";
int seshRenew = 10 * 60;
int idleTimeOut = 30 * 60;
int seshTimeOut = 24 * 60 * 60;
int newbieTimeOut = 30;
float loadAverageInc = 0.7;
int simTimeOut = 45;
int bulkSims = 0;
boolean DEBUG = FALSE;
boolean VERBOSE = FALSE;
qhashtbl_t *mimeTypes;
qlist_t *dbRequests;
// TODO - log to file. The problem is we don't know where to log until after we have loaded the configs, and before that we are spewing log messages.
// Now that we are using spawn-fcgi, all the logs are going to STDERR, which we can capture and write to a file.
// Unfortunately spawn-fcgi in deamon mode sends all the output to /dev/null or something.
// A better idea, when we spawn tmux or spawn-fcgi, capture STDERR, full log everything to that, filtered log to the tmux console (STDOUT).
// Then we can use STDOUT / STDIN to run the console stuff.
// TODO - escape anything that will turn the console into garbage.
// https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences
char *logTypes[] =
{
"91;1;4", "CRITICAL", // red underlined
"31", "ERROR", // dark red
"93", "WARNING", // yellow
"36", "TIMEOUT", // cyan
"97;40", "INFO", // white
"92;40", "VERBOSE", // green
"90", "DEBUG", // grey
// UNKNOWN? FATAL? SILENT? All from Android apparently.
"35", "debug", // magenta
"34", "timeout", // blue
};
#define DATE_TIME_LEN 42
void logMe(int v, char *format, ...)
{
va_list va, va2;
int len;
char *ret;
struct timeval tv;
time_t curtime;
char date[DATE_TIME_LEN];
if ((!VERBOSE) && (4 < v))
return;
if ((!DEBUG) && (5 < v))
return;
va_start(va, format);
va_copy(va2, va);
// How long is it?
len = vsnprintf(0, 0, format, va);
len++;
va_end(va);
// Allocate and do the sprintf()
ret = xmalloc(len);
vsnprintf(ret, len, format, va2);
va_end(va2);
gettimeofday(&tv, NULL);
curtime = tv.tv_sec;
strftime(date, DATE_TIME_LEN, "(%Z %z) %F %T", localtime(&curtime));
v *= 2;
fprintf(stderr, "%s.%.6ld \e[%sm%-8s sledjchisl: %s\e[0m\n", date, tv.tv_usec, logTypes[v], logTypes[v + 1], ret);
free(ret);
}
#define C(...) logMe(0, __VA_ARGS__)
#define E(...) logMe(1, __VA_ARGS__)
#define W(...) logMe(2, __VA_ARGS__)
#define T(...) logMe(3, __VA_ARGS__)
#define I(...) logMe(4, __VA_ARGS__)
#define V(...) logMe(5, __VA_ARGS__)
#define D(...) logMe(6, __VA_ARGS__)
#define d(...) logMe(7, __VA_ARGS__)
#define t(...) logMe(8, __VA_ARGS__)
int shellMeFailVf(char *format, ...)
{
va_list va, va2;
int len;
char *ret;
int result = FALSE;
va_start(va, format);
va_copy(va2, va);
// How long is it?
len = vsnprintf(0, 0, format, va);
len++;
va_end(va);
// Allocate and do the sprintf()
ret = xmalloc(len);
vsnprintf(ret, len, format, va2);
va_end(va2);
V(ret);
free(ret);
return result;
}
int shellMeFailVt(char *format, ...)
{
va_list va, va2;
int len;
char *ret;
int result = TRUE;
va_start(va, format);
va_copy(va2, va);
// How long is it?
len = vsnprintf(0, 0, format, va);
len++;
va_end(va);
// Allocate and do the sprintf()
ret = xmalloc(len);
vsnprintf(ret, len, format, va2);
va_end(va2);
V(ret);
free(ret);
return result;
}
int shellMeFail(char *format, ...)
{
va_list va, va2;
int len;
char *ret;
int result;
va_start(va, format);
va_copy(va2, va);
// How long is it?
len = vsnprintf(0, 0, format, va);
len++;
va_end(va);
// Allocate and do the sprintf()
ret = xmalloc(len);
vsnprintf(ret, len, format, va2);
va_end(va2);
result = !WIFEXITED(system(ret));
free(ret);
return result;
}
int shellMe(char *format, ...)
{
va_list va, va2;
int len;
char *ret;
int result;
va_start(va, format);
va_copy(va2, va);
// How long is it?
len = vsnprintf(0, 0, format, va);
len++;
va_end(va);
// Allocate and do the sprintf()
ret = xmalloc(len);
vsnprintf(ret, len, format, va2);
va_end(va2);
result = system(ret);
free(ret);
return result;
}
int hasContents(char *file)
{
struct stat st;
if (0 == lstat(file, &st))
{
if (0 != st.st_size)
return TRUE;
}
return FALSE;
}
static void addStrL(qlist_t *list, char *s)
{
list->addlast(list, s, strlen(s) + 1);
}
static char *getStrH(qhashtbl_t *hash, char *key)
{
char *ret = "", *t;
t = hash->getstr(hash, key, false);
if (NULL != t)
ret = t;
return ret;
}
static void bitch(reqData *Rd, char *message, char *log)
{
addStrL(Rd->errors, message);
E("%s %s %s - %s %s", getStrH(Rd->headers, "REMOTE_ADDR"), Rd->shs.UUID, Rd->shs.name, message, log);
}
/* "A token cookie that references a non-existent session, its value should be replaced immediately to prevent session fixation."
https://owasp.org/www-community/attacks/Session_fixation
Which describes the problem, but offers no solution.
See https://stackoverflow.com/questions/549/the-definitive-guide-to-form-based-website-authentication?rq=1.
I think this means send a new cookie.
I clear out the cookies and send blank ones with -1 maxAge, so they should get deleted.
*/
static void bitchSession(reqData *Rd, char *message, char *log)
{
if ('\0' != message[0])
addStrL(Rd->errors, message);
C("%s %s %s - %s %s", getStrH(Rd->headers, "REMOTE_ADDR"), Rd->shs.UUID, Rd->shs.name, message, log);
Rd->shs.status = SHS_BOGUS;
}
char *myHMAC(char *in, boolean b64)
{
EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); // Gets renamed to EVP_MD_CTX_new() in later versions.
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
EVP_DigestInit_ex(mdctx, EVP_sha512(), NULL); // EVP_sha3_512() isn't available until later versions.
EVP_DigestUpdate(mdctx, in, strlen(in));
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx); // Gets renamed to EVP_MD_CTX_free() in later versions.
if (b64)
return qB64_encode(md_value, md_len);
else
return qhex_encode(md_value, md_len);
}
char *myHMACkey(char *key, char *in, boolean b64)
{
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
unsigned char* digest = HMAC(EVP_sha512(), key, strlen(key), (unsigned char *) in, strlen(in), md_value, &md_len);
if (b64)
return qB64_encode(md_value, md_len);
else
return qhex_encode(md_value, md_len);
}
// In Lua 5.0 reference manual is a table traversal example at page 29.
void PrintTable(lua_State *L)
{
lua_pushnil(L);
while (lua_next(L, -2) != 0)
{
// Numbers can convert to strings, so check for numbers before checking for strings.
if (lua_isnumber(L, -1))
printf("%s = %f\n", lua_tostring(L, -2), lua_tonumber(L, -1));
else if (lua_isstring(L, -1))
printf("%s = '%s'\n", lua_tostring(L, -2), lua_tostring(L, -1));
else if (lua_istable(L, -1))
PrintTable(L);
lua_pop(L, 1);
}
}
typedef struct _qLua qLua;
struct _qLua
{
int type;
union
{
boolean b;
int i;
float f;
char *s;
qtreetbl_t *t;
} v;
};
qLua *qLuaGet(qtreetbl_t *tree, char *key)
{
return (qLua *) tree->get(tree, key, NULL, false);
}
void dumpLuaTree(qtreetbl_t *tree, char *name, int depth)
{
qtreetbl_obj_t obj0;
if (0 == depth)
fprintf(stderr, "DUMP Lua table %s -\n%s =\n{\n", name, name);
else
fprintf(stderr, "%*s[%s] =\n%*s{\n", depth * 2, "", name, depth * 2, "");
memset((void*)&obj0, 0, sizeof(obj0)); // must be cleared before call
tree->lock(tree); // lock it when thread condition is expected
while(tree->getnext(tree, &obj0, false) == true)
{
qLua *q0 = obj0.data;
switch (q0->type)
{
case LUA_TBOOLEAN : {fprintf(stderr, "%*s[%s] = %d,\n", (depth + 1) * 2, "", obj0.name, q0->v.b); break;}
case LUA_TINTEGER : {fprintf(stderr, "%*s[%s] = %d,\n", (depth + 1) * 2, "", obj0.name, q0->v.i); break;}
case LUA_TNUMBER : {fprintf(stderr, "%*s[%s] = %f,\n", (depth + 1) * 2, "", obj0.name, q0->v.f); break;}
case LUA_TSTRING : {fprintf(stderr, "%*s[%s] = %s,\n", (depth + 1) * 2, "", obj0.name, q0->v.s); break;}
case LUA_TTABLE : {dumpLuaTree(q0->v.t, obj0.name, depth + 1); break;}
default : {fprintf(stderr, "%*s[%s] ? ??,\n", (depth + 1) * 2, "", obj0.name); break;}
}
}
tree->unlock(tree);
fprintf(stderr, "%*s},\n", depth * 2, "");
}
qtreetbl_t *lua2tree()
{
qtreetbl_t *ret = qtreetbl(0);
if (NULL != ret)
{
qLua q;
lua_pushnil(L); // +1 nil, first key
while(lua_next(L, -2) != 0) // -1 key, +2 next key, value (or 0 if nothing left in table)
{
// stack now contains: -1 => value; -2 => key; -3 => table
// copy the key so that lua_tostring does not modify the original
lua_pushvalue(L, -2);
// stack now contains: -1 => key; -2 => value; -3 => key; -4 => table
char *n = (char *) lua_tostring(L, -1); // 0, modifies key copy
int t = lua_type(L, -3);
// Correct the sort order. Assuming we will never have more than 999,999 sims. Think that's a safe assumption.
/* https://www.hypergridbusiness.com/2021/07/opensim-land-growth/
"Total area increased by the equivalent of 2,252 standard regions, for a new record high of 103,625 regions.
That’s nearly four times the area of Second Life,"
*/
if ((LUA_TINTEGER == t) || (LUA_TNUMBER == t))
{
char *tmp = xmprintf("%6s", n);
n = tmp;
}
q.type = lua_type(L, -2); // 0
switch(q.type)
{
case LUA_TBOOLEAN : {q.v.b = lua_toboolean(L, -2); break;}
case LUA_TINTEGER : {q.v.i = lua_tointeger(L, -2); break;}
case LUA_TNUMBER : {q.v.f = lua_tonumber(L, -2); break;}
case LUA_TSTRING : {q.v.s = (char *) lua_tostring(L, -2); break;}
case LUA_TTABLE : {lua_pushvalue(L, -2); q.v.t = lua2tree(); lua_pop(L, 1); break;}
default :
{
q.v.s = (char *) lua_tostring(L, -2); // 0
E("Unknown Lua variable type for %s = %s is %d", n, q.v.s, q.type);
break;
}
}
ret->put(ret, n, &q, sizeof(qLua));
if ((LUA_TINTEGER == t) || (LUA_TNUMBER == t))
free(n);
// pop value + copy of key, leaving original key
lua_pop(L, 2); // -2 value and copy of key
// stack now contains: -1 => key; -2 => table
}
}
else
{
D("No memory left.");
perror_msg("Unable to allocate memory");
}
return ret;
}
qtreetbl_t *Lua2tree(char *file, char *var)
{
qtreetbl_t *ret = NULL;
struct stat st;
if (0 != lstat(file, &st))
{
D("No %s file.", file);
perror_msg("Unable to stat %s", file);
}
else
{
if (luaL_loadfile(L, file)) // +1 the chunk or an error message. If something went wrong, error message is at the top of the stack.
E("Couldn't load Lua file: %s", lua_tostring(L, -1)); // 0
else
{
if (lua_pcall(L, 0, LUA_MULTRET, 0)) // +1 result or an error message. Except we get 0 or error?
{
E("Failed to run Lua script: %s", lua_tostring(L, -1)); // 0
lua_pop(L, 1); // -1 chunk or error message
}
else
{
lua_getglobal(L, var); // +1 the value of var
ret = lua2tree();
lua_pop(L, 1); // -1 var
}
}
lua_pop(L, 1); // -1 chunk or error message
}
return ret;
}
void freeLuaTree(qtreetbl_t *tree)
{
qtreetbl_obj_t obj0;
memset((void*)&obj0, 0, sizeof(obj0)); // must be cleared before call
tree->lock(tree); // lock it when thread condition is expected
while(tree->getnext(tree, &obj0, false) == true)
{
qLua *q0 = obj0.data;
if (LUA_TTABLE == q0->type)
freeLuaTree(q0->v.t);
}
tree->unlock(tree);
tree->free(tree);
}
int Lua2hashtbl(char *file, qhashtbl_t *hash, char *var)
{
int ret = FALSE;
struct stat st;
if (0 != lstat(file, &st))
{
D("No %s file.", file);
perror_msg("Unable to stat %s", file);
return FALSE;
}
else
{
int status = luaL_loadfile(L, file); // +1 the chunk or an error message.
if (status) // If something went wrong, error message is at the top of the stack.
E("Couldn't load Lua file: %s", lua_tostring(L, -1)); // 0
else
{
int result = lua_pcall(L, 0, LUA_MULTRET, 0); // +1 result or an error message. Except we get 0 or error?
if (result)
{
E("Failed to run Lua script: %s", lua_tostring(L, -1)); // 0
lua_pop(L, 1); // -1 chunk or error message
}
else
{
lua_getglobal(L, var); // +1 the value of var
lua_pushnil(L); // +1 nil, first key
while(lua_next(L, -2) != 0) // -1 key, +2 next key, value (or 0 if nothing left in table)
{
char *n = (char *) lua_tostring(L, -2); // 0
// Numbers can convert to strings, so check for numbers before checking for strings.
// On the other hand, strings that can be converted to numbers also pass lua_isnumber(). sigh
if (lua_isnumber(L, -1)) // 0
{
float v = lua_tonumber(L, -1); // 0
hash->put(hash, n, &v, sizeof(float));
}
else if (lua_isstring(L, -1)) // 0
hash->putstr(hash, n, (char *) lua_tostring(L, -1)); // 0
else if (lua_isboolean(L, -1)) // 0
{
int v = lua_toboolean(L, -1); // 0
hash->putint(hash, n, v);
}
else
{
char *v = (char *) lua_tostring(L, -1); // 0
E("Unknown Lua variable type for %s = %s", n, v);
}
lua_pop(L, 1); // -1 value
}
lua_pop(L, 1); // -1 var
ret = TRUE;
}
}
}
lua_pop(L, 1); // -1 chunk or error message
return ret;
}
int LuaToHash(reqData *Rd, char *file, char *var, qhashtbl_t *tnm, int ret, struct stat *st, struct timespec *now, char *type)
{
struct timespec then;
if (-1 == clock_gettime(CLOCK_REALTIME, &then))
perror_msg("Unable to get the time.");
I("Reading %s file %s", type, file);
if (!Lua2hashtbl(file, tnm, var))
{
bitch(Rd, "Broken thing.", "Can't run file.");
ret++;
}
else
{
if (-1 == clock_gettime(CLOCK_REALTIME, now))
perror_msg("Unable to get the time.");
double n = (now->tv_sec * 1000000000.0) + now->tv_nsec;
double t = (then.tv_sec * 1000000000.0) + then.tv_nsec;
t("Reading %s file took %lf seconds", type, (n - t) / 1000000000.0);
}
return ret;
}
boolean writeLuaDouble(reqData *Rd, int fd, char *file, char *name, double number)
{
boolean ret = TRUE;
// TODO - putting these in Lua as numbers causes lua_tolstring to barf when we read them. Though Lua is supposed to convert between numbers and strings.
char *t = xmprintf(" ['%s'] = '%f',\n", name, number); // NOTE - default precision is 6 decimal places.
size_t l = strlen(t);
if (l != writeall(fd, t, l))
{
perror_msg("Writing %s", file);
ret = FALSE;
}
free(t);
return ret;
}
boolean writeLuaInteger(reqData *Rd, int fd, char *file, char *name, long number)
{
boolean ret = TRUE;
// TODO - putting these in Lua as numbers causes lua_tolstring to barf when we read them. Though Lua is supposed to convert between numbers and strings.
char *t = xmprintf(" ['%s'] = '%ld',\n", name, number);
size_t l = strlen(t);
if (l != writeall(fd, t, l))
{
perror_msg("Writing %s", file);
ret = FALSE;
}
free(t);
return ret;
}
boolean writeLuaString(reqData *Rd, int fd, char *file, char *name, char *string)
{
boolean ret = TRUE;
if (NULL == string)
string = getStrH(Rd->stuff, name);
size_t l = strlen(string);
char *t0 = xmalloc(l * 2 + 1);
int i, j = 0;
// TODO - maybe escape other non printables as well?
for (i = 0; i < l; i++)
{
// We don't need to escape [] here, coz we are using '' below. Same applies to ", but do it anyway.
switch(string[i])
{
case '\n':
case '\\':
case '\'':
case '"':
t0[j++] = '\\'; break;
}
if ('\n' == string[i])
t0[j++] = 'n';
else if ('\r' == string[i])
;
else
t0[j++] = string[i];
}
t0[j] = '\0';
char *t1 = xmprintf(" ['%s'] = '%s',\n", name, t0);
l = strlen(t1);
if (l != writeall(fd, t1, l))
{
perror_msg("Writing %s to %s", name, file);
ret = FALSE;
}
free(t1);
free(t0);
return ret;
}
void doTmuxCmd(char *format, ...)
{
va_list va, va2;
int len;
char *ret;
va_start(va, format);
va_copy(va2, va);
// How long is it?
len = vsnprintf(0, 0, format, va);
len++;
va_end(va);
// Allocate and do the sprintf()
ret = xmalloc(len);
vsnprintf(ret, len, format, va2);
va_end(va2);
if (shellMeFail("%s %s/%s %s", Tcmd, scRun, Tsocket, ret))
E("tmux command failed! %s", ret);
free(ret);
}
void sendTmuxCmd(char *dest, char *cmd)
{
doTmuxCmd("send-keys -t %s:'%s' '%s' Enter", Tconsole, dest, cmd);
}
void sendTmuxKeys(char *dest, char *keys)
{
doTmuxCmd("send-keys -t %s:%s '%s'", Tconsole, dest, keys);
}
void waitTmuxText(char *dest, char *text)
{
int i;
// Using " for the grep pattern, coz ' might be used in a sim name.
// TODO - should escape \ " ` in text.
char *c = xmprintf("sleep 1; %s %s/%s capture-pane -Jt %s -p | grep -E \"%s\" 2>&1 > /dev/null", Tcmd, scRun, Tsocket, dest, text);
T("Waiting for '%s'.", text);
do
{
i = system(c);
if (!WIFEXITED(i))
{
E("tmux capture-pane command failed!");
break;
}
else if (0 == WEXITSTATUS(i))
break;
} while (1);
free(c);
}
float waitLoadAverage(float la, float extra, int timeout)
{
struct sysinfo info;
struct timespec timeOut;
float l;
int to = timeout;
T("Sleeping until load average is below %.02f (%.02f + %.02f) or for %d seconds.", la + extra, la, extra, timeout);
clock_gettime(CLOCK_MONOTONIC, &timeOut);
to += timeOut.tv_sec;
do
{
msleep(5000);
sysinfo(&info);
l = info.loads[0]/65536.0;
clock_gettime(CLOCK_MONOTONIC, &timeOut);
timeout -= 5;
t("Tick, load average is %.02f, countdown %d seconds.", l, timeout);
} while (((la + extra) < l) && (timeOut.tv_sec < to));
return l;
}
// Rob forget to do this, but at least he didn't declare it static.
struct dirtree *dirtree_handle_callback(struct dirtree *new, int (*callback)(struct dirtree *node));
// A sim structure for holding all the stuff from the sim.ini file.
typedef struct _simData simData;
struct _simData
{
// portH is the HTTP port for the sim, portU is the UDP port for the sim.
int locX, locY, sizeX, sizeY, sizeZ, portH, portU, maxPrims;
char *name, *tab, *UUID, *regionType, *estate, *owner;
char *paneID;
int window, pane, users;
};
typedef struct _simList simList;
struct _simList
{
int len, num;
char **sims;
qtreetbl_t *byTab, *simsLua, *unsorted, *byUUID;
// Stuff for the looping through sims, doing things, and waiting.
int doIt;
float la;
char *target, *backup;
};
simList *ourSims = NULL;
static int getIntFromIni(qlisttbl_t *ini, char *name)
{
int ret;
char *t = "0";
t = ini->getstr(ini, name, false);
if (NULL == t)
t = "0";
else if ('"' == t[0])
t = qstrunchar(t, '"', '"');
return strtol(t, NULL, 10);
}
static int filterSims(struct dirtree *node)
{
if (!node->parent) return DIRTREE_RECURSE | DIRTREE_SHUTUP;
if ((strncmp(node->name, "sim", 3) == 0) && ((strcmp(node->name, "sim_skeleton") != 0)))
{
simList *list = (simList *) node->parent->extra;
if ((list->num + 1) > list->len)
{
list->len = list->len + 1;
list->sims = xrealloc(list->sims, list->len * sizeof(char *));
}
list->sims[list->num] = xstrdup(node->name);
list->num++;
}
return 0;
}
/*
// We particularly don't want \ " `
char *cleanSimName(char *name)
{
size_t l = strlen(name);
char *ret = xmalloc(l + 1);
int i, j = 0;
for (i = 0; i < l; i++)
{
char r = name[i];
if ((' ' == r) || (isalnum(r) != 0))
ret[j++] = r;
}
ret[j] = '\0';
return ret;
}
*/
static int filterInis(struct dirtree *node)
{
if (!node->parent) return DIRTREE_RECURSE | DIRTREE_SHUTUP;
int l = strlen(node->name);
if (strncmp(&(node->name[l - 4]), ".ini", 4) == 0)
{
strncpy((char *) node->parent->extra, node->name, l - 4);
return DIRTREE_ABORT;
}
return 0;
}
static int filterShinis(struct dirtree *node)
{
if (!node->parent) return DIRTREE_RECURSE | DIRTREE_SHUTUP;
int l = strlen(node->name);
if ((6 < l) && ((strncmp(&(node->name[l - 6]), ".shini", 6) == 0)))
{
simList *list = (simList *) node->parent->extra;
if ((list->num + 1) > list->len)
{
list->len = list->len + 1;
list->sims = xrealloc(list->sims, list->len * sizeof(char *));
}
list->sims[list->num] = xstrndup(node->name, l - 6);
list->num++;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Sim wrangling loop.
////////////////////////////////////////////////////////////////////////////////////////////////////
typedef void (*simFunction)(simData *simd, char *sim, char *type, int count, int window, int panes, int pane);
void forEachSim(char *verb, simFunction func, simFunction not)
{
qtreetbl_obj_t obj0, obj1;
qLua *q0, *q1;
int count = 0, window = 0, panes = 4, pane = 0;
memset((void*)&obj0, 0, sizeof(obj0));
ourSims->simsLua->lock(ourSims->simsLua);
while(ourSims->simsLua->getnext(ourSims->simsLua, &obj0, false) == true)
{
q0 = obj0.data;
char *type = "unsorted";
if (LUA_TTABLE == q0->type)
{
panes = 4;
q1 = q0->v.t->get(q0->v.t, "number", NULL, false); if (NULL != q1) window = q1->v.f - 1;
q1 = q0->v.t->get(q0->v.t, "panes", NULL, false); if (NULL != q1) panes = q1->v.f;
q1 = q0->v.t->get(q0->v.t, "type", NULL, false); if (NULL != q1) type = q1->v.s;
if (0 == panes)
{
pane = 3;
window = 0;
type = Ttab;
}
else if (0 != pane)
{
pane = 0;
window++;
}
if (verb)
V("%s sims of type %s, window %d, %d panes per window.", verb, type, window, panes);
memset((void*)&obj1, 0, sizeof(obj1));
q0->v.t->lock(q0->v.t);
while(q0->v.t->getnext(q0->v.t, &obj1, false) == true)
{
q1 = obj1.data;
if ((strcmp("number", obj1.name) != 0) && (strcmp("panes", obj1.name) != 0) && (strcmp("type", obj1.name) != 0))
{
simData *simd = ourSims->byTab->get(ourSims->byTab, q1->v.s, NULL, false);
if (NULL == simd)
{
if (not)
not(simd, q1->v.s, type, count, window, panes, pane);
else
E("Sim %s not found in ini list!", q1->v.s);
}
else
{
func(simd, q1->v.s, type, count, window, panes, pane);
count++;
pane++;
if (pane >= panes)
{
pane = 0;
window++;
}
}
}
}
q0->v.t->unlock(q0->v.t);
}
}
ourSims->simsLua->unlock(ourSims->simsLua);
}
void simNotFound(simData *simd, char *sim, char *type, int count, int window, int panes, int pane)
{
char *path = xmprintf("%s/%s.shini", scEtc, sim);
qlisttbl_t *ini = qconfig_parse_file(NULL, path, '=');
if (NULL == ini)
E("Can't find %s", path);
else
{
simd = xzalloc(sizeof(simData));
simd->tab = sim;
simd->name = qstrunchar(ini->getstr(ini, "Region.RegionName", true), '"', '"');
simd->UUID = qstrunchar(ini->getstr(ini, "Region.RegionUUID", true), '"', '"');
// simd->regionType = qstrunchar(ini->getstr(ini, "Region.RegionType", true), '"', '"');
simd->sizeX = getIntFromIni(ini, "Region.SizeX");
simd->sizeY = getIntFromIni(ini, "Region.SizeY");
simd->sizeZ = getIntFromIni(ini, "Region.SizeZ");
// TODO - store a pointer instead of multiple copies of the data.
ourSims->byTab->put(ourSims->byTab, sim, simd, sizeof(simData));
ourSims->byUUID->put(ourSims->byUUID, simd->UUID, simd, sizeof(simData));
if (strcmp("unsorted", type) == 0)
ourSims->unsorted->put(ourSims->unsorted, sim, simd, sizeof(simData));
ini->free(ini);
free(simd);
}
free(path);
}
void freeSimList(simList *sims)
{
int i;
if (NULL == sims)
return;
for (i = 0; i < sims->num; i++)
free(sims->sims[i]);
free(sims->sims);
qtreetbl_obj_t obj;
memset((void*) &obj, 0, sizeof(obj)); // start from the minimum.
sims->byTab->lock(sims->byTab);
while (sims->byTab->getnext(sims->byTab, &obj, false) == true)
{
char *name = qmemdup(obj.name, obj.namesize); // keep the name
size_t namesize = obj.namesize; // for removal argument
{
simData *simd = (simData *) obj.data;
if (NULL != simd)
{
free(simd->name);
// free(simd->tab);
free(simd->UUID);
// free(simd->regionType);
free(simd->estate);
free(simd->owner);
free(simd->paneID);
}
}
// sims->byTab->remove_by_obj(sims->byTab, obj.name, obj.namesize); // remove
// obj = sims->byTab->find_nearest(sims->byTab, name, namesize, false); // rewind one step back
free(name); // clean up
}
sims->byTab->unlock(sims->byTab);
sims->byTab->free(sims->byTab);
freeLuaTree(sims->simsLua);
freeLuaTree(sims->unsorted);
freeLuaTree(sims->byUUID);
free(sims->target);
free(sims->backup);
free(sims);
}
// Get the details from all the .ini or .shini sim files.
// Creates the .shini and sims.lua files if it's an old install.
simList *getSims()
{
if (NULL != ourSims) return ourSims;
int i, fd = -1;
size_t l;
char *file = xmprintf("%s/sims.lua", scEtc);
ourSims = xzalloc(sizeof(simList));
ourSims->byTab = qtreetbl(0);
ourSims->unsorted = qtreetbl(0);
ourSims->byUUID = qtreetbl(0);
ourSims->doIt = FALSE;
// Read or create simsLua
ourSims->simsLua = Lua2tree(file, "sims");
if (NULL == ourSims->simsLua)
{
ourSims->simsLua = qtreetbl(0);
ourSims->doIt = TRUE;
}
// Find all the old .ini files, convert them to .shini files if they don't exist.
char *path = xmprintf("%s/config", scRoot), *newPath;
struct dirtree *new = dirtree_add_node(0, path, 0);
new->extra = (long) ourSims;
dirtree_handle_callback(new, filterSims);
free(path);
for (i = 0; i < ourSims->num; i++)
{
char *sim = ourSims->sims[i], *name = xmprintf("%s/config/%s", scRoot, sim);
qlisttbl_t *ini;
struct dirtree *new = dirtree_add_node(0, name, 0);
free(name);
name = xzalloc(1024);
new->extra = (long) name;
dirtree_handle_callback(new, filterInis);
if ('\0' != name[0])
{
path = xmprintf("%s/config/%s/%s.ini", scRoot, sim, name);
newPath = xmprintf("%s/%s.shini", scEtc, name);
if (!qfile_exist(newPath))
{
char *cmd = xmprintf("sed -E"
" -e 's#\\[Const]#\\[Const] ; fakeVariableCozOpenSim='' ; pushd ../current/bin; ./sledjchisl $1 `basename $0`; popd ; exit 0#'"
" -e 's/mysim=\"[[:digit:]]*\"/mysim=\"%s\"/'"
" -e 's/sim\\$\\{Const\\|mysim\\}/\\$\\{Const\\|mysim\\}/g'"
" -e '/\\[Startup\\]/d'"
" -e '/PIDFile.*/d'"
" -e '/LogFile.*/d'"
" -e '/StatsLogFile.*/d'"
" -e '/ConsoleHistoryFile.*/d'"
" %s >%s", name, path, newPath);
V("Converting %s.ini -> %s", path, newPath);
D(cmd);
if (shellMeFail(cmd))
E("sed command failed!");
else
{
if (shellMeFail("chmod ugo+x %s", newPath))
E("chmod command failed!");
char *link = xmprintf("%s/%s.shini", scBin, name);
I("Symlinking %s to %s", newPath, link);
if (qfile_exist(link))
{
if (shellMeFail("rm %s", link))
E("rm command failed!");
}
if (0 != symlink(newPath, link))
perror_msg("Symlinking %s to %s", newPath, link);
free(link);
}
free(cmd);
}
free(newPath);
free(path);
}
free(name);
}
// dumpLuaTree(ourSims->simsLua, "simsLua", 0);
// dumpLuaTree(ourSims->byTab, "byTab", 0);
// Read all the .shini files.
forEachSim(NULL, NULL, simNotFound);
// dumpLuaTree(ourSims->simsLua, "simsLua", 0);
// dumpLuaTree(ourSims->byTab, "byTab", 0);
// dumpLuaTree(ourSims->unsorted, "unsorted", 0);
// Check for any .shini files not in sims.lua, add them to the unsorted list.
for (i = 0; i < ourSims->num; i++)
free(ourSims->sims[i]);
ourSims->num = 0;
new = dirtree_add_node(0, scEtc, 0);
new->extra = (long) ourSims;
dirtree_handle_callback(new, filterShinis);
for (i = 0; i < ourSims->num; i++)
{
simData *simd = ourSims->byTab->get(ourSims->byTab, ourSims->sims[i], NULL, false);
if (NULL == simd)
{
V("Shini NOT found in list - %s/%s.shini", scEtc, ourSims->sims[i]);
simNotFound(simd, ourSims->sims[i], "unsorted", 0, 0, 0, 0);
ourSims->doIt = TRUE;
}
}
// dumpLuaTree(ourSims->simsLua, "simsLua", 0);
// dumpLuaTree(ourSims->byTab, "byTab", 0);
// dumpLuaTree(ourSims->unsorted, "unsorted", 0);
// Write the sims.lua_NEW file if needed.
if (ourSims->doIt)
{
char *tnm;
if (shellMeFail("mv -f %s/sims.lua %s/sims.lua.BACKUP", scEtc, scEtc))
E("mv command failed!");
free(file);
file = xmprintf("%s/sims.lua", scEtc);
I("Creating sims %s.", file);
fd = notstdio(xcreate_stdio(file, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR));
if (-1 != fd)
{
tnm = "sims = -- Note these are .shini / tmux tab short names.\n{\n";
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
qtreetbl_obj_t obj0, obj1;
qLua *q0, *q1;
memset((void*)&obj0, 0, sizeof(obj0));
ourSims->simsLua->lock(ourSims->simsLua);
while(ourSims->simsLua->getnext(ourSims->simsLua, &obj0, false) == true)
{
q0 = obj0.data;
char *type = "unsorted";
if (LUA_TTABLE == q0->type)
{
tnm = " {";
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
q1 = q0->v.t->get(q0->v.t, "type", NULL, false);
if (NULL != q1)
{
type = q1->v.s;
tnm = xmprintf("['type'] = '%s'; ", type);
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
free(tnm);
}
q1 = q0->v.t->get(q0->v.t, "number", NULL, false);
if (NULL != q1)
{
tnm = xmprintf("['number'] = %d; ", (int) q1->v.f);
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
free(tnm);
}
q1 = q0->v.t->get(q0->v.t, "panes", NULL, false);
if (NULL != q1)
{
tnm = xmprintf("['panes'] = %d; ", (int) q1->v.f);
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
free(tnm);
}
if (strcmp("unsorted", type) != 0)
{
memset((void*)&obj1, 0, sizeof(obj1));
q0->v.t->lock(q0->v.t);
while(q0->v.t->getnext(q0->v.t, &obj1, false) == true)
{
q1 = obj1.data;
if ((strcmp("number", obj1.name) != 0) && (strcmp("panes", obj1.name) != 0) && (strcmp("type", obj1.name) != 0))
{
tnm = xmprintf("\n '%s',", q1->v.s);
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
free(tnm);
}
}
q0->v.t->unlock(q0->v.t);
}
else
{
memset((void*)&obj1, 0, sizeof(obj1));
ourSims->unsorted->lock(ourSims->unsorted);
while(ourSims->unsorted->getnext(ourSims->unsorted, &obj1, false) == true)
{
simData *simd = obj1.data;
if ((strcmp("number", obj1.name) != 0) && (strcmp("panes", obj1.name) != 0) && (strcmp("type", obj1.name) != 0))
{
tnm = xmprintf("\n '%s',", simd->tab);
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
free(tnm);
}
}
ourSims->unsorted->unlock(ourSims->unsorted);
}
}
tnm = "\n },\n";
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
}
ourSims->simsLua->unlock(ourSims->simsLua);
tnm = "}\nreturn sims\n";
l = strlen(tnm);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
xclose(fd);
}
freeSimList(ourSims);
free(file);
// Reread everything.
file = xmprintf("%s/sims.lua", scEtc);
ourSims = xzalloc(sizeof(simList));
ourSims->byTab = qtreetbl(0);
ourSims->unsorted = qtreetbl(0);
ourSims->doIt = FALSE;
ourSims->simsLua = Lua2tree(file, "sims");
forEachSim(NULL, NULL, simNotFound);
// dumpLuaTree(ourSims->simsLua, "simsLua", 0);
// dumpLuaTree(ourSims->byTab, "byTab", 0);
// dumpLuaTree(ourSims->unsorted, "unsorted", 0);
}
free(file);
// dumpLuaTree(ourSims->simsLua, "simsLua", 0);
// dumpLuaTree(ourSims->byTab, "byTab", 0);
return ourSims;
}
// Expects either "simXX" or "ROBUST".
int checkSimIsRunning(char *sim)
{
int ret = 0;
struct stat st;
// Check if it's running.
char *path = xmprintf("%s/%s.pid", scRun, sim);
if (0 == stat(path, &st))
{
int fd, i;
char *pid = NULL;
// Double check if it's REALLY running.
if ((fd = xopenro(path)) == -1)
perror_msg("xopenro(%s)", path);
else
{
pid = get_line(fd);
if (NULL == pid)
perror_msg("get_line(%s)", path);
else
{
xclose(fd);
// I'd rather re-use the toysh command running stuff, since ps is a toy, but that's private.
// TODO - switch to toybox ps and rm.
free(path);
path = xmprintf("ps -p %s --no-headers -o comm >/dev/null", pid);
i = system(path);
if (WIFEXITED(i))
{
if (0 != WEXITSTATUS(i)) // No such pid.
{
free(path);
path = xmprintf("rm -f %s/%s.pid", scRun, sim);
d("%s", path);
i = system(path);
if (WIFEXITED(i))
{
if (0 != WEXITSTATUS(i)) // No such pid.
E("Cannot remove stale PID file %s", path);
}
}
else
d("checkSimIsRunning(%s) has PID %s, which is actually running.", sim, pid);
}
// TODO - WTF?
// free(path);
}
}
free(pid);
}
// Now check if it's really really running. lol
free(path);
path = xmprintf("%s/%s.pid", scRun, sim);
if (0 == stat(path, &st))
{
D("checkSimIsRunning(%s) -> %s is really really running.", sim, path);
ret = 1;
}
else
D("checkSimIsRunning(%s) -> %s is not running.", sim, path);
free(path);
return ret;
}
void findWindow(simData *simd, char *sim, char *type, int count, int window, int panes, int pane)
{
snprintf(toybuf, sizeof(toybuf), "%s/IDs_%d.lua", scTemp, window);
qtreetbl_t *IDs = Lua2tree(toybuf, "IDs");
snprintf(toybuf, sizeof(toybuf), "%d %d", window, pane);
free(simd->paneID);
simd->paneID = xmprintf("%s", qLuaGet(IDs, toybuf)->v.s);
freeLuaTree(IDs);
if (strcmp(backupIARsim, sim) == 0)
{
ourSims->backup = xstrdup(simd->paneID);
V("Found backup sim %s in %s", sim, simd->paneID);
}
}
void prepSims(simData *simd, char *sim, char *type, int count, int window, int panes, int pane)
{
char *path = xmprintf("%s/%s.shini", scEtc, simd->tab);
char *newPath = xmprintf("%s/sim%d/%s.ini", scTemp, count, simd->tab); // Coz OpenSim sucks.
char *cmd;
simd->window = window;
simd->pane = pane;
// Make sure all tmux windows and panes are startned.
if (0 == panes)
{
// doTmuxCmd("split-window -hp 50 -d -t '%s:0.0'", Tconsole);
// doTmuxCmd("split-window -vp 50 -d -t '%s:0.1'", Tconsole);
// doTmuxCmd("split-window -vp 50 -d -t '%s:0.0'", Tconsole);
}
else if (0 == pane)
{
doTmuxCmd("new-window -dc '%s/current/bin' -n '%s' -t '%s:%d'", scRoot, type, Tconsole, window);
if (2 <= panes)
doTmuxCmd("split-window -hp 50 -d -t '%s:%d.0'", Tconsole, window);
if (4 <= panes)
{
doTmuxCmd("split-window -vp 50 -d -t '%s:%d.1'", Tconsole, window);
doTmuxCmd("split-window -vp 50 -d -t '%s:%d.0'", Tconsole, window);
}
if (8 <= panes)
{
doTmuxCmd("split-window -hp 50 -d -t '%s:%d.3'", Tconsole, window);
doTmuxCmd("split-window -hp 50 -d -t '%s:%d.2'", Tconsole, window);
doTmuxCmd("split-window -hp 50 -d -t '%s:%d.1'", Tconsole, window);
doTmuxCmd("split-window -hp 50 -d -t '%s:%d.0'", Tconsole, window);
}
}
// Create the temporary .ini files.
shellMe("echo 'IDs={' >%s/IDs_%d.lua", scTemp, window);
doTmuxCmd("list-panes -t %d -F \"['%d #{pane_index}'] = '#{window_id}.#{pane_id}',\" >> %s/IDs_%d.lua", window, window, scTemp, window);
shellMe("echo '}\nreturn IDs' >>%s/IDs_%d.lua", scTemp, window);
findWindow(simd, sim, type, count, window, panes, pane);
simd->portH = 8004 + count * 2;
simd->portU = 8005 + count * 2;
cmd = xmprintf("rm -fr %s/sim%d; mkdir -p %s/sim%d; sed -E"
" -e 's@\\[Region\\]@"
" paneID = \"\\%s\"\\n"
"\\[Startup\\]\\n"
" PIDFile = \"\\$\\{Paths\\|PIDPath\\}\\/\\$\\{Const\\|mysim\\}\\.pid\"\\n"
" LogFile = \"\\$\\{Paths\\|LogPath\\}\\/OpenSim_\\$\\{Const\\|mysim\\}\\.log\"\\n"
" StatsLogFile = \"\\$\\{Paths\\|LogPath\\}\\/OpenSimStats_\\$\\{Const\\|mysim\\}\\.log\"\\n"
" ConsoleHistoryFile = \"\\$\\{Paths\\|LogPath\\}\\/OpenSimConsoleHistory_\\$\\{Const\\|mysim\\}\\.txt\"\\n"
"\\n\\[Region\\]@'"
" -e 's/InternalPort[[:space:]]*=[[:space:]]*[[:digit:]]+/InternalPort = %d/'"
" -e 's/InternalPort[[:space:]]*=[[:space:]]*\"[[:digit:]]+\"/InternalPort = %d/'"
" -e 's/http_listener_port[[:space:]]*=[[:space:]]*[[:digit:]]+/http_listener_port = %d/'"
" -e 's/http_listener_port[[:space:]]*=[[:space:]]*\"[[:digit:]]+\"/http_listener_port = %d/'"
" %s >%s",
scTemp, count,
scTemp, count,
simd->paneID,
simd->portU,
simd->portU,
simd->portH,
simd->portH,
path, newPath);
D("Writing .ini file %s with ports %d %d", newPath, simd->portH, simd->portU);
if (shellMeFail(cmd))
E("sed command failed!");
free(cmd);
free(newPath);
free(path);
}
// Figure out where the sims are running.
void findSimsTmux(simData *simd, char *sim, char *type, int count, int window, int panes, int pane)
{
simd->window = window;
simd->pane = pane;
snprintf(toybuf, sizeof(toybuf), "%s/IDs_%d.lua", scTemp, window);
qtreetbl_t *IDs = Lua2tree(toybuf, "IDs");
snprintf(toybuf, sizeof(toybuf), "%d %d", window, pane);
simd->paneID = xmprintf("%s", qLuaGet(IDs, toybuf)->v.s);
freeLuaTree(IDs);
}
void startSim(simData *simd, char *sim, char *type, int count, int window, int panes, int pane)
{
if (!checkSimIsRunning(simd->tab))
{
I("Tmux tab [%d:%s](pane %d) tmux ID %s, from %s/sim%d - %s is starting.", window, type, pane, simd->paneID, scTemp, count, simd->name);
doTmuxCmd("select-pane -t %s:%s -T '%s'", Tconsole, simd->paneID, simd->tab);
snprintf(toybuf, sizeof(toybuf), "mono OpenSim.exe -inidirectory=%s/sim%d", scTemp, count);
sendTmuxCmd(simd->paneID, toybuf);
if (0 == ourSims->doIt)
{
snprintf(toybuf, sizeof(toybuf), "INITIALIZATION COMPLETE FOR %s", simd->name);
waitTmuxText(simd->paneID, toybuf);
I("%s is done starting up.", simd->name);
sendTmuxCmd(simd->paneID, "");
sendTmuxCmd(simd->paneID, "");
ourSims->la = waitLoadAverage(ourSims->la, loadAverageInc, simTimeOut);
if (1 < bulkSims)
bulkSims = bulkSims / 2;
}
else
{
// TODO - some compromise, do a premptive load check if we are not doing a wait anyway.
}
ourSims->doIt = ((count + 1) % bulkSims);
}
}
void stopSim(simData *simd, char *sim, char *type, int count, int window, int panes, int pane)
{
if (checkSimIsRunning(simd->tab))
{
// Leave empty panes as is.
V("Attempting to shut down sim %s.", simd->tab);
sendTmuxCmd(simd->paneID, "show users");
sleep(1);
if (shellMeFail("%s %s/%s capture-pane -Jt '%s' -p | grep -E '^Agents connected: [[:digit:]]*[[:space:]]*$' | tail -n 1 | cut -d ' ' -f 3 >%s/STOP_%s",
Tcmd, scRun, Tsocket, simd->paneID, scTemp, simd->tab))
E("Problem with shutting down sim %s - Failed find 'Agents connected'", simd->tab);
else
{
char *cmd = xmprintf("%s/STOP_%s", scTemp, simd->tab);
char *r = (char *) qfile_load(cmd, NULL);
if (r)
{
if ('0' == r[0])
sendTmuxCmd(simd->paneID, "quit");
else
{
r[strlen(r) - 1] = '\0';
simd->users = atoi(r);
sendTmuxCmd(simd->paneID, "alert Shutting down this sim, please leave.");
sendTmuxCmd(simd->paneID, "region restart bluebox \"Shutting down this sim, please leave.\" 300");
sendTmuxCmd(simd->paneID, "region restart notice \"Shutting down this sim, please leave.\" 300");
sendTmuxCmd(simd->paneID, "region restart abort \"Shutting down this sim, please leave.\"");
W("Not shutting down %s coz %d people are still on it. They have been warned.", simd->tab, simd->users);
}
free(r);
}
else
E("Problem with shutting down sim %s - Failed to read file %s", simd->tab, cmd);
free(cmd);
}
// There's three things that might happen -
// Sim will quit, tmux pane will go away before we can see the shutdown message.
// pane-exited hook might be useful here.
// Sim will quit, tmux pane wont go away. Dunno yet if waitTmuxText() will still work.
// pane-died hook might be useful here.
// Sim fails to quit, error message on the pane that we want to read, wont see the shutdown message.
// Also sim might not have finished starting up, and may even not be accepting comands yet.
// TODO - cater for and test them all.
// Could also loop on checkSimIsRunning(sim)
// snprintf(toybuf, sizeof(toybuf), "[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
// waitTmuxText(nm, toybuf);
// I("%s is done stopping.", simd->name);
// la = waitLoadAverage(la, loadAverageInc, simTimeOut);
}
}
typedef struct _ARList ARList;
struct _ARList
{
int len, num;
char **ARs, *this;
};
static int filterARs(struct dirtree *node)
{
if (!node->parent) return DIRTREE_RECURSE | DIRTREE_SHUTUP;
ARList *list = (ARList *) node->parent->extra;
int l0 = strlen(node->name), l1 = strlen(list->this);
// TODO - ignore zero sized ones.
if ((4 < l0) && ((strncmp(&(node->name[l0 - 4]), ".iar", 4) == 0) || (strncmp(&(node->name[l0 - 4]), ".oar", 4) == 0)) && (strncmp(node->name, list->this, l1) == 0))
{
if ((list->num + 1) > list->len)
{
list->len = list->len + 1;
list->ARs = xrealloc(list->ARs, list->len * sizeof(char *));
}
list->ARs[list->num] = xstrdup(node->name);
list->num++;
}
return 0;
}
// Forward declare this.
my_ulonglong dbCount(char *table, char *where);
void doSimsThing(simData *simd, char *sim, char *type, int count, int window, int panes, int pane)
{
// Check if only doing a single sim.
int cont = FALSE, member = false;
char *last = strchr(sim, ' ');
if (FLAG(m))
{
// check if it's a real user.
last[0] = '\0'; last++;
// Double check it's a real member.
snprintf(toybuf, sizeof(toybuf), "FirstName='%s' and LastName='%s'", sim, last);
if (1 == dbCount("UserAccounts", toybuf))
member = TRUE;
else
E("Can't find member %s %s.", sim, last);
}
else if (NULL != ourSims->target)
{
/* TODO - maybe?
byTab has the short name as the key, simData as the value.
Iterate through it looking for target sims if specified in the sledjchisl arguments.
Which can be short name, long name, foo.shini file name.
Though short name is a direct lookup, and "foo.shini" we can strip off the .shini and direct lookup the short name.
So only need to iterate if it's a long name.
Keep in mind the argument might be a user name for IAR backups. Or perhaps a UUID.
*/
cont = TRUE;
snprintf(toybuf, sizeof(toybuf), "%s.shini", simd->tab);
if
(
(strcmp(ourSims->target, simd->name) == 0) ||
(strcmp(ourSims->target, simd->tab) == 0) ||
(strcmp(ourSims->target, toybuf) == 0)
)
cont = FALSE;
snprintf(toybuf, sizeof(toybuf), "%s.ini", simd->tab);
if (strcmp(ourSims->target, toybuf) == 0)
cont = FALSE;
snprintf(toybuf, sizeof(toybuf), "sim%d.ini", count);
if (strcmp(ourSims->target, toybuf) == 0)
cont = FALSE;
}
if (cont)
return;
switch (currentMode)
{
case START : // "start 'Welcome sim'" "start Welcome.shini" "Welcome.shini" "start Welcome.ini" "start Welcome" "start" start everything
{
startSim(simd, sim, type, count, window, panes, pane);
break;
}
case BACKUP : // "backup -m 'onefang rejected'" "backup 'Welcome sim'" "backup Welcome.shini" "Welcome.shini backup" "backup Welcome.ini" "backup Welcome" "backup" backup everything
{
struct timeval tv;
time_t curtime;
char date[DATE_TIME_LEN];
gettimeofday(&tv, NULL);
curtime = tv.tv_sec;
strftime(date, DATE_TIME_LEN, "%F_%T", localtime(&curtime));
if (FLAG(m))
{
if (member)
{
I("Member %s %s is being backed up to %s/%s_%s-%s.iar in tmux windo %s.", sim, last, scBackup, sim, last, date, ourSims->backup);
snprintf(toybuf, sizeof(toybuf), "save iar -c %s %s / password %s/%s_%s-%s.iar", sim, last, scBackup, sim, last, date);
if (NULL != ourSims->backup)
{
if ('\0' == rSync[0])
{
I("Running gitar on %s %s", sim, last);
shellMeFail("%s/current/bin/sledjchisl gitar -m %s %s %s", scRoot, FLAG(v) ? "-v" : "", sim, last);
}
sendTmuxCmd(ourSims->backup, toybuf);
// if (0 == do)
{
snprintf(toybuf, sizeof(toybuf), "Saved archive with [[:digit:]]+ items for %s %s", sim, last);
waitTmuxText(ourSims->backup, toybuf);
I("%s %s is done backing up.", sim, last);
sendTmuxCmd(ourSims->backup, "");
sendTmuxCmd(ourSims->backup, "");
if ('\0' != rSync[0])
{
if (shellMeFail("time ionice -c3 nice -n 19 rsync -Ha -R --modify-window=2 --partial --port=%d --remove-source-files %s/*.iar %s",
rSyncPort, scBackup, rSync))
E("rsync failed");
}
ourSims->la = waitLoadAverage(ourSims->la, loadAverageInc, simTimeOut);
}
}
else
E("Can't find backup sim.");
}
}
else if (checkSimIsRunning(simd->tab))
{
// TODO - should collect names of existing backups, both tmux / ini name and proper name.
// Scan backups directory once before this for loop, add details to sims list.
// strip off the last bit of file name (YYYY-mm-dd_HH:MM:SS.oar) to get the name
// keep in mind some old files had munged names like "Tiffanie_s_Paradise-2021-06-23_05:11:38.oar"
I("Sim %s is being backed up to %s/backups/%s-%s.oar.", simd->name, scRoot, simd->tab, date);
if ('\0' == rSync[0])
{
I("Running gitar on %s", simd->tab);
shellMeFail("%s/current/bin/sledjchisl gitar %s %s", scRoot, FLAG(v) ? "-v" : "", simd->tab);
}
snprintf(toybuf, sizeof(toybuf), "save oar --all %s/%s-%s.oar", scBackup, simd->tab, date);
sendTmuxCmd(simd->paneID, toybuf);
// if (0 == do)
{
snprintf(toybuf, sizeof(toybuf), "Finished writing out OAR for %s", simd->name);
waitTmuxText(simd->paneID, toybuf);
I("%s is done backing up.", simd->name);
sendTmuxCmd(simd->paneID, "");
sendTmuxCmd(simd->paneID, "");
if ('\0' != rSync[0])
{
if (shellMeFail("time ionice -c3 nice -n 19 rsync -Ha -R --modify-window=2 --partial --port=%d --remove-source-files %s/*.oar %s",
rSyncPort, scBackup, rSync))
E("rsync failed");
}
ourSims->la = waitLoadAverage(ourSims->la, loadAverageInc, simTimeOut);
}
}
break;
}
case GITAR : // "gitAR -m avatar name" "gitAR sim name"
{
/* Work around OpenSims slow database corruption bug by using git to store all old backups.
Try to squeeze every last byte out of the tarballs. Seems to cut the total storage size down to one third the size of just the raw I/OAR files.
Saves even more if there's been no changes.
On the other hand, these backup files will grow indefinately, the more changes, the faster it grows. I can live with that for more reliable backups that go back further.
Tries to avoid loosing data if things go wrong. I think the main remaining problem would be running out of space, in which case you have bigger problems to deal with.
Strategy - unpack the last one, unpack and commit any old I/OARs, pack up the result, delete it's working directory, THEN run the save i/oar.
Avoids having to sync with OpenSim finishing the current I/OAR, and as a bonus, an easy to deliver latest I/OAR for people that want it.
*/
char *name = xstrdup(sim);
if (FLAG(m))
{
if (member)
{
free(name);
name = xmprintf("%s_%s", sim, last);
}
else
{
free(name);
return;
}
}
char type = FLAG(m) ? 'I' : 'O';
char *gar = xmprintf("%s-git%cAR", name, type), *gtr = xmprintf("%s/%s.tar.xz", scBackup, gar);
char *dir = xmprintf("%s/temp_%c_%s", scBackup, type, name);
char *glog = xmprintf("%s/log.log", scBackup), *gerr = xmprintf("%s/errors", dir);
// Make sure stuff that's already compressed doesn't get compressed by git.
// Also tries to protect binaries from mangling.
char *gab = xmprintf("%s/%s/.gitattributes", dir, gar), *gad =
"*.bvh -delta -diff -text\n"
"*.jp2 -delta -diff -text\n"
"*.jpg -delta -diff -text\n"
"*.llmesh -delta -diff -text\n"
"*.ogg -delta -diff -text\n"
"*.png -delta -diff -text\n"
"*.r32 -delta -diff -text\n"
"*.tga -delta -diff -text\n";
ARList *ourARs = xzalloc(sizeof(ARList));
if (qfile_exist(dir))
{
if (shellMeFail("echo 'Mess left over from last backup in %d, not gonna run!' >>%s", dir, gerr)) E("Cleaning up the mess!");
if (shellMeFail("mv %s/*.%car %s 2>&1 >>%s", dir, tolower(type), scBackup, gerr)) E("Failed cleaning up the mess!");
goto gitARend;
}
// Either unpack the old gitAR, or create a new one.
qfile_mkdir(dir, S_IRWXU | S_IRGRP | S_IXGRP, true);
if (qfile_exist(gtr))
{
I("Unpacking %s", gtr);
if (shellMeFail("cd %s; ionice -c3 nice -n 19 tar -xf %s >>%s", dir, gtr, gerr)) E("Failed to unpack %s!", gtr);
char *t = xmprintf("%s/%s_git%cAR", dir, name, type);
// Changed from _ to -, but deal with old archives.
if (qfile_exist(t))
{
if (shellMeFail("mv %s %s/%s", t, dir, gar)) E("Failed to move %s!", t);
}
free(t);
}
else
{
qfile_mkdir(gar, S_IRWXU | S_IRGRP | S_IXGRP, true);
// git will create gar for us.
if (shellMeFail("cd %s; git init --quiet %s >>%s", dir, gar, gerr)) E("Failed to git init %s/%s!", dir, gar);
// Coz git insists.
if (shellMeFail("cd %s/%s; git config user.email \"opensim@$(hostname -A | cut -d ' ' -f 1)\"", dir, gar)) E("Failed to git config user.email!");
if (shellMeFail("cd %s/%s; git config user.name \"opensim\"", dir, gar)) E("Failed to git config user.name!");
// Coz git insists on having something comitted before it can change the branch name.
if (-1 == qfile_save(gab, gad, strlen(gad), false)) E("Faild to write %s file!", gad);
if (shellMeFail("cd %s/%s; git add .gitattributes >>%s", dir, gar, gerr)) E("Failed to git add!");
V("Committing initial git.");
if (shellMeFail("cd %s/%s; git commit -qm \"Initial commit\" >>%s || echo \"ERROR - Could not commit!\" >>%s",
dir, gar, glog, gerr)) E("Failed to git commit!");
if (shellMeFail("cd %s/%s; git branch -m master Domme >>%s", dir, gar, gerr)) E("Failed to git branch -m master Domme!");
}
// Doing these each time, to catch those old ones that didn't have them.
// Coz otherwise git commit starts a gc run IN THE BACKGROUD, which screws up trying to tarball it.
if (shellMeFail("cd %s/%s; git config gc.autodetach false", dir, gar)) E("Failed to git config gc.autodetach!");
// Don't want it running in the foreground either, coz it dumps on the console, we do a gc --quiet later anyway.
if (shellMeFail("cd %s/%s; git config gc.auto 0", dir, gar)) E("Failed to git config gc.auto!");
// Git is such a pedantic bitch, let's just fucking ignore any errors it gives due to lack of anything to do.
// Even worse the OpenSim devs breaking logout tracking gives git plenty of nothing to do. lol
// Loop through the .iar / .oar files in backups, ignoring zero sized files.
struct dirtree *new = dirtree_add_node(0, scBackup, 0);
int i;
ourARs->num = 0;
ourARs->this = xmprintf("%s-", name);
new->extra = (long) ourARs;
dirtree_handle_callback(new, filterARs);
qsort(ourARs->ARs, ourARs->num, sizeof(char *), qstrcmp);
for (i = 0; i < ourARs->num; i++)
{
I("Adding %s to %s", ourARs->ARs[i], gtr);
// Deal with deletions in the inventory / sim, easy method, which becomes a nop for files that stay in the git add below.
if (shellMeFail("cd %s/%s; rm -fr * >>%s", dir, gar, gerr)) E("Failed to rm!");
if (shellMeFail("cd %s/%s; ionice -c3 nice -n 19 tar -xzf \"%s/%s\" || echo \"ERROR - Could not unpack %s !\" >>%s",
dir, gar, scBackup, ourARs->ARs[i], ourARs->ARs[i], gerr)) E("Failed to unpack %s!", ourARs->ARs[i]);
if (!hasContents(gerr))
{
if (shellMeFail("cd %s/%s; git add * >>%s", dir, gar, glog)) E("Failed to git add!");
// The \\* bit is to escape the \ from snprintf, which itself escapes the * from the shell.
if (shellMeFail("cd %s/%s; git add */\\* >>%s", dir, gar, gerr)) E("Failed to git add!");
// Gotta add this again, coz of the rm. Apparently rm removes dotfiles, but add doesn't!
if (-1 == qfile_save(gab, gad, strlen(gad), false)) E("Faild to write %s file!", gab);
if (shellMeFail("cd %s/%s; git add .gitattributes >>%s", dir, gar, gerr)) E("Failed to git add!");
// Magic needed to figure out if there's anything to commit.
// After all the pain to get this to work, there's an ever changing timestamp in archive.xml that screws it up.
// Like this system didn't have enough timestamps in it already. lol
// TODO - I could sed out that timestamp, and put it back again based on the OAR file name when extracting.
// IARs don't seem to have the timestamp.
int j = shellMe("cd %s/%s; t=$(git status --porcelain) && [ -z \"${t}\" ]", dir, gar);
if (!WIFEXITED(j)) E("git status failed!");
else if (1 == WEXITSTATUS(j))
{
V("Committing changes from %s", ourARs->ARs[i]);
// Note this commit message has to be just the file name, as the ungitAR script uses it.
if (shellMeFail("cd %s/%s; git commit -a -qm \"%s\" >>%s || echo \"ERROR - Could not commit %s !\" >>%s ",
dir, gar, ourARs->ARs[i], ourARs->ARs[i], glog, gerr)) E("Failed to git commit!");
if (hasContents(gerr))
{
free(ourARs->ARs[i]);
goto gitARend;
}
}
else
V("No changes to commit from %s.", ourARs->ARs[i]);
}
if (!hasContents(gerr))
{
if (shellMeFail("mv %s/%s %s", scBackup, ourARs->ARs[i], dir)) E("Failed to move %s!", ourARs->ARs[i]);
}
free(ourARs->ARs[i]);
}
if (!hasContents(gerr))
{
I("Checking git repo %s", gtr);
if (shellMeFail("cd %s/%s; git fsck --strict --lost-found --no-progress >>%s || echo \"ERROR - Problem with git fsck %s !\" >>%s ",
dir, gar, glog, gtr, gerr)) E("Failed to git fsck!");
if (shellMeFail("cd %s/%s; git gc --aggressive --prune=all --quiet >>%s || echo \"ERROR - Problem with git gc %s !\" >>%s ",
dir, gar, glog, gtr, gerr)) E("Failed to git gc!");
I("Compressing %s", gtr);
if (shellMeFail("cd %s; XZ_OPT='-9e' ionice -c3 nice -n 19 tar -c --xz %s -f %s || echo 'ERROR - Could not pack gitAR!' >>%s",
dir, gar, gtr, gerr)) E("Failed to git add!");
}
gitARend:
if (hasContents(gerr)) E("Failed to process the archives, look in %s for errors!", gerr);
else
{
if (shellMeFail("rm -fr %s", dir)) E("Failed to rm!");
}
free(ourARs->ARs);
free(ourARs->this);
free(ourARs);
free(gab);
free(gerr);
free(glog);
free(dir);
free(gtr);
free(gar);
free(name);
break;
}
case RESTART : // "restart 'Welcome sim'" "restart Welcome.shini" "Welcome.shini restart" "restart Welcome.ini" "restart Welcome" "restart" restart everything
{
I("Tmux tab [%d:%s](pane %d) tmux ID %s, from %s/sim%d - %s is stopping.", window, type, pane, simd->paneID, scTemp, count, simd->name);
stopSim(simd, sim, type, count, window, panes, pane);
while (checkSimIsRunning(simd->tab))
usleep(100000);
usleep(100000);
startSim(simd, sim, type, count, window, panes, pane);
break;
}
case STATUS : // "status 'Welcome sim'" "status Welcome.shini" "Welcome.shini status" "status Welcome.ini" "status Welcome" "status" status everything
{
// TODO - report CPU and memory used as well.
if (FLAG(m))
{
; // Do nothing, this is better done in the calling function, coz it has the details.
}
else if (checkSimIsRunning(simd->tab))
I("%s is running in Tmux tab [%d:%s](pane %d) tmux ID %s, from %s/sim%d", simd->name, window, type, pane, simd->paneID, scTemp, count);
else
W("%s is not running.", simd->name);
break;
}
case STOP : // "stop 'Welcome sim'" "stop Welcome.shini" "Welcome.shini stop" "stop Welcome.ini" "stop Welcome" "stop" stop everything
{
stopSim(simd, sim, type, count, window, panes, pane);
break;
}
default :
{
E("Unknown command! %s", toys.optargs[0]);
break;
}
}
}
void stopSims(simData *simd, char *sim, char *type, int count, int window, int panes, int pane)
{
// TODO - should move onto others if this one takes too long, and come back later.
// NOTE - these sleeps are guesses, seems to work on my super desktop during testing.
if (checkSimIsRunning(simd->tab))
T("Tmux tab [%d:%s](pane %d) tmux ID %s, from %s/sim%d - %s has NOT stopped YET.", window, type, pane, simd->paneID, scTemp, count, simd->name);
if (simd->users)
{
ourSims->doIt = 0;
W("Not shutting down %s coz %d people are still on it. They have been warned.", simd->tab, simd->users);
}
else
{
while (checkSimIsRunning(simd->tab))
usleep(100000);
usleep(10000);
doTmuxCmd("kill-pane -t %s", simd->paneID);
I("Tmux tab [%d:%s](pane %d) tmux ID %s, from %s/sim%d - %s has stopped.", window, type, pane, simd->paneID, scTemp, count, simd->name);
}
}
static void PrintEnv(qgrow_t *reply, char *label, char **envp)
{
reply->addstrf(reply, "%s:<br>\n<pre>\n", label);
for ( ; *envp != NULL; envp++)
reply->addstrf(reply, "%s\n", *envp);
reply->addstr(reply, "</pre>\n");
}
static void printEnv(char **envp)
{
for ( ; *envp != NULL; envp++)
D("%s", *envp);
}
typedef struct _rowData rowData;
struct _rowData
{
char **fieldNames;
qlist_t *rows;
};
static void dumpHash(qhashtbl_t *tbl)
{
qhashtbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj));
tbl->lock(tbl);
while(tbl->getnext(tbl, &obj, true) == true)
d("%s = %s", obj.name, (char *) obj.data);
tbl->unlock(tbl);
}
static void dumpArray(int d, char **ar)
{
int i = 0;
while (ar[i] != NULL)
{
d("%d %d %s", d, i, ar[i]);
i++;
}
}
typedef struct _dbFields dbFields;
struct _dbFields
{
qlisttbl_t *flds;
int count;
};
typedef struct _dbField dbField;
struct _dbField
{
char *name;
enum enum_field_types type;
unsigned long length;
unsigned int flags;
unsigned int decimals;
};
void dbFreeFields(dbFields *flds, boolean all)
{
flds->count--;
// TODO - sigh, looks to be inconsistant why some do and some don't leak.
// I guess the ones that don't leak are the ones that crash?
// It's only a tiny leak anyway, 80 bytes total.
// if ((0 >= flds->count) || all) // CRASHY
if ((0 >= flds->count)) // LEAKY
{
qlisttbl_obj_t obj;
memset((void *) &obj, 0, sizeof(obj));
flds->flds->lock(flds->flds);
while(flds->flds->getnext(flds->flds, &obj, NULL, false) == true)
{
dbField *fld = (dbField *) obj.data;
free(fld->name);
}
flds->flds->unlock(flds->flds);
flds->flds->free(flds->flds);
flds->flds = NULL;
free(flds);
}
}
enum dbCommandType
{
CT_SELECT,
CT_CREATE,
CT_UPDATE,
CT_NONE
};
typedef struct _dbRequest dbRequest;
struct _dbRequest
{
char *table, *join, *where, *order, *sql;
MYSQL_STMT *prep; // NOTE - executing it stores state in this.
dbFields *fields;
int inCount, outCount, rowCount;
char **inParams, **outParams;
MYSQL_BIND *inBind, *outBind;
rowData *rows;
my_ulonglong count;
enum dbCommandType type;
boolean freeOutParams;
};
void dbFreeRequest(dbRequest *req, boolean all)
{
int i;
D("Cleaning up prepared database request %s - %s %d %d", req->table, req->where, req->outCount, req->inCount);
if (NULL != req->outBind)
{
for (i = 0; i < req->outCount; i++)
{
if (NULL != req->outBind[i].buffer) free(req->outBind[i].buffer);
if (NULL != req->outBind[i].length) free(req->outBind[i].length);
if (NULL != req->outBind[i].error) free(req->outBind[i].error);
if (NULL != req->outBind[i].is_null) free(req->outBind[i].is_null);
}
free(req->outBind);
req->outBind = NULL;
}
else
D(" No out binds to clean up for %s - %s.", req->table, req->where);
if (NULL != req->inBind)
{
for (i = 0; i < req->inCount; i++)
{
if (NULL != req->inBind[i].buffer) free(req->inBind[i].buffer);
if (NULL != req->inBind[i].length) free(req->inBind[i].length);
if (NULL != req->inBind[i].error) free(req->inBind[i].error);
if (NULL != req->inBind[i].is_null) free(req->inBind[i].is_null);
}
free(req->inBind);
req->inBind = NULL;
}
else
D(" No in binds to clean up for %s - %s.", req->table, req->where);
if (req->freeOutParams && all)
{
if (NULL != req->outParams)
{
free(req->outParams);
req->outParams = NULL;
}
else
D(" No out params to clean up for %s - %s.", req->table, req->where);
}
if (NULL != req->sql) free(req->sql);
else
D(" No SQL to clean up for %s - %s.", req->table, req->where);
req->sql = NULL;
if (NULL != req->prep)
{
if (0 != mysql_stmt_close(req->prep))
C(" Unable to close the prepared statement!");
req->prep = NULL;
}
if (all)
{
if (NULL != req->fields)
{
dbFreeFields(req->fields, all);
req->fields = NULL;
}
else
D(" No fields to clean up for %s - %s.", req->table, req->where);
}
}
void freeDb(boolean all)
{
dbRequest **rq;
if (dbRequests)
{
if (all)
{
while (NULL != (rq = (dbRequest **) dbRequests->popfirst(dbRequests, NULL)))
{
dbFreeRequest(*rq, all);
free(rq);
}
dbRequests->free(dbRequests);
dbRequests = NULL;
}
else
{
qlist_obj_t obj;
memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
dbRequests->lock(dbRequests);
while (dbRequests->getnext(dbRequests, &obj, false) == true)
dbFreeRequest(*((dbRequest **) obj.data), all);
dbRequests->unlock(dbRequests);
}
}
if (database) mysql_close(database);
database = NULL;
mysql_library_end();
}
static boolean dbConnect()
{
database = mysql_init(NULL);
if (NULL == database)
{
E("mysql_init() failed - %s", mysql_error(database));
return FALSE;
}
/* TODO - dammit, no mysql_get_option(), MariaDB docs say mysql_get_optionv(), which doesn't exist either.
Says "This function was added in MariaDB Connector/C 3.0.0.", I have MariaDB / MySQL client version: 10.1.44-MariaDB.
if (mysql_get_option(database, MYSQL_OPT_CONNECT_TIMEOUT, &dbTimeout))
E("mysql_get_option(MYSQL_OPT_CONNECT_TIMEOUT) failed - %s", mysql_error(database));
else
D("Database MYSQL_OPT_CONNECT_TIMEOUT = %d", dbTimeout);
if (mysql_get_option(database, MYSQL_OPT_RECONNECT, &dbReconnect))
E("mysql_get_option(MYSQL_OPT_RECONNECT) failed - %s", mysql_error(database));
else
D("Database MYSQL_OPT_RECONNECT = %d", (int) dbReconnect);
*/
// Seems best to disable auto-reconnect, so I have more control over reconnections.
dbReconnect = 0;
if (mysql_options(database, MYSQL_OPT_RECONNECT, &dbReconnect))
E("mysql_options(MYSQL_OPT_RECONNECT) failed - %s", mysql_error(database));
else
D("Database MYSQL_OPT_RECONNECT is now %d", (int) dbReconnect);
dbconn = mysql_real_connect(database,
getStrH(configs, "Data Source"),
getStrH(configs, "User ID"),
getStrH(configs, "Password"),
getStrH(configs, "Database"),
// 3036, "/var/run/mysqld/mysqld.sock",
0, NULL,
CLIENT_FOUND_ROWS | CLIENT_LOCAL_FILES | CLIENT_MULTI_STATEMENTS | CLIENT_MULTI_RESULTS);
if (NULL == dbconn)
{
E("mysql_real_connect() failed - %s", mysql_error(database));
return FALSE;
}
// Just set the fucking thing to a year. Pffft.
dbTimeout = 60 * 60 * 24 * 7 * 52;
char *sql = xmprintf("SET SESSION wait_timeout=%d", (int) dbTimeout);
if (mysql_query(database, sql))
E("SET SESSION wait_timeout=%d failed - %s", (int) dbTimeout, mysql_error(database));
else
D("Database wait_timeout = %d", (int) dbTimeout);
free(sql);
if (-1 == clock_gettime(CLOCK_REALTIME, &dbLast))
perror_msg("Unable to get the time.");
return TRUE;
}
// A general error function that checks for certain errors that mean we should try to connect to the server MariaDB again.
// https://mariadb.com/kb/en/mariadb-error-codes/
// 1129? 1152? 1184? 1218? 1927 3032? 4150?
// "server has gone away" isn't listed there, that's the one I was getting. Pffft
// It's 2006, https://dev.mysql.com/doc/refman/8.0/en/gone-away.html
// Ah it could be "connection inactive for 8 hours".
// Which might be why OpenSim opens a new connection for EVERYTHING.
// https://dev.mysql.com/doc/refman/5.7/en/c-api-auto-reconnect.html
// Has more details.
static boolean dbCheckError(char *error, char *sql)
{
int e = mysql_errno(database);
E("MariaDB error %d - %s: %s\n%s", e, error, mysql_error(database), sql);
if (2006 == e)
{
W("Reconnecting to database.");
freeDb(false);
return dbConnect();
}
return FALSE;
}
// "Statement execute failed 2013: Lost connection to MySQL server during query"
static boolean dbStmtCheckError(dbRequest *req, char *error, char *sql)
{
int e = mysql_stmt_errno(req->prep);
E("MariaDB prepared statement error %d - %s: %s\n%s", e, error, mysql_stmt_error(req->prep), sql);
if (2013 == e)
{
W("Reconnecting to database.");
freeDb(false);
return dbConnect();
}
return FALSE;
}
dbFields *dbGetFields(char *table)
{
static qhashtbl_t *tables = NULL;
if (NULL == tables) tables = qhashtbl(0, 0);
dbFields *ret = tables->get(tables, table, NULL, false);
if (NULL == ret)
{
// Seems the only way to get field metadata is to actually perform a SQL statement, then you get the field metadata for the result set.
// Chicken, meet egg, sorry you had to cross the road for this.
char *sql = xmprintf("SELECT * FROM %s LIMIT 0", table);
d("Getting field metadata for %s", table);
if (mysql_query(database, sql))
{
// E("MariaDB error %d - Query failed 0: %s\n%s", mysql_errno(database), mysql_error(database), sql);
if (dbCheckError("Query failed 0", sql))
{
ret = dbGetFields(table);
free(sql);
return ret;
}
}
else
{
MYSQL_RES *res = mysql_store_result(database);
if (!res)
E("MariaDB error %d - Couldn't get results set from %s\n %s", mysql_errno(database), mysql_error(database), sql);
else
{
MYSQL_FIELD *fields = mysql_fetch_fields(res);
if (!fields)
E("MariaDB error %d - Failed fetching fields: %s", mysql_errno(database), mysql_error(database));
else
{
unsigned int i, num_fields = mysql_num_fields(res);
ret = xmalloc(sizeof(dbFields)); // Little bit LEAKY
ret->flds = qlisttbl(QLISTTBL_UNIQUE | QLISTTBL_LOOKUPFORWARD);
ret->count = 1;
for (i = 0; i < num_fields; i++)
{
dbField *fld = xmalloc(sizeof(dbField));
fld->name = xstrdup(fields[i].name);
fld->type = fields[i].type;
fld->length = fields[i].length;
fld->flags = fields[i].flags;
fld->decimals = fields[i].decimals;
ret->flds->put(ret->flds, fld->name, fld, sizeof(*fld));
free(fld);
}
tables->put(tables, table, ret, sizeof(*ret));
}
mysql_free_result(res);
}
}
free(sql);
}
else // Reference count these, coz some tables are used more than once.
ret->count++;
return ret;
}
/* How to deal with prepared SQL statements.
http://karlssonondatabases.blogspot.com/2010/07/prepared-statements-are-they-useful-or.html
https://blog.cotten.io/a-taste-of-mysql-in-c-87c5de84a31d?gi=ab3dd1425b29
https://raspberry-projects.com/pi/programming-in-c/databases-programming-in-c/mysql/accessing-the-database
IG and CG now both have sims connected to other grids, so some sort of
multi database solution would be good, then we can run the grid and the
external sims all in one.
Not sure if this'll work with Count(*).
---------------------------------------------
The complicated bit is the binds.
You are binding field values to C memory locations.
The parameters and returned fields need binds.
Mostly seems to be the value parts of the SQL statements.
I suspect most will be of the form -
... WHERE x=? and foo=?
INSERT INTO table VALUES (?,?,?)
UPDATE table SET x=?, foo=? WHERE id=?
A multi table update -
UPDATE items,month SET items.price=month.price WHERE items.id=month.id;
*/
int dbDoSomething(dbRequest *req, boolean count, ...)
{
int ret = 0;
va_list ap;
struct timespec then;
int i, j;
MYSQL_RES *prepare_meta_result = NULL;
if (-1 == clock_gettime(CLOCK_REALTIME, &then))
perror_msg("Unable to get the time.");
// TODO - should factor this out to it's own function, and call that function in dbCount() and dbCountJoin().
// Or better yet, finally migrate those functions to using dbDoSomething().
double n = (dbLast.tv_sec * 1000000000.0) + dbLast.tv_nsec;
double t = (then.tv_sec * 1000000000.0) + then.tv_nsec;
t("Database timeout test %lf > %lf", ((t - n) / 1000000000.0), (dbTimeout / 2.0));
if (((t - n) / 1000000000.0) > (dbTimeout / 2.0))
{
T("Avoid database timeout of %d seconds, pinging it.", dbTimeout);
if (0 != mysql_ping(database))
{
W("Reconnecting to database.");
freeDb(false);
dbConnect();
}
}
va_start(ap, count);
if (NULL == req->prep)
{
D("Creating prepared statement for %s - %s", req->table, req->where);
if (0 == req->type)
req->type = CT_SELECT;
req->fields = dbGetFields(req->table);
if (NULL == req->fields)
{
E("Unknown fields for table %s.", req->table);
ret++;
goto end;
}
switch (req->type)
{
case CT_SELECT :
{
char *select = xmprintf("");
i = 0;
while (req->outParams[i] != NULL)
{
char *t = xmprintf("%s,%s", select, req->outParams[i]);
free(select);
select = t;
i++;
}
if (0 == i)
{
free(select);
if (count)
select = xmprintf(",Count(*)");
else
select = xmprintf(",*");
}
if (NULL == req->join)
req->join = "";
if (req->where)
req->sql = xmprintf("SELECT %s FROM %s %s WHERE %s", &select[1], req->table, req->join, req->where);
else
req->sql = xmprintf("SELECT %s FROM %s", &select[1], req->table, req->join);
free(select);
if (req->order)
{
char *t = xmprintf("%s ORDER BY %s", req->sql, req->order);
free(req->sql);
req->sql = t;
}
break;
}
case CT_CREATE :
{
char *values = xmprintf("");
i = 0;
while (req->inParams[i] != NULL)
{
char *t = xmprintf("%s, %s=?", values, req->inParams[i]);
free(values);
values = t;
i++;
}
if (0 == i)
{
E("Statement prepare for INSERT must have in paramaters.");
ret++;
free(values);
values = xmprintf("");
}
req->sql = xmprintf("INSERT INTO %s SET %s", req->table, &values[1]);
free(values);
break;
}
case CT_UPDATE :
{
break;
}
case CT_NONE :
{
W("No SQL type!");
break;
}
}
d("New SQL statement - %s", req->sql);
// prepare statement with the other fields
req->prep = mysql_stmt_init(database);
if (NULL == req->prep)
{
E("Statement prepare init failed: %s\n", mysql_stmt_error(req->prep));
ret++;
goto end;
}
if (mysql_stmt_prepare(req->prep, req->sql, strlen(req->sql)))
{
E("Statement prepare failed: %s\n", mysql_stmt_error(req->prep));
ret++;
goto end;
}
// setup the bind stuff for any "?" parameters in the SQL.
req->inCount = mysql_stmt_param_count(req->prep);
i = 0;
while (req->inParams[i] != NULL)
i++;
if (i != req->inCount)
{
E("In parameters count don't match %d != %d for - %s", i, req->inCount, req->sql);
ret++;
goto freeIt;
}
req->inBind = xzalloc(i * sizeof(MYSQL_BIND));
//W("Allocated %d %d inBinds for %s", i, req->inCount, req->sql);
for (i = 0; i < req->inCount; i++)
{
dbField *fld = req->fields->flds->get(req->fields->flds, req->inParams[i], NULL, false);
if (NULL == fld)
{
E("Unknown input field %d %s.%s for - %s", i, req->table, req->inParams[i], req->sql);
ret++;
goto freeIt;
}
else
{
// https://blog.cotten.io/a-taste-of-mysql-in-c-87c5de84a31d?gi=ab3dd1425b29
// For some gotchas about all of this binding bit.
req->inBind[i].buffer_type = fld->type;
req->inBind[i].buffer = xzalloc(fld->length + 1); // Note the + 1 is for string types, and a waste for the rest.
req->inBind[i].buffer_length = fld->length + 1;
switch(fld->type)
{
case MYSQL_TYPE_TINY:
{
//d("TINY %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_SHORT:
{
req->inBind[i].is_unsigned = FALSE;
//d("SHORT %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_INT24:
{
req->inBind[i].is_unsigned = FALSE;
//d("INT24 %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_LONG:
{
req->inBind[i].is_unsigned = FALSE;
//d("LONG %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_LONGLONG:
{
req->inBind[i].is_unsigned = FALSE;
//d("LONGLONG %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_FLOAT:
{
//d("FLOAT %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_DOUBLE:
{
//d("DOUBLE %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_NEWDECIMAL:
{
//d("NEWDECIMAL %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP:
{
//d("DATE / TIME ish %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
{
//d("STRING / VARSTRING %d %s %d", i, fld->name, req->inBind[i].buffer_length);
req->inBind[i].is_null = xzalloc(sizeof(my_bool));
req->inBind[i].length = xzalloc(sizeof(unsigned long));
break;
}
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
{
//d("BLOBs %d %s %d", i, fld->name, req->inBind[i].buffer_length);
req->inBind[i].is_null = xzalloc(sizeof(my_bool));
break;
}
case MYSQL_TYPE_BIT:
{
req->inBind[i].is_null = xzalloc(sizeof(my_bool));
//d("BIT %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_NULL:
{
//d("NULL %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
}
}
}
// TODO - if this is not a count, setup result bind paramateres, may be needed for counts as well.
if (CT_SELECT == req->type)
{
prepare_meta_result = mysql_stmt_result_metadata(req->prep);
if (!prepare_meta_result)
{
E(" mysql_stmt_result_metadata() error %d, returned no meta information - %s\n", mysql_stmt_errno(req->prep), mysql_stmt_error(req->prep));
ret++;
goto freeIt;
}
}
if (count)
{
I("count!!!!!!!!!!!!!!!!");
}
else if (CT_SELECT == req->type)
{
req->outCount = mysql_num_fields(prepare_meta_result);
i = 0;
while (req->outParams[i] != NULL)
i++;
if (0 == i) // Passing in {NULL} as req->outParams means "return all of them".
{
req->outParams = xzalloc((req->outCount + 1) * sizeof(char *));
req->freeOutParams = TRUE;
qlisttbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj));
req->fields->flds->lock(req->fields->flds);
while (req->fields->flds->getnext(req->fields->flds, &obj, NULL, false) == true)
{
dbField *fld = (dbField *) obj.data;
req->outParams[i] = fld->name;
i++;
}
req->outParams[i] = NULL;
req->fields->flds->unlock(req->fields->flds);
}
if (i != req->outCount)
{
E("Out parameters count doesn't match %d != %d foqr - %s", i, req->outCount, req->sql);
ret++;
goto freeIt;
}
req->outBind = xzalloc(i * sizeof(MYSQL_BIND));
//W("Allocated %d %d outBinds for %s", i, req->outCount, req->sql);
for (i = 0; i < req->outCount; i++)
{
dbField *fld = req->fields->flds->get(req->fields->flds, req->outParams[i], NULL, false);
if (NULL == fld)
{
E("Unknown output field %d %s.%s foqr - %s", i, req->table, req->outParams[i], req->sql);
ret++;
goto freeIt;
}
else
{
// https://blog.cotten.io/a-taste-of-mysql-in-c-87c5de84a31d?gi=ab3dd1425b29
// For some gotchas about all of this binding bit.
req->outBind[i].buffer_type = fld->type;
req->outBind[i].buffer = xzalloc(fld->length + 1); // Note the + 1 is for string types, and a waste for the rest.
req->outBind[i].buffer_length = fld->length + 1;
req->outBind[i].error = xzalloc(sizeof(my_bool));
req->outBind[i].is_null = xzalloc(sizeof(my_bool));
switch(fld->type)
{
case MYSQL_TYPE_TINY:
{
//d("TINY %d %s %d", i, fld->name, req->outBind[i].buffer_length);
break;
}
case MYSQL_TYPE_SHORT:
{
//d("SHORT %s %d", fld->name, req->outBind[i].buffer_length);
req->outBind[i].is_unsigned = FALSE;
break;
}
case MYSQL_TYPE_INT24:
{
//d("INT24 %s %d", fld->name, req->outBind[i].buffer_length);
req->outBind[i].is_unsigned = FALSE;
break;
}
case MYSQL_TYPE_LONG:
{
//d("LONG %d %s %d", i, fld->name, req->outBind[i].buffer_length);
req->outBind[i].is_unsigned = FALSE;
break;
}
case MYSQL_TYPE_LONGLONG:
{
//d("LONGLONG %s %d", fld->name, req->outBind[i].buffer_length);
req->outBind[i].is_unsigned = FALSE;
break;
}
case MYSQL_TYPE_FLOAT:
{
//d("FLOAT %s %d", fld->name, req->outBind[i].buffer_length);
break;
}
case MYSQL_TYPE_DOUBLE:
{
//d("DOUBLE %s %d", fld->name, req->outBind[i].buffer_length);
break;
}
case MYSQL_TYPE_NEWDECIMAL:
{
//d("NEWDECIMAL %s %d", fld->name, req->outBind[i].buffer_length);
break;
}
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP:
{
//d("DATE / TIME ish %s %d", fld->name, req->outBind[i].buffer_length);
break;
}
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
{
//d("STRING / VARSTRING %s %d", fld->name, req->outBind[i].buffer_length);
req->outBind[i].length = xzalloc(sizeof(unsigned long));
break;
}
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
{
//d("BLOBs %s %d", fld->name, req->outBind[i].buffer_length);
break;
}
case MYSQL_TYPE_BIT:
{
//d("BIT %s %d", fld->name, req->outBind[i].buffer_length);
break;
}
case MYSQL_TYPE_NULL:
{
//d("NULL %s %d", fld->name, req->outBind[i].buffer_length);
break;
}
}
}
}
if (mysql_stmt_bind_result(req->prep, req->outBind))
{
E("Bind failed error %d.", mysql_stmt_errno(req->prep));
ret++;
goto freeIt;
}
}
}
//d("input bind for %s", req->sql);
for (i = 0; i < req->inCount; i++)
{
dbField *fld = req->fields->flds->get(req->fields->flds, req->inParams[i], NULL, false);
if (NULL == fld)
{
E("Unknown input field %s.%s for - %s", req->table, req->inParams[i], req->sql);
ret++;
goto freeIt;
}
else
{
switch(fld->type)
{
case MYSQL_TYPE_TINY:
{
int c = va_arg(ap, int);
signed char d = (signed char) c;
memcpy(req->inBind[i].buffer, &d, (size_t) fld->length);
//V("TINY %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_SHORT:
{
int c = va_arg(ap, int);
short int d = (short int) c;
memcpy(req->inBind[i].buffer, &d, (size_t) fld->length);
//V("SHORT %d %s %d = %d", i, fld->name, req->inBind[i].buffer_length, c);
break;
}
case MYSQL_TYPE_INT24:
{
int d = va_arg(ap, int);
memcpy(req->inBind[i].buffer, &d, (size_t) fld->length);
//V("INT24 %d %s %d - %d", i, fld->name, req->inBind[i].buffer_length, d);
break;
}
case MYSQL_TYPE_LONG:
{
long d = va_arg(ap, long);
memcpy(req->inBind[i].buffer, &d, (size_t) fld->length);
//V("LONG %d %s %d = %ld", i, fld->name, req->inBind[i].buffer_length, d);
break;
}
case MYSQL_TYPE_LONGLONG:
{
long long int d = va_arg(ap, long long int);
memcpy(req->inBind[i].buffer, &d, (size_t) fld->length);
//V("LONGLONG %d %s %d = %lld", i, fld->name, req->inBind[i].buffer_length, d);
break;
}
case MYSQL_TYPE_FLOAT:
{
double c = va_arg(ap, double);
float d = (float) c;
memcpy(req->inBind[i].buffer, &d, (size_t) fld->length);
//V("FLOAT %d %s %d = %f", i, fld->name, req->inBind[i].buffer_length, d);
break;
}
case MYSQL_TYPE_DOUBLE:
{
double d = va_arg(ap, double);
memcpy(req->inBind[i].buffer, &d, (size_t) fld->length);
//V("DOUBLE %d %s %d = %f", i, fld->name, req->inBind[i].buffer_length, d);
break;
}
case MYSQL_TYPE_NEWDECIMAL:
{
//V("NEWDECIMAL %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP:
{
MYSQL_TIME d = va_arg(ap, MYSQL_TIME);
memcpy(req->inBind[i].buffer, &d, (size_t) fld->length);
//V("DATE / TIME ish %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
{
char *d = va_arg(ap, char *);
unsigned long l = strlen(d);
if (l > fld->length)
l = fld->length;
*(req->inBind[i].length) = l;
strncpy(req->inBind[i].buffer, d, (size_t) l);
((char *) req->inBind[i].buffer)[l] = '\0';
//V("STRING / VARSTRING %d %s %d = %s", i, fld->name, req->inBind[i].buffer_length, d);
break;
}
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
{
// TODO - should write this, we will likely need it. Main problem is - how long is this blob? Probably should add a length param before the blob.
//V("BLOBs %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_BIT:
{
//V("BIT %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
case MYSQL_TYPE_NULL:
{
//V("NULL %d %s %d", i, fld->name, req->inBind[i].buffer_length);
break;
}
}
}
}
if (mysql_stmt_bind_param(req->prep, req->inBind))
{
E("Bind failed error %d.", mysql_stmt_errno(req->prep));
ret++;
goto freeIt;
}
//d("Execute %s", req->sql);
// do the prepared statement req->prep.
if (mysql_stmt_execute(req->prep))
{
if (dbStmtCheckError(req, "Statement failed 0", req->sql))
{
ret++;
goto freeIt;
}
}
int fs = mysql_stmt_field_count(req->prep);
// stuff results back into req.
if (NULL != req->outBind)
{
req->rows = xmalloc(sizeof(rowData));
req->rows->fieldNames = xzalloc(fs * sizeof(char *));
if (mysql_stmt_store_result(req->prep))
{
E(" mysql_stmt_store_result() failed %d: %s", mysql_stmt_errno(req->prep), mysql_stmt_error(req->prep));
ret++;
goto freeIt;
}
req->rowCount = mysql_stmt_num_rows(req->prep);
if (0 == req->rowCount)
D("No rows returned from : %s\n", req->sql);
else
D("%d rows of %d fields returned from : %s\n", req->rowCount, fs, req->sql);
req->rows->rows = qlist(0);
while (MYSQL_NO_DATA != mysql_stmt_fetch(req->prep))
{
qhashtbl_t *flds = qhashtbl(0, 0);
for (i = 0; i < req->outCount; i++)
{
dbField *fld = req->fields->flds->get(req->fields->flds, req->outParams[i], NULL, false);
req->rows->fieldNames[i] = fld->name;
if (!*(req->outBind[i].is_null))
{
//d("2.8 %s", req->rows->fieldNames[i]);
flds->put(flds, req->rows->fieldNames[i], req->outBind[i].buffer, req->outBind[i].buffer_length);
switch(fld->type)
{
case MYSQL_TYPE_TINY:
{
break;
}
case MYSQL_TYPE_SHORT:
{
char *t = xmprintf("%d", (int) *((int *) req->outBind[i].buffer));
flds->putstr(flds, req->rows->fieldNames[i], t);
free(t);
break;
}
case MYSQL_TYPE_INT24:
{
char *t = xmprintf("%d", (int) *((int *) req->outBind[i].buffer));
flds->putstr(flds, req->rows->fieldNames[i], t);
free(t);
break;
}
case MYSQL_TYPE_LONG:
{
if (NULL == req->outBind[i].buffer)
{
E("Field %d %s is NULL", i, fld->name);
ret++;
goto freeIt;
}
char *t = xmprintf("%d", (int) *((int *) (req->outBind[i].buffer)));
//d("Setting %i %s %s", i, fld->name, t);
flds->putstr(flds, req->rows->fieldNames[i], t);
free(t);
break;
}
case MYSQL_TYPE_LONGLONG:
{
char *t = xmprintf("%d", (int) *((int *) req->outBind[i].buffer));
flds->putstr(flds, req->rows->fieldNames[i], t);
free(t);
break;
}
case MYSQL_TYPE_FLOAT:
{
break;
}
case MYSQL_TYPE_DOUBLE:
{
break;
}
case MYSQL_TYPE_NEWDECIMAL:
{
break;
}
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP:
{
break;
}
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
{
break;
}
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
{
break;
}
case MYSQL_TYPE_BIT:
{
break;
}
case MYSQL_TYPE_NULL:
{
break;
}
}
}
else
D("Not setting data %s, coz it's NULL", fld->name);
}
req->rows->rows->addlast(req->rows->rows, flds, sizeof(qhashtbl_t));
free(flds);
}
}
freeIt:
if (prepare_meta_result)
mysql_free_result(prepare_meta_result);
if (mysql_stmt_free_result(req->prep))
{
E("Statement result freeing failed %d: %s\n", mysql_stmt_errno(req->prep), mysql_stmt_error(req->prep));
ret++;
}
end:
va_end(ap);
if (-1 == clock_gettime(CLOCK_REALTIME, &dbLast))
perror_msg("Unable to get the time.");
n = (dbLast.tv_sec * 1000000000.0) + dbLast.tv_nsec;
t("dbDoSomething(%s) took %lf seconds", req->sql, (n - t) / 1000000000.0);
return ret;
}
// Copy the SQL results into the request structure.
void dbPull(reqData *Rd, char *table, rowData *rows)
{
char *where;
qhashtbl_t *me = rows->rows->popfirst(rows->rows, NULL);
qhashtbl_obj_t obj;
if (NULL != me)
{
memset((void*)&obj, 0, sizeof(obj));
me->lock(me);
while(me->getnext(me, &obj, false) == true)
{
where = xmprintf("%s.%s", table, obj.name);
d("dbPull(Rd->database) %s = %s", where, (char *) obj.data);
Rd->database->putstr(Rd->database, where, (char *) obj.data);
free(where);
}
me->unlock(me);
me->free(me);
}
free(rows->fieldNames);
rows->rows->free(rows->rows);
free(rows);
}
my_ulonglong dbCount(char *table, char *where)
{
my_ulonglong ret = 0;
char *sql;
struct timespec now, then;
if (-1 == clock_gettime(CLOCK_REALTIME, &then))
perror_msg("Unable to get the time.");
if (where)
sql = xmprintf("SELECT Count(*) FROM %s WHERE %s", table, where);
else
sql = xmprintf("SELECT Count(*) FROM %s", table);
if (mysql_query(database, sql))
{
// E("MariaDB error %d - Query failed 1: %s", mysql_errno(database), mysql_error(database));
if (dbCheckError("Query failed 1", sql))
{
ret = dbCount(table, where);
free(sql);
return ret;
}
}
else
{
MYSQL_RES *result = mysql_store_result(database);
if (!result)
E("Couldn't get results set from %s\n: %s", sql, mysql_error(database));
else
{
MYSQL_ROW row = mysql_fetch_row(result);
if (!row)
E("MariaDB error %d - Couldn't get row from %s\n: %s", mysql_errno(database), sql, mysql_error(database));
else
ret = atoll(row[0]);
mysql_free_result(result);
}
}
if (-1 == clock_gettime(CLOCK_REALTIME, &now))
perror_msg("Unable to get the time.");
double n = (now.tv_sec * 1000000000.0) + now.tv_nsec;
double t = (then.tv_sec * 1000000000.0) + then.tv_nsec;
// t("dbCount(%s) took %lf seconds", sql, (n - t) / 1000000000.0);
free(sql);
return ret;
}
my_ulonglong dbCountJoin(char *table, char *select, char *join, char *where)
{
my_ulonglong ret = 0;
char *sql;
struct timespec now, then;
if (-1 == clock_gettime(CLOCK_REALTIME, &then))
perror_msg("Unable to get the time.");
if (NULL == select)
select = "*";
if (NULL == join)
join = "";
if (where)
sql = xmprintf("SELECT %s FROM %s %s WHERE %s", select, table, join, where);
else
sql = xmprintf("SELECT %s FROM %s", select, table, join);
if (mysql_query(database, sql))
{
// E("MariaDB error %d - Query failed 2: %s", mysql_errno(database), mysql_error(database));
if (dbCheckError("Query failed 2", sql))
{
ret = dbCountJoin(table, select, join, where);
free(sql);
return ret;
}
}
else
{
MYSQL_RES *result = mysql_store_result(database);
if (!result)
E("MariaDB error %d - Couldn't get results set from %s\n: %s", mysql_errno(database), sql, mysql_error(database));
else
ret = mysql_num_rows(result);
mysql_free_result(result);
}
if (-1 == clock_gettime(CLOCK_REALTIME, &now))
perror_msg("Unable to get the time.");
double n = (now.tv_sec * 1000000000.0) + now.tv_nsec;
double t = (then.tv_sec * 1000000000.0) + then.tv_nsec;
// t("dbCointJoin(%s) took %lf seconds", sql, (n - t) / 1000000000.0);
free(sql);
return ret;
}
void replaceStr(qhashtbl_t *ssi, char *key, char *value)
{
ssi->putstr(ssi, key, value);
}
void replaceLong(qhashtbl_t *ssi, char *key, my_ulonglong value)
{
char *tmp = xmprintf("%lu", value);
replaceStr(ssi, key, tmp);
free(tmp);
}
float timeDiff(struct timeval *now, struct timeval *then)
{
if (0 == gettimeofday(now, NULL))
{
struct timeval thisTime = { 0, 0 };
double result = 0.0;
thisTime.tv_sec = now->tv_sec;
thisTime.tv_usec = now->tv_usec;
if (thisTime.tv_usec < then->tv_usec)
{
thisTime.tv_sec--;
thisTime.tv_usec += 1000000;
}
thisTime.tv_usec -= then->tv_usec;
thisTime.tv_sec -= then->tv_sec;
result = ((double) thisTime.tv_usec) / ((double) 1000000.0);
result += thisTime.tv_sec;
return result;
}
return 0.0;
}
gridStats *getStats(MYSQL *db, gridStats *stats)
{
if (NULL == stats)
{
stats = xmalloc(sizeof(gridStats));
stats->next = 30;
gettimeofday(&(stats->last), NULL);
stats->stats = qhashtbl(0, 0);
stats->stats->putstr(stats->stats, "version", "SledjChisl FCGI Dev 0.1");
stats->stats->putstr(stats->stats, "grid", "my grid");
stats->stats->putstr(stats->stats, "uri", "http://localhost:8002/");
if (checkSimIsRunning("ROBUST"))
stats->stats->putstr(stats->stats, "gridOnline", "online");
else
stats->stats->putstr(stats->stats, "gridOnline", "offline");
}
else
{
static struct timeval thisTime;
if (stats->next > timeDiff(&thisTime, &(stats->last)))
return stats;
}
V("Getting fresh grid stats.");
if (checkSimIsRunning("ROBUST"))
replaceStr(stats->stats, "gridOnline", "online");
else
replaceStr(stats->stats, "gridOnline", "offline");
char *tmp;
my_ulonglong locIn = dbCount("Presence", "RegionID != '00000000-0000-0000-0000-000000000000'"); // Locals online but not HGing, and HGers in world.
my_ulonglong HGin = dbCount("Presence", "UserID NOT IN (SELECT PrincipalID FROM UserAccounts)"); // HGers in world.
// Collect stats about members.
replaceLong(stats->stats, "hgers", HGin);
if (locIn >= HGin) // Does OpenSim have too many ghosts?
replaceLong(stats->stats, "inworld", locIn - HGin);
else
replaceLong(stats->stats, "inworld", 0);
tmp = xmprintf("GridExternalName != '%s'", stats->stats->getstr(stats->stats, "uri", false));
replaceLong(stats->stats, "outworld", dbCount("hg_traveling_data", tmp));
free(tmp);
replaceLong(stats->stats, "members", dbCount("UserAccounts", NULL));
// Count local and HG visitors for the last 30 and 60 days.
locIn = dbCountJoin("GridUser", "GridUser.UserID", "INNER JOIN UserAccounts ON GridUser.UserID = UserAccounts.PrincipalID",
"Login > UNIX_TIMESTAMP(FROM_UNIXTIME(UNIX_TIMESTAMP(now()) - 2419200))");
HGin = dbCount("GridUser", "Login > UNIX_TIMESTAMP(FROM_UNIXTIME(UNIX_TIMESTAMP(now()) - 2419200))");
replaceLong(stats->stats, "locDay30", locIn);
replaceLong(stats->stats, "day30", HGin);
replaceLong(stats->stats, "HGday30", HGin - locIn);
locIn = dbCountJoin("GridUser", "GridUser.UserID", "INNER JOIN UserAccounts ON GridUser.UserID = UserAccounts.PrincipalID",
"Login > UNIX_TIMESTAMP(FROM_UNIXTIME(UNIX_TIMESTAMP(now()) - 4838400))");
HGin = dbCount("GridUser", "Login > UNIX_TIMESTAMP(FROM_UNIXTIME(UNIX_TIMESTAMP(now()) - 4838400))");
replaceLong(stats->stats, "locDay60", locIn);
replaceLong(stats->stats, "day60", HGin);
replaceLong(stats->stats, "HGday60", HGin - locIn);
// Collect stats about sims.
replaceLong(stats->stats, "sims", dbCount("regions", NULL));
replaceLong(stats->stats, "onlineSims", dbCount("regions", "sizeX != 0"));
replaceLong(stats->stats, "varRegions", dbCount("regions", "sizeX > 256 or sizeY > 256"));
replaceLong(stats->stats, "singleSims", dbCount("regions", "sizeX = 256 and sizeY = 256"));
replaceLong(stats->stats, "offlineSims", dbCount("regions", "sizeX = 0"));
// Calculate total size of all regions.
my_ulonglong simSize = 0;
static dbRequest *rgnSizes = NULL;
if (NULL == rgnSizes)
{
static char *szi[] = {NULL};
static char *szo[] = {"sizeX", "sizeY", NULL};
rgnSizes = xzalloc(sizeof(dbRequest));
rgnSizes->table = "regions";
rgnSizes->inParams = szi;
rgnSizes->outParams = szo;
rgnSizes->where = "sizeX != 0";
dbRequests->addfirst(dbRequests, &rgnSizes, sizeof(dbRequest *));
}
dbDoSomething(rgnSizes, FALSE); // LEAKY
rowData *rows = rgnSizes->rows;
qhashtbl_t *row;
while (NULL != (row = rows->rows->getat(rows->rows, 0, NULL, true)))
{
my_ulonglong x = 0, y = 0;
tmp = row->getstr(row, "sizeX", false);
if (NULL == tmp)
E("No regions.sizeX!");
else
x = atoll(tmp);
tmp = row->getstr(row, "sizeY", false);
if (NULL == tmp)
E("No regions.sizeY!");
else
y = atoll(tmp);
simSize += x * y;
row->free(row);
rows->rows->removefirst(rows->rows);
}
free(rows->fieldNames);
rows->rows->free(rows->rows);
free(rows);
tmp = xmprintf("%lu", simSize);
stats->stats->putstr(stats->stats, "simsSize", tmp);
free(tmp);
gettimeofday(&(stats->last), NULL);
return stats;
}
qhashtbl_t *toknize(char *text, char *delims)
{
qhashtbl_t *ret = qhashtbl(0, 0);
if (NULL == text)
return ret;
char *txt = xstrdup(text), *token, dlm = ' ', *key, *val = NULL;
int offset = 0;
while((token = qstrtok(txt, delims, &dlm, &offset)) != NULL)
{
if (delims[0] == dlm)
{
key = token;
val = &txt[offset];
}
else if (delims[1] == dlm)
{
ret->putstr(ret, qstrtrim_head(key), token);
d(" %s = %s", qstrtrim_head(key), val);
val = NULL;
}
}
if (NULL != val)
{
ret->putstr(ret, qstrtrim_head(key), val);
d(" %s = %s", qstrtrim_head(key), val);
}
free(txt);
return ret;
}
void santize(qhashtbl_t *tbl)
{
qhashtbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj));
tbl->lock(tbl);
while(tbl->getnext(tbl, &obj, false) == true)
{
char *n = obj.name, *o = (char *) obj.data;
qurl_decode(o);
tbl->putstr(tbl, n, o);
}
tbl->unlock(tbl);
}
void outize(qgrow_t *reply, qhashtbl_t *tbl, char *label)
{
reply->addstrf(reply, "%s:<br>\n<pre>\n", label);
qhashtbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj));
tbl->lock(tbl);
while(tbl->getnext(tbl, &obj, false) == true)
reply->addstrf(reply, " %s = %s\n", obj.name, (char *) obj.data);
tbl->unlock(tbl);
reply->addstr(reply, "</pre>\n");
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
enum cookieSame
{
CS_NOT,
CS_STRICT,
CS_LAX, // Apparently the default set by browsers these days.
CS_NONE
};
typedef struct _cookie cookie;
struct _cookie
{
char *value, *domain, *path;
// char *expires; // Use maxAge instead, it's far simpler to figure out.
int maxAge;
boolean secure, httpOnly;
enum cookieSame site;
};
void freeCookie(reqData *Rd, char *cki)
{
cookie *ck0 = Rd->Rcookies->get(Rd->Rcookies, cki, NULL, false);
if (NULL != ck0)
{
if (NULL != ck0->value)
free(ck0->value);
Rd->Rcookies->remove(Rd->Rcookies, cki);
}
}
cookie *setCookie(reqData *Rd, char *cki, char *value)
{
cookie *ret = xzalloc(sizeof(cookie));
char *cook = xstrdup(cki);
int l, i;
// TODO - would URL encoding do the trick?
// Validate this, as there is a limited set of characters allowed.
qstrreplace("tr", cook, "()<>@,;:\\\"/[]?={} \t", "_");
freeCookie(Rd, cook);
l = strlen(cook);
for (i = 0; i < l; i++)
{
if (iscntrl(cook[i]) != 0)
cook[i] = '_';
}
l = strlen(value);
if (0 != l)
ret->value = qurl_encode(value, l);
else
ret->value = xstrdup("");
ret->httpOnly = TRUE;
ret->site = CS_STRICT;
ret->secure = TRUE;
ret->path = getStrH(Rd->headers, "SCRIPT_NAME");
Rd->Rcookies->put(Rd->Rcookies, cook, ret, sizeof(cookie));
free(ret);
ret = Rd->Rcookies->get(Rd->Rcookies, cook, NULL, false);
free(cook);
return ret;
}
char *getCookie(qhashtbl_t *cookies, char *cki)
{
char *ret = NULL;
cookie *ck = (cookie *) cookies->get(cookies, cki, NULL, false);
if (NULL != ck)
ret = ck->value;
return ret;
}
void outizeCookie(qgrow_t *reply, qhashtbl_t *tbl, char *label)
{
reply->addstrf(reply, "%s:<br>\n<pre>\n", label);
qhashtbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj));
tbl->lock(tbl);
while(tbl->getnext(tbl, &obj, false) == true)
reply->addstrf(reply, " %s = %s\n", obj.name, ((cookie *) obj.data)->value);
tbl->unlock(tbl);
reply->addstr(reply, "</pre>\n");
}
void list2cookie(reqData *Rd, char *cki, qlist_t *list)
{
char *t0 = xstrdup("");
qlist_obj_t obj;
memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
list->lock(list);
while (list->getnext(list, &obj, false) == true)
{
char *t1 = xmprintf("%s\n%s", t0, (char *) obj.data);
free(t0);
t0 = t1;
}
list->unlock(list);
setCookie(Rd, cki, &t0[1]); // Skip the first empty one.
// TODO - should set a very short maxAge.
free(t0);
}
qlist_t *cookie2list(qhashtbl_t *cookies, char *cki)
{
qlist_t *ret = NULL;
cookie *ck = (cookie *) cookies->get(cookies, cki, NULL, false);
if (NULL != ck)
{
if (NULL != ck->value)
{
qurl_decode(ck->value);
ret = qstrtokenizer(ck->value, "\n");
free(ck->value);
}
// TODO - should send the "delete this cookie" thing to the browser.
cookies->remove(cookies, cki);
}
return ret;
}
enum fragmentType
{
FT_TEXT,
FT_PARAM,
FT_LUA
};
typedef struct _fragment fragment;
struct _fragment
{
enum fragmentType type;
int length;
char *text;
};
static void HTMLdebug(qgrow_t *reply)
{
reply->addstrf(reply,
" <p class='hoverItem'>\n"
" <div class='hoverWrapper0'>\n"
" <p>DEBUG</p>\n"
" <div id='hoverShow0'>\n"
" <h1>DEBUG log</h1>\n"
" <!--#echo var=\"DEBUG\" -->\n"
" </div>\n"
" </div>\n"
" </p>\n"
);
}
static void HTMLheader(qgrow_t *reply, char *title)
{
reply->addstrf(reply,
"<html>\n"
" <head>\n"
" <title>%s</title>\n"
" <meta charset=\"UTF-8\">\n"
" <link rel=\"shortcut icon\" href=\"/SledjHamrIconSmall.png\">\n"
, title);
reply->addstrf(reply, " <link type='text/css' rel='stylesheet' href='/SledjChisl.css' media='all' />\n");
if (DEBUG)
reply->addstrf(reply, " <link type='text/css' rel='stylesheet' href='/debugStyle.css' media='all' />\n");
reply->addstrf(reply,
" <style> \n"
" html, body {background-color: black; color: white; font-family: 'sans-serif'; margin: 0; padding: 0;}\n"
" a:link {color: aqua;}\n"
" a:visited {color: fuchsia;}\n"
" a:hover {color: blue;}\n"
" a:active {color: red;}\n"
" button {background-color: darkgreen; color: white; font-family: 'sans-serif';}\n"
" button:hover {color: blue;}\n"
" button:active {color: red;}\n"
" label {background-color:darkgreen; color: white; font-family: 'sans-serif'; font-size: 160%;}\n"
" input {background-color:darkblue; color: white; font-family: 'sans-serif'; font-size: 80%;}\n"
// What idiot thought aligning the label with the bottom of textareas was a good default?
" textarea {background-color:darkblue; color: white; font-family: 'sans-serif'; font-size: 80%; vertical-align: top;}\n"
" </style>\n"
" </head>\n"
" <body bgcolor='black' text='white' link='aqua' vlink='fuchsia' alink='red'>\n"
" <font face='sans-serif'>\n"
);
reply->addstrf(reply, " <div class='top-left'>\n");
if (DEBUG)
HTMLdebug(reply);
}
// TODO - maybe escape non printables as well?
char *HTMLentities[] =
{
"", "", "", "", "", "", "", "", "", // NUL SOH STX ETX EOT ENQ ACK BEL BS
"	", "
",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // VT FF CR SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US
" ", // Space
"!", """,
"#", "$",
"%", "&",
"'",
"(", ")",
"*",
"+",
",",
"-",
".",
"/",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
":", ";",
"<", "=", ">",
"?",
"@",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"[", "\", "]",
"^",
"_",
"`",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"{", "|", "}",
"~",
"", // DEL
" " // This is actually 160, not 128, but I hack around that.
};
static void HTMLescapeString(qgrow_t *reply, char *string)
{
size_t l = strlen(string);
char *t = xmalloc(l * 10 + 1);
int i, j = 0;
boolean space = FALSE;
for (i = 0; i < l; i++)
{
int s = string[i];
// Alternate long line of spaces with space and .
if (' ' == s)
{
if (space)
{
s = 128;
space = FALSE;
}
else
space = TRUE;
}
else
{
space = FALSE;
if (128 == s) // The real 128 character.
{
t[j++] = ' ';
continue;
}
}
if (128 >= s)
{
char *r = HTMLentities[s];
size_t m = strlen(r);
int k;
for (k = 0; k < m; k++)
t[j++] = r[k];
}
else
t[j++] = ' ';
}
t[j] = '\0';
reply->addstr(reply, t);
free(t);
}
static void HTMLtable(qgrow_t *reply, MYSQL *db, MYSQL_RES *result, char *caption, char *URL, char *id)
{
char *tbl = "";
char *address, *addrend, *t, *t0;
int count = 0, c = -1, i;
MYSQL_ROW row;
MYSQL_FIELD *fields = mysql_fetch_fields(result);
reply->addstrf(reply, "<table border=\"1\"><caption>%s</caption>\n", caption);
if (!fields)
E("Failed fetching fields: %s", mysql_error(db));
while ((row = mysql_fetch_row(result)))
{
reply->addstr(reply, "<tr>");
address = xmprintf("");
addrend = "";
if (-1 == c)
c = mysql_num_fields(result);
if (0 == count)
{
for (i = 0; i < c; i++)
{
char *s = fields[i].name;
reply->addstrf(reply, "<th>%s</th>", s);
}
reply->addstr(reply, "</tr>\n<tr>");
}
if (NULL != URL)
{
free(address);
address = xmprintf("<a href=\"%s", URL);
addrend = "</a>";
}
for (i = 0; i < c; i++)
{
char *s = fields[i].name;
t0 = row[i];
if (NULL == t0)
E("No field %s!", s);
else
{
if ((NULL != id) && (strcmp(s, id) == 0))
reply->addstrf(reply, "<td>%s&%s=%s\">%s%s</td>", address, id, t0, t0, addrend);
else
reply->addstrf(reply, "<td>%s</td>", t0);
}
}
reply->addstr(reply, "</tr>\n");
free(address);
count++;
}
reply->addstr(reply, "</table>");
mysql_free_result(result);
}
static void HTMLhidden(qgrow_t *reply, char *name, char *val)
{
if ((NULL != val) && ("" != val))
{
reply->addstrf(reply, " <input type=\"hidden\" name=\"%s\" value=\"", name);
HTMLescapeString(reply, val);
reply->addstr(reply, "\">\n");
}
}
static void HTMLform(qgrow_t *reply, char *action, char *token)
{
reply->addstrf(reply, " <form action=\"%s\" method=\"POST\">\n", action);
if ((NULL != token) && ('\0' != token[0]))
HTMLhidden(reply, "munchie", token);
}
static void HTMLformEnd(qgrow_t *reply)
{
reply->addstrf(reply, " </form>\n");
}
static void HTMLcheckBox(qgrow_t *reply, char *name, char *title, boolean checked, boolean required)
{
// HTML is an absolute fucking horror. This is so that we got an off sent to us if the checkbox is off, otherwise we get nothing.
HTMLhidden(reply, name, "off");
reply->addstrf(reply, " <p>");
reply->addstrf(reply, "<label><input type=\"checkbox\" name=\"%s\"", name);
if (checked)
reply->addstrf(reply, " checked", name);
// if (required)
// reply->addstr(reply, " required");
reply->addstrf(reply, "> %s </label>", title);
// reply->addstrf(reply, "> %s ⛝ □ 🞐 🞎 🞎 ☐ ▣️ ◉ ○ </label>", title);
reply->addstrf(reply, "</p>\n");
}
static void HTMLtextArea(qgrow_t *reply, char *name, char *title, int rows, int cols, int min, int max, char *holder, char *comp, char *spell, char *wrap, char *val, boolean required, boolean readOnly)
{
reply->addstrf(reply, " <p><label>%s : <textarea name=\"%s\"", title, name);
if (0 < rows)
reply->addstrf(reply, " rows=\"%d\"", rows);
if (0 < cols)
reply->addstrf(reply, " cols=\"%d\"", cols);
if (0 < min)
reply->addstrf(reply, " minlength=\"%d\"", min);
if (0 < max)
reply->addstrf(reply, " maxlength=\"%d\"", max);
if (required)
reply->addstr(reply, " required");
if (readOnly)
reply->addstr(reply, " readonly");
if ("" != holder)
reply->addstrf(reply, " placeholder=\"%s\"", holder);
if ("" != comp)
reply->addstrf(reply, " autocomplete=\"%s\"", comp);
if ("" != spell)
reply->addstrf(reply, " spellcheck=\"%s\"", spell);
if ("" != wrap)
reply->addstrf(reply, " wrap=\"%s\"", wrap);
if ((NULL != val) && ("" != val))
{
reply->addstr(reply, ">");
HTMLescapeString(reply, val);
reply->addstr(reply, "</textarea></label></p>\n");
}
else
reply->addstrf(reply, "></textarea></label></p>\n");
}
static void HTMLtext(qgrow_t *reply, char *type, char *title, char *name, char *val, int size, int max, boolean required)
{
reply->addstrf(reply, " <p><label>%s : <input type=\"%s\" name=\"%s\"", title, type, name);
if ((NULL != val) && ("" != val))
{
reply->addstr(reply, " value=\"");
HTMLescapeString(reply, val);
reply->addstr(reply, "\"");
}
if (0 < size)
reply->addstrf(reply, " size=\"%d\"", size);
if (0 < max)
reply->addstrf(reply, " maxlength=\"%d\"", max);
if (required)
reply->addstr(reply, " required");
reply->addstr(reply, "></label></p>\n");
}
static void HTMLselect(qgrow_t *reply, char *title, char *name)
{
if (NULL == title)
reply->addstrf(reply, " <p><select name=\"%s\">", name);
else
reply->addstrf(reply, " <p><label>%s : \n <select name=\"%s\">\n", title, name);
}
static void HTMLselectEnd(qgrow_t *reply)
{
reply->addstr(reply, " </select></label></p>\n \n");
}
static void HTMLselectEndNo(qgrow_t *reply)
{
reply->addstr(reply, " </select></p>");
}
static void HTMLoption(qgrow_t *reply, char *title, boolean selected)
{
char *sel = "";
if (selected)
sel = " selected";
reply->addstrf(reply, " <option value=\"%s\"%s>%s</option>\n", title, sel, title);
}
static void HTMLbutton(qgrow_t *reply, char *name, char *title)
{
reply->addstrf(reply, " <button type=\"submit\" name=\"doit\" value=\"%s\">%s</button>\n", name, title);
}
static void HTMLlist(qgrow_t *reply, char *title, qlist_t *list)
{
qlist_obj_t obj;
reply->addstrf(reply, "<ul>%s\n", title);
memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
list->lock(list);
while (list->getnext(list, &obj, false) == true)
{
reply->addstr(reply, "<li>");
HTMLescapeString(reply, (char *) obj.data);
reply->addstr(reply, "</li>\n");
}
list->unlock(list);
reply->addstr(reply, "</ul>\n");
}
static int count = 0;
void HTMLfill(reqData *Rd, enum fragmentType type, char *text, int length)
{
char *tmp;
switch (type)
{
case FT_TEXT:
{
if (length)
Rd->reply->add(Rd->reply, (void *) text, length * sizeof(char));
break;
}
case FT_PARAM:
{
if (strcmp("DEBUG", text) == 0)
{
if (DEBUG)
{
Rd->reply->addstrf(Rd->reply, "<h1>FastCGI SledjChisl</h1>\n"
"<p>Request number %d, Process ID: %d</p>\n", count++, getpid());
Rd->reply->addstrf(Rd->reply, "<p>libfcgi version: %s</p>\n", FCGI_VERSION);
Rd->reply->addstrf(Rd->reply, "<p>Lua version: %s</p>\n", LUA_RELEASE);
Rd->reply->addstrf(Rd->reply, "<p>LuaJIT version: %s</p>\n", LUAJIT_VERSION);
Rd->reply->addstrf(Rd->reply, "<p>MySQL client version: %s</p>\n", mysql_get_client_info());
outize(Rd->reply, Rd->headers, "Environment");
outize(Rd->reply, Rd->cookies, "Cookies");
outize(Rd->reply, Rd->queries, "Query");
outize(Rd->reply, Rd->body, "POST body");
outize(Rd->reply, Rd->stuff, "Stuff");
showSesh(Rd->reply, &Rd->shs);
if (Rd->lnk) showSesh(Rd->reply, Rd->lnk);
outize(Rd->reply, Rd->database, "Database");
outizeCookie(Rd->reply, Rd->Rcookies, "Reply Cookies");
outize(Rd->reply, Rd->Rheaders, "Reply HEADERS");
}
}
else if (strcmp("URL", text) == 0)
Rd->reply->addstrf(Rd->reply, "%s://%s%s", Rd->Scheme, Rd->Host, Rd->Script);
else
{
if ((tmp = Rd->stats->stats->getstr(Rd->stats->stats, text, false)) != NULL)
Rd->reply->addstr(Rd->reply, tmp);
else
Rd->reply->addstrf(Rd->reply, "<b>%s</b>", text);
}
break;
}
case FT_LUA:
break;
}
}
static void HTMLfooter(qgrow_t *reply)
{
reply->addstrf(reply, " </div>\n");
reply->addstr(reply,
" <div class='top-right'>\n"
" <h1>Experimental account manager</h1>\n"
" <p>This account manager system is currently experimental, and under heavy development. "
" Which means it's not all written yet, and things may break.</p>\n"
" <p>To create an account, choose a name and password, type them in, click the 'create account' button.</p>"
" <p>On the next page, fill in all your details, then click on the 'confirm' button.</p>"
" <p>We follow the usual web site registration process, which sends a validation email, with a link to click. "
" When you get that email, click on the link, or copy it into a web browser.</p>"
" <p>You will then be logged off. Now you have to wait for an admin to approve your new account. "
" They should check with the person you listed as vouching for you first. They will tell you after they approve your account.</p>"
" <p>Missing bits that are still being written - editing accounts, listing accounts, deleting accounts.</p>\n"
" </div>\n");
// reply->addstr(reply, " <div class='centre'>\n </div>\n");
reply->addstr(reply,
// " <div class='bottom-left'>\n"
// " </div>\n"
" <div class='bottom-right'>\n"
" <iframe src='stats.html' style='border:none;height:100%;width:100%;'></iframe>\n"
" </div>\n"
" </font>\n"
"</body>\n</html>\n");
}
fragment *newFragment(enum fragmentType type, char *text, int len)
{
fragment *frg = xmalloc(sizeof(fragment));
frg->type = type;
frg->length = len;
frg->text = xmalloc(len + 1);
memcpy(frg->text, text, len);
frg->text[len] = '\0';
return frg;
}
qlist_t *fragize(char *mm, size_t length)
{
qlist_t *fragments = qlist(QLIST_THREADSAFE);
fragment *frg0, *frg1;
char *h;
int i, j = 0, k = 0, l, m;
// Scan for server side includes style markings.
for (i = 0; i < length; i++)
{
if (i + 5 < length)
{
if (('<' == mm[i]) && ('!' == mm[i + 1]) && ('-' == mm[i + 2]) && ('-' == mm[i + 3]) && ('#' == mm[i + 4])) // '<!--#'
{
m = i;
i += 5;
if (i < length)
{
if (('e' == mm[i]) && ('c' == mm[i + 1]) && ('h' == mm[i + 2]) && ('o' == mm[i + 3]) && (' ' == mm[i + 4])) // 'echo '
{
i += 5;
if (i + 5 < length)
{
if (('v' == mm[i]) && ('a' == mm[i + 1]) && ('r' == mm[i + 2]) && ('=' == mm[i + 3]) && ('"' == mm[i + 4])) // 'var="'
{
i += 5;
for (j = i; j < length; j++)
{
if ('"' == mm[j]) // '"'
{
frg1 = newFragment(FT_PARAM, &mm[i], j - i);
i = j + 1;
if (i + 4 < length)
{
if ((' ' == mm[i]) && ('-' == mm[i + 1]) && ('-' == mm[i + 2]) && ('>' == mm[i + 3])) // ' -->'
i += 4;
}
frg0 = newFragment(FT_TEXT, &mm[k], m - k);
fragments->addlast(fragments, frg0, sizeof(fragment));
fragments->addlast(fragments, frg1, sizeof(fragment));
free(frg0);
free(frg1);
k = i;
break;
}
}
}
}
}
}
}
}
}
frg0 = newFragment(FT_TEXT, &mm[k], length - k);
fragments->addlast(fragments, frg0, sizeof(*frg0));
free(frg0);
return fragments;
}
void unfragize(qlist_t *fragments, reqData *Rd, boolean fre)
{
qlist_obj_t lobj;
memset((void *) &lobj, 0, sizeof(lobj));
fragments->lock(fragments);
while (fragments->getnext(fragments, &lobj, false) == true)
{
fragment *frg = (fragment *) lobj.data;
if (NULL == frg->text)
{
E("NULL fragment!");
continue;
}
if (NULL != Rd)
HTMLfill(Rd, frg->type, frg->text, frg->length);
if (fre)
free(frg->text);
}
fragments->unlock(fragments);
if (fre)
fragments->free(fragments);
}
HTMLfile *checkHTMLcache(char *file)
{
if (NULL == HTMLfileCache)
HTMLfileCache = qhashtbl(0, 0);
HTMLfile *ret = (HTMLfile *) HTMLfileCache->get(HTMLfileCache, file, NULL, true);
int fd = open(file, O_RDONLY);
size_t length = 0;
if (-1 == fd)
{
HTMLfileCache->remove(HTMLfileCache, file);
free(ret);
ret = NULL;
}
else
{
struct stat sb;
if (fstat(fd, &sb) == -1)
{
HTMLfileCache->remove(HTMLfileCache, file);
free(ret);
ret = NULL;
E("Failed to stat %s", file);
}
else
{
if ((NULL != ret) && (ret->last.tv_sec < sb.st_mtim.tv_sec))
{
HTMLfileCache->remove(HTMLfileCache, file);
free(ret);
ret = NULL;
}
if (NULL == ret)
{
char *mm = MAP_FAILED;
ret = xmalloc(sizeof(HTMLfile));
length = sb.st_size;
ret->last.tv_sec = sb.st_mtim.tv_sec;
ret->last.tv_nsec = sb.st_mtim.tv_nsec;
D("Loading web template %s, which is %d bytes long.", file, length);
mm = mmap(NULL, length, PROT_READ, MAP_SHARED | MAP_POPULATE, fd, 0);
if (mm == MAP_FAILED)
{
HTMLfileCache->remove(HTMLfileCache, file);
free(ret);
ret = NULL;
E("Failed to mmap %s", file);
}
else
{
ret->fragments = fragize(mm, length);
if (-1 == munmap(mm, length))
FCGI_fprintf(FCGI_stderr, "Failed to munmap %s\n", file);
HTMLfileCache->put(HTMLfileCache, file, ret, sizeof(*ret));
}
}
close(fd);
}
}
return ret;
}
/* TODO -
On new user / password reset.
. Both should have all the same security concerns as the login page, they are basically logins.
. Codes should be "very long", "(for example, 16 case-sensitive alphanumeric characters)"
. "confirm" button hit on "accountCreationPage" or "resetPasswordPage"
. generate a new token, keep it around for idleTimeOut (or at least 24 hours), call it .linky instead of .lua
. hash the linky for the file name, for the same reason we hash the hashish with pepper for the leaf-node.
. Include user level field, new users get -200.
. Store the linky itself around somewhere we can find it quickly for logged in users.
. store it in the regenerated session
. Scratch that, we should never store the raw linky, see above about hashing the linky.
. The linky is just like the session token, create it in exactly the same way.
. Linky is base64() of the binary, so it's short enough to be a file name, and not too long for the URL.
. But we only get to send one of them as a linky URL, no backup cookies / body / headers.
. Sooo, need to separate the session stuff out of Rd->stuff.
. Use two separate qhashtbl's, Rd->session and Rd->linky.
For new user
. create their /opt/opensim_SC/var/lib/users/UUID.lua account record, and symlink firstName_lastName.lua to it.
. They can log on,
but all they can do is edit their email to send a new validation code, and enter the validation code.
They can reset their password.
. Warn them on login and any page refresh that there is an outstanding validation awaiting them.
For reset password
. Let them do things as normal, in case this was just someone being mean to them, coz their email addy might be public.
. Including the usual logging out and in again with their old password.
. Warn them on login and any page refresh that there is an outstanding password reset awaiting them.
. email linky, which is some or all of the token result bits strung together, BASE64 encode the result.
. regenerate the usual token
. user clicks on the linky (or just enters the linky in a field)
. validate the linky token.
compare the level field to the linky type in the linky URL, new users -200 would be "../validateUser/.." and not "../resetPassword/.."
. delete the linky token
. Particularly important for the forgotten password email, since now that token is in the wild, and is used to reset a password.
Which begs the question, other than being able to recieve the email, how do we tell it's them?
Security questions suck, too easily guessed.
Ask their DoB. Still sucky, coz "hey it's my birthday today" is way too leaky.
This is what Multi Factor Autentication is good for, and that's on the TODO list.
Also, admins should have a harder time doing password resets.
Must be approved by another admin?
Must log onto the server via other means to twiddle something there?
For password reset page
Ask their DoB to help confirm it's them.
validate the DoB, delete tokens and back to the login page if they get it wrong
Should warn people on the accountCreationPage that DoB might be used this way.
ask them for the new password, twice
Create a new passwordSalt and passwordHash, store them in the auth table.
. For validate new user page
. tell them they have validated
. create their OpenSim account UserAccounts.UserTitle and auth tables, not GridUser table
. create their GridUser record.
. update their UserAccounts.Userlevel and UserAccounts.UserTitle
. send them to the login page.
. regenerate the usual token
? let user stay logged on?
Check best practices for this.
Check password strength.
https://stackoverflow.com/questions/549/the-definitive-guide-to-form-based-website-authentication?rq=1
Has some pointers to resources in the top answers "PART V: Checking Password Strength" section.
"PART VI: Much More - Or: Preventing Rapid-Fire Login Attempts" and "PART VII: Distributed Brute Force Attacks" is also good for -
Login attempt throttling.
Deal with dictionary attacks by slowing down access on password failures etc.
Deal with editing yourself.
Deal with editing others, but only as god.
Regularly delete old session files and ancient newbies.
Salts should be "lengthy" (128 bytes suggested in 2007) and random. Should be per user to. Or use a per user and a global one, and store the global one very securely.
And store hash(salt+password).
On the other hand, the OpenSim / SL password hashing function may be set in concrete in all the viewers. I'll have to find out.
So far I have discovered -
On login server side if the password doesn't start with $1$, then password = "$1$" + Util.Md5Hash(passwd);
remove the "$1$ bit
string hashed = Util.Md5Hash(password + ":" + data.Data["passwordSalt"].ToString());
if (data.Data["passwordHash"].ToString() == hashed)
passwordHash is char(32), and as implied above, doesn't include the $1$ bit. passwordSalt is also char(32)
Cool VL and Impy at least sends the $1$ md5 hashed version over the wire.
Modern viewers obfuscate the details buried deep in C++ OOP crap.
Sent via XMLRPC
MD5 is considered broken since 2013, possibly longer.
Otherwise use a slow hashing function. bcrypt? scrypt? Argon2? PBKDF2?
https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords
Should include a code in the result that tells us which algorithm was used, so we can change the algorithm at a later date. /etc/passwd does this.
Which is what the $1$ bit currently used between server and client is sorta for.
+ Would be good to have one more level of this Rd->database stuff, so we know the type of the thing.
While qhashtbl has API for putting strings, ints, and memory, it has none for finding out what type a stored thing is.
Once I have a structure, I add things like "level needed to edit it", "OpenSim db structure to Lua file mapping", and other fanciness.
Would also help with the timestamp being stored for the session, it prints out binary gunk in the DEBUG <div>.
Starting to get into object oriented territory here. B-)
I'll have to do it eventually anyway.
object->tostring(object), and replace the big switch() statements in the existing db code with small functions.
That's why the qLibc stuff has that format, coz C doesn't understand the concept of passing "this" as the first argument.
https://stackoverflow.com/questions/351733/how-would-one-write-object-oriented-code-in-c
https://stackoverflow.com/questions/415452/object-orientation-in-c
http://ooc-coding.sourceforge.net/
https://owasp.org/www-project-cheat-sheets/cheatsheets/Input_Validation_Cheat_Sheet.html#Email_Address_Validation
https://cheatsheetseries.owasp.org/
https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
https://owasp.org/www-project-cheat-sheets/cheatsheets/Authentication_Cheat_Sheet.html
https://softwareengineering.stackexchange.com/questions/46716/what-technical-details-should-a-programmer-of-a-web-application-consider-before
https://wiki.owasp.org/index.php/OWASP_Guide_Project
https://stackoverflow.com/questions/549/the-definitive-guide-to-form-based-website-authentication?rq=1
https://owasp.org/www-community/xss-filter-evasion-cheatsheet
A list of example XSS things to try.
*/
/* Four choices for the token - (https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
https://en.wikipedia.org/wiki/Cross-site_request_forgery
Has some more info.
Large random value generated by a secure method (getrandom(2)).
Keep it secret, put it in hidden fields, or custom HTTP header (requires JavaScript but more secure than hidden fields).
NOT cookies or GET. Don't log it.
Cryptographically sign a session ID and timestamp.
Timestamp is for session timeouts.
Keep it secret, put it in hidden fields, or custom HTTP header (requires JavaScript but more secure than hidden fields).
Needs a secret key server side.
A strong HMAC (SHA-256 or better) of a session ID and timestamp.
The above document seems to imply that a key is used for this, the openssl EVP functions don't mention any way of supplying this key.
https://en.wikipedia.org/wiki/HMAC says there is a key as well.
https://www.openssl.org/docs/man1.1.0/man3/HMAC.html HAH! They can have keys. OpenSSL's docs suck.
Token = HMAC(sessionID+timestamp)+timestamp (Yes, timestamp is used twice).
Keep it secret, put it in hidden fields, or custom HTTP header (requires JavaScript but more secure than hidden fields).
Needs a secret key server side.
Double cookie
Large random value generated by a secure method set as a cookie and hidden field. Check they match.
Optional - encrypt / salted hash it in another cookie / hidden field.
+ Also a resin (BASE64 session key in the query string).
Not such a good idea to have something in the query, coz that screws with bookmarks.
https://security.stackexchange.com/questions/59470/double-submit-cookies-vulnerabilities
Though so far all the pages I find saying this don't say flat out say "use headers instead", though they do say "use HSTS".
https://security.stackexchange.com/questions/220797/is-the-double-submit-cookie-pattern-still-effective
+ Includes a work around that I might already be doing.
TODO - think it through, is it really secure against session hijacking?
TODO - document why we redirect POST to GET, coz it's a pain in the arse, and we have to do things twice.
SOOOOO - use double cookie + hidden field.
No headers, coz I need JavaScript to do that.
No hidden field when redirecting post POST to GET, coz GET doesn't get those.
pepper = long pass phrase or some such stored in .sledjChisl.conf.lua, which has to be protected dvs1/opensimsc/0640 as well as the database credentials.
salt = large random value generated by a secure method (getrandom(2)).
seshID = large random value generated by a secure method (getrandom(2)).
timeStamp = mtime of the leaf-node file, set to current time when we are creating the token.
sesh = seshID + timeStamp
munchie = HMAC(sesh) + timeStamp The token hidden field
toke_n_munchie = HMAC(UUID + munchie) The token cookie
hashish = HMACkey(toke_n_munchie, salt) Salted token cookie & linky query
? resin = BASE64(hashish) Base64 token cookie
leaf-node = HMACkey(hashish, pepper) Stored token file name
Leaf-node.lua (mtime is timeStamp)
IP, UUID, salt, seshID, user name, passwordSalt, passwordHash (last two for OpenSim password protocol)
The test - (validateSesh() below)
we get hashish and toke_n_munchie
HMACkey(hashish + pepper) -> leaf-node
read leaf-node.lua -> IP, UUID, salt, seshID
get it's mtime -> timeStamp
seshID + timeStamp -> sesh
HMAC(sesh) + timeStamp -> munchie
if we got munchie in the hidden field, compare it
toke_n_munchie == HMAC(UUID + munchie)
For linky it'll be -
HMAC(UUID + munchie) -> toke_n_munchie
hashish == HMACkey(toke_n_munchie + salt)
+ If it's too old according to mtime, delete it and logout.
I should make it easy to change the HMAC() function. Less important for these short lived sessions, more important for the linky URLs, most important for stored password hashes.
Same for the pepper.
The required JavaScript might be like https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#xmlhttprequest--native-javascript-
NOTE - they somehow fucked up that anchor tag.
NOTE - storing a pepper on the same RAID array as everything else will be a problem when it comes time to replace one of the disks.
It might have failed badly enough that you can't wipe it, but an attacker can dumpster dive it, replace the broken bit (firmware board), and might get lucky.
Also is a problem with SSD and rust storing good data on bad sectors in the spare sector pool, wear levelling, etc.
https://stackoverflow.com/questions/16891729/best-practices-salting-peppering-passwords
*/
qlisttbl_t *accountLevels = NULL;
// The ancient, insecure since 2011, Second Life / OpenSim password hashing algorithm.
char *newSLOSsalt(reqData *Rd)
{
char *salt = NULL;
unsigned char *md5hash = xzalloc(17);
char uuid[37];
uuid_t binuuid;
uuid_generate_random(binuuid);
uuid_unparse_lower(binuuid, uuid);
if (!qhashmd5((void *) uuid, strlen(uuid), md5hash))
bitch(Rd, "Internal error.", "newSLOSsalt() - qhashmd5(new uuid) failed.");
else
salt = qhex_encode(md5hash, 16);
free(md5hash);
return salt;
}
char *checkSLOSpassword(reqData *Rd, char *salt, char *password, char *passwordHash, char *fail)
{
char *ret = NULL;
int rt = 0;
unsigned char *md5hash = xzalloc(17);
char *hash = NULL, *passHash = NULL;
t("checkSLOSpassword(%s, %s, %s, ", password, salt, passwordHash, fail);
// Calculate passHash.
if (!qhashmd5((void *) password, strlen(password), md5hash))
{
bitch(Rd, "Internal error.", "checkSLOSpassword() - qhashmd5(password) failed.");
rt++;
}
else
{
passHash = qhex_encode(md5hash, 16);
hash = xmprintf("%s:%s", passHash, salt);
if (!qhashmd5((void *) hash, strlen(hash), md5hash))
{
bitch(Rd, "Internal error.", "checkSLOSpassword() - qhashmd5(password:salt) failed.");
rt++;
}
else
{
ret = qhex_encode(md5hash, 16);
}
free(hash);
free(passHash);
}
// If one was passed in, compare it.
if ((NULL != ret) && (NULL != passwordHash) && (strcmp(ret, passwordHash) != 0))
{
bitch(Rd, fail, "Password doesn't match passwordHash");
E(" %s %s - %s != %s", password, salt, ret, passwordHash);
rt++;
free(ret);
ret = NULL;
}
free(md5hash);
return ret;
}
char *checkLinky(reqData *Rd)
{
// TODO - should be from Rd.shs->linky-hashish
char *ret = xstrdup(""), *t0 = getStrH(Rd->stuff, "linky-hashish");
if ('\0' != t0[0])
{
char *t1 = qurl_encode(t0, strlen(t0));
free(ret);
ret = xmprintf("<p><font color='red'><b>You have an email waiting with a validation link in it, please check your email. "
"THE FOLLOWING IS REPEATED, COZ PEOPLE JUST DON'T FOLLOW DIRECTIONS!"
"It will be from %s@%s, and it might be in your spam folder, coz these sorts of emails sometimes end up there. "
"You should add that email address to your contacts, or otherwise let it through your spam filter. "
"It will be from %s@%s, and it might be in your spam folder, coz these sorts of emails sometimes end up there. "
"You should add that email address to your contacts, or otherwise let it through your spam filter. "
"It will be from %s@%s, and it might be in your spam folder, coz these sorts of emails sometimes end up there. "
"You should add that email address to your contacts, or otherwise let it through your spam filter. "
"It will be from %s@%s, and it might be in your spam folder, coz these sorts of emails sometimes end up there. "
"You should add that email address to your contacts, or otherwise let it through your spam filter. "
"If your email client wont let you click the validation link, just copy and paste it into your web browser. "
"If your email client wont let you click the validation link, just copy and paste it into your web browser. "
"If your email client wont let you click the validation link, just copy and paste it into your web browser. "
"If your email client wont let you click the validation link, just copy and paste it into your web browser. "
// "<a href='https://%s%s?hashish=%s'>%s</a>"
"</b></font></p>\n",
"grid_no_reply", Rd->Host,
Rd->Host, Rd->RUri
// ,t1, t0
);
free(t1);
}
return ret;
}
static void freeSesh(reqData *Rd, boolean linky, boolean wipe)
{
char *file = NULL;
sesh *shs = &Rd->shs;
T("free sesh %s %s", linky ? "linky" : "session", wipe ? "wipe" : "delete");
if (linky)
{
shs = Rd->lnk;
file = xmprintf("%s/sessions/%s.linky", scCache, shs->leaf);
}
else
file = xmprintf("%s/sessions/%s.lua", scCache, shs->leaf);
if (wipe)
I("Wiping session %s.", file);
else
I("Deleting session %s.", file);
if ('\0' != shs->leaf[0])
{
if (unlink(file))
perror_msg("Unable to delete %s", file);
}
Rd->body-> remove(Rd->body, "munchie");
freeCookie(Rd, "toke_n_munchie");
freeCookie(Rd, "hashish");
cookie *ck = setCookie(Rd, "toke_n_munchie", "");
cookie *ckh = setCookie(Rd, "hashish", "");
ck->maxAge = -1; // Should expire immediately.
ckh->maxAge = -1; // Should expire immediately.
qhashtbl_obj_t obj;
if (wipe)
{
memset((void*)&obj, 0, sizeof(obj));
Rd->database->lock(Rd->database);
while(Rd->database->getnext(Rd->database, &obj, false) == true)
Rd->database->remove(Rd->database, obj.name);
Rd->database->unlock(Rd->database);
if (NULL != shs->name) free(shs->name);
shs->name = NULL;
if (NULL != shs->UUID) free(shs->UUID);
shs->UUID = NULL;
shs->level = -256;
// TODO - should I wipe the rest of Rd->shs as well?
Rd->stuff->remove(Rd->stuff, "name");
Rd->stuff->remove(Rd->stuff, "firstName");
Rd->stuff->remove(Rd->stuff, "lastName");
Rd->stuff->remove(Rd->stuff, "email");
Rd->stuff->remove(Rd->stuff, "passwordSalt");
Rd->stuff->remove(Rd->stuff, "passwordHash");
Rd->stuff->remove(Rd->stuff, "passHash");
Rd->stuff->remove(Rd->stuff, "passSalt");
Rd->stuff->remove(Rd->stuff, "linky-hashish");
}
if (shs->isLinky)
{
free(Rd->lnk);
Rd->lnk = NULL;
}
else
{
shs->leaf[0] = '\0';
}
free(file);
}
static void setToken_n_munchie(reqData *Rd, boolean linky)
{
sesh *shs = &Rd->shs;
char *file;
if (linky)
{
shs = Rd->lnk;
file = xmprintf("%s/sessions/%s.linky", scCache, shs->leaf);
}
else
{
file = xmprintf("%s/sessions/%s.lua", scCache, shs->leaf);
}
struct stat st;
int s = stat(file, &st);
if (!linky)
{
setCookie(Rd, "toke_n_munchie", shs->toke_n_munchie);
setCookie(Rd, "hashish", shs->hashish);
}
char *tnm0 = xmprintf( "toke_n_munchie = \n"
"{\n"
" ['IP']='%s',\n"
" ['salt']='%s',\n"
" ['seshID']='%s',\n",
getStrH(Rd->headers, "REMOTE_ADDR"),
shs->salt,
shs->seshID
);
char *tnm1 = xmprintf(" ['name']='%s',\n ['level']='%d',\n", shs->name, (int) shs->level);
char *tnm2 = xmprintf(" ['UUID']='%s',\n", shs->UUID);
char *tnm3 = xmprintf(" ['passHash']='%s',\n", getStrH(Rd->stuff, "passHash"));
char *tnm4 = xmprintf(" ['passSalt']='%s',\n", getStrH(Rd->stuff, "passSalt"));
char *tnm9 = xmprintf("}\n"
"return toke_n_munchie\n");
int fd = notstdio(xcreate_stdio(file, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR));
size_t l = strlen(tnm0);
if (s)
I("Creating session %s.", file);
else
C("Updating session %s.", file); // I don't think updates can occur now.
t("Write shs %s", tnm0);
if (l != writeall(fd, tnm0, l))
{
perror_msg("Writing %s", file);
freeSesh(Rd, linky, TRUE);
}
if (NULL != shs->name)
{
t("Write shs %s", tnm1);
l = strlen(tnm1);
if (l != writeall(fd, tnm1, l))
{
perror_msg("Writing %s", file);
freeSesh(Rd, linky, TRUE);
}
}
if (NULL != shs->UUID)
{
t("Write shs %s", tnm2);
l = strlen(tnm2);
if (l != writeall(fd, tnm2, l))
{
perror_msg("Writing %s", file);
freeSesh(Rd, linky, TRUE);
}
}
if ('\0' != getStrH(Rd->stuff, "passHash")[0])
{
t("Write shs %s", tnm3);
l = strlen(tnm3);
if (l != writeall(fd, tnm3, l))
{
perror_msg("Writing %s", file);
freeSesh(Rd, linky, TRUE);
}
}
if ('\0' != getStrH(Rd->stuff, "passSalt")[0])
{
t("Write shs %s", tnm4);
l = strlen(tnm4);
if (l != writeall(fd, tnm4, l))
{
perror_msg("Writing %s", file);
freeSesh(Rd, linky, TRUE);
}
}
l = strlen(tnm9);
if (l != writeall(fd, tnm9, l))
{
perror_msg("Writing %s", file);
freeSesh(Rd, linky, TRUE);
}
// Set the mtime on the file.
futimens(fd, shs->timeStamp);
xclose(fd);
free(tnm9);
free(tnm4);
free(tnm3);
free(tnm2);
free(tnm1);
free(tnm0);
free(file);
if (linky)
{
// TODO - Later use libcurl.
char *first = getStrH(Rd->stuff, "firstName"), *last = getStrH(Rd->stuff, "lastName");
// TODO - should be from Rd.shs->linky-hashish
char *t0 = xstrdup(Rd->lnk->hashish), *content, *command;
if ('\0' != t0[0])
{
size_t sz = qhex_decode(t0);
char *t1 = qB64_encode(t0, sz);
content = xmprintf(
"From: grid_no_reply@%s\n"
"Relpy-to: grid_no_reply@%s\n"
"Return-Path: bounce_email@%s\n"
"To: %s\n"
"Subject: Validate your new account on %s\n"
"\n"
"This is an automated validation email sent from %s.\n"
"\n"
"Dear %s %s,\n"
"\n"
"Some one has created the account '%s %s' on \n"
"https://%s%s, and hopefully it was you.\n"
"If it wasn't you, you can ignore this email.\n"
"\n"
"Please go to this web link to validate your new account -\n"
"https://%s%s?hashish=%s\n"
"THE FOLLOWING IS REPEATED, COZ PEOPLE JUST DON'T FOLLOW DIRECTIONS!"
"If your email client wont let you click the validation\n"
"link, just copy and paste it into your web browser.\n"
"If your email client wont let you click the validation\n"
"link, just copy and paste it into your web browser.\n"
"If your email client wont let you click the validation\n"
"link, just copy and paste it into your web browser.\n"
"If your email client wont let you click the validation\n"
"link, just copy and paste it into your web browser.\n"
"\n"
"\n"
"Do not reply to this email.\n"
"\n"
"\n"
"A copy of the grids Terms of Service that you agreed to\n"
"when you created your account is included below.\n"
"%s",
Rd->Host, Rd->Host, Rd->Host,
getStrH(Rd->stuff, "email"),
Rd->Host, Rd->Host,
first, last,
first, last, Rd->Host, Rd->RUri,
Rd->Host, Rd->RUri, t1, ToS
);
l = strlen(content);
file = xmprintf("%s/sessions/%s.email", scCache, shs->leaf);
fd = notstdio(xcreate_stdio(file, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR));
if (l != writeall(fd, content, l))
{
perror_msg("Writing %s", file);
// freeSesh(Rd, linky, TRUE);
}
xclose(fd);
I("Sending linky email to %s %s", getStrH(Rd->stuff, "email"), t1);
if (shellMeFail("sendmail -oi -t <'%s'", file))
E("sendmail command failed!");
free(file);
free(content);
free(t1);
free(t0);
}
}
}
static void generateAccountUUID(reqData *Rd)
{
// Generate a UUID, check it isn't already being used.
char uuid[37], *where;
uuid_t binuuid;
my_ulonglong users = 0;
int c;
do // UserAccounts.PrincipalID is a unique primary index anyway, but we want the user creation process to be a little on the slow side.
{
struct stat st;
uuid_generate_random(binuuid);
uuid_unparse_lower(binuuid, uuid);
// Try Lua user file.
where = xmprintf("%s/users/%s.lua", scData, uuid);
c = stat(where, &st);
if (c)
users = 1;
free(where);
// Try database.
where = xmprintf("UserAccounts.PrincipalID = '%s'", uuid);
D("Trying new UUID %s.", where);
users = dbCount("UserAccounts", where);
free(where);
} while (users != 0);
if (NULL != Rd->shs.UUID) free(Rd->shs.UUID);
Rd->shs.UUID = xstrdup(uuid);
Rd->shs.level = -200;
Rd->database->putstr(Rd->database, "UserAccounts.PrincipalID", uuid);
Rd->database->putstr(Rd->database, "UserAccounts.Userlevel", "-200");
}
char *getLevel(short level)
{
char *ret = "", *lvl = xmprintf("%d", level);
ret = accountLevels->getstr(accountLevels, lvl, false);
if (NULL == ret)
{
qlisttbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
accountLevels->lock(accountLevels);
while(accountLevels->getnext(accountLevels, &obj, NULL, false) == true)
{
if (atoi(obj.name) <= level)
ret = (char *) obj.data;
}
}
free(lvl);
return ret;
}
typedef struct _systemFolders systemFolders;
struct _systemFolders
{
char *name;
short type;
};
systemFolders sysFolders[] =
{
{"My Inventory", 8},
{"Animations", 20},
{"Body Parts", 13},
{"Calling Cards", 2},
// {"Friends", 2},
// {"All", 2},
{"Clothing", 5},
{"Current Outfit", 46},
{"Favorites", 23},
{"Gestures", 21},
{"Landmarks", 3},
{"Lost And Found", 16},
{"Mesh", 49},
{"My Outfits", 48},
{"My Suitcase", 100}, // All the others are replicated inside.
{"Notecards", 7},
{"Objects", 6},
{"Outfit", 47},
{"Photo Album", 15},
{"Scripts", 10},
{"Sounds", 1},
{"Textures", 0},
{"Trash", 14},
{NULL, -1}
};
static void accountWrite(reqData *Rd)
{
char *uuid = getStrH(Rd->database, "UserAccounts.PrincipalID");
char *file = xmprintf("%s/users/%s.lua", scData, uuid);
char *level = getStrH(Rd->database, "UserAccounts.UserLevel");
char *link = (NULL == Rd->lnk) ? "" : Rd->lnk->hashish;
char *tnm = "user = \n{\n";
struct stat st;
int s = stat(file, &st);
int fd = notstdio(xcreate_stdio(file, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR));
size_t l = strlen(tnm);
uuid_t binuuid;
uuid_clear(binuuid);
if ((NULL != uuid) && ('\0' != uuid[0]))
uuid_parse(uuid, binuuid);
if ((NULL != uuid) && ('\0' != uuid[0]) && (!uuid_is_null(binuuid)))
{
if (s)
I("Creating user %s.", file);
else
I("Updating user %s.", file);
if (l != writeall(fd, tnm, l))
perror_msg("Writing %s", file);
else
{
char *name = Rd->stuff->getstr(Rd->stuff, "name", true);
char *end = "}\nreturn user\n";
if (!writeLuaString (Rd, fd, file, "name", name)) goto notWritten;
if (!writeLuaInteger(Rd, fd, file, "created",
(strcmp("", getStrH(Rd->stuff, "created")) != 0) ? atol(getStrH(Rd->stuff, "created")) : (long) Rd->shs.timeStamp[1].tv_sec)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "email", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "title", getLevel(atoi(level)))) goto notWritten;
if (!writeLuaString (Rd, fd, file, "level", level)) goto notWritten;
if (!writeLuaInteger(Rd, fd, file, "flags", 0)) goto notWritten;
if (!writeLuaInteger(Rd, fd, file, "active", 1)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "passwordHash", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "passwordSalt", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "UUID", uuid)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "DoB", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "agree", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "adult", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "aboutMe", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "vouched", "off")) goto notWritten;
if (!writeLuaString (Rd, fd, file, "voucher", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "approver", NULL)) goto notWritten;
if (!writeLuaString (Rd, fd, file, "link", link)) goto notWritten;
l = strlen(end);
if (l != writeall(fd, end, l))
perror_msg("Writing %s", file);
else
{
char *nm = xmprintf("%s/users/%s.lua", scData, qstrreplace("tr", name, " ", "_"));
free(file);
file = xmprintf("%s.lua", uuid);
I("Symlinking %s to %s", file, nm);
if (0 != symlink(file, nm))
perror_msg("Symlinking %s to %s", file, nm);
free(nm);
}
notWritten:
free(name);
}
xclose(fd);
short lvl = atoi(level);
if (0 <= lvl) // Note that http://opensimulator.org/wiki/Userlevel claims that 1 and above are "GOD_LIKE".
{
if (Rd->fromDb)
{
I("Updating database user %s.", getStrH(Rd->stuff, "name"));
}
else
{
// Setup the database stuff.
static dbRequest *acntsI = NULL;
if (NULL == acntsI)
{
static char *szi[] =
{
"FirstName",
"LastName",
"Email",
"Created",
"PrincipalID",
"ScopeID",
"UserLevel",
"UserFlags",
"UserTitle",
// "ServiceURLs", // No worky "text", filled with crap. Leaving it blank works fine.
"active",
NULL
};
static char *szo[] = {NULL};
acntsI = xzalloc(sizeof(dbRequest));
acntsI->table = "UserAccounts";
acntsI->inParams = szi;
acntsI->outParams = szo;
acntsI->where = "";
acntsI->type = CT_CREATE;
dbRequests->addfirst(dbRequests, &acntsI, sizeof(dbRequest *));
}
static dbRequest *authI = NULL;
if (NULL == authI)
{
static char *szi[] = {"UUID", "passwordSalt", "passwordHash", "accountType", "webLoginKey", NULL};
static char *szo[] = {NULL};
authI = xzalloc(sizeof(dbRequest));
authI->table = "auth";
authI->inParams = szi;
authI->outParams = szo;
authI->where = "";
authI->type = CT_CREATE;
dbRequests->addfirst(dbRequests, &authI, sizeof(dbRequest *));
}
static dbRequest *invFolderI = NULL;
if (NULL == invFolderI)
{
static char *szi[] =
{
"agentID",
"folderName",
"type", // smallint(6)
"version", // int(11)
"folderID",
"parentFolderID",
NULL
};
static char *szo[] = {NULL};
invFolderI = xzalloc(sizeof(dbRequest));
invFolderI->table = "inventoryfolders";
invFolderI->inParams = szi;
invFolderI->outParams = szo;
invFolderI->where = "";
invFolderI->type = CT_CREATE;
dbRequests->addfirst(dbRequests, &invFolderI, sizeof(dbRequest *));
}
static dbRequest *gUserI = NULL;
if (NULL == gUserI)
{
// static char *szi[] = {"UserID", "HomeRegionID", "HomePosition", "HomeLookAt", "LastRegionID", "LastPosition", "LastLookAt", "Online", "Login", "Logout", NULL};
static char *szi[] = {"UserID", NULL}; // All the defaults are what we would set anyway.
static char *szo[] = {NULL};
gUserI = xzalloc(sizeof(dbRequest));
gUserI->table = "GridUser";
gUserI->inParams = szi;
gUserI->outParams = szo;
gUserI->where = "";
gUserI->type = CT_CREATE;
dbRequests->addfirst(dbRequests, &gUserI, sizeof(dbRequest *));
}
I("Creating database user %s %s.", uuid, getStrH(Rd->stuff, "name"));
char *first = Rd->stuff->getstr(Rd->stuff, "name", true), *last = strchr(first, ' ');
// create user record.
*last++ = '\0';
if (0 != dbDoSomething(acntsI, FALSE,
first,
last,
getStrH(Rd->stuff, "email"),
(strcmp("", getStrH(Rd->stuff, "created")) != 0) ? atoi(getStrH(Rd->stuff, "created")) : (int) Rd->shs.timeStamp[1].tv_sec,
uuid,
"00000000-0000-0000-0000-000000000000",
atoi(level),
0,
getLevel(atoi(level)),
// "", // Defaults to NULL, empty string seems OK to. Then gets filled in later.
1
))
bitch(Rd, "Internal error.", "Failed to create UserAccounts record.");
else
{
char uuidI[37], uuidR[37], uuidC[37], uuidS[37];
uuid_t binuuidI;
int r = 0, i;
// Create inventory records.
strcpy(uuidR, "00000000-0000-0000-0000-000000000000");
for (i = 0; (NULL != sysFolders[i].name) && (0 == r); i++)
{
uuid_generate_random(binuuidI);
uuid_unparse_lower(binuuidI, uuidI);
// TODO - should check there isn't a folder with this UUID already.
D("Creating %s inventory folder for user %s.", sysFolders[i].name, getStrH(Rd->stuff, "name"));
r += dbDoSomething(invFolderI, FALSE, uuid, sysFolders[i].name, sysFolders[i].type, 1, uuidI, uuidR); // LEAKY
if (0 != r)
bitch(Rd, "Internal error.", "Failed to create invenoryFolder record.");
if (strcmp("My Inventory", sysFolders[i].name) == 0)
strcpy(uuidR, uuidI);
if (strcmp("Calling Cards", sysFolders[i].name) == 0)
strcpy(uuidC, uuidI);
if (strcmp("My Suitcase", sysFolders[i].name) == 0)
strcpy(uuidS, uuidI);
}
uuid_generate_random(binuuidI);
uuid_unparse_lower(binuuidI, uuidI);
// TODO - should check there isn't a folder with this UUID already.
D("Creating %s inventory folder for user %s.", "Friends", getStrH(Rd->stuff, "name"));
r += dbDoSomething(invFolderI, FALSE, uuid, "Friends", 2, 1, uuidI, uuidC);
if (0 != r)
bitch(Rd, "Internal error.", "Failed to create invenoryFolder record.");
strcpy(uuidC, uuidI);
uuid_generate_random(binuuidI);
uuid_unparse_lower(binuuidI, uuidI);
// TODO - should check there isn't a folder with this UUID already.
D("Creating %s inventory folder for user %s.", "All", getStrH(Rd->stuff, "name"));
r += dbDoSomething(invFolderI, FALSE, uuid, "All", 2, 1, uuidI, uuidC);
if (0 != r)
bitch(Rd, "Internal error.", "Failed to create invenoryFolder record.");
for (i = 1; (NULL != sysFolders[i].name) && (0 == r); i++)
{
uuid_generate_random(binuuidI);
uuid_unparse_lower(binuuidI, uuidI);
// TODO - should check there isn't a folder with this UUID already.
D("Creating %s inventory folder for user %s.", sysFolders[i].name, getStrH(Rd->stuff, "name"));
r += dbDoSomething(invFolderI, FALSE, uuid, sysFolders[i].name, sysFolders[i].type, 1, uuidI, uuidS);
if (0 != r)
bitch(Rd, "Internal error.", "Failed to create invenoryFolder record.");
}
if (0 == r)
{
// Create location record.
D("Creating home and last positions for user %s.", getStrH(Rd->stuff, "name"));
if (0 != dbDoSomething(gUserI, FALSE, uuid)) // LEAKY
bitch(Rd, "Internal error.", "Failed to create GridUser record.");
else
{
// Finally create auth record, so they can log in.
D("Creating auth record for user %s %s.", uuid, getStrH(Rd->stuff, "name"));
if (0 != dbDoSomething(authI, FALSE, uuid, getStrH(Rd->stuff, "passwordSalt"), getStrH(Rd->stuff, "passwordHash"), "UserAccount", "00000000-0000-0000-0000-000000000000"))
bitch(Rd, "Internal error.", "Failed to create auth record.");
}
}
// load iar -m first last / password /opt/opensim_SC/backups/DefaultMember.IAR
struct sysinfo info;
float la;
sysinfo(&info);
la = info.loads[0]/65536.0;
char *name;
simData *simd = ourSims->byTab->get(ourSims->byTab, backupIARsim, NULL, false);
if (NULL == simd)
E("Sim %s not found in ini list! Can't create inventory for %s %s", backupIARsim, first, last);
else
name = simd->name;
if (checkSimIsRunning(backupIARsim))
{
char *cmd = xmprintf("%d.%d", simd->window, simd->pane);
char *c = xmprintf("load iar -m %s %s / password /opt/opensim_SC/backups/DefaultMember.IAR", first, last);
I("Loading default member IAR for %s %s in sim %s, this might take a couple of minutes.", first, last, name);
V(c);
sendTmuxCmd(cmd, c);
free(cmd);
free(c);
}
}
free(first);
}
}
}
else
W("Not writing NULL UUID user!");
free(file);
}
static sesh *newSesh(reqData *Rd, boolean linky)
{
unsigned char *md5hash = xzalloc(17);
char *toke_n_munchie, *munchie, *hashish, *t0, *t1;
char uuid[37];
uuid_t binuuid;
sesh *ret = &Rd->shs;
T("new sesh %s %s %s", linky ? "linky" : "session", ret->UUID, ret->name);
if (linky)
{
Rd->lnk = xzalloc(sizeof(sesh));
ret = Rd->lnk;
ret->UUID = Rd->shs.UUID;
}
char buf[128]; // 512 bits.
int numBytes = getrandom((void *)buf, sizeof(buf), GRND_NONBLOCK);
// NOTE that getrandom() returns random bytes, which may include '\0'.
if (-1 == numBytes)
{
perror_msg("Unable to generate a suitable random number.");
// EAGAIN - not enough entropy, try again.
// EINTR - signal handler interrupted it, try again.
}
else
{
t0 = qhex_encode(buf, sizeof(buf));
qstrcpy(ret->salt, sizeof(ret->salt), t0);
free(t0);
//d("salt %s", ret->salt);
numBytes = getrandom((void *)buf, sizeof(buf), GRND_NONBLOCK);
if (-1 == numBytes)
perror_msg("Unable to generate a suitable random number.");
else
{
t0 = qhex_encode(buf, sizeof(buf));
qstrcpy(ret->seshID, sizeof(ret->seshID), t0);
free(t0);
//d("seshID %s", ret->seshID);
ret->timeStamp[0].tv_nsec = UTIME_OMIT;
ret->timeStamp[0].tv_sec = UTIME_OMIT;
if (-1 == clock_gettime(CLOCK_REALTIME, &ret->timeStamp[1]))
perror_msg("Unable to get the time.");
else
{
// tv_sec is a time_t, tv_nsec is a long, but the actual type of time_t isn't well defined, it's some sort of integer.
t0 = xmprintf("%s%ld.%ld", ret->seshID, (long) ret->timeStamp[1].tv_sec, ret->timeStamp[1].tv_nsec);
qstrcpy(ret->sesh, sizeof(ret->sesh), t0);
//d("sesh %s", ret->sesh);
t1 = myHMAC(t0, FALSE);
free(t0);
munchie = xmprintf("%s%ld.%ld", t1, (long) ret->timeStamp[1].tv_sec, ret->timeStamp[1].tv_nsec);
free(t1);
qstrcpy(ret->munchie, sizeof(ret->munchie), munchie);
//d("munchie %s", ret->munchie);
// TODO - chicken and egg? Used to be from stuff->UUID.
t1 = ret->UUID;
if (NULL == t1)
{
uuid_clear(binuuid);
uuid_unparse_lower(binuuid, uuid);
ret->UUID = xstrdup(uuid);
}
t0 = xmprintf("%s%s", ret->UUID, munchie);
free(munchie);
toke_n_munchie = myHMAC(t0, FALSE);
free(t0);
qstrcpy(ret->toke_n_munchie, sizeof(ret->toke_n_munchie), toke_n_munchie);
//d("toke_n_munchie %s", ret->toke_n_munchie);
hashish = myHMACkey(ret->salt, toke_n_munchie, FALSE);
free(toke_n_munchie);
qstrcpy(ret->hashish, sizeof(ret->hashish), hashish);
//d("hashish %s", ret->hashish);
t0 = myHMACkey(getStrH(Rd->configs, "pepper"), hashish, TRUE);
free(hashish);
qstrcpy(ret->leaf, sizeof(ret->leaf), t0);
//d("leaf %s", ret->leaf);
free(t0);
ret->isLinky = linky;
setToken_n_munchie(Rd, linky);
}
}
}
free(md5hash);
return ret;
}
/* CRUD (Create, Read, Update, Delete)
CRAP (Create, Replicate, Append, Process)
Though I prefer -
DAVE (Delete, Add, View, Edit), coz the names are shorter. B-)
On the other hand, list or browse needs to be added, which is why they have
BREAD (Browse, Read, Edit, Add, Delete)
CRUDL (Create, Read, Update, Delete, List)
CRUDE (Create, Read, Update, Delete, Experience)
Maybe -
DAVEE (Delete, Add, View, Edit, Explore)
*/
#define FLD_NONE 0
#define FLD_EDITABLE 1
#define FLD_HIDDEN 2
#define FLD_REQUIRED 4
typedef struct _inputField inputField;
typedef struct _inputSub inputSub;
typedef struct _inputForm inputForm;
typedef struct _inputValue inputValue;
typedef int (*inputFieldValidFunc) (reqData *Rd, inputForm *iF, inputValue *iV);
typedef void (*inputFieldShowFunc) (reqData *Rd, inputForm *iF, inputValue *iV);
typedef int (*inputSubmitFunc) (reqData *Rd, inputForm *iF, inputValue *iV);
typedef void (*inputFormShowFunc) (reqData *Rd, inputForm *iF, inputValue *iV);
struct _inputField
{
char *name, *title, *help;
inputFieldValidFunc validate; // Alas C doesn't have any anonymous function standard.
inputFieldShowFunc web, console, gui;
inputField **group; // If this is a LUA_TGROUP, then this will be a null terminated array of the fields in the group.
// database details
// lua file details
signed char type, flags;
short editLevel, viewLevel, viewLength, maxLength;
};
struct _inputSub
{
char *name, *title, *help, *outputForm;
inputSubmitFunc submit;
};
struct _inputForm
{
char *name, *title, *help;
qlisttbl_t *fields; // qlisttbl coz iteration in order and lookup are important.
qhashtbl_t *subs;
inputFormShowFunc web, eWeb; // display web, console, gui;
// read function
// write function
};
struct _inputValue
{
inputField *field;
void *value; // If this is a LUA_TGROUP, then this will be a null.
short valid; // 0 for not yet validated, negative for invalid, positive for valid.
short source, index;
};
static int sessionValidate(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
boolean linky = FALSE;
char *toke_n_munchie = "", *munchie = "", *hashish = "", *leaf = "", *timeStamp = "", *seshion = "", *seshID = "", *t0, *t1;
// In this case the session stuff has to come from specific places.
hashish = Rd->queries->getstr(Rd->queries, "hashish", true);
//d("O hashish %s", hashish);
if (NULL != hashish)
{
char *t = xstrdup(hashish);
size_t sz = qB64_decode(t);
// TODO - should validate the cookie version as well, if it was sent.
// Coz it later tries to delete the linky as if it was the cookie session, and might give us a chance to delete the old session.
// Though only if there's a munchie in the body?
I("Validating LINKY hashish %s", hashish);
free(hashish);
hashish = qhex_encode(t, sz);
free(t);
linky = TRUE;
}
else
{
toke_n_munchie = getStrH(Rd->cookies, "toke_n_munchie");
// munchie = getStrH(Rd->body, "munchie");
hashish = Rd->cookies->getstr(Rd->cookies, "hashish", true);
if (('\0' == toke_n_munchie[0]) || ((NULL == hashish)))
{
if (strcmp("logout", Rd->doit) == 0)
{
I("Not checking session, coz we are logging out.");
Rd->shs.status = SHS_NUKE;
return ret;
}
bitchSession(Rd, "Invalid session.", "No or blank hashish or toke_n_munchie.");
Rd->shs.status = SHS_NONE;
ret++;
}
else
I("Validating SESSION hashish %s", hashish);
}
//d("O toke_n_munchie %s", toke_n_munchie);
//d("O munchie %s", munchie);
if (0 == ret)
{
struct stat st;
struct timespec now;
leaf = myHMACkey(getStrH(Rd->configs, "pepper"), hashish, TRUE);
//d("leaf %s", leaf);
if (linky)
t0 = xmprintf("%s/sessions/%s.linky", scCache, leaf);
else
t0 = xmprintf("%s/sessions/%s.lua", scCache, leaf);
qhashtbl_t *tnm = qhashtbl(0, 0);
ret = LuaToHash(Rd, t0, "toke_n_munchie", tnm, ret, &st, &now, "session");
free(t0);
if (0 != ret)
{
// This might be coz it's a stale session that was deleted already, so shouldn't complain really if they are just getting the login page.
// They might also have a stale doit and form cookie.
// bitchSession(Rd, "Invalid session.", "No session file.");
bitchSession(Rd, "", "No session file.");
ret++;
}
else
{
// This is apparently controversial, I added it coz some of the various security docs suggested it's a good idea.
// https://security.stackexchange.com/questions/139952/why-arent-sessions-exclusive-to-an-ip-address?rq=1
// Includes various reasons why it's bad.
// Another good reason why it is bad, TOR.
// So should make this a user option, like Mantis does.
if (strcmp(getStrH(Rd->headers, "REMOTE_ADDR"), getStrH(tnm, "IP")) != 0)
{
bitchSession(Rd, "Wrong IP for session.", "Session IP doesn't match.");
ret++;
}
else
{
timeStamp = xmprintf("%ld.%ld", (long) st.st_mtim.tv_sec, st.st_mtim.tv_nsec);
//d("timeStamp %s", timeStamp);
seshion = xmprintf("%s%s", tnm->getstr(tnm, "seshID", false), timeStamp);
//d("sesh %s", seshion);
t0 = myHMAC(seshion, FALSE);
munchie = xmprintf("%s%s", t0, timeStamp);
//d("munchie %s", munchie);
free(t0);
free(timeStamp);
t1 = getStrH(Rd->body, "munchie");
if ('\0' != t1[0])
{
if (strcmp(t1, munchie) != 0)
{
// TODO if newbie user has not logged out, but clicks the email linky, and they end up on a new browser tab, they'll see this on the logged in tab.
bitchSession(Rd, "Wrong munchie for session, may have been eaten, please try again.", "HMAC(seshID + timeStamp) != munchie");
ret++;
}
else
{
t0 = xmprintf("%s%s", getStrH(tnm, "UUID"), munchie);
t1 = myHMAC(t0, FALSE);
free(t0);
//d("toke_n_munchie %s", t1);
if (strcmp(t1, toke_n_munchie) != 0)
{
bitchSession(Rd, "Wrong toke_n_munchie for session.", "HMAC(UUID + munchie) != toke_n_munchie");
ret++;
}
free(t1);
}
if (linky)
{
t0 = xmprintf("%s%s", getStrH(tnm, "UUID"), munchie);
t1 = myHMAC(t0, FALSE);
free(t0);
toke_n_munchie = t1;
//d("toke_n_munchie %s", t1);
}
t1 = myHMACkey(getStrH(tnm, "salt"), toke_n_munchie, FALSE);
//d("hashish %s", t1);
if (strcmp(t1, hashish) != 0)
{
bitchSession(Rd, "Wrong hashish for session.", "HMAC(toke_n_munchie + salt) != hashish");
ret++;
}
free(t1);
}
// TODO - should carefully review all of this, especially the moving of session data to and fro.
if (0 == ret)
{
W("Validated session.");
sesh *shs = &Rd->shs;
qstrcpy(shs->leaf, sizeof(shs->leaf), leaf);
if (NULL != shs->name) free(shs->name);
shs->name = tnm->getstr(tnm, "name", true);
if (NULL != shs->UUID) free(shs->UUID);
shs->UUID = tnm->getstr(tnm, "UUID", true);
if (linky)
{
W("Validated session linky.");
addStrL(Rd->messages, "Congratulations, you have validated your new account. Now you can log onto the web site.");
addStrL(Rd->messages, "NOTE - you wont be able to log onto the grid until your new account has been approved.");
Rd->lnk = xzalloc(sizeof(sesh));
Rd->lnk->status = SHS_NUKE;
qstrcpy(Rd->lnk->leaf, sizeof(Rd->lnk->leaf), leaf);
freeSesh(Rd, linky, FALSE);
qstrcpy(Rd->lnk->leaf, sizeof(Rd->lnk->leaf), "");
Rd->doit = "validate";
Rd->output = "accountLogin";
Rd->form = "accountLogin";
// TODO - we might want to delete their old .lua session as well. Maybe? Don't think we have any suitable codes to find it.
}
else
{
char *level = tnm->getstr(tnm, "level", false);
// Check for session timeouts etc.
if (now.tv_sec > st.st_mtim.tv_sec + seshTimeOut)
{
bitch(Rd, "Session timed out.", "No activity for longer than seshTimeOut, session is ancient.");
ret++;
Rd->shs.status = SHS_ANCIENT;
}
else if (now.tv_sec > st.st_mtim.tv_sec + idleTimeOut)
{
bitch(Rd, "Session idled out.", "No activity for longer than idleTimeOut, session is idle.");
ret++;
Rd->shs.status = SHS_IDLE;
}
else if (now.tv_sec > st.st_mtim.tv_sec + seshRenew)
{
D("Session needs renewing.");
Rd->shs.status = SHS_RENEW;
}
else
Rd->shs.status = SHS_VALID;
if (NULL == level)
level = "-256";
qstrcpy(shs->sesh, sizeof(shs->sesh), seshion);
qstrcpy(shs->toke_n_munchie, sizeof(shs->toke_n_munchie), toke_n_munchie);
qstrcpy(shs->hashish, sizeof(shs->hashish), hashish);
qstrcpy(shs->munchie, sizeof(shs->munchie), munchie);
qstrcpy(shs->salt, sizeof(shs->salt), tnm->getstr(tnm, "salt", false));
qstrcpy(shs->seshID, sizeof(shs->seshID), tnm->getstr(tnm, "seshID", false));
shs->level = atoi(level);
// TODO - get level from somewhere and stuff it in shs.
shs->timeStamp[0].tv_nsec = UTIME_OMIT;
shs->timeStamp[0].tv_sec = UTIME_OMIT;
memcpy(&shs->timeStamp[1], &st.st_mtim, sizeof(struct timespec));
}
}
qhashtbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj));
tnm->lock(tnm);
while(tnm->getnext(tnm, &obj, false) == true)
{
char *n = obj.name;
if ((strcmp("salt", n) != 0) && (strcmp("seshID", n) != 0) && (strcmp("UUID", n) != 0))
{
t("SessionValidate() Lua read %s = %s", n, (char *) obj.data);
Rd->stuff->putstr(Rd->stuff, obj.name, (char *) obj.data);
}
}
tnm->unlock(tnm);
// TODO - check this.
// Rd->database->putstr(Rd->database, "UserAccounts.PrincipalID", tnm->getstr(tnm, "UUID", false));
}
free(munchie);
free(seshion);
}
free(leaf);
tnm->free(tnm);
free(hashish);
}
return ret;
}
static void sessionWeb(reqData *Rd, inputForm *iF, inputValue *iV)
{
HTMLhidden(Rd->reply, iV->field->name, iV->value);
}
/*
static int UUIDValidate(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
char *UUID = (char *) iV->value;
if (36 != strlen(UUID))
{
bitch(Rd, "Internal error.", "UUID isn't long enough.");
ret++;
}
// TODO - check the characters and dashes as well.
if (0 == ret)
Rd->stuff->putstr(Rd->stuff, "UUID", UUID);
return ret;
}
static void UUIDWeb(reqData *Rd, inputForm *iF, inputValue *iV)
{
HTMLhidden(Rd->reply, iV->field->name, iV->value);
}
*/
static int nameValidate(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
unsigned char *name; // We have to be unsigned coz of isalnum().
char *where = NULL;
name = xstrdup(iV->value);
if ((NULL == name) || ('\0' == name[0]))
{
bitch(Rd, "Please supply an account name.", "None supplied.");
ret++;
}
else
{
int l0 = strlen(name), l1 = 0, l2 = 0;
if (0 == l0)
{
bitch(Rd, "Please supply an account name.", "Name is empty.");
ret++;
}
else
{
int i;
unsigned char *s = NULL;
for (i = 0; i < l0; i++)
{
if (isalnum(name[i]) == 0)
{
if ((' ' == name[i] /*&& (NULL == s)*/))
{
s = &name[i];
*s++ = '\0';
while(' ' == *s)
{
i++;
s++;
}
l1 = strlen(name);
l2 = strlen(s);
// Apparently names are not case sensitive on login, but stored with case in the database.
// I confirmed that, can log in no matter what case you use.
// Seems to be good security for names to be case insensitive.
// UserAccounts FirstName and LastName fields are both varchar(64) utf8_general_ci.
// The MySQL docs say that the "_ci" bit means comparisons will be case insensitive. So that should work fine.
// SL docs say 31 characters each for first and last name. UserAccounts table is varchar(64) each. userinfo has varchar(50) for the combined name.
// The userinfo table seems to be obsolete.
// Singularity at least limits the total name to 64.
// I can't find any limitations on characters allowed, but I only ever see letters and digits used. Case is stored, but not significant.
// OpenSims "create user" console command doesn't sanitize it at all, even crashing on some names.
}
else
{
bitch(Rd, "First and last names are limited to ordinary letters and digits, no special characters or fonts.", "");
ret++;
break;
}
// TODO - compare first, last, and fullname against god names, complain and fail if there's a match.
}
}
if (NULL == s)
{
bitch(Rd, "Account names have to be two words.", "");
ret++;
}
if ((31 < l1) || (31 < l2))
{
bitch(Rd, "First and last names are limited to 31 letters each.", "");
ret++;
}
if ((0 == l1) || (0 == l2))
{
bitch(Rd, "First and last names have to be one or more ordinary letters or digits each.", "");
ret++;
}
if (0 == ret)
{
Rd->stuff->putstr(Rd->stuff, "firstName", name);
Rd->stuff->putstr(Rd->stuff, "lastName", s);
Rd->stuff->putstrf(Rd->stuff, "name", "%s %s", name, s);
}
}
}
free(name);
return ret;
}
static void nameWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
if (oV->field->flags & FLD_HIDDEN)
HTMLhidden(Rd->reply, oV->field->name, oV->value);
else
HTMLtext(Rd->reply, "text", oV->field->title, oV->field->name, oV->value, oV->field->viewLength, oV->field->maxLength, oV->field->flags & FLD_REQUIRED);
}
static int passwordValidate(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
char *password = (char *) iV->value, *salt = getStrH(Rd->stuff, "passSalt"), *hash = getStrH(Rd->stuff, "passHash");
if ((NULL == password) || ('\0' == password[0]))
{
bitch(Rd, "Please supply a password.", "Password empty or missing.");
ret++;
}
else if (('\0' != salt[0]) && ('\0' != hash[0]) && (strcmp("psswrd", iV->field->name) == 0))
{
D("Comparing passwords. %s %s %s", password, salt, hash);
char *h = checkSLOSpassword(Rd, salt, password, hash, "Passwords are not the same.");
if (NULL == h)
ret++;
else
free(h);
}
// TODO - once the password is validated, store it as the salt and hash.
// If it's an existing account, compare it? Or do that later?
if (0 == ret)
Rd->stuff->putstr(Rd->stuff, "password", password);
return ret;
}
static void passwordWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
HTMLtext(Rd->reply, "password", oV->field->title, oV->field->name, "", oV->field->viewLength, oV->field->maxLength, oV->field->flags & FLD_REQUIRED);
Rd->reply->addstr(Rd->reply, "<p>While viewers will usually remember your name and password for you, you'll need to remember it for this web site to. "
"I highly recommend using a password manager. KeePass and it's variations is a great password manager.</p>\n");
}
static int emailValidate(reqData *Rd, inputForm *iF, inputValue *iV)
{
// inputField **group = iV->field->group;
int ret = 0, i;
boolean notSame = FALSE;
i = iV->index;
if (2 == i)
{
char *email = (char *) iV->value;
char *emayl = (char *) (iV + 1)->value;
if ((NULL == email) || (NULL == emayl) || ('\0' == email[0]) || ('\0' == emayl[0]))
{
bitch(Rd, "Please supply an email address.", "None supplied.");
ret++;
}
else if (strcmp(email, emayl) != 0)
{
bitch(Rd, "Email addresses are not the same.", "");
ret++;
notSame = TRUE;
}
else if (!qstr_is_email(email))
{
bitch(Rd, "Please supply a proper email address.", "Failed qstr_is_email()");
ret++;
}
else
{
// TODO - do other email checks - does the domain exist, ..
}
if ((NULL != email) && (NULL != emayl))
{
char *t0 = qurl_encode(email, strlen(email));
// In theory it's the correct thing to do to NOT load email into stuff on failure,
// In practice, that means it wont show the old email and emayl in the create page when they don't match.
if ((0 == ret) || notSame)
Rd->stuff->putstrf(Rd->stuff, "email", "%s", t0);
free(t0);
}
if ((NULL != email) && (NULL != emayl))
{
char *t1 = qurl_encode(emayl, strlen(emayl));
Rd->stuff->putstrf(Rd->stuff, "emayl", "%s", t1);
free(t1);
}
}
return ret;
}
static void emailWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
HTMLtext(Rd->reply, "email", oV->field->title, oV->field->name, getStrH(Rd->stuff, oV->field->name), oV->field->viewLength, oV->field->maxLength, oV->field->flags & FLD_REQUIRED);
Rd->reply->addstrf(Rd->reply, "<p>An email will be sent from %s@%s, and it might be in your spam folder, coz these sorts of emails sometimes end up there. "
"You should add that email address to your contacts, or otherwise let it through your spam filter.</p>",
"grid_no_reply", Rd->Host);
}
char *months[] =
{
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december"
};
static int DoBValidate(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0, i;
char *t0, *t1;
// inputField **group = iV->field->group;
i = iV->index;
if (2 == i)
{
t0 = (char *) iV->value;
if ((NULL == t0) || ('\0' == t0[0]))
{
bitch(Rd, "Please supply a year of birth.", "None supplied.");
ret++;
}
else
{
i = atoi(t0);
// TODO - get this to use current year instead of 2021.
if ((1900 > i) || (i > 2021))
{
bitch(Rd, "Please supply a year of birth.", "Out of range.");
ret++;
}
else if (i < 1901)
{
bitch(Rd, "Please supply a proper year of birth.", "Out of range, too old.");
ret++;
}
else if (i >2005)
{
bitch(Rd, "This grid is Adult rated, you are too young.", "Out of range, too young.");
ret++;
}
}
t1 = (char *) (iV + 1)->value;
if ((NULL == t1) || ('\0' == t1[0]))
{
bitch(Rd, "Please supply a month of birth.", "None supplied.");
ret++;
}
else
{
for (i = 0; i < 12; i++)
{
if (strcmp(months[i], t1) == 0)
break;
}
if (12 == i)
{
bitch(Rd, "Please supply a month of birth.", "Out of range");
ret++;
}
}
if (0 == ret)
{
Rd->stuff->putstr(Rd->stuff, "year", t0);
Rd->stuff->putstr(Rd->stuff, "month", t1);
Rd->stuff->putstrf(Rd->stuff, "DoB", "%s %s", t0, t1);
}
}
return ret;
}
static void DoByWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
char *tmp = xmalloc(16), *t;
int i, d;
Rd->reply->addstr(Rd->reply, "<label>Date of birth :<table><tr><td>\n");
HTMLselect(Rd->reply, NULL, oV->field->name);
t = getStrH(Rd->stuff, "year");
if (NULL == t)
d = -1;
else
d = atoi(t);
HTMLoption(Rd->reply, "", FALSE);
for (i = 1900; i <= 2020; i++)
{
boolean sel = FALSE;
if (i == d)
sel = TRUE;
sprintf(tmp, "%d", i);
HTMLoption(Rd->reply, tmp, sel);
}
free(tmp);
HTMLselectEndNo(Rd->reply);
}
static void DoBmWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
char *t;
int i, d;
Rd->reply->addstr(Rd->reply, "</td><td>\n");
HTMLselect(Rd->reply, NULL, oV->field->name);
t = getStrH(Rd->stuff, "month");
HTMLoption(Rd->reply, "", FALSE);
for (i = 0; i <= 11; i++)
{
boolean sel = FALSE;
if ((NULL != t) && (strcmp(t, months[i]) == 0))
sel = TRUE;
HTMLoption(Rd->reply, months[i], sel);
}
HTMLselectEndNo(Rd->reply);
Rd->reply->addstr(Rd->reply, "</td></tr></table></label>\n");
}
static void DoBWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
}
static int legalValidate(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0, i;
char *t;
inputField **group = iV->field->group;
i = iV->index;
if (2 == i)
{
t = (char *) iV->value;
if ((NULL == t) || (strcmp("on", t) != 0))
{
bitch(Rd, "You must be an adult to enter this site.", "");
ret++;
}
else
Rd->stuff->putstr(Rd->stuff, "adult", t);
t = (char *) (iV + 1)->value;
if ((NULL == t) || (strcmp("on", t) != 0))
{
bitch(Rd, "You must agree to the Terms & Conditions of Use.", "");
ret++;
}
else
Rd->stuff->putstr(Rd->stuff, "agree", t);
}
return ret;
}
static void adultWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
HTMLcheckBox(Rd->reply, oV->field->name, oV->field->title, !strcmp("on", getStrH(Rd->body, "adult")), oV->field->flags & FLD_REQUIRED);
}
static void agreeWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
HTMLcheckBox(Rd->reply, oV->field->name, oV->field->title, !strcmp("on", getStrH(Rd->body, "agree")), oV->field->flags & FLD_REQUIRED);
}
static void legalWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
}
static void ToSWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
Rd->reply->addstrf(Rd->reply, "<h2>Terms of Service</h2><pre>%s</pre>\n", getStrH(Rd->configs, "ToS"));
}
static int voucherValidate(reqData *Rd, inputForm *oF, inputValue *oV)
{
int ret = 0;
char *voucher = (char *) oV->value;
if ((NULL == voucher) || ('\0' == voucher[0]))
{
bitch(Rd, "Please fill in the 'Voucher' section.", "None supplied.");
ret++;
}
if ((0 == ret) && (NULL != voucher))
Rd->stuff->putstr(Rd->stuff, "voucher", voucher);
return ret;
}
static void voucherWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
HTMLtext(Rd->reply, "text", oV->field->title, oV->field->name, oV->value, oV->field->viewLength, oV->field->maxLength, oV->field->flags & FLD_REQUIRED);
}
static int aboutMeValidate(reqData *Rd, inputForm *oF, inputValue *oV)
{
int ret = 0;
char *about = (char *) oV->value;
if ((NULL == about) || ('\0' == about[0]))
{
bitch(Rd, "Please fill in the 'About me' section.", "None supplied.");
ret++;
}
if ((0 == ret) && (NULL != about))
Rd->stuff->putstr(Rd->stuff, "aboutMe", about);
return ret;
}
static void aboutMeWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
// For maxlength - the MySQL database field is type text, which has a max length of 64 Kilobytes byets, but characters might take up 1 - 4 bytes, and maxlength is in characters.
// For rows and cols, seems a bit broken, I ask for 5/42, I get 6,36. In world it seems to be 7,46
// TODO - check against the limit for in world profiles, coz this will become that.
// TODO - validate aboutMe, it should not be empty, and should not be longer than 64 kilobytes.
HTMLtextArea(Rd->reply, oV->field->name, oV->field->title, 7, oV->field->viewLength, 4, oV->field->maxLength, "Describe yourself here.", "off", "true", "soft", oV->value, FALSE, FALSE);
}
static void accountWebHeaders(reqData *Rd, inputForm *oF) //, char *name)
{
char *linky = checkLinky(Rd);
HTMLheader(Rd->reply, "<!--#echo var=\"grid\" --> account manager");
Rd->reply->addstrf(Rd->reply, "<h1><!--#echo var=\"grid\" --> account manager</h1>\n");
if (NULL != Rd->shs.name)
{
char *nm = qstrreplace("tr", xstrdup(Rd->shs.name), " ", "+");
Rd->reply->addstrf(Rd->reply, "<h3>You are <a href='https://%s%s%s?user=%s'>%s</a></h3>\n", Rd->Host, Rd->Script, Rd->Path, nm, Rd->shs.name);
Rd->reply->addstr(Rd->reply, linky);
free(nm);
}
free(linky);
if (0 != Rd->errors->size(Rd->messages))
HTMLlist(Rd->reply, "messages -", Rd->messages);
if (NULL != oF->help)
Rd->reply->addstrf(Rd->reply, "<p>%s</p>\n", oF->help);
HTMLform(Rd->reply, "", Rd->shs.munchie);
HTMLhidden(Rd->reply, "form", oF->name);
}
static void accountWebFields(reqData *Rd, inputForm *oF, inputValue *oV)
{
int count = oF->fields->size(oF->fields), i;
for (i = 0; i < count; i++)
{
if (NULL != oV[i].field->web)
oV[i].field->web(Rd, oF, &oV[i]);
if ((NULL != oV[i].field->help) && ('\0' != oV[i].field->help[0]))
Rd->reply->addstrf(Rd->reply, "<p>%s</p>\n", oV[i].field->help);
//d("accountWebFeilds(%s, %s)", oF->name, oV[i].field->name);
}
}
static void accountWebSubs(reqData *Rd, inputForm *oF)
{
qhashtbl_obj_t obj;
Rd->reply->addstrf(Rd->reply, "<input type='submit' disabled style='display: none' aria-hidden='true' />\n"); // Stop Enter key on text fields triggering the first submit button.
memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
oF->subs->lock(oF->subs);
while(oF->subs->getnext(oF->subs, &obj, false) == true)
{
inputSub *sub = (inputSub *) obj.data;
if ('\0' != sub->title[0])
HTMLbutton(Rd->reply, sub->name, sub->title);
//d("accountWebSubs(%s, %s '%s')", oF->name, sub->name, sub->title);
}
oF->subs->unlock(oF->subs);
}
static void accountWebFooter(reqData *Rd, inputForm *oF)
{
if (0 != Rd->errors->size(Rd->errors))
HTMLlist(Rd->reply, "errors -", Rd->errors);
HTMLformEnd(Rd->reply);
HTMLfooter(Rd->reply);
}
static void accountAddWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
accountWebHeaders(Rd, oF);
accountWebFields(Rd, oF, oV);
accountWebSubs(Rd, oF);
accountWebFooter(Rd, oF);
}
static void accountLoginWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
if (NULL != Rd->shs.name) free(Rd->shs.name);
Rd->shs.name = NULL;
if (NULL != Rd->shs.UUID) free(Rd->shs.UUID);
Rd->shs.UUID = NULL;
accountWebHeaders(Rd, oF);
accountWebFields(Rd, oF, oV);
accountWebSubs(Rd, oF);
accountWebFooter(Rd, oF);
}
// TODO - accountViewWeb() and accountViewWeb() should view and edit arbitrary accounts the user is not logged in as,
// but limit things based on being that viewed / edited account, and the users level.
static void accountViewWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
char *name = getStrH(Rd->database, "Lua.name"),
*level = getStrH(Rd->database, "UserAccounts.UserLevel"),
*email = getStrH(Rd->database, "UserAccounts.Email"),
*voucher = getStrH(Rd->database, "Lua.voucher"),
*approver = getStrH(Rd->database, "Lua.approver"),
*about = getStrH(Rd->database, "Lua.aboutMe");
time_t crtd = atol(getStrH(Rd->database, "UserAccounts.Created"));
accountWebHeaders(Rd, oF);
accountWebFields(Rd, oF, oV);
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Name :</b></span></font> %s</p>", name);
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Title / level :</b></span></font> %s / %s</p>", getLevel(atoi(level)), level);
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Date of birth :</b></span></font> %s</p>", getStrH(Rd->database, "Lua.DoB"));
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Created :</b></span></font> %s</p>", ctime(&crtd));
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Email :</b></span></font> %s</p>", email);
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>UUID :</b></span></font> %s</p>", getStrH(Rd->database, "UserAccounts.PrincipalID"));
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Voucher :</b></span></font> %s</p>", voucher);
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Approver :</b></span></font> %s</p>", approver);
HTMLtextArea(Rd->reply, "aboutMe", "About", 7, 50, 4, 16384, "", "off", "true", "soft", about, FALSE, TRUE);
accountWebSubs(Rd, oF);
accountWebFooter(Rd, oF);
}
static void accountEditWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
char *name = getStrH(Rd->database, "Lua.name"),
*level = getStrH(Rd->database, "UserAccounts.UserLevel"),
*email = getStrH(Rd->database, "UserAccounts.Email"),
*voucher = getStrH(Rd->database, "Lua.voucher"),
*approver = getStrH(Rd->database, "Lua.approver"),
*about = getStrH(Rd->database, "Lua.aboutMe"),
*lvl = getLevel(atoi(level));
short lv = atoi(level);
accountWebHeaders(Rd, oF);
accountWebFields(Rd, oF, oV);
// HTMLtext(Rd->reply, "password", "Old password", "password", "", 16, 0, FALSE);
// Rd->reply->addstr(Rd->reply, "<p>Warning, the limit on password length is set by your viewer, some can't handle longer than 16 characters.</p>\n");
//// HTMLtext(Rd->reply, "title", "text", "title", getStrH(Rh->stuff, "title"), 16, 64, TRUE);
HTMLhidden(Rd->reply, "user", name);
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Name :</b></span></font> %s</p>", name);
// Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Email :</b></span></font> %s</p>", email);
HTMLtextArea(Rd->reply, "aboutMe", "About", 7, 50, 4, 16384, "", "off", "true", "soft", about, FALSE, TRUE);
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Voucher :</b></span></font> %s</p>", voucher);
if (200 <= Rd->shs.level)
{
qlisttbl_obj_t obj;
HTMLhidden(Rd->reply, "approver", approver);
HTMLselect(Rd->reply, "level", "level");
memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
accountLevels->lock(accountLevels);
while(accountLevels->getnext(accountLevels, &obj, NULL, false) == true)
{
boolean is = false;
short l = atoi((char *) obj.name);
if (strcmp(lvl, (char *) obj.data) == 0)
is = true;
// if ((is) || ((l <= Rd->shs.level) && (l != -200) && (l != -100) && (l != -50))) // Not above our pay grade, not newbie, validated, nor vouched for.
if ((is) || ((l <= Rd->shs.level) && (lv <= l))) // As per discussions, can't lower level. Do that in the console.
HTMLoption(Rd->reply, (char *) obj.data, is);
}
accountLevels->unlock(accountLevels);
HTMLselectEnd(Rd->reply);
Rd->reply->addstrf(Rd->reply, "<p><dl>");
Rd->reply->addstrf(Rd->reply, "<dt>disabled</dt><dd>Account cannot log in anywhere.</dd>");
Rd->reply->addstrf(Rd->reply, "<dt>newbie</dt><dd>Newly created account, not yet validated.</dd>");
Rd->reply->addstrf(Rd->reply, "<dt>validated</dt><dd>Newly created account, they have clicked on the validation link in their validation email.</dd>");
Rd->reply->addstrf(Rd->reply, "<dt>vouched for</dt><dd>Someone has vouched for this person.</dd>");
Rd->reply->addstrf(Rd->reply, "<dt>approved</dt><dd>This person is approved, and can log into the world.</dd>");
Rd->reply->addstrf(Rd->reply, "<dt>god</dt><dd>This is a god admin person.</dd>");
Rd->reply->addstrf(Rd->reply, "</dl></p>");
}
else
Rd->reply->addstrf(Rd->reply, "<p><font size='5'><span style='font-size: x-large'><b>Title / level :</b></span></font> %s / %s</p>", lvl, level);
accountWebSubs(Rd, oF);
accountWebFooter(Rd, oF);
}
static int accountRead(reqData *Rd, char *uuid, char *firstName, char *lastName)
{
int ret = 0, rt = -1;
struct stat st;
struct timespec now;
qhashtbl_t *tnm = qhashtbl(0, 0);
uuid_t binuuid;
rowData *rows = NULL;
// Setup the database stuff.
static dbRequest *uuids = NULL;
if (NULL == uuids)
{
static char *szi[] = {"PrincipalID", NULL};
static char *szo[] = {NULL};
uuids = xzalloc(sizeof(dbRequest));
uuids->table = "UserAccounts";
uuids->inParams = szi;
uuids->outParams = szo;
uuids->where = "PrincipalID=?";
dbRequests->addfirst(dbRequests, &uuids, sizeof(dbRequest *));
}
static dbRequest *acnts = NULL;
if (NULL == acnts)
{
static char *szi[] = {"FirstName", "LastName", NULL};
static char *szo[] = {NULL};
acnts = xzalloc(sizeof(dbRequest));
acnts->table = "UserAccounts";
acnts->inParams = szi;
acnts->outParams = szo;
acnts->where = "FirstName=? and LastName=?";
dbRequests->addfirst(dbRequests, &acnts, sizeof(dbRequest *));
}
static dbRequest *auth = NULL;
if (NULL == auth)
{
static char *szi[] = {"UUID", NULL};
static char *szo[] = {"passwordSalt", "passwordHash", NULL};
auth = xzalloc(sizeof(dbRequest));
auth->table = "auth";
auth->inParams = szi;
auth->outParams = szo;
auth->where = "UUID=?";
dbRequests->addfirst(dbRequests, &auth, sizeof(dbRequest *));
}
Rd->fromDb = FALSE;
// uuid = Rd->shs.UUID; first = getStrH(Rd->stuff, "firstName"); last = getStrH(Rd->stuff, "lastName");
// Special for showing another users details.
if ('\0' != getStrH(Rd->queries, "user")[0])
uuid = "";
char *first = xstrdup(""), *last = xstrdup("");
if (NULL != firstName)
{
free(first);
first = xstrdup(firstName);
if (NULL == lastName)
{
char *t = strchr(first, ' ');
d("accountRead() single name |%s| |%s|", first, last);
if (NULL == t)
t = strchr(first, '+');
if (NULL != t)
{
*t++ = '\0';
free(last);
last = xstrdup(t);
}
}
else
{
free(last);
last = xstrdup(lastName);
}
}
d("accountRead() UUID %s, name %s %s", uuid, first, last);
uuid_clear(binuuid);
if ((NULL != uuid) && ('\0' != uuid[0]))
uuid_parse(uuid, binuuid);
if ((NULL != uuid) && ('\0' != uuid[0]) && (!uuid_is_null(binuuid)))
{
char *where = xmprintf("%s/users/%s.lua", scData, uuid);
rt = LuaToHash(Rd, where, "user", tnm, ret, &st, &now, "user");
free(where);
dbDoSomething(uuids, FALSE, uuid);
rows = uuids->rows;
}
else
{
if ('\0' != first[0])
{
char *where = xmprintf("%s/users/%s_%s.lua", scData, first, last);
rt = LuaToHash(Rd, where, "user", tnm, ret, &st, &now, "user");
free(where);
dbDoSomething(acnts, FALSE, first, last); // LEAKY
rows = acnts->rows;
}
}
// else
// {
// bitch(Rd, "Unable to read user record.", "Nothing available to look up a user record with.");
// rt = 1;
// }
if (0 == rt)
{
V("Found Lua record.");
ret += 1;
Rd->database->putstr(Rd->database, "UserAccounts.FirstName", first);
Rd->database->putstr(Rd->database, "UserAccounts.LastName", last);
Rd->database->putstr(Rd->database, "UserAccounts.Email", getStrH(tnm, "email"));
Rd->database->putstr(Rd->database, "UserAccounts.Created", getStrH(tnm, "created"));
Rd->database->putstr(Rd->database, "UserAccounts.PrincipalID", getStrH(tnm, "UUID"));
Rd->database->putstr(Rd->database, "UserAccounts.UserLevel", getStrH(tnm, "level"));
Rd->database->putstr(Rd->database, "UserAccounts.UserFlags", getStrH(tnm, "flags"));
Rd->database->putstr(Rd->database, "UserAccounts.UserTitle", getStrH(tnm, "title"));
Rd->database->putstr(Rd->database, "UserAccounts.active", getStrH(tnm, "active"));
Rd->database->putstr(Rd->database, "auth.passwordSalt", getStrH(tnm, "passwordSalt"));
Rd->database->putstr(Rd->database, "auth.passwordHash", getStrH(tnm, "passwordHash"));
Rd->stuff-> putstr(Rd->stuff, "linky-hashish", getStrH(tnm, "linky-hashish"));
Rd->database->putstr(Rd->database, "Lua.name", getStrH(tnm, "name"));
Rd->database->putstr(Rd->database, "Lua.DoB", getStrH(tnm, "DoB"));
Rd->database->putstr(Rd->database, "Lua.agree", getStrH(tnm, "agree"));
Rd->database->putstr(Rd->database, "Lua.adult", getStrH(tnm, "adult"));
Rd->database->putstr(Rd->database, "Lua.aboutMe", getStrH(tnm, "aboutMe"));
Rd->database->putstr(Rd->database, "Lua.vouched", getStrH(tnm, "vouched"));
Rd->database->putstr(Rd->database, "Lua.voucher", getStrH(tnm, "voucher"));
Rd->database->putstr(Rd->database, "Lua.approver", getStrH(tnm, "approver"));
}
// else if (rows)
if (rows)
{
rt = rows->rows->size(rows->rows);
if (1 == rt)
{
ret = rt;
V("Found database record.");
dbPull(Rd, "UserAccounts", rows);
char *name = xmprintf("%s %s", getStrH(Rd->database, "UserAccounts.FirstName"), getStrH(Rd->database, "UserAccounts.LastName"));
Rd->fromDb = TRUE;
Rd->database->putstr(Rd->database, "Lua.name", name);
free(name);
dbDoSomething(auth, FALSE, getStrH(Rd->database, "UserAccounts.PrincipalID")); // LEAKY
rows = auth->rows;
if (rows)
{
if (1 == rows->rows->size(rows->rows))
dbPull(Rd, "auth", rows);
else
{
free(rows->fieldNames);
rows->rows->free(rows->rows);
free(rows);
}
}
else
{
free(rows->fieldNames);
rows->rows->free(rows->rows);
free(rows);
}
}
else
{
free(rows->fieldNames);
rows->rows->free(rows->rows);
free(rows);
}
}
else
{
d("No user name or UUID to get an account for.");
}
if (1 == ret)
{
// TODO - this has to change when we are editing other peoples accounts.
if ('\0' == getStrH(Rd->queries, "user")[0])
{
// Rd->shs.level = atoi(getStrH(Rd->database, "UserAccounts.UserLevel"));
// TODO - might have to combine first and last here.
// Rd->shs.name = Rd->database->getstr(Rd->database, "Lua.name", true);
// Rd->shs.UUID = Rd->database->getstr(Rd->database, "UserAccounts.PrincipalID", true);
//d("accountRead() setting session uuid %s level %d name %s ", Rd->shs.UUID, (int) Rd->shs.level, Rd->shs.name);
}
// Rd->stuff->putstr(Rd->stuff, "email", getStrH(Rd->database, "UserAccounts.Email"));
}
free(last);
free(first);
tnm->free(tnm);
return ret;
}
static int accountDelSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
char *uuid = Rd->shs.UUID, *first = getStrH(Rd->stuff, "firstName"), *last = getStrH(Rd->stuff, "lastName");
int c = accountRead(Rd, uuid, first, last);
if (1 != c)
{
bitch(Rd, "Cannot delete account.", "Account doesn't exist.");
ret++;
}
else
{
// TODO - check if logged in user is allowed to delete this account
// TODO - delete user record
// TODO - log the user out if they are logged in
}
return ret;
}
// The [create member] button on accountLoginWeb()
static int accountCreateSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
char *uuid = Rd->shs.UUID, *first = getStrH(Rd->stuff, "name"), *last = NULL;
int c = accountRead(Rd, uuid, first, last);
if (strcmp("POST", Rd->Method) == 0)
{
if (0 != c)
{
bitch(Rd, "Cannot create account.", "Account exists.");
Rd->shs.status = SHS_NUKE;
ret++;
}
else
{
char *salt = newSLOSsalt(Rd);
char *h = checkSLOSpassword(Rd, salt, getStrH(Rd->body, "password"), NULL, NULL);
if (NULL == h)
ret++;
else
{
Rd->stuff->putstr(Rd->stuff, "passHash", h);
Rd->stuff->putstr(Rd->stuff, "passSalt", salt);
if (NULL != Rd->shs.name) free(Rd->shs.name);
// So that we can get the name later when we show the account data entry page via GET.
Rd->shs.name = Rd->stuff->getstr(Rd->stuff, "name", true);
free(h);
Rd->shs.status = SHS_REFRESH;
}
free(salt);
if (0 != ret)
Rd->shs.status = SHS_NUKE;
}
}
return ret;
}
// The [confirm] button on accountAddWeb()
static int accountAddSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
char *uuid = Rd->shs.UUID, *first = getStrH(Rd->stuff, "firstName"), *last = getStrH(Rd->stuff, "lastName");
int c = accountRead(Rd, uuid, first, last);
if (0 != c)
{
bitch(Rd, "Cannot add account.", "Account exists.");
Rd->shs.status = SHS_NUKE;
ret++;
}
else if ((0 == ret) && (strcmp("POST", Rd->Method) == 0))
{
char *h = checkSLOSpassword(Rd, getStrH(Rd->stuff, "passSalt"), getStrH(Rd->stuff, "password"), getStrH(Rd->stuff, "passHash"), "Passwords are not the same.");
if (NULL == h)
{
ret++;
Rd->shs.status = SHS_NUKE;
}
else
{
free(h);
generateAccountUUID(Rd);
Rd->stuff->putstr(Rd->stuff, "passwordHash", getStrH(Rd->stuff, "passHash"));
Rd->stuff->putstr(Rd->stuff, "passwordSalt", getStrH(Rd->stuff, "passSalt"));
Rd->shs.level = -200;
Rd->database->putstr(Rd->database, "UserAccounts.UserLevel", "-200");
// Generate the linky for the email.
newSesh(Rd, TRUE);
accountWrite(Rd);
// log them in
I("Logged on %s %s Level %d %s", Rd->shs.UUID, Rd->shs.name, Rd->shs.level, getLevel(Rd->shs.level));
Rd->output = "accountView";
Rd->form = "accountView";
Rd->doit = "login";
Rd->shs.status = SHS_LOGIN;
}
}
return ret;
}
static int accountSaveSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
// Using body[user] here, coz we got to this page via a URL query.
char *uuid = Rd->shs.UUID, *first = getStrH(Rd->body, "user"), *last = NULL,
*level = getStrH(Rd->database, "UserAccounts.UserLevel");
int c = accountRead(Rd, NULL, first, last);
if (1 != c)
{
bitch(Rd, "Cannot save account.", "Account doesn't exist.");
ret++;
}
else if ((0 == ret) && (strcmp("POST", Rd->Method) == 0))
{
char *lvl = getStrH(Rd->body, "level");
qlisttbl_obj_t obj;
if (strcmp(level, lvl) != 0)
{
if (200 <= Rd->shs.level)
{
I("%s %s approved by %s.", getStrH(Rd->database, "UserAccounts.FirstName"), getStrH(Rd->database, "UserAccounts.LastName"), Rd->shs.name);
Rd->stuff->putstr(Rd->stuff, "approver", Rd->shs.name);
}
else
{
bitch(Rd, "Cannot change level.", "User level not high enough.");
lvl = level;
Rd->stuff->putstr(Rd->stuff, "approver", getStrH(Rd->database, "Lua.approver"));
}
}
Rd->stuff->putstr(Rd->stuff, "email", getStrH(Rd->database, "UserAccounts.Email"));
Rd->stuff->putstr(Rd->stuff, "created", getStrH(Rd->database, "UserAccounts.Created"));
Rd->stuff->putstr(Rd->stuff, "flags", getStrH(Rd->database, "UserAccounts.UserFlags"));
Rd->stuff->putstr(Rd->stuff, "active", getStrH(Rd->database, "UserAccounts.active"));
Rd->stuff->putstr(Rd->stuff, "passwordSalt", getStrH(Rd->database, "auth.passwordSalt"));
Rd->stuff->putstr(Rd->stuff, "passwordHash", getStrH(Rd->database, "auth.passwordHash"));
Rd->stuff->putstr(Rd->stuff, "name", getStrH(Rd->database, "Lua.name"));
Rd->stuff->putstr(Rd->stuff, "DoB", getStrH(Rd->database, "Lua.DoB"));
Rd->stuff->putstr(Rd->stuff, "agree", getStrH(Rd->database, "Lua.agree"));
Rd->stuff->putstr(Rd->stuff, "adult", getStrH(Rd->database, "Lua.adult"));
Rd->stuff->putstr(Rd->stuff, "aboutMe", getStrH(Rd->database, "Lua.aboutMe"));
Rd->stuff->putstr(Rd->stuff, "vouched", getStrH(Rd->database, "Lua.vouched"));
Rd->stuff->putstr(Rd->stuff, "voucher", getStrH(Rd->database, "Lua.voucher"));
memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
accountLevels->lock(accountLevels);
while(accountLevels->getnext(accountLevels, &obj, NULL, false) == true)
{
if (strcmp(lvl, (char *) obj.data) == 0)
{
Rd->database->putstr(Rd->database, "UserAccounts.UserLevel", obj.name);
}
}
accountLevels->unlock(accountLevels);
accountWrite(Rd);
free(Rd->outQuery);
Rd->outQuery = xmprintf("?user=%s+%s", getStrH(Rd->database, "UserAccounts.FirstName"), getStrH(Rd->database, "UserAccounts.LastName"));
// TODO - this isn't being shown.
addStrL(Rd->messages, "Account saved.");
}
return ret;
}
// The unique validation URL sent in email.
static int accountValidateSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
char *uuid = Rd->shs.UUID, *first = getStrH(Rd->stuff, "firstName"), *last = getStrH(Rd->stuff, "lastName");
int c = accountRead(Rd, uuid, first, last);
if (1 != c)
{
bitch(Rd, "Cannot validate account.", "Account doesn't exist.");
ret++;
}
else
{
Rd->stuff->putstr(Rd->stuff, "email", getStrH(Rd->database, "UserAccounts.Email"));
Rd->stuff->putstr(Rd->stuff, "created", getStrH(Rd->database, "UserAccounts.Created"));
Rd->stuff->putstr(Rd->stuff, "flags", getStrH(Rd->database, "UserAccounts.UserFlags"));
Rd->stuff->putstr(Rd->stuff, "active", getStrH(Rd->database, "UserAccounts.active"));
Rd->stuff->putstr(Rd->stuff, "passwordSalt", getStrH(Rd->database, "auth.passwordSalt"));
Rd->stuff->putstr(Rd->stuff, "passwordHash", getStrH(Rd->database, "auth.passwordHash"));
Rd->stuff->putstr(Rd->stuff, "name", getStrH(Rd->database, "Lua.name"));
Rd->stuff->putstr(Rd->stuff, "DoB", getStrH(Rd->database, "Lua.DoB"));
Rd->stuff->putstr(Rd->stuff, "agree", getStrH(Rd->database, "Lua.agree"));
Rd->stuff->putstr(Rd->stuff, "adult", getStrH(Rd->database, "Lua.adult"));
Rd->stuff->putstr(Rd->stuff, "aboutMe", getStrH(Rd->database, "Lua.aboutMe"));
Rd->stuff->putstr(Rd->stuff, "vouched", getStrH(Rd->database, "Lua.vouched"));
Rd->stuff->putstr(Rd->stuff, "voucher", getStrH(Rd->database, "Lua.voucher"));
Rd->stuff->putstr(Rd->stuff, "approver", getStrH(Rd->database, "Lua.approver"));
Rd->shs.level = -100;
Rd->database->putstr(Rd->database, "UserAccounts.UserLevel", "-100");
accountWrite(Rd);
Rd->doit = "logout";
Rd->output = "accountLogin";
Rd->form = "accountLogin";
Rd->shs.status = SHS_NUKE;
}
return ret;
}
static int accountViewSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
// TODO - this has to change when we are editing other peoples accounts.
int ret = 0;
char *uuid = Rd->shs.UUID, *first = getStrH(Rd->stuff, "firstName"), *last = getStrH(Rd->stuff, "lastName");
int c = accountRead(Rd, uuid, first, last);
d("Sub accountViewSub() %s %s %s", uuid, first, last);
if (1 != c)
{
bitch(Rd, "Cannot view account.", "Account doesn't exist.");
ret++;
Rd->shs.status = SHS_NUKE;
}
else
{
// Check password on POST if the session user is the same as the shown user, coz this is the page shown on login.
// Also only check on login.
if ((strcmp("POST", Rd->Method) == 0) //&& (strcmp(Rd->shs.UUID, getStrH(Rd->database, "UserAccounts.PrincipalID")) == 0)
&& (strcmp("login", Rd->doit) == 0) && (strcmp("accountLogin", Rd->form) == 0))
{
char *h = checkSLOSpassword(Rd, getStrH(Rd->database, "auth.passwordSalt"), getStrH(Rd->body, "password"), getStrH(Rd->database, "auth.passwordHash"), "Login failed.");
if (NULL == h)
{
ret++;
Rd->shs.status = SHS_NUKE;
}
else
{
Rd->shs.level = atoi(getStrH(Rd->database, "UserAccounts.UserLevel"));
if (NULL != Rd->shs.name) free(Rd->shs.name);
Rd->shs.name = Rd->database->getstr(Rd->database, "Lua.name", true);
if (NULL != Rd->shs.UUID) free(Rd->shs.UUID);
Rd->shs.UUID = Rd->database->getstr(Rd->database, "UserAccounts.PrincipalID", true);
free(h);
I("Logged on %s %s Level %d %s", Rd->shs.UUID, Rd->shs.name, Rd->shs.level, getLevel(Rd->shs.level));
Rd->shs.status = SHS_LOGIN;
}
}
}
return ret;
}
static int accountEditSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
char *uuid = Rd->shs.UUID, *first = getStrH(Rd->stuff, "firstName"), *last = getStrH(Rd->stuff, "lastName");
int c = accountRead(Rd, uuid, first, last);
d("Sub accountEditSub %s %s %s", uuid, first, last);
if (1 != c)
{
bitch(Rd, "Cannot edit account.", "Account doesn't exist.");
ret++;
}
else
{
// TODO - check if logged in user is allowed to make these changes
// TODO - update user record
}
return ret;
}
static int accountExploreSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
// get a list of user records
return ret;
}
static int accountOutSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
char *uuid = Rd->shs.UUID, *first = getStrH(Rd->stuff, "firstName"), *last = getStrH(Rd->stuff, "lastName");
int c = accountRead(Rd, uuid, first, last);
if (1 != c)
{
// bitch(Rd, "Cannot logout account.", "Account doesn't exist.");
// ret++;
}
Rd->shs.status = SHS_NUKE;
return ret;
}
/* TODO - instead of searching through all the users, ...
have a bunch of separate folders with symlinks
scData/users/aaproved
scData/users/disabled
scData/users/god
onefang_rejected.lua -> ../uuid.lua
scData/users/newbie
foo_bar.lua -> ../uuid.lua
scData/users/validated
*/
typedef struct _RdAndListTbl RdAndListTbl;
struct _RdAndListTbl
{
reqData *Rd;
qlisttbl_t *list;
};
static int accountFilterValidated(struct dirtree *node)
{
if (!node->parent) return DIRTREE_RECURSE | DIRTREE_SHUTUP;
if (S_ISREG(node->st.st_mode))
{
struct stat st;
struct timespec now;
RdAndListTbl *rdl = (RdAndListTbl *) node->parent->extra;
qhashtbl_t *tnm = qhashtbl(0, 0);
char *name = node->name;
char *where = xmprintf("%s/users/%s", scData, node->name);
int rt = LuaToHash(rdl->Rd, where, "user", tnm, 0, &st, &now, "user");
t("accountFilterValidatedVoucher %s (%s) -> %s -> %s", name, getStrH(tnm, "level"), getStrH(tnm, "name"), getStrH(tnm, "voucher"));
if ((0 == rt) && (strcmp("-100", getStrH(tnm, "level")) == 0))
rdl->list->put(rdl->list, getStrH(tnm, "name"), &tnm, sizeof(qhashtbl_t *));
else
tnm->free(tnm);
free(where);
}
return 0;
}
qlisttbl_t *getAccounts(reqData *Rd)
{
qlisttbl_t *ret = qlisttbl(0);
RdAndListTbl rdl = {Rd, ret};
char *path = xmprintf("%s/users", scData);
struct dirtree *new = dirtree_add_node(0, path, 0);
new->extra = (long) &rdl;
dirtree_handle_callback(new, accountFilterValidated);
ret->sort(ret);
free(path);
return ret;
}
static void accountExploreValidatedVouchersWeb(reqData *Rd, inputForm *oF, inputValue *oV)
{
qlisttbl_t *list =getAccounts(Rd);
if (NULL != Rd->shs.name) free(Rd->shs.name);
Rd->shs.name = NULL;
if (NULL != Rd->shs.UUID) free(Rd->shs.UUID);
Rd->shs.UUID = NULL;
Rd->shs.level = -256;
accountWebHeaders(Rd, oF);
accountWebFields(Rd, oF, oV);
count = list->size(list);
Rd->reply->addstrf(Rd->reply, "<table border=\"1\"><caption>Validated users</caption>\n");
Rd->reply->addstr(Rd->reply, "<tr>");
Rd->reply->addstr(Rd->reply, "<th>name</th>");
Rd->reply->addstr(Rd->reply, "<th>voucher</th>");
Rd->reply->addstr(Rd->reply, "<th>level</th>");
Rd->reply->addstr(Rd->reply, "<th>title</th>");
Rd->reply->addstr(Rd->reply, "</tr>\n<tr>");
qlisttbl_obj_t obj;
memset((void *) &obj, 0, sizeof(obj));
list->lock(list);
while(list->getnext(list, &obj, NULL, false) == true)
{
qhashtbl_t *tnm = *((qhashtbl_t **) obj.data);
char *nm = qstrreplace("tr", xstrdup(obj.name), " ", "+");
Rd->reply->addstrf(Rd->reply, "<tr><td><a href='https://%s%s%s?user=%s'>%s</a></td>", Rd->Host, Rd->Script, Rd->Path, nm, obj.name);
Rd->reply->addstrf(Rd->reply, "<td>%s</td><td>%s</td><td>%s</td></tr>", getStrH(tnm, "voucher"), getStrH(tnm, "level"), getStrH(tnm, "title"));
free(nm);
tnm->clear(tnm);
list->removeobj(list, &obj);
tnm->free(tnm);
}
list->unlock(list);
Rd->reply->addstr(Rd->reply, "</table>");
list->free(list);
accountWebSubs(Rd, oF);
accountWebFooter(Rd, oF);
}
static int accountExploreValidatedVoucherSub(reqData *Rd, inputForm *iF, inputValue *iV)
{
int ret = 0;
return ret;
}
qhashtbl_t *accountPages = NULL;
inputForm *newInputForm(char *name, char *title, char *help, inputFormShowFunc web, inputFormShowFunc eWeb)
{
inputForm *ret = xmalloc(sizeof(inputForm));
d("newInputForm(%s)", name);
ret->name = name; ret->title = title; ret->help = help;
ret->web = web; ret->eWeb = eWeb;
ret->fields = qlisttbl(QLISTTBL_THREADSAFE | QLISTTBL_UNIQUE | QLISTTBL_LOOKUPFORWARD);
ret->subs = qhashtbl(0, 0);
accountPages->put(accountPages, ret->name, ret, sizeof(inputForm));
free(ret);
return accountPages->get(accountPages, name, NULL, false);
}
inputField *addInputField(inputForm *iF, signed char type, char *name, char *title, char *help, inputFieldValidFunc validate, inputFieldShowFunc web)
{
inputField *ret = xzalloc(sizeof(inputField));
//d("addInputField(%s, %s)", iF->name, name);
ret->name = name; ret->title = title; ret->help = help;
ret->validate = validate; ret->web = web; ret->type = type;
ret->flags = FLD_EDITABLE;
iF->fields->put(iF->fields, ret->name, ret, sizeof(inputField));
free(ret);
return iF->fields->get(iF->fields, name, NULL, false);
}
void inputFieldExtra(inputField *ret, signed char flags, short viewLength, short maxLength)
{
ret->flags = flags;
ret->viewLength = viewLength; ret->maxLength = maxLength;
}
void addSession(inputForm *iF)
{
inputField *fld, **flds = xzalloc(3 * sizeof(*flds));
//d("addSession(%s)", iF->name);
flds[0] = addInputField(iF, LUA_TSTRING, "hashish", "hashish", "", sessionValidate, sessionWeb);
inputFieldExtra(flds[0], FLD_HIDDEN, 0, 0);
flds[1] = addInputField(iF, LUA_TSTRING, "toke_n_munchie", "toke_n_munchie", "", sessionValidate, sessionWeb);
inputFieldExtra(flds[1], FLD_HIDDEN, 0, 0);
fld = addInputField(iF, LUA_TGROUP, "sessionGroup", "sessionGroup", "", sessionValidate, sessionWeb);
inputFieldExtra(fld, FLD_HIDDEN, 0, 0);
fld->group = flds;
flds[0]->group = flds;
flds[1]->group = flds;
}
void addEmailFields(inputForm *iF)
{
inputField *fld, **flds = xzalloc(3 * sizeof(*flds));
flds[0] = addInputField(iF, LUA_TEMAIL, "email", "email", NULL, emailValidate, emailWeb);
inputFieldExtra(flds[0], FLD_EDITABLE, 42, 254);
flds[1] = addInputField(iF, LUA_TEMAIL, "emayl", "Re-enter your email, to be sure you got it correct",
"A validation email will be sent to this email address, you will need to click on the link in it to continue your account creation.", emailValidate, emailWeb);
inputFieldExtra(flds[1], FLD_EDITABLE, 42, 254);
fld = addInputField(iF, LUA_TGROUP, "emailGroup", "emailGroup", "", emailValidate, NULL);
inputFieldExtra(fld, FLD_HIDDEN, 0, 0);
fld->group = flds;
flds[0]->group = flds;
flds[1]->group = flds;
}
void addDoBFields(inputForm *iF)
{
inputField *fld, **flds = xzalloc(3 * sizeof(*flds));
flds[0] = addInputField(iF, LUA_TSTRING, "DoByear", "year", NULL, DoBValidate, DoByWeb);
flds[1] = addInputField(iF, LUA_TSTRING, "DoBmonth", "month", NULL, DoBValidate, DoBmWeb);
fld = addInputField(iF, LUA_TGROUP, "DoBGroup", "DoBGroup", "", DoBValidate, DoBWeb);
inputFieldExtra(fld, FLD_HIDDEN, 0, 0);
fld->group = flds;
flds[0]->group = flds;
flds[1]->group = flds;
}
void addLegalFields(inputForm *iF)
{
inputField *fld, **flds = xzalloc(3 * sizeof(*flds));
flds[0] = addInputField(iF, LUA_TBOOLEAN, "adult", "I'm allegedly an adult in my country.", NULL, legalValidate, adultWeb);
flds[1] = addInputField(iF, LUA_TBOOLEAN, "agree", "I accept the Terms of Service.", NULL, legalValidate, agreeWeb);
fld = addInputField(iF, LUA_TGROUP, "legalGroup", "legalGroup", "", legalValidate, legalWeb);
inputFieldExtra(fld, FLD_HIDDEN, 0, 0);
fld->group = flds;
flds[0]->group = flds;
flds[1]->group = flds;
}
inputSub *addSubmit(inputForm *iF, char *name, char *title, char *help, inputSubmitFunc submit, char *output)
{
inputSub *ret = xmalloc(sizeof(inputSub));
//d("addSubmit(%s, %s)", iF->name, name);
ret->name = name; ret->title = title; ret->help = help; ret->submit = submit; ret->outputForm = output;
iF->subs->put(iF->subs, ret->name, ret, sizeof(inputSub));
free(ret);
return iF->subs->get(iF->subs, name, NULL, false);
}
/* There should be some precedence for values overriding values here.
https://www.w3.org/standards/webarch/protocols
"This intro text is boilerplate for the beta release of w3.org." Fucking useless. Pffft
https://www.w3.org/Protocols/
Still nothing official, though the ENV / HEADER stuff tends to be about the protocol things, and cookies / body / queries are about the data things.
http://docs.gantry.org/gantry4/advanced/setby
Says that query overrides cookies, but that might be just for their platform.
https://framework.zend.com/manual/1.11/en/zend.controller.request.html
Says - "1. GET, 2. POST, 3. COOKIE, 4. SERVER, 5. ENV."
We don't actually get the headers directly, it's all sent via the env.
URL query Values actually provided by the user in the FORM, and other things.
POST body Values actually provided by the user in the FORM.
cookies
https://stackoverflow.com/questions/4056306/how-to-handle-multiple-cookies-with-the-same-name
headers includes HTTP_COOKIE and QUERY_STRING
env includes headers and HTTP_COOKIE and QUERY_STRING
database Since all of the above are for updating the database anyway, this goes on the bottom, overridden by all.
Though be wary of security stuff.
Sending cookie headers is a special case, multiples can be sent, otherwise headers are singletons, only send one for each name.
*/
char *sourceTypes[] =
{
"cookies",
"body",
"queries",
"stuff"
};
static int collectFields(reqData *Rd, inputForm *iF, inputValue *iV, int t)
{
int i = 0, j;
qlisttbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
iF->fields->lock(iF->fields);
while(iF->fields->getnext(iF->fields, &obj, NULL, false) == true)
{
inputField *fld = (inputField *) obj.data;
//if (0 > t)
// d("Collecting %d %s - %s", t, iF->name, fld->name);
//else
// d("Collecting %s %s - %s", sourceTypes[t], iF->name, fld->name);
iV[i].field = fld;
if (LUA_TGROUP == fld->type)
{
if (0 >= t)
{
j = 0;
// If it's a group, number the members relative to the group field.
// Assume the members for this group are the previous ones.
while (iV[i].field->group[j])
{
j++;
iV[i - j].index = j;
}
}
}
else
{
char *vl = NULL;
switch (t)
{
// We don't get the cookies metadata.
case 0 : vl = Rd->cookies->getstr(Rd->cookies, obj.name, false); break;
case 1 : vl = Rd->body-> getstr(Rd->body, obj.name, false); break;
case 2 : vl = Rd->queries->getstr(Rd->queries, obj.name, false); break;
case 3 : vl = Rd->queries->getstr(Rd->stuff, obj.name, false); break;
default: break;
}
if ((NULL != iV[i].value) && (NULL != vl))
{
if (strcmp(vl, iV[i].value) != 0)
W("Collected %s value for %s - %s from %s overriding value from %s", sourceTypes[t], iF->name, fld->name, sourceTypes[t], sourceTypes[iV[i].source]);
else
W("Collected %s value for %s - %s from %s same as value from %s", sourceTypes[t], iF->name, fld->name, sourceTypes[t], sourceTypes[iV[i].source]);
}
if (NULL != vl)
{
iV[i].source = t;
iV[i].value = vl;
D("Collected %s value for %s - %s = %s", sourceTypes[t], iF->name, fld->name, vl);
}
}
i++;
}
iF->fields->unlock(iF->fields);
return i;
}
void sessionStateEngine(reqData *Rd, char *type)
{
switch (Rd->shs.status)
{
case SHS_UNKNOWN: d("sessionStateEngine(SHS_UNKNOWN, %s)", type); break;
case SHS_NONE: d("sessionStateEngine(SHS_NONE, %s)", type); break;
case SHS_BOGUS: d("sessionStateEngine(SHS_BOGUS, %s)", type); break;
case SHS_PROBLEM: d("sessionStateEngine(SHS_PROBLEM, %s)", type); break;
case SHS_VALID: d("sessionStateEngine(SHS_VALID, %s)", type); break;
case SHS_LOGIN: d("sessionStateEngine(SHS_LOGIN, %s)", type); break;
case SHS_RENEW: d("sessionStateEngine(SHS_RENEW, %s)", type); break;
case SHS_REFRESH: d("sessionStateEngine(SHS_REFRESH, %s)", type); break;
case SHS_IDLE: d("sessionStateEngine(SHS_IDLE, %s)", type); break;
case SHS_ANCIENT: d("sessionStateEngine(SHS_ANCIENT, %s)", type); break;
case SHS_SECURITY: d("sessionStateEngine(SHS_SECURITY, %s)", type); break;
case SHS_RELOGIN: d("sessionStateEngine(SHS_RELOGIN, %s)", type); break;
case SHS_KEEP: d("sessionStateEngine(SHS_KEEP, %s)", type); break;
case SHS_WIPE: d("sessionStateEngine(SHS_WIPE, %s)", type); break;
case SHS_NUKE: d("sessionStateEngine(SHS_NUKE, %s)", type); break;
}
}
void account_html(char *file, reqData *Rd, HTMLfile *thisFile)
{
inputForm *iF;
inputField *fld;
inputSub *sub;
boolean isGET = FALSE;
int e = 0, t = 0, i, j;
char *doit = getStrH(Rd->body, "doit"), *form = getStrH(Rd->body, "form");
if (NULL == accountLevels)
{
accountLevels = qlisttbl(QLISTTBL_LOOKUPFORWARD | QLISTTBL_THREADSAFE | QLISTTBL_UNIQUE);
accountLevels->putstr(accountLevels, "-256", "disabled");
accountLevels->putstr(accountLevels, "-200", "newbie");
accountLevels->putstr(accountLevels, "-100", "validated");
accountLevels->putstr(accountLevels, "-50", "vouched for");
accountLevels->putstr(accountLevels, "0", "approved"); // Note that http://opensimulator.org/wiki/Userlevel claims that 1 and above are "GOD_LIKE".
accountLevels->putstr(accountLevels, "200", "god");
}
// Check "Origin" header and /or HTTP_REFERER header.
// "Origin" is either HTTP_HOST or X-FORWARDED-HOST. Which could be "null".
char *ref = xmprintf("https://%s%s/account.html", getStrH(Rd->headers, "SERVER_NAME"), getStrH(Rd->headers, "SCRIPT_NAME"));
char *href = Rd->headers->getstr(Rd->headers, "HTTP_REFERER", true);
if (NULL != href)
{
char *f = strchr(href, '?');
if (NULL != f)
*f = '\0';
if (('\0' != href[0]) && (strcmp(ref, href) != 0))
{
bitch(Rd, "Invalid referer.", ref);
D("Invalid referer - %s isn't %s", ref, href);
form = "accountLogin";
Rd->shs.status = SHS_PROBLEM;
}
free(href);
}
free(ref);
ref = getStrH(Rd->headers, "SERVER_NAME");
href = getStrH(Rd->headers, "HTTP_HOST");
if ('\0' == href[0])
href = getStrH(Rd->headers, "X-FORWARDED-HOST");
if (('\0' != href[0]) && (strcmp(ref, href) != 0))
{
bitch(Rd, "Invalid HOST.", ref);
D("Invalid HOST - %s isn't %s", ref, href);
form = "accountLogin";
Rd->shs.status = SHS_PROBLEM;
}
// Redirect to HTTPS if it's HTTP.
if (strcmp("https", Rd->Scheme) != 0)
{
Rd->Rheaders->putstr (Rd->Rheaders, "Status", "301 Moved Permanently");
Rd->Rheaders->putstrf(Rd->Rheaders, "Location", "https://%s%s", Rd->Host, Rd->RUri);
Rd->reply->addstrf(Rd->reply, "<html><title>404 Unknown page</title><head>"
"<meta http-equiv='refresh' content='0; URL=https://%s%s' />"
"</head><body>You should get redirected to <a href='https://%s%s'>https://%s%s</a></body></html>",
Rd->Host, Rd->RUri, Rd->Host, Rd->RUri, Rd->Host, Rd->RUri
);
D("Redirecting dynamic page %s -> https://%s%s", file, Rd->Host, Rd->RUri);
return;
}
// Create the dynamic web pages for account.html.
if (NULL == accountPages)
{
accountPages = qhashtbl(0, 0);
iF = newInputForm("accountAdd", "", NULL, accountAddWeb, accountLoginWeb);
addSession(iF);
// fld = addInputField(iF, LUA_TSTRING, "UUID", "UUID", NULL, UUIDValidate, UUIDWeb);
// inputFieldExtra(fld, FLD_HIDDEN, 0, 0);
fld = addInputField(iF, LUA_TSTRING, "name", "name", NULL, nameValidate, nameWeb);
inputFieldExtra(fld, FLD_EDITABLE | FLD_REQUIRED, 42, 63);
fld = addInputField(iF, LUA_TPASSWORD, "psswrd", "Re-enter your password",
"Warning, the limit on password length is set by your viewer, some can't handle longer than 16 characters.", passwordValidate, passwordWeb);
inputFieldExtra(fld, FLD_EDITABLE, 16, 0);
addEmailFields(iF);
addDoBFields(iF);
addLegalFields(iF);
fld = addInputField(iF, LUA_TSTRING, "ToS", "Terms of Service", "", NULL, ToSWeb);
fld = addInputField(iF, LUA_TSTRING, "voucher", "The grid name of someone that will vouch for you",
"We use a vouching system here, an existing member must know you well enough to tell us you'll be good for our grid.", voucherValidate, voucherWeb);
inputFieldExtra(fld, FLD_EDITABLE, 42, 63);
fld = addInputField(iF, LUA_TSTRING, "aboutMe", "About me", NULL, aboutMeValidate, aboutMeWeb);
inputFieldExtra(fld, FLD_EDITABLE, 50, 16384);
addSubmit(iF, "confirm", "confirm", NULL, accountAddSub, "accountView");
addSubmit(iF, "cancel", "cancel", NULL, accountOutSub, "accountLogin");
iF = newInputForm("accountView", "account view", NULL, accountViewWeb, accountLoginWeb);
addSession(iF);
// fld = addInputField(iF, LUA_TSTRING, "UUID", "UUID", NULL, UUIDValidate, UUIDWeb);
// inputFieldExtra(fld, FLD_HIDDEN, 0, 0);
fld = addInputField(iF, LUA_TSTRING, "name", "name", NULL, nameValidate, nameWeb);
inputFieldExtra(fld, FLD_HIDDEN, 42, 63);
fld = addInputField(iF, LUA_TSTRING, "user", "user", NULL, nameValidate, nameWeb);
inputFieldExtra(fld, FLD_HIDDEN, 42, 63);
addSubmit(iF, "login", "", NULL, accountViewSub, "accountView"); // Coz we sometimes want to trigger this from code.
addSubmit(iF, "validate", "", NULL, accountValidateSub, "accountLogin"); // Coz we sometimes want to trigger this from code.
addSubmit(iF, "edit", "", NULL, accountEditSub, "accountEdit"); // Coz we sometimes want to trigger this from code.
addSubmit(iF, "validated_members", "validated members", NULL, accountExploreValidatedVoucherSub, "accountValidated");
addSubmit(iF, "logout", "logout", NULL, accountOutSub, "accountLogin");
iF = newInputForm("accountValidated", "account validated list", NULL, accountExploreValidatedVouchersWeb, accountLoginWeb);
addSession(iF);
fld = addInputField(iF, LUA_TSTRING, "name", "name", NULL, nameValidate, nameWeb);
inputFieldExtra(fld, FLD_HIDDEN, 42, 63);
addSubmit(iF, "login", "", NULL, accountViewSub, "accountView"); // Coz we sometimes want to trigger this from code.
addSubmit(iF, "back", "back", NULL, accountViewSub, "accountView");
iF = newInputForm("accountEdit", "account edit", NULL, accountEditWeb, accountLoginWeb);
addSession(iF);
// fld = addInputField(iF, LUA_TSTRING, "UUID", "UUID", NULL, UUIDValidate, UUIDWeb);
// inputFieldExtra(fld, FLD_HIDDEN, 0, 0);
// fld = addInputField(iF, LUA_TSTRING, "name", "name", NULL, nameValidate, nameWeb);
// inputFieldExtra(fld, FLD_HIDDEN, 42, 63);
// fld = addInputField(iF, LUA_TSTRING, "user", "user", NULL, nameValidate, nameWeb);
// inputFieldExtra(fld, FLD_HIDDEN, 42, 63);
// fld = addInputField(iF, LUA_TEMAIL, "email", "email", "", emailValidate, emailWeb);
// inputFieldExtra(fld, FLD_NONE, 42, 254);
addSubmit(iF, "login", "", NULL, accountViewSub, "accountView"); // Coz we sometimes want to trigger this from code.
addSubmit(iF, "save", "save", NULL, accountSaveSub, "accountView");
addSubmit(iF, "back", "back", NULL, accountViewSub, "accountView");
// addSubmit(iF, "members", "members", NULL, accountExploreSub, "accountExplore");
addSubmit(iF, "logout", "logout", NULL, accountOutSub, "accountLogin");
// addSubmit(iF, "delete", "delete", NULL, accountDelSub, "accountDel");
iF = newInputForm("accountLogin", "account login", "Please login, or create your new account.", accountLoginWeb, accountLoginWeb);
addSession(iF);
fld = addInputField(iF, LUA_TSTRING, "name", "name", "Your name needs to be two words, only ordinary letters and digits, no special characters or fonts.", nameValidate, nameWeb);
inputFieldExtra(fld, FLD_EDITABLE | FLD_REQUIRED, 42, 63);
fld = addInputField(iF, LUA_TPASSWORD, "password", "password",
"Warning, the limit on password length is set by your viewer, some can't handle longer than 16 characters.", passwordValidate, passwordWeb);
inputFieldExtra(fld, FLD_EDITABLE | FLD_REQUIRED, 16, 0);
addSubmit(iF, "logout", "", NULL, accountOutSub, "accountLogin"); // Coz we sometimes want to trigger this from code.
addSubmit(iF, "validate", "", NULL, accountValidateSub, "accountLogin"); // Coz we sometimes want to trigger this from code.
addSubmit(iF, "login", "login", NULL, accountViewSub, "accountView");
addSubmit(iF, "create", "create account", NULL, accountCreateSub, "accountAdd");
}
// Figure out what we are doing.
if ('\0' == form[0])
form = getStrH(Rd->cookies, "form");
if ('\0' == form[0])
{
form = "accountLogin";
Rd->shs.status = SHS_NUKE;
}
if ('\0' == doit[0])
doit = getStrH(Rd->cookies, "doit");
if ('\0' == doit[0])
{
doit = "logout";
Rd->shs.status = SHS_NUKE;
}
if ('\0' != doit[0])
{
setCookie(Rd, "doit", doit);
Rd->doit = doit;
}
iF = accountPages->get(accountPages, form, NULL, false);
if (NULL == iF)
{
E("No such account page - %s", form);
form = "accountLogin";
doit = "logout";
Rd->shs.status = SHS_PROBLEM;
iF = accountPages->get(accountPages, form, NULL, false);
}
sub = iF->subs->get(iF->subs, doit, NULL, false);
if (NULL == sub)
{
E("No such account action - %s", doit);
form = "accountLogin";
doit = "logout";
Rd->shs.status = SHS_PROBLEM;
iF = accountPages->get(accountPages, form, NULL, false);
sub = iF->subs->get(iF->subs, doit, NULL, false);
}
// Special for showing a users details.
if ('\0' != getStrH(Rd->queries, "user")[0])
{
doit = "edit";
form = "accountView";
iF = accountPages->get(accountPages, form, NULL, false);
sub = iF->subs->get(iF->subs, doit, NULL, false);
}
Rd->doit = doit;
Rd->form = form;
Rd->output = sub->outputForm;
C("Starting dynamic page %s %s -> %s [%s -> %s]", Rd->RUri, form, doit, sub->name, Rd->output);
// Collect the input data.
int count = iF->fields->size(iF->fields);
inputValue *iV = xzalloc(count * sizeof(inputValue));
qlisttbl_obj_t obj;
sessionStateEngine(Rd, "collected");
if (strcmp("cancel", sub->name) != 0)
{
// TODO - complain about any extra body or query parameter that we where not expecting.
for (t = 0; t < 3; t++)
i = collectFields(Rd, iF, iV, t);
// Validate the input data.
D("For page %s -> %s, start of validation.", iF->name, sub->name);
t = i;
for (i = 0; i < t; i++)
{
if ((NULL != iV[i].value) || (LUA_TGROUP == iV[i].field->type))
{
if (NULL == iV[i].field->validate)
E("No validation function for %s - %s", iF->name, iV[i].field->name);
else
{
if (0 == iV[i].valid)
{
D("Validating %s - %s", iF->name, iV[i].field->name);
int rt = iV[i].field->validate(Rd, iF, &iV[i]);
if (rt)
{
W("Invalidated %s - %s returned %d errors", iF->name, iV[i].field->name, rt);
iV[i].valid = -1;
}
else
{
D("Validated %s - %s", iF->name, iV[i].field->name);
iV[i].valid = 1;
}
e += rt;
if (NULL != iV[i].field->group)
{
// Use the indexes to set the validation result for the other members of the group.
// The assumption is that the validation functions for each are the same, and it validates the members as a group.
for (j = iV[i].index; j > 0; j--)
iV[i + j].valid = iV[i].valid;
// TODO - Possible off by one error, but I don't think it matters. Needs more testing.
for (j = 0; j <= iV[i].index; j++)
iV[i + j].valid = iV[i].valid;
}
}
else if (0 > iV[i].valid)
D("Already invalidated %s - %s", iF->name, iV[i].field->name);
else if (0 < iV[i].valid)
D("Already validated %s - %s", iF->name, iV[i].field->name);
}
}
doit = Rd->doit;
form = Rd->form;
}
sessionStateEngine(Rd, "validated");
// Submit the data. Reload input form and sub in case things got changed by the validation functions.
iF = accountPages->get(accountPages, Rd->form, NULL, false);
sub = iF->subs->get(iF->subs, Rd->doit, NULL, false);
//if (strcmp("POST", Rd->Method) == 0) // Not such a good idea, since we are faking a submit for account validation, which is a GET.
{
if (0 == e)
{
D("For page %s, start of %s submission.", iF->name, sub->name);
if (NULL != sub->submit)
e += sub->submit(Rd, iF, iV);
}
}
free(iV);
}
else
{
sessionStateEngine(Rd, "CANCELLED");
}
sessionStateEngine(Rd, "submited");
switch (Rd->shs.status)
{
case SHS_RENEW:
case SHS_REFRESH:
{
freeSesh(Rd, FALSE, FALSE);
newSesh(Rd, FALSE);
break;
}
case SHS_VALID:
case SHS_KEEP:
{
// Do nothing here.
break;
}
case SHS_LOGIN:
case SHS_WIPE:
{
// TODO - should wipe the old one, and create this new one with the users UUID.
// I think that's what we are doing anyway.
freeSesh(Rd, FALSE, FALSE);
newSesh(Rd, FALSE);
break;
}
// TODO - these three should store state, so they can go back to where the user was (or where they where going) before asking them to confirm their login credentials.
case SHS_IDLE:
case SHS_SECURITY:
case SHS_RELOGIN:
case SHS_UNKNOWN:
case SHS_NONE:
case SHS_BOGUS:
case SHS_PROBLEM:
case SHS_ANCIENT:
case SHS_NUKE:
{
freeSesh(Rd, FALSE, TRUE); // Wipe mode clears out all of Rd->database, selected Rd->stuff, and the above commented out Rd->shs.
newSesh(Rd, FALSE);
form = "accountLogin";
doit = "logout";
Rd->doit = doit;
Rd->form = form;
iF = accountPages->get(accountPages, Rd->form, NULL, false);
sub = iF->subs->get(iF->subs, Rd->doit, NULL, false);
Rd->output = sub->outputForm;
break;
}
}
// Return the result.
if (0 == e)
{
if (strcmp("GET", Rd->Method) == 0)
{
// Find the output form.
inputForm *oF = accountPages->get(accountPages, Rd->output, NULL, false);
if (NULL == oF)
{
E("No such account page - %s", Rd->output);
form = "accountLogin";
doit = "logout";
oF = accountPages->get(accountPages, form, NULL, false);
}
D("Building output page %s", oF->name);
count = oF->fields->size(oF->fields);
iV = xzalloc(count * sizeof(inputValue));
collectFields(Rd, oF, iV, -1);
collectFields(Rd, oF, iV, 3);
oF->web(Rd, oF, iV);
free(iV);
}
else
{
// Redirect to a GET if it was a POST.
// The reason here is to avoid a refresh turning into a rePOST.
if ((strcmp("POST", Rd->Method) == 0))
{
if ('\0' != Rd->form[0])
setCookie(Rd, "form", Rd->form);
if ('\0' != Rd->doit[0])
setCookie(Rd, "doit", Rd->doit);
Rd->Rheaders->putstr (Rd->Rheaders, "Status", "303 See Other");
Rd->Rheaders->putstrf(Rd->Rheaders, "Location", "https://%s%s%s", Rd->Host, Rd->RUri, Rd->outQuery);
Rd->reply->addstrf(Rd->reply, "<html><title>Post POST redirect</title><head>"
"<meta http-equiv='refresh' content='0; URL=https://%s%s%s' />"
"</head><body>You should get redirected to <a href='https://%s%s%s'>https://%s%s%s</a></body></html>",
Rd->Host, Rd->RUri, Rd->outQuery, Rd->Host, Rd->RUri, Rd->outQuery, Rd->Host, Rd->RUri, Rd->outQuery
);
I("Redirecting dynamic page %s -> https://%s%s%s (%s)", file, Rd->Host, Rd->RUri, Rd->outQuery, Rd->form);
}
}
}
else
{
if (0 < e)
E("Building output ERROR page %s, coz of %d errors.", iF->name, e);
else
D("Building alternate output page %s", iF->name);
// First just sort out input groups, then get the data from Rd->stuff.
count = iF->fields->size(iF->fields);
iV = xzalloc(count * sizeof(inputValue));
collectFields(Rd, iF, iV, -1);
collectFields(Rd, iF, iV, 3);
iF->eWeb(Rd, iF, iV);
free(iV);
}
free(Rd->outQuery);
Rd->outQuery = NULL;
C("Ending dynamic page %s %s", Rd->RUri, form);
}
void forEachMember(char *verb, simFunction func, simFunction not)
{
char *last = xstrdup("0");
if (BACKUP == currentMode)
{
char *file = xmprintf("%s/.lastTime", scBackup);
free(last);
last = (char *) qfile_load(file, NULL);
if (shellMeFail("date +%%s > %s", file))
E("date command failed!");
free(file);
if ((NULL == last) || (NULL != ourSims->target))
{
free(last);
last = xstrdup("0");
}
}
static dbRequest *users = NULL;
if (NULL == users)
{
static char *szi[] = {NULL};
static char *szo[] = {"FirstName", "LastName", "UserLevel", "Online", "LastRegionID", NULL};
users = xzalloc(sizeof(dbRequest));
users->table = "UserAccounts,GridUser";
users->inParams = szi;
users->outParams = szo;
users->where = xmprintf("UserAccounts.PrincipalID=LEFT(GridUser.UserID,36) and GridUser.Login>%s order by LastName,FirstName", last);
dbRequests->addfirst(dbRequests, &users, sizeof(dbRequest *));
}
dbDoSomething(users, FALSE);
rowData *rows = users->rows;
if (rows)
{
qhashtbl_t *row;
while (NULL != (row = rows->rows->getat(rows->rows, 0, NULL, true)))
{
char *firstName = row->getstr(row, "FirstName", false);
char *lastName = row->getstr(row, "LastName", false);
char *name = xmprintf("%s %s", firstName, lastName);
if ((NULL == ourSims->target) || (strcmp(ourSims->target, name) == 0))
{
if (STATUS == currentMode)
{
char *level = row->getstr(row, "UserLevel", false);
char *online = row->getstr(row, "Online", false);
char *region = row->getstr(row, "LastRegionID", false);
simData *simd = ourSims->byUUID->get(ourSims->byUUID, region, NULL, false);
if (NULL != simd)
region = simd->name;
if (strcmp("False", online) == 0)
region = "";
I("Member level %s, online %s, name %s %s @ %s", level, online, firstName, lastName, region);
}
func(NULL, name, "Member", 0, 0, 0, 0);
}
free(name);
row->free(row);
rows->rows->removefirst(rows->rows);
}
free(rows->fieldNames);
rows->rows->free(rows->rows);
free(rows);
}
free(last);
}
static void cleanup(void)
{
C("Caught signal, or quitting, cleaning up.");
char *cmd = xmprintf("%s/sledjchisl.socket", scRun);
if (isWeb && qfile_exist(cmd))
{
V("Deleting web socket.");
if (shellMeFail("rm %s/sledjchisl.socket", scRun))
E("rm command failed!");
}
free(cmd);
if (accountPages)
{
qhashtbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj));
accountPages->lock(accountPages);
while(accountPages->getnext(accountPages, &obj, false) == true)
{
inputForm *f = (inputForm *) obj.data;
f->subs->free(f->subs);
qlisttbl_obj_t fobj;
memset((void *) &fobj, 0, sizeof(fobj));
f->fields->lock(f->fields);
while(f->fields->getnext(f->fields, &fobj, NULL, false) == true)
{
inputField *fld = (inputField *) fobj.data;
if (LUA_TGROUP == fld->type)
free(fld->group);
}
f->fields->unlock(f->fields);
f->fields->free(f->fields);
}
accountPages->unlock(accountPages);
accountPages->free(accountPages);
accountPages = NULL;
}
if (dynPages) dynPages->free(dynPages);
dynPages = NULL;
if (HTMLfileCache)
{
qhashtbl_obj_t obj;
memset((void*)&obj, 0, sizeof(obj));
HTMLfileCache->lock(HTMLfileCache);
while(HTMLfileCache->getnext(HTMLfileCache, &obj, false) == true)
{
HTMLfile *f = (HTMLfile *) obj.data;
unfragize(f->fragments, NULL, TRUE);
}
HTMLfileCache->unlock(HTMLfileCache);
HTMLfileCache->free(HTMLfileCache);
HTMLfileCache = NULL;
}
if (mimeTypes) mimeTypes->free(mimeTypes);
mimeTypes = NULL;
freeDb(true);
if (L) lua_close(L);
L = NULL;
if (stats)
{
if (stats->stats) stats->stats->free(stats->stats);
free(stats);
stats = NULL;
}
if (configs) configs->free(configs);
configs = NULL;
/* tmux should clean up it's own socket. Doesn't seem to care anyway.
cmd = xmprintf("%s/%s", scRun, Tsocket);
if (qfile_exist(cmd))
{
if (shellMeFail("rm %s/%s", scRun, Tsocket))
E("rm command failed!");
}
free(cmd);
*/
}
int scanForConfigs(char **cPaths)
{
int result = FALSE, i;
struct stat st;
for (i = 0; cPaths[i]; i++)
{
if (('/' == cPaths[i][0]) || ('~' == cPaths[i][0]))
snprintf(toybuf, sizeof(toybuf), "%s", cPaths[i]);
else
snprintf(toybuf, sizeof(toybuf), "%s/%s", pwd, cPaths[i]);
if (qfile_exist(toybuf))
{
I("Loading configuration file (maybe) - %s", toybuf);
Lua2hashtbl(toybuf, configs, "config");
result = TRUE;
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Main function.
////////////////////////////////////////////////////////////////////////////////////////////////////
void sledjchisl_main(void)
{
char *cmd = *toys.optargs;
char *tmp, *t0 = NULL, *t1 = NULL;
struct stat statbuf;
int status, result, i;
void *vd;
if(FLAG(v))
VERBOSE = TRUE;
V("SledjChisl command - %s", toys.argv[0]);
V("SledjChisl arguments - %d %d", toys.optc, toys.optflags);
for (i = 0; i < toys.optc; i++)
V(" argument %d %s", i, toys.optargs[i] );
configs = qhashtbl(0, 0);
L = luaL_newstate();
V("libfcgi version: %s", FCGI_VERSION);
V("Lua version: %s", LUA_RELEASE);
V("LuaJIT version: %s", LUAJIT_VERSION);
V("MariaDB / MySQL client version: %s", mysql_get_client_info());
V("OpenSSL version: %s", OPENSSL_VERSION_TEXT);
V("qLibc version: qLibc only git tags for version numbers. Sooo, 2.4.4, unless I forgot to update this.");
V("toybox version: %s", TOYBOX_VERSION);
dbRequests = qlist(0);
sigatexit(cleanup);
pwd = xgetcwd();
V("Running in directory %s", pwd);
if (-1 == fstat(STDIN_FILENO, &statbuf))
{
error_msg("fstat() failed");
if (1 != isatty(STDIN_FILENO))
isWeb = TRUE;
}
else
{
if (S_ISREG (statbuf.st_mode)) D("STDIN is a regular file.");
else if (S_ISDIR (statbuf.st_mode)) D("STDIN is a directory.");
else if (S_ISCHR (statbuf.st_mode)) D("STDIN is a character device.");
else if (S_ISBLK (statbuf.st_mode)) D("STDIN is a block device.");
else if (S_ISFIFO(statbuf.st_mode)) D("STDIN is a FIFO (named pipe).");
else if (S_ISLNK (statbuf.st_mode)) D("STDIN is a symbolic link.");
else if (S_ISSOCK(statbuf.st_mode)) D("STDIN is a socket.");
else D("STDIN is a unknown file descriptor type.");
if (!S_ISCHR(statbuf.st_mode))
isWeb = TRUE;
}
// Print our user name and groups.
struct passwd *pw;
struct group *grp;
uid_t euid = geteuid();
gid_t egid = getegid();
gid_t *groups = (gid_t *)toybuf;
i = sizeof(toybuf)/sizeof(gid_t);
int ngroups;
pw = xgetpwuid(euid);
V("Running as user %s", pw->pw_name);
grp = xgetgrgid(egid);
ngroups = getgroups(i, groups);
if (ngroups < 0) perror_exit("getgroups");
V("User is in group %s", grp->gr_name);
for (i = 0; i < ngroups; i++) {
if (groups[i] != egid)
{
if ((grp = getgrgid(groups[i])))
V("User is in group %s", grp->gr_name);
else
V("User is in group %u", groups[i]);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Read configuration.
////////////////////////////////////////////////////////////////////////////////////////////////////
/* From http://luajit.org/install.html -
To change or extend the list of standard libraries to load, copy
src/lib_init.c to your project and modify it accordingly. Make sure the
jit library is loaded or the JIT compiler will not be activated.
*/
luaL_openlibs(L); // Load Lua libraries.
/* Load the config scripts.
Normally we start in /opt/opensim_SC/current/bin
sledjchisl here is a symlink to ../src/build/toybox/toybox or ../src/build/toybox/generated/unstripped/toybox
So that .sledjChisl.conf.lua is found, which is normally a symlink to ../src/.sledjChisl.conf.lua
Other possibilities -
Normally sledjchisl isn't in the path, though it is once our tmux is running.
No doubt someone will put it in the path, so then we can start anywhere.
Someone could run it from a downloaded opensim-SC and run it from that bin, then it's not installed.
*/
char *cPaths[] =
{
"/etc/sledjChisl.conf.lua",
// "/etc/sledjChisl.d/*.lua",
"~/.sledjChisl.conf.lua",
// "~/.config/sledjChisl/*.lua",
NULL
};
char *oPaths[] =
{
".sledjChisl.conf.lua",
"./etc/sledjChisl.conf.lua",
NULL
};
result = scanForConfigs(cPaths);
result = result | scanForConfigs(oPaths);
if (result)
{
if ((tmp = configs->getstr(configs, "scRoot", false)) != NULL) {scRoot = tmp; V("Setting scRoot = %s", scRoot);}
snprintf(toybuf, sizeof(toybuf), "%s/current/bin", scRoot);
t0 = realpath(pwd, NULL);
t1 = realpath(toybuf, NULL);
if (strcmp(t0, t1) != 0)
{
I("Not in the configured scRoot. %s != %s", t0, t1);
if (qfile_exist(toybuf))
{
chdir(toybuf);
free(pwd);
pwd = xgetcwd();
I("Now running in directory %s", pwd);
free(t0);
t0 = realpath(pwd, NULL);
result = scanForConfigs(cPaths);
result = result | scanForConfigs(oPaths);
}
else
{
C("The configured scRoot doesn't exist! Might need to actually install this. %s", scRoot);
goto finished;
}
}
free(t1);
}
if (result)
{
DEBUG = configs->getint(configs, "debug");
V("Setting DEBUG = %d", DEBUG);
if ((vd = configs->get (configs, "loadAverageInc", NULL, false)) != NULL) {loadAverageInc = *((float *) vd); V("Setting loadAverageInc = %f", loadAverageInc);}
if ((vd = configs->get (configs, "simTimeOut", NULL, false)) != NULL) {simTimeOut = (int) *((float *) vd); V("Setting simTimeOut = %d", simTimeOut);}
if ((vd = configs->get (configs, "bulkSims", NULL, false)) != NULL) {bulkSims = (int) *((float *) vd); V("Setting bulkSims = %d", bulkSims);}
if ((tmp = configs->getstr(configs, "scRoot", false)) != NULL) {scRoot = tmp; V("Setting scRoot = %s", scRoot);}
if ((tmp = configs->getstr(configs, "scUser", false)) != NULL) {scUser = tmp; V("Setting scUser = %s", scUser);}
if ((tmp = configs->getstr(configs, "Tconsole", false)) != NULL) {Tconsole = tmp; V("Setting Tconsole = %s", Tconsole);}
if ((tmp = configs->getstr(configs, "Tsocket", false)) != NULL) {Tsocket = tmp; V("Setting Tsocket = %s", Tsocket);}
if ((tmp = configs->getstr(configs, "Ttab", false)) != NULL) {Ttab = tmp; V("Setting Ttab = %s", Ttab);}
if ((tmp = configs->getstr(configs, "backupIARsim", false)) != NULL) {backupIARsim = tmp; V("Setting backupIARsim = %s", backupIARsim);}
if ((tmp = configs->getstr(configs, "rsync", false)) != NULL) {rSync = tmp; V("Setting rsync = %s", rSync);}
if ((vd = configs->getstr(configs, "rsyncPort", false)) != NULL) {rSyncPort = (int) *((float *) vd); V("Setting rsyncPort = %s", rSyncPort);}
if ((tmp = configs->getstr(configs, "webRoot", false)) != NULL) {webRoot = tmp; V("Setting webRoot = %s", webRoot);}
if ((tmp = configs->getstr(configs, "URL", false)) != NULL) {URL = tmp; V("Setting URL = %s", URL);}
if ((vd = configs->get (configs, "seshRenew", NULL, false)) != NULL) {seshRenew = (int) *((float *) vd); V("Setting seshRenew = %d", seshRenew);}
if ((vd = configs->get (configs, "idleTimeOut", NULL, false)) != NULL) {idleTimeOut = (int) *((float *) vd); V("Setting idleTimeOut = %d", idleTimeOut);}
if ((vd = configs->get (configs, "seshTimeOut", NULL, false)) != NULL) {seshTimeOut = (int) *((float *) vd); V("Setting seshTimeOut = %d", seshTimeOut);}
if ((vd = configs->get (configs, "newbieTimeOut", NULL, false)) != NULL) {newbieTimeOut = (int) *((float *) vd); V("Setting newbieTimeOut = %d", newbieTimeOut);}
if ((tmp = configs->getstr(configs, "ToS", false)) != NULL) {ToS = tmp; V("Setting ToS = %s", ToS);}
if ((tmp = configs->getstr(configs, "webIframers", false)) != NULL) {webIframers = tmp; V("Setting webIframers = %s", webIframers);}
}
else
{
C("No sledjChisl.conf.lua found!");
goto finished;
}
snprintf(toybuf, sizeof(toybuf), "%s/current/bin", scRoot);
t1 = realpath(toybuf, NULL);
if ((NULL != t0) && (strcmp(t0, t1)))
C("scRoot moved unexpectedly, check your sledjChisl.conf.lua files! %s != %s", t0, t1);
free(t1);
free(t0);
/* TODO - stuff that used to be in InstallItAll.sh
Grab old database details from the config/config.ini file.
Check the external requirements are met.
sudo apt install mariadb-server libmariadbclient-dev tmux mono-complete mono-devel nunit uuid-runtime uuid-dev libapache2-mod-fcgid libssl1.0-dev spawn-fcgi
sudo apt install nant
Make sure the database is running.
sudo /etc/init.d/mysql restart
Setup the database stuff.
create database if not exists $MYSQL_DB;
create user if not exists '$MYSQL_USER' identified by '$MYSQL_PASSWORD';
create user if not exists '$MYSQL_USER'@localhost identified by '$MYSQL_PASSWORD';
grant all on $MYSQL_DB.* to '$MYSQL_USER';
grant all on $MYSQL_DB.* to '$MYSQL_USER'@localhost;
FLUSH PRIVILEGES;
Deal with the user.
sudo adduser --system --shell /bin/bash --group ${OS_USER}
sudo addgroup ${USER} ${OS_USER}
Copy the tmux config to user's homes.
Copy this version of opensim-SC to /opt/opensim-SC, and make the current symlink to it.
Copy correct config/config.ini to there.
Put new database credentials in config/config.ini
Build the OpenSim.
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// Sort out directories.
////////////////////////////////////////////////////////////////////////////////////////////////////
// Use a FHS compatible setup -
if (strcmp("/", scRoot) == 0)
{
scBin = "/bin";
scEtc = "/etc/opensim_SC";
scLib = "/usr/lib/opensim_SC";
scRun = "/run/opensim_SC";
scBackup = "/var/backups/opensim_SC";
scCache = "/var/cache/opensim_SC";
scData = "/var/lib/opensim_SC";
scLog = "/var/log/opensim_SC";
scTemp = "/tmp";
}
else if (strcmp("/usr/local", scRoot) == 0)
{
scBin = "/usr/local/bin";
scEtc = "/usr/local/etc/opensim_SC";
scLib = "/usr/local/lib/opensim_SC";
scRun = "/run/opensim_SC";
scBackup = "/var/local/backups/opensim_SC";
scCache = "/var/local/cache/opensim_SC";
scData = "/var/local/lib/opensim_SC";
scLog = "/var/local/log/opensim_SC";
scTemp = "/tmp";
}
else // A place for everything to live, like /opt/opensim_SC
{
char *slsh = "";
if ('/' != scRoot[0])
{
E("scRoot is not an absolute path - %s.", scRoot);
slsh = "/";
}
// The problem here is that OpenSim already uses /opt/opensim_SC/current/bin for all of it's crap, where they mix everything together.
// Don't want it in the path.
// Could put the .dlls into lib. Most of the rest is config files or common assets.
// Or just slowly migrate opensim stuff to FHS.
// TODO - free these. Though valgrind isn't bitching about them.
scBin = xmprintf("%s%s/bin", slsh, scRoot);
scEtc = xmprintf("%s%s/etc", slsh, scRoot);
scLib = xmprintf("%s%s/lib", slsh, scRoot);
scRun = xmprintf("%s%s/var/run", slsh, scRoot);
scBackup = xmprintf("%s%s/var/backups", slsh, scRoot);
scCache = xmprintf("%s%s/var/cache", slsh, scRoot);
scData = xmprintf("%s%s/var/lib", slsh, scRoot);
scLog = xmprintf("%s%s/var/log", slsh, scRoot);
scTemp = xmprintf("%s%s/tmp", slsh, scRoot);
}
// A bit chicken and egg here.
// We need to be the correct user to set the correct perms on the scRun directory
// But we wont be the correct user until we run tmux as that user.
// The path to sledjchisl.socket needs to be readable by the www-data group. So the FCGI socket will work.
// AND it needs to be group sticky on opensimsc group. So the tmux socket will work.
// Put both in scRun, and make it other readable?
// No idea of the SECURITY HOLE that might cause.
if(!qfile_exist(scRun))
{
W("Creating the proper %s directory.", scRun);
if (shellMeFail("sudo -Hu %s mkdir -p %s", scUser, scRun))
{
C("Can't make the %s directory.", scRun);
goto finished;
}
else
{
if (shellMeFail("sudo -Hu %s chmod 2755 %s", scUser, scRun))
{
C("Can't set proper permissions for the %s directory.", scRun);
goto finished;
}
}
}
if (!isWeb)
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// Figure out what and where we are.
////////////////////////////////////////////////////////////////////////////////////////////////////
V("Outputting to a terminal, not a web server.");
// Check if we are already running inside the proper tmux server.
char *eTMUX = getenv("TMUX");
snprintf(toybuf, sizeof(toybuf), "%s/%s", scRun, Tsocket);
if (((eTMUX) && (0 == strncmp(toybuf, eTMUX, strlen(toybuf)))))
{
V("Running inside the proper tmux server. %s", eTMUX);
isTmux = TRUE;
}
else
V("Not running inside the proper tmux server. %s == %s", eTMUX, toybuf);
}
// Note this block of code assumes we are running inside current/bin. Which RunIt.sh does for us. Earlier code also tries to ensure this.
if (!isTmux)
{ // Let's see if the proper tmux server is even running.
i = shellMe("%s %s/%s -q list-sessions 2>/dev/null | grep -q %s:", Tcmd, scRun, Tsocket, Tconsole);
if (WIFEXITED(i))
{
if (0 != WEXITSTATUS(i)) // No such session, create it.
{
char *pre = xmprintf("sudo -Hu %s ", scUser);
memset(toybuf, 0, sizeof(toybuf));
if (strcmp(pw->pw_name, scUser) == 0)
{
I("Not running inside the proper tmux server, starting it.");
pre = xmprintf("");
}
else
{
I("Not running inside the proper tmux server, starting it with sudo.");
// The sudo is only so that the session is owned by opensim, otherwise it's owned by whoever ran this script, which is a likely security hole.
// After the session is created, we rely on the scRun directory to be group sticky, so that anyone in the opensim group can attach to the tmux socket.
pre = xmprintf("sudo -Hu %s ", scUser);
}
snprintf(toybuf, sizeof(toybuf),
"%s %s %s/%s set-option -g default-command 'export PATH=%s:$PATH; bash'\\; "
// Set x,y to huge values, to work around an OpenSim bug.
"new-session -d -x 256 -y 420 -s %s -n '%s' bash -c 'export PATH=%s:$PATH; /usr/bin/valgrind --leak-check=full ./sledjchisl; cd %s/current/bin; bash' \\; "
"split-window -vp 50 -d -t '%s:0.0' \\; "
"split-window -hp 50 -d -t '%s:0.1' \\; "
"split-window -hp 50 -d -t '%s:0.0' "
// TODO - remove this once we handle the fcgi stuff ourselves.
// Make the FCGI socket world read / write, coz we can't set it to group www-data, since -G only works for root, and we ain't root.
// TODO - BIG SECURITY HOLE???
"bash -c 'export PATH=%s:$PATH; "
"spawn-fcgi -n -u %s -s %s/sledjchisl.socket -M 0666 -G www-data -- /usr/bin/valgrind --leak-check=full sledjchisl; "
"cd %s/current/bin; bash'"
,
pre, Tcmd, scRun, Tsocket, scBin, Tconsole, Ttab, scBin, scRoot, Tconsole, Tconsole, Tconsole, scBin, scUser, scRun, scBin, scRoot);
free(pre);
if (shellMeFail(toybuf))
E("tmux new-session command failed! %s", toybuf);
else
{
if (shellMeFail("%s %s/%s select-pane -t 1 -T 'SledjChisl' \\; select-pane -t @0.%%3 -T 'FCGI web server'", Tcmd, scRun, Tsocket))
E("tmux select-pane command failed!");
}
// toybox argument parsing is half working.
if (!FLAG(q))
{
V("Joining the session.");
// Join the session.
if (shellMeFail("%s %s/%s select-window -t '%s' \\; attach-session -t '%s'", Tcmd, scRun, Tsocket, Tconsole, Tconsole))
E("tmux attach-session command failed! %s", toybuf);
}
else
V("NOT joining the session.");
goto finished;
}
}
else
E("tmux list-sessions command failed! %s", toybuf);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Other start up stuff.
////////////////////////////////////////////////////////////////////////////////////////////////////
getSims();
if (isTmux || isWeb)
{
char *d;
mimeTypes = qhashtbl(0, 0);
mimeTypes->putstr(mimeTypes, "gz", "application/gzip");
mimeTypes->putstr(mimeTypes, "js", "application/javascript");
mimeTypes->putstr(mimeTypes, "json", "application/json");
mimeTypes->putstr(mimeTypes, "pdf", "application/pdf");
mimeTypes->putstr(mimeTypes, "rtf", "application/rtf");
mimeTypes->putstr(mimeTypes, "zip", "application/zip");
mimeTypes->putstr(mimeTypes, "xz", "application/x-xz");
mimeTypes->putstr(mimeTypes, "gif", "image/gif");
mimeTypes->putstr(mimeTypes, "png", "image/png");
mimeTypes->putstr(mimeTypes, "jp2", "image/jp2");
mimeTypes->putstr(mimeTypes, "jpg2", "image/jp2");
mimeTypes->putstr(mimeTypes, "jpe", "image/jpeg");
mimeTypes->putstr(mimeTypes, "jpg", "image/jpeg");
mimeTypes->putstr(mimeTypes, "jpeg", "image/jpeg");
mimeTypes->putstr(mimeTypes, "svg", "image/svg+xml");
mimeTypes->putstr(mimeTypes, "svgz", "image/svg+xml");
mimeTypes->putstr(mimeTypes, "tif", "image/tiff");
mimeTypes->putstr(mimeTypes, "tiff", "image/tiff");
mimeTypes->putstr(mimeTypes, "css", "text/css");
mimeTypes->putstr(mimeTypes, "html", "text/html");
mimeTypes->putstr(mimeTypes, "htm", "text/html");
mimeTypes->putstr(mimeTypes, "shtml", "text/html");
// mimeTypes->putstr(mimeTypes, "md", "text/markdown");
// mimeTypes->putstr(mimeTypes, "markdown", "text/markdown");
mimeTypes->putstr(mimeTypes, "txt", "text/plain");
////////////////////////////////////////////////////////////////////////////////////////////////////
// Connect to database.
////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO - it looks like OpenSim invented their own half arsed backwards INI file include system.
// I doubt qLibc supports it, like it supports what seems to be the standard include system.
// Not sure if we need to worry about it just yet.
// TODO - this leaks memory, but it's a bug in qLibc. Send the bug fix upstream.
snprintf(toybuf, sizeof(toybuf), "%s/config/config.ini", scRoot);
qlisttbl_t *qconfig = qconfig_parse_file(NULL, toybuf, '=');
if (NULL == qconfig)
{
E("Can't read config file %s", toybuf);
goto finished;
}
d = qstrunchar(qconfig->getstr(qconfig, "Const.ConnectionString", false), '"', '"');
if (NULL == d)
{
E("No database credentials in %s!", toybuf);
goto finished;
}
else
{
char *p0, *p1, *p2;
if (NULL == (d = strdup(d)))
{
E("Out of memory!");
goto finished;
}
// Data Source=MYSQL_HOST;Database=MYSQL_DB;User ID=MYSQL_USER;Password=MYSQL_PASSWORD;Old Guids=true;
p0 = d;
while (NULL != p0)
{
p1 = strchr(p0, '=');
if (NULL == p1) break;
*p1 = '\0';
p2 = strchr(p1 + 1, ';');
if (NULL == p2) break;
*p2 = '\0';
configs->putstr(configs, p0, p1 + 1); // NOTE - this allocs memory for it's key and it's data.
p0 = p2 + 1;
if ('\0' == *p0)
p0 = NULL;
};
free(d);
}
// TODO - should also load god names, and maybe the SMTP stuff.
// Note that the OpenSim SMTP stuff is ONLY for LSL script usage, we probably want to put it in the Lua config file instead.
if (mysql_library_init(toys.optc, toys.optargs, NULL))
{
E("mysql_library_init() failed!");
goto finished;
}
if (!dbConnect())
goto finished;
// Need to kick this off.
stats = getStats(database, stats);
char *h = qstrunchar(qconfig->getstr(qconfig, "Const.HostName", false), '"', '"');
char *p = qstrunchar(qconfig->getstr(qconfig, "Const.PublicPort", false), '"', '"');
stats->stats->putstr(stats->stats, "grid", qstrunchar(qconfig->getstr(qconfig, "Const.GridName", false), '"', '"'));
stats->stats->putstr(stats->stats, "HostName", h);
stats->stats->putstr(stats->stats, "PublicPort", p);
snprintf(toybuf, sizeof(toybuf), "http://%s:%s/", h, p);
stats->stats->putstr(stats->stats, "uri", toybuf);
qconfig->free(qconfig);
}
if (!isWeb)
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// Start of OpenSim wrangling section.
////////////////////////////////////////////////////////////////////////////////////////////////////
struct sysinfo info;
// TODO - See https://stackoverflow.com/questions/2693948/how-do-i-retrieve-the-number-of-processors-on-c-linux, there are more portable ways, this seems to be GNU specific.
int cpus = (int) sysconf(_SC_NPROCESSORS_CONF), cpusOnline = (int) sysconf(_SC_NPROCESSORS_ONLN);
ourSims->doIt = 1;
if (0 == bulkSims)
bulkSims = (cpusOnline / 3) - 1;
sysinfo(&info);
ourSims->la = info.loads[0]/65536.0;
I("There are %i CPUs, %i of them are online. Doing %i sims at once. LoadAverage = %f", cpus, cpusOnline, bulkSims, ourSims->la);
if (0 == toys.optc)
;
else if (strcmp(toys.optargs[0], "backup") == 0)
currentMode = BACKUP;
else if (strcmp(toys.optargs[0], "gitar") == 0)
currentMode = GITAR;
else if (strcmp(toys.optargs[0], "restart") == 0)
currentMode = RESTART;
else if (strcmp(toys.optargs[0], "start") == 0)
currentMode = START;
else if (strcmp(toys.optargs[0], "status") == 0)
currentMode = STATUS;
else if (strcmp(toys.optargs[0], "stop") == 0)
currentMode = STOP;
if (2 == toys.optc)
ourSims->target = xstrdup(toys.optargs[1]);
else if (3 == toys.optc)
ourSims->target = xmprintf("%s %s", toys.optargs[1], toys.optargs[2]);
else
ourSims->target = NULL;
//V("Doing %s for %s '%s' %s %s", modeStrings[currentMode], FLAG(m) ? "member" : "", ourSims->target, FLAG(q) ? "quiet" : "", FLAG(a) ? "all" : "");
// Start ROBUST or join the tmux session, or just figure out where the sims are running in tmux.
if ((START == currentMode) && !checkSimIsRunning("ROBUST"))
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// Sort out directories, part 2
////////////////////////////////////////////////////////////////////////////////////////////////////
// Doing this here coz at this point we should be the correct user, and we only want to do this during initial startup.
/* From man 7 inode -
S_ISUID 04000 set-user-ID bit
S_ISGID 02000 set-group-ID bit (see below)
S_ISVTX 01000 sticky bit (see below)
S_IRWXU 00700 owner has read, write, and execute permission
S_IRUSR 00400 owner has read permission
S_IWUSR 00200 owner has write permission
S_IXUSR 00100 owner has execute permission
S_IRWXG 00070 group has read, write, and execute permission
S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
S_IRWXO 00007 others (not in group) have read, write, and execute permission
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
The set-group-ID bit (S_ISGID) has several special uses. For a directory, it indicates that BSD semantics is to be used for that directory: files created there inherit their group
ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the
group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking.
The sticky bit (S_ISVTX) on a directory means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory,
and by a privileged process
*/
V("Making directories in %s.", scRoot);
if ((! qfile_exist(scBin)) && (! qfile_mkdir(scBin, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", scBin);
if ((! qfile_exist(scEtc)) && (! qfile_mkdir(scEtc, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", scEtc);
if ((! qfile_exist(scLib)) && (! qfile_mkdir(scLib, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", scLib);
if ((! qfile_exist(scBackup)) && (! qfile_mkdir(scBackup, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", scBackup);
if ((! qfile_exist(scCache)) && (! qfile_mkdir(scCache, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", scCache);
if ((! qfile_exist(scData)) && (! qfile_mkdir(scData, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", scData);
if ((! qfile_exist(scLog)) && (! qfile_mkdir(scLog, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", scLog);
if ((! qfile_exist(scTemp)) && (! qfile_mkdir(scTemp, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", scTemp);
tmp = xmprintf("%s/sessions", scCache);
if ((! qfile_exist(tmp)) && (! qfile_mkdir(tmp, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", tmp);
free(tmp);
tmp = xmprintf("%s/users", scData);
if ((! qfile_exist(tmp)) && (! qfile_mkdir(tmp, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", tmp);
free(tmp);
tmp = xmprintf("%s/db", scData);
if ((! qfile_exist(tmp)) && (! qfile_mkdir(tmp, S_IRWXU | S_IRGRP | S_IXGRP, true))) C("Unable to create path %s", tmp);
free(tmp);
/* TODO - tighten up security.
Make sure correct permissions are set everywhere.
sudo chown -R ${OS_USER}:${OS_USER} ${OS_PATH}
Create the /opt/opensim-SC directory structure.
AssetFiles/data Think OpenSim creates all the sub directories itself?
AssetFiles/tmp/spool Think OpenSim creates all the sub directories itself?
config/config.ini (move that etc/config.ini later)
. var/backups Copy examples/var/backups/*.IAR files, which are the newbie starter inventories.
. var/cache Think OpenSim creates all the sub directories itself?
. var/run HAS to be setup correctly BEFORE we try to start up tmux.
web // Fill it with default web stuff from current -> example..
*/
I("Securing directories and files in %s. This might take awhile.", scRoot);
if (shellMeFail("chmod u=rw,go= %s/config/*.ini", scRoot)) C("Can't set proper permissions for %s/config*.ini", scRoot);
if (shellMeFail("chmod u=rw,go= %s/config/ROBUST/*.ini", scRoot)) C("Can't set proper permissions for %s/config/ROBUST/*.ini", scRoot);
if (shellMeFail("chmod u=rw,go= %s/.sledjChisl.conf.lua", scEtc)) C("Can't set proper permissions for %s/.sledjChisl.conf.lua", scEtc);
if (shellMeFail("chmod ug+rw %s/config", scRoot)) C("Can't set proper permissions for %s/config", scRoot);
if (shellMeFail("chmod g+s %s/config", scRoot)) C("Can't set proper permissions for %s/config", scRoot);
if (shellMeFail("chmod u=rw,go= %s/config/*.ini", scRoot)) C("Can't set proper permissions for %s/config/*.ini", scRoot);
if (shellMeFail("chmod u=rw,go= %s/config/ROBUST/*.ini", scRoot)) C("Can't set proper permissions for %s/configROBUST/*.ini", scRoot);
if (shellMeFail("chmod ug=rwx,o= %s/AssetFiles", scRoot)) C("Can't set proper permissions for %s/AssetFiles", scRoot);
if (shellMeFail("chmod -fR ug=rw,o=,a+X %s", scBackup)) C("Can't set proper permissions for %s", scBackup);
if (shellMeFail("chmod -fR a=r,ug=rw,a+X %s", scBin)) C("Can't set proper permissions for %s", scBin);
if (shellMeFail("chmod -fR ug=rw,o=,a+X %s", scCache)) C("Can't set proper permissions for %s", scCache);
if (shellMeFail("chmod ug=rwx,o= %s", scCache)) C("Can't set proper permissions for %s", scCache);
if (shellMeFail("chmod -fR a=r,ug=rw,a+X %s", scData)) C("Can't set proper permissions for %s", scData);
if (shellMeFail("chmod -fR a=r,ug=rw,a+X %s", scEtc)) C("Can't set proper permissions for %s", scEtc);
if (shellMeFail("chmod u=rw,go= %s/.sledjChisl.conf.lua", scEtc)) C("Can't set proper permissions for %s/.sledjChisl.conf.lua", scEtc);
if (shellMeFail("chmod g+s %s", scEtc)) C("Can't set proper permissions for %s", scEtc);
if (shellMeFail("chmod a+x %s/*.shini", scEtc)) C("Can't set proper permissions for %s/*.shini", scEtc);
if (shellMeFail("chmod -fR a=r,ug=rw,a+X %s", scLib)) C("Can't set proper permissions for %s", scLib);
if (shellMeFail("chmod -fR a=r,ug=rw,a+X %s", scLog)) C("Can't set proper permissions for %s", scLog);
if (shellMeFail("chmod -fR a=r,ug=rw,a+X %s", scTemp)) C("Can't set proper permissions for %s", scTemp);
// if (shellMeFail("chmod -R a+x %s/current/*.sh", scRoot)) C("Can't set proper permissions for %s/current/*.sh", scRoot);
// if (shellMeFail("chmod -R a+x %s/current/scripts/*.sh", scRoot)) C("Can't set proper permissions for %s/current/scripts/*.sh", scRoot);
// if (shellMeFail("chmod -R a+x %s/current/scripts/install/*.sh", scRoot)) C("Can't set proper permissions for %s/current/scripts/install/*.sh", scRoot);
// if (shellMeFail("chmod a+x %s/current/scripts/show-console", scRoot)) C("Can't set proper permissions for %s/current/scripts/show-console", scRoot);
// if (shellMeFail("chmod a+x %s/current/scripts/start-sim", scRoot)) C("Can't set proper permissions for %s/current/scripts/start-sim", scRoot);
char *newPath = xmprintf("%s/current/bin/sledjchisl", scRoot);
tmp = xmprintf("%s/sledjchisl", scBin);
V("Symlinking %s to %s", newPath, tmp);
if (qfile_exist(tmp))
{
if (shellMeFail("rm %s", tmp))
E("rm command failed!");
}
if (0 != symlink(newPath, tmp))
perror_msg("Symlinking %s to %s", newPath, tmp);
free(tmp);
free(newPath);
char *c = xmprintf("cd %s/current/bin", scRoot);
I("ROBUST is starting up.");
sendTmuxCmd("@0.%1", c);
free(c);
c = xmprintf("mono Robust.exe -inidirectory=%s/config/ROBUST", scRoot);
sendTmuxCmd("@0.%1", c);
free(c);
doTmuxCmd("select-pane -t @0.%%1 -T 'ROBUST'", Tcmd, scRun, Tsocket);
// Create all the tmux windows, panes, and temporary .ini files coz OpenSim sucketh.
forEachSim("Prepping", prepSims, NULL);
waitTmuxText("@0.%1", "INITIALIZATION COMPLETE FOR ROBUST");
I("ROBUST is done starting up.");
}
else if ((0 == toys.optc) && (checkSimIsRunning("ROBUST")))
{
// Join the session.
doTmuxCmd("select-window -t '%s' \\; attach-session -t '%s'", Tconsole, Tconsole);
goto finished;
}
else // Find out where the sims are in tmux.
forEachSim(NULL, findSimsTmux, NULL);
if (FLAG(m))
{
// Do stuff with the members.
ourSims->doIt = 1;
// Find the correct window to do backups in.
forEachSim(NULL, findWindow, NULL);
forEachMember("Doing", doSimsThing, NULL);
}
else
{
// Do stuff with the sims.
ourSims->doIt = 1;
forEachSim("Doing", doSimsThing, NULL);
}
if ((STOP == currentMode) && (NULL == ourSims->target))
{
// Stop all the sims.
I("Stopping all the sims.");
ourSims->doIt = 1;
forEachSim(NULL, stopSims, NULL);
if (ourSims->doIt)
{
if (checkSimIsRunning("ROBUST"))
{
I("Stopping ROBUST.");
sendTmuxCmd("@0.%1", "quit");
while (checkSimIsRunning("ROBUST"))
usleep(100000);
usleep(100000);
sendTmuxCmd("@0.%1", "exit");
usleep(100000);
sendTmuxCmd("@0.%1", "exit");
I("ROBUST has stopped in tmux ID @0.%%1.");
}
if (FLAG(a))
{
I("Closing all the other windows.");
// First figure out what panes and windows are left.
shellMeFail("echo 'IDs={' >%s/IDs_ALL.lua", scTemp);
doTmuxCmd("list-panes -s -F '\"#{window_id}.#{pane_id}\",' >> %s/IDs_ALL.lua", scTemp);
shellMeFail("echo '}\nreturn IDs' >>%s/IDs_ALL.lua", scTemp);
snprintf(toybuf, sizeof(toybuf), "%s/IDs_ALL.lua", scTemp);
qtreetbl_t *IDs = Lua2tree(toybuf, "IDs");
if (shellMeFail("rm -fr %s/*", scTemp))
E("rm command failed! %s/*", scTemp);
qtreetbl_obj_t obj0;
memset((void*)&obj0, 0, sizeof(obj0));
IDs->lock(IDs);
while(IDs->getnext(IDs, &obj0, false) == true)
{
qLua *q0 = obj0.data;
if ('0' != q0->v.s[1])
doTmuxCmd("kill-pane -t %s", q0->v.s);
}
IDs->unlock(IDs);
I("Closing the original window.");
memset((void*)&obj0, 0, sizeof(obj0));
IDs->lock(IDs);
while(IDs->getnext(IDs, &obj0, false) == true)
{
qLua *q0 = obj0.data;
if ('0' == q0->v.s[1])
doTmuxCmd("kill-pane -t %s", q0->v.s);
}
IDs->unlock(IDs);
freeLuaTree(IDs);
}
}
}
}
else
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// Start of web wrangling section.
////////////////////////////////////////////////////////////////////////////////////////////////////
char **initialEnv = environ;
char *tmp0, *tmp1;
int count = 0, entries, bytes;
dynPages = qhashtbl(0, 0);
newDynPage("account.html", (pageFunction) account_html);
// FCGI_LISTENSOCK_FILENO is the socket to the web server.
// STDOUT and STDERR go to the web servers error log, or at least it does in Apache 2 mod_fcgid.
I("Running SledjChisl inside a web server, pid %d.", getpid());
if (0 == toys.optc)
D("no args");
else
{
for (entries = 0, bytes = -1; entries < toys.optc; entries++)
D("ARG %s\n", toys.optargs[entries]);
}
printEnv(environ);
////////////////////////////////////////////////////////////////////////////////////////////////////
// Web processing loop.
////////////////////////////////////////////////////////////////////////////////////////////////////
/*
? https://stackoverflow.com/questions/30707792/how-to-disable-buffering-with-apache2-and-mod-proxy-fcgi
https://z-issue.com/wp/apache-2-4-the-event-mpm-php-via-mod_proxy_fcgi-and-php-fpm-with-vhosts/
A lengthy and detailed "how to set this up with PHP" that might be useful.
https://www.apachelounge.com/viewtopic.php?t=4385
"Also the new mod_proxy_fcgi for Apache 2.4 seems to be crippled just like mod_fcgid in terms of being limited to just one request per process at a time."
But then so is the silly fcgi2 SDK, which basically assumes it's a CGI wrapper, not proper FCGI.
+ I could even start the spawn-fcgi process from the tmux instance of sledjchisl.
+ Orrr just open the socket / port myself from the tmux instance and do the raw FCGI thing through it.
*/
while (FCGI_Accept() != -1)
{
reqData *Rd = xzalloc(sizeof(reqData));
if (-1 == clock_gettime(CLOCK_REALTIME, &Rd->then))
perror_msg("Unable to get the time.");
Rd->L = L;
Rd->configs = configs;
// Rd->queries = qhashtbl(0, 0); // Inited in toknize below.
// Rd->body = qhashtbl(0, 0); // Inited in toknize below.
// Rd->cookies = qhashtbl(0, 0); // Inited in toknize below.
Rd->headers = qhashtbl(0, 0);
Rd->valid = qhashtbl(0, 0);
Rd->stuff = qhashtbl(0, 0);
Rd->database = qhashtbl(0, 0);
Rd->Rcookies = qhashtbl(0, 0);
Rd->Rheaders = qhashtbl(0, 0);
Rd->stats = stats;
Rd->errors = qlist(0);
Rd->messages = qlist(0);
Rd->reply = qgrow(QGROW_THREADSAFE);
Rd->outQuery = xstrdup("");
Rd->shs.status = SHS_UNKNOWN;
qhashtbl_obj_t hobj;
qlist_obj_t lobj;
// So far I'm seeing these as all caps, but I don't think they are defined that way. Case insensitive per the spec.
// So convert them now, also "-" -> "_".
t("HEADERS");
char **envp = environ;
for ( ; *envp != NULL; envp++)
{
char *k = xstrdup(*envp);
char *v = strchr(k, '=');
if (NULL != v)
{
*v = '\0';
char *ky = qstrreplace("tr", qstrupper(k), "-", "_");
Rd->headers->putstr(Rd->headers, ky, v + 1);
if ((strcmp("HTTP_COOKIE", ky) == 0) || (strcmp("CONTENT_LENGTH", ky) == 0) || (strcmp("QUERY_STRING", ky) == 0))
d(" %s = %s", ky, v + 1);
}
free(k);
}
// The FCGI paramaters sent from the server, are converted to environment variablse for the fcgi2 SDK.
// The FCGI spec doesn't mention what these are. except FCGI_WEB_SERVER_ADDRS.
char *Role = Rd->headers->getstr(Rd->headers, "FCGI_ROLE", false);
Rd->Path = Rd->headers->getstr(Rd->headers, "PATH_INFO", false);
// if (NULL == Rd->Path) {msleep(1000); continue;}
char *Length = Rd->headers->getstr(Rd->headers, "CONTENT_LENGTH", false);
//char *Type = Rd->headers->getstr(Rd->headers, "CONTENT_TYPE", false);
Rd->Method = Rd->headers->getstr(Rd->headers, "REQUEST_METHOD", false);
Rd->Script = Rd->headers->getstr(Rd->headers, "SCRIPT_NAME", false);
Rd->Scheme = Rd->headers->getstr(Rd->headers, "REQUEST_SCHEME", false);
Rd->Host = Rd->headers->getstr(Rd->headers, "HTTP_HOST", false);
//char *SUri = Rd->headers->getstr(Rd->headers, "SCRIPT_URI", false);
Rd->RUri = Rd->headers->getstr(Rd->headers, "REQUEST_URI", true);
//char *Cookies = Rd->headers->getstr(Rd->headers, "HTTP_COOKIE", false);
//char *Referer = Rd->headers->getstr(Rd->headers, "HTTP_REFERER", false);
//char *RAddr = Rd->headers->getstr(Rd->headers, "REMOTE_ADDR", false);
//char *Cache = Rd->headers->getstr(Rd->headers, "HTTP_CACHE_CONTROL", false);
//char *FAddrs = Rd->headers->getstr(Rd->headers, "FCGI_WEB_SERVER_ADDRS", false);
//char *Since = Rd->headers->getstr(Rd->headers, "IF_MODIFIED_SINCE", false);
/* Per the spec CGI https://www.ietf.org/rfc/rfc3875
meta-variable-name = "AUTH_TYPE" | "CONTENT_LENGTH" |
"CONTENT_TYPE" | "GATEWAY_INTERFACE" |
"PATH_INFO" | "PATH_TRANSLATED" |
"QUERY_STRING" | "REMOTE_ADDR" |
"REMOTE_HOST" | "REMOTE_IDENT" |
"REMOTE_USER" | "REQUEST_METHOD" |
"SCRIPT_NAME" | "SERVER_NAME" |
"SERVER_PORT" | "SERVER_PROTOCOL" |
"SERVER_SOFTWARE"
Also protocol / scheme specific ones -
HTTP_* comes from some of the request header. The rest are likely part of the other env variables.
Also covers HTTPS headers, with the HTTP_* names.
*/
t("COOKIES");
Rd->cookies = toknize(Rd->headers->getstr(Rd->headers, "HTTP_COOKIE", false), "=;");
santize(Rd->cookies);
if (strcmp("GET", Rd->Method) == 0)
{ // In theory a POST has body fields INSTEAD of query fields. Especially for ignoring the linky-hashish after the validation page.
t("QUERY");
Rd->queries = toknize(Rd->headers->getstr(Rd->headers, "QUERY_STRING", false), "=&");
santize(Rd->queries);
}
else
{
T("ignoring QUERY");
Rd->queries = qhashtbl(0, 0);
free(Rd->RUri);
Rd->RUri = xmprintf("%s%s", Rd->Script, Rd->Path);
}
t("BODY");
char *Body = NULL;
if (Length != NULL)
{
size_t len = strtol(Length, NULL, 10);
Body = xmalloc(len + 1);
int c = FCGI_fread(Body, 1, len, FCGI_stdin);
if (c != len)
{
E("Tried to read %d of the body, only got %d!", len, c);
}
Body[len] = '\0';
}
else
Length = "0";
Rd->body = toknize(Body, "=&");
free(Body);
santize(Rd->body);
D("%s %s://%s%s -> %s%s", Rd->Method, Rd->Scheme, Rd->Host, Rd->RUri, webRoot, Rd->Path);
D("Started FCGI web request ROLE = %s, body is %s bytes, pid %d.", Role, Length, getpid());
if (NULL == Rd->Path)
{
E("NULL path in FCGI request!");
Rd->Rheaders->putstr(Rd->Rheaders, "Status", "404 Not Found");
goto sendReply;
}
/* TODO - other headers may include -
different Content-type
Status: 304 Not Modified
Last-Modified: timedatemumble
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
*/
Rd->Rheaders->putstr(Rd->Rheaders, "Status", "200 OK");
Rd->Rheaders->putstr(Rd->Rheaders, "Content-type", "text/html");
// TODO - check these.
// This is all dynamic web pages, and likeley secure to.
// Most of these are from https://www.smashingmagazine.com/2017/04/secure-web-app-http-headers/
// https://www.twilio.com/blog/a-http-headers-for-the-responsible-developer is good to, and includes useful compression and image stuff.
// On the other hand, .css files are referenced, which might be better off being cached, so should tweak some of thees.
Rd->Rheaders->putstr(Rd->Rheaders, "Cache-Control", "no-cache, no-store, must-revalidate");
Rd->Rheaders->putstr(Rd->Rheaders, "Pragma", "no-cache");
Rd->Rheaders->putstr(Rd->Rheaders, "Expires", "-1");
Rd->Rheaders->putstr(Rd->Rheaders, "Strict-Transport-Security", "max-age=63072000"); // Two years.
// TODO - do something about this -
/* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src
"Note: Disallowing inline styles and inline scripts is one of
the biggest security wins CSP provides. However, if you
absolutely have to use it, there are a few mechanisms that
will allow them."
WTF? And the mechanisms include nonces, hashes, or 'unsafe-inline'.
Not sure why inline styles need to be that secure, when downloaded ones are not.
Ah, it's for user input that is sent back to other users, they might include funky CSS in their input.
SOOOO, proper validation and escaping is needed.
OOOOR, use the nonce, and make it a different nonce per page serve.
OOOOR, just put all the style stuff in a .css file. Then we can use style-src 'self' without the 'unsafe-inline'?
There's only one block of <style in the header I think.
*/
// Content-Security-Policy can get complex, and I first wrote that when it was very simple. lol
if ('\0' != webIframers[0])
Rd->Rheaders->putstrf(Rd->Rheaders, "Content-Security-Policy",
"default-src 'self'; script-src 'none'; form-action 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self' %s", webIframers);
else
{
Rd->Rheaders->putstr(Rd->Rheaders, "Content-Security-Policy", "default-src 'self'; script-src 'none'; form-action 'self'; style-src 'self' 'unsafe-inline'");
Rd->Rheaders->putstr(Rd->Rheaders, "X-Frame-Options", "SAMEORIGIN"); // This is deprecated, and is an all or nothing thing.
}
Rd->Rheaders->putstr(Rd->Rheaders, "X-XSS-Protection", "1;mode=block");
Rd->Rheaders->putstr(Rd->Rheaders, "X-Content-Type-Options", "nosniff");
// Failed experiment, looks like JavaScript is the only way to change headers for the session ID.
// Rd->Rheaders->putstr(Rd->Rheaders, "X-Toke-N-Munchie", "foo, bar");
if ((strcmp("GET", Rd->Method) != 0) && (strcmp("HEAD", Rd->Method) != 0) && (strcmp("POST", Rd->Method) != 0))
{
E("Unsupported HTTP method %s", Rd->Method);
Rd->Rheaders->putstr(Rd->Rheaders, "Status", "405 Method Not Allowed");
goto sendReply;
}
memset(toybuf, 0, sizeof(toybuf));
snprintf(toybuf, sizeof(toybuf), "%s%s", webRoot, Rd->Path);
HTMLfile *thisFile = checkHTMLcache(toybuf);
if (NULL == thisFile)
{
dynPage *dp = dynPages->get(dynPages, &Rd->Path[1], NULL, false);
if (NULL == dp)
{
E("Can't access file %s", toybuf);
Rd->Rheaders->putstr(Rd->Rheaders, "Status", "404 Not Found");
E("Failed to open %s, it's not a virtual file either", toybuf);
goto sendReply;
}
dp->func(toybuf, Rd, thisFile);
char *finl = Rd->reply->tostring(Rd->reply); // This mallocs new storage and returns it to us.
// TODO - maybe cache this?
qlist_t *fragments = fragize(finl, Rd->reply->datasize(Rd->reply));
Rd->reply->free(Rd->reply);
Rd->reply = qgrow(QGROW_THREADSAFE);
unfragize(fragments, Rd, TRUE);
free(finl);
goto sendReply;
}
tmp0 = qfile_get_ext(toybuf);
tmp1 = mimeTypes->getstr(mimeTypes, tmp0, false);
free(tmp0);
if (NULL != tmp1)
{
if (strncmp("text/", tmp1, 5) != 0)
{
E("Only text formats are supported - %s", toybuf);
Rd->Rheaders->putstr(Rd->Rheaders, "Status", "415 Unsupported Media Type");
goto sendReply;
}
}
else
{
E("Not actually a teapot, er I mean file has no extension, can't determine media type the easy way - %s", toybuf);
Rd->Rheaders->putstr(Rd->Rheaders, "Status", "418 I'm a teapot");
goto sendReply;
}
// Rd->Rheaders->putstr(Rd->Rheaders, "Last-Modified", thisFile->last.tv_sec);
// This is dynamic content, it's always gonna be modified. I think.
// if (NULL != Since)
// {
// time_t snc = qtime_parse_gmtstr(Since);
// TODO - should validate the time, log and ignore it if not valid.
// if (thisFile->last.tv_sec < snc)
// {
// D("Status: 304 Not Modified - %s", toybuf);
// setHeader("Status", "304 Not Modified");
// goto sendReply;
// }
// }
if (strcmp("HEAD", Rd->Method) == 0)
goto sendReply;
getStats(database, stats);
unfragize(thisFile->fragments, Rd, FALSE);
free(thisFile);
sendReply:
/* Send headers.
BTW, the Status header should be sent first I think.
https://www.ietf.org/rfc/rfc3875 6.2 says order isn't important.
It even says Status is optional, 200 is assumed. Content-Type is mandatory.
8.2 "Recommendations for Scripts" is worth complying with.
9 "Security Considerations"
https://tools.ietf.org/html/rfc7230 3.1.2 says status line must be first. lol
*/
FCGI_printf("Status: %s\r\n", getStrH(Rd->Rheaders, "Status"));
memset((void *) &hobj, 0, sizeof(hobj));
Rd->Rheaders->lock(Rd->Rheaders);
while (Rd->Rheaders->getnext(Rd->Rheaders, &hobj, false) == true)
{
if (strcmp("Status", (char *) hobj.name) != 0)
FCGI_printf("%s: %s\r\n", (char *) hobj.name, (char *) hobj.data);
}
Rd->Rheaders->unlock(Rd->Rheaders);
// Send cookies.
memset((void *) &hobj, 0, sizeof(hobj));
Rd->Rcookies->lock(Rd->Rcookies);
while (Rd->Rcookies->getnext(Rd->Rcookies, &hobj, false) == true)
{
cookie *ck = (cookie *) hobj.data;
FCGI_printf("Set-Cookie: %s=%s", hobj.name, ck->value);
// if (NULL != ck->expires) FCGI_printf("; Expires=%s", ck->expires);
if (NULL != ck->domain) FCGI_printf("; Domain=%s", ck->domain);
if (NULL != ck->path) FCGI_printf("; Path=%s", ck->path);
if (0 != ck->maxAge) FCGI_printf("; Max-Age=%d", ck->maxAge);
if ( ck->secure) FCGI_printf("; Secure");
if ( ck->httpOnly) FCGI_printf("; HttpOnly");
if (CS_STRICT == ck->site) FCGI_printf("; SameSite=Strict");
if (CS_LAX == ck->site) FCGI_printf("; SameSite=Lax");
if (CS_NONE == ck->site) FCGI_printf("; SameSite=None");
FCGI_printf("\r\n");
free(ck->value);
ck->value = NULL;
}
FCGI_printf("\r\n");
Rd->cookies->unlock(Rd->cookies);
// Send body.
char *final = Rd->reply->tostring(Rd->reply);
if (NULL == final)
{
tmp0 = Rd->Rheaders->getstr(Rd->Rheaders, "Status", false);
if (NULL == tmp0)
{
E("Some sort of error happpened! Status: UNKNOWN!!");
FCGI_printf("Some sort of error happpened! Status: UNKNOWN!!");
}
else
{
E("Some sort of error happpened! Status: %s", tmp0);
FCGI_printf("Some sort of error happpened! Status: %s", tmp0);
}
}
else
{
FCGI_printf("%s", final);
free(final);
}
fcgiDone:
FCGI_Finish();
snprintf(toybuf, sizeof(toybuf), " for %s %s://%s%s -> %s%s", Rd->Method, Rd->Scheme, Rd->Host, Rd->RUri, webRoot, Rd->Path);
if (NULL != Rd->outQuery) free(Rd->outQuery);
if (NULL != Rd->shs.name) free(Rd->shs.name);
Rd->shs.name = NULL;
if (NULL != Rd->shs.UUID) free(Rd->shs.UUID);
Rd->shs.UUID = NULL;
qgrow_free(Rd->reply);
qlist_free(Rd->messages);
qlist_free(Rd->errors);
qhashtbl_free(Rd->Rheaders);
qhashtbl_free(Rd->Rcookies);
qhashtbl_free(Rd->database);
qhashtbl_free(Rd->stuff);
qhashtbl_free(Rd->valid);
qhashtbl_free(Rd->headers);
qhashtbl_free(Rd->cookies);
qhashtbl_free(Rd->body);
qhashtbl_free(Rd->queries);
if (Rd->lnk) free(Rd->lnk);
free(Rd->RUri);
struct timespec now;
if (-1 == clock_gettime(CLOCK_REALTIME, &now))
perror_msg("Unable to get the time.");
double n = (now.tv_sec * 1000000000.0) + now.tv_nsec;
double t = (Rd->then.tv_sec * 1000000000.0) + Rd->then.tv_nsec;
T("Finished web request, took %lf seconds%s", (n - t) / 1000000000.0, toybuf);
free(Rd);
}
FCGI_fprintf(FCGI_stderr, "Stopped SledjChisl web server.\n");
V("Stopped SledjChisl web server.");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// End of web wrangling section.
////////////////////////////////////////////////////////////////////////////////////////////////////
/*
double sum;
// Load the file containing the script we are going to run
status = luaL_loadfile(L, "script.lua");
if (status)
{
// If something went wrong, error message is at the top of the stack
E("Couldn't load file: %s", lua_tostring(L, -1));
goto finished;
}
*/
/*
* Ok, now here we go: We pass data to the lua script on the stack.
* That is, we first have to prepare Lua's virtual stack the way we
* want the script to receive it, then ask Lua to run it.
*/
// lua_newtable(L); /* We will pass a table */
/*
* To put values into the table, we first push the index, then the
* value, and then call lua_rawset() with the index of the table in the
* stack. Let's see why it's -3: In Lua, the value -1 always refers to
* the top of the stack. When you create the table with lua_newtable(),
* the table gets pushed into the top of the stack. When you push the
* index and then the cell value, the stack looks like:
*
* <- [stack bottom] -- table, index, value [top]
*
* So the -1 will refer to the cell value, thus -3 is used to refer to
* the table itself. Note that lua_rawset() pops the two last elements
* of the stack, so that after it has been called, the table is at the
* top of the stack.
*/
/*
for (i = 1; i <= 5; i++)
{
lua_pushnumber(L, i); // Push the table index
lua_pushnumber(L, i*2); // Push the cell value
lua_rawset(L, -3); // Stores the pair in the table
}
// By what name is the script going to reference our table?
lua_setglobal(L, "foo");
// Ask Lua to run our little script
result = lua_pcall(L, 0, LUA_MULTRET, 0);
if (result)
{
E("Failed to run script: %s", lua_tostring(L, -1));
goto finished;
}
// Get the returned value at the top of the stack (index -1)
sum = lua_tonumber(L, -1);
I("Script returned: %.0f", sum);
lua_pop(L, 1); // Take the returned value out of the stack
*/
finished:
freeSimList(ourSims);
ourSims = NULL;
// An example of calling a toy directly.
// printf("\n\n");
// char *argv[] = {"ls", "-l", "-a", NULL};
// printf("%d\n", runToy(argv));
puts("This is the end my friend.");
fflush(stdout);
}
|