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
|
/*****************************************************************************
$Id$
File: binder.cpp
Date: 07Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
#define DEV_URANDOM "/dev/urandom"
map<string, Bindable_t*> Bindable_t::BindingBag;
/********************************
STATIC Bindable_t::CreateBinding
********************************/
string Bindable_t::CreateBinding()
{
static int index = 0;
static string seed;
if ((index >= 1000000) || (seed.length() == 0)) {
#ifdef OS_UNIX
int fd = open (DEV_URANDOM, O_RDONLY);
if (fd < 0)
throw std::runtime_error ("No entropy device");
unsigned char u[16];
size_t r = read (fd, u, sizeof(u));
if (r < sizeof(u))
throw std::runtime_error ("Unable to read entropy device");
unsigned char *u1 = (unsigned char*)u;
char u2 [sizeof(u) * 2 + 1];
for (size_t i=0; i < sizeof(u); i++)
sprintf (u2 + (i * 2), "%02x", u1[i]);
seed = string (u2);
#endif
#ifdef OS_WIN32
UUID uuid;
UuidCreate (&uuid);
unsigned char *uuidstring = NULL;
UuidToString (&uuid, &uuidstring);
if (!uuidstring)
throw std::runtime_error ("Unable to read uuid");
seed = string ((const char*)uuidstring);
RpcStringFree (&uuidstring);
#endif
index = 0;
}
stringstream ss;
ss << seed << (++index);
return ss.str();
}
/*****************************
STATIC: Bindable_t::GetObject
*****************************/
Bindable_t *Bindable_t::GetObject (const char *binding)
{
string s (binding ? binding : "");
return GetObject (s);
}
/*****************************
STATIC: Bindable_t::GetObject
*****************************/
Bindable_t *Bindable_t::GetObject (const string &binding)
{
map<string, Bindable_t*>::const_iterator i = BindingBag.find (binding);
if (i != BindingBag.end())
return i->second;
else
return NULL;
}
/**********************
Bindable_t::Bindable_t
**********************/
Bindable_t::Bindable_t()
{
Binding = Bindable_t::CreateBinding();
BindingBag [Binding] = this;
}
/***********************
Bindable_t::~Bindable_t
***********************/
Bindable_t::~Bindable_t()
{
BindingBag.erase (Binding);
}
/*****************************************************************************
$Id$
File: cmain.cpp
Date: 06Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
static EventMachine_t *EventMachine;
static int bUseEpoll = 0;
static int bUseKqueue = 0;
extern "C" void ensure_eventmachine (const char *caller = "unknown caller")
{
if (!EventMachine) {
const int err_size = 128;
char err_string[err_size];
snprintf (err_string, err_size, "eventmachine not initialized: %s", caller);
#ifdef BUILD_FOR_RUBY
rb_raise(rb_eRuntimeError, err_string);
#else
throw std::runtime_error (err_string);
#endif
}
}
/***********************
evma_initialize_library
***********************/
extern "C" void evma_initialize_library (void(*cb)(const char*, int, const char*, int))
{
// Probably a bad idea to mess with the signal mask of a process
// we're just being linked into.
//InstallSignalHandlers();
if (EventMachine)
#ifdef BUILD_FOR_RUBY
rb_raise(rb_eRuntimeError, "eventmachine already initialized: evma_initialize_library");
#else
throw std::runtime_error ("eventmachine already initialized: evma_initialize_library");
#endif
EventMachine = new EventMachine_t (cb);
if (bUseEpoll)
EventMachine->_UseEpoll();
if (bUseKqueue)
EventMachine->_UseKqueue();
}
/********************
evma_release_library
********************/
extern "C" void evma_release_library()
{
ensure_eventmachine("evma_release_library");
delete EventMachine;
EventMachine = NULL;
}
/****************
evma_run_machine
****************/
extern "C" void evma_run_machine()
{
ensure_eventmachine("evma_run_machine");
EventMachine->Run();
}
/**************************
evma_install_oneshot_timer
**************************/
extern "C" const char *evma_install_oneshot_timer (int seconds)
{
ensure_eventmachine("evma_install_oneshot_timer");
return EventMachine->InstallOneshotTimer (seconds);
}
/**********************
evma_connect_to_server
**********************/
extern "C" const char *evma_connect_to_server (const char *server, int port)
{
ensure_eventmachine("evma_connect_to_server");
return EventMachine->ConnectToServer (server, port);
}
/***************************
evma_connect_to_unix_server
***************************/
extern "C" const char *evma_connect_to_unix_server (const char *server)
{
ensure_eventmachine("evma_connect_to_unix_server");
return EventMachine->ConnectToUnixServer (server);
}
/**************
evma_attach_fd
**************/
extern "C" const char *evma_attach_fd (int file_descriptor, int notify_readable, int notify_writable)
{
ensure_eventmachine("evma_attach_fd");
return EventMachine->AttachFD (file_descriptor, (notify_readable ? true : false), (notify_writable ? true : false));
}
/**************
evma_detach_fd
**************/
extern "C" int evma_detach_fd (const char *binding)
{
ensure_eventmachine("evma_dettach_fd");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed)
return EventMachine->DetachFD (ed);
else
#ifdef BUILD_FOR_RUBY
rb_raise(rb_eRuntimeError, "invalid binding to detach");
#else
throw std::runtime_error ("invalid binding to detach");
#endif
}
/**********************
evma_create_tcp_server
**********************/
extern "C" const char *evma_create_tcp_server (const char *address, int port)
{
ensure_eventmachine("evma_create_tcp_server");
return EventMachine->CreateTcpServer (address, port);
}
/******************************
evma_create_unix_domain_server
******************************/
extern "C" const char *evma_create_unix_domain_server (const char *filename)
{
ensure_eventmachine("evma_create_unix_domain_server");
return EventMachine->CreateUnixDomainServer (filename);
}
/*************************
evma_open_datagram_socket
*************************/
extern "C" const char *evma_open_datagram_socket (const char *address, int port)
{
ensure_eventmachine("evma_open_datagram_socket");
return EventMachine->OpenDatagramSocket (address, port);
}
/******************
evma_open_keyboard
******************/
extern "C" const char *evma_open_keyboard()
{
ensure_eventmachine("evma_open_keyboard");
return EventMachine->OpenKeyboard();
}
/****************************
evma_send_data_to_connection
****************************/
extern "C" int evma_send_data_to_connection (const char *binding, const char *data, int data_length)
{
ensure_eventmachine("evma_send_data_to_connection");
return ConnectionDescriptor::SendDataToConnection (binding, data, data_length);
}
/******************
evma_send_datagram
******************/
extern "C" int evma_send_datagram (const char *binding, const char *data, int data_length, const char *address, int port)
{
ensure_eventmachine("evma_send_datagram");
return DatagramDescriptor::SendDatagram (binding, data, data_length, address, port);
}
/*********************
evma_close_connection
*********************/
extern "C" void evma_close_connection (const char *binding, int after_writing)
{
ensure_eventmachine("evma_close_connection");
ConnectionDescriptor::CloseConnection (binding, (after_writing ? true : false));
}
/***********************************
evma_report_connection_error_status
***********************************/
extern "C" int evma_report_connection_error_status (const char *binding)
{
ensure_eventmachine("evma_report_connection_error_status");
return ConnectionDescriptor::ReportErrorStatus (binding);
}
/********************
evma_stop_tcp_server
********************/
extern "C" void evma_stop_tcp_server (const char *binding)
{
ensure_eventmachine("evma_stop_tcp_server");
AcceptorDescriptor::StopAcceptor (binding);
}
/*****************
evma_stop_machine
*****************/
extern "C" void evma_stop_machine()
{
ensure_eventmachine("evma_stop_machine");
EventMachine->ScheduleHalt();
}
/**************
evma_start_tls
**************/
extern "C" void evma_start_tls (const char *binding)
{
ensure_eventmachine("evma_start_tls");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed)
ed->StartTls();
}
/******************
evma_set_tls_parms
******************/
extern "C" void evma_set_tls_parms (const char *binding, const char *privatekey_filename, const char *certchain_filename)
{
ensure_eventmachine("evma_set_tls_parms");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed)
ed->SetTlsParms (privatekey_filename, certchain_filename);
}
/*****************
evma_get_peername
*****************/
extern "C" int evma_get_peername (const char *binding, struct sockaddr *sa)
{
ensure_eventmachine("evma_get_peername");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed) {
return ed->GetPeername (sa) ? 1 : 0;
}
else
return 0;
}
/*****************
evma_get_sockname
*****************/
extern "C" int evma_get_sockname (const char *binding, struct sockaddr *sa)
{
ensure_eventmachine("evma_get_sockname");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed) {
return ed->GetSockname (sa) ? 1 : 0;
}
else
return 0;
}
/***********************
evma_get_subprocess_pid
***********************/
extern "C" int evma_get_subprocess_pid (const char *binding, pid_t *pid)
{
ensure_eventmachine("evma_get_subprocess_pid");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed) {
return ed->GetSubprocessPid (pid) ? 1 : 0;
}
else
return 0;
}
/**************************
evma_get_subprocess_status
**************************/
extern "C" int evma_get_subprocess_status (const char *binding, int *status)
{
ensure_eventmachine("evma_get_subprocess_status");
if (status) {
*status = EventMachine->SubprocessExitStatus;
return 1;
}
else
return 0;
}
/*********************
evma_signal_loopbreak
*********************/
extern "C" void evma_signal_loopbreak()
{
ensure_eventmachine("evma_signal_loopbreak");
EventMachine->SignalLoopBreaker();
}
/****************
evma__write_file
****************/
extern "C" const char *evma__write_file (const char *filename)
{
ensure_eventmachine("evma__write_file");
return EventMachine->_OpenFileForWriting (filename);
}
/********************************
evma_get_comm_inactivity_timeout
********************************/
extern "C" int evma_get_comm_inactivity_timeout (const char *binding, int *value)
{
ensure_eventmachine("evma_get_comm_inactivity_timeout");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed) {
return ed->GetCommInactivityTimeout (value);
}
else
return 0; //Perhaps this should be an exception. Access to an unknown binding.
}
/********************************
evma_set_comm_inactivity_timeout
********************************/
extern "C" int evma_set_comm_inactivity_timeout (const char *binding, int *value)
{
ensure_eventmachine("evma_set_comm_inactivity_timeout");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed) {
return ed->SetCommInactivityTimeout (value);
}
else
return 0; //Perhaps this should be an exception. Access to an unknown binding.
}
/**********************
evma_set_timer_quantum
**********************/
extern "C" void evma_set_timer_quantum (int interval)
{
ensure_eventmachine("evma_set_timer_quantum");
EventMachine->SetTimerQuantum (interval);
}
/************************
evma_set_max_timer_count
************************/
extern "C" void evma_set_max_timer_count (int ct)
{
// This may only be called if the reactor is not running.
if (EventMachine)
#ifdef BUILD_FOR_RUBY
rb_raise(rb_eRuntimeError, "eventmachine already initialized: evma_set_max_timer_count");
#else
throw std::runtime_error ("eventmachine already initialized: evma_set_max_timer_count");
#endif
EventMachine_t::SetMaxTimerCount (ct);
}
/******************
evma_setuid_string
******************/
extern "C" void evma_setuid_string (const char *username)
{
// We do NOT need to be running an EM instance because this method is static.
EventMachine_t::SetuidString (username);
}
/**********
evma_popen
**********/
extern "C" const char *evma_popen (char * const*cmd_strings)
{
ensure_eventmachine("evma_popen");
return EventMachine->Socketpair (cmd_strings);
}
/***************************
evma_get_outbound_data_size
***************************/
extern "C" int evma_get_outbound_data_size (const char *binding)
{
ensure_eventmachine("evma_get_outbound_data_size");
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
return ed ? ed->GetOutboundDataSize() : 0;
}
/***********
evma__epoll
***********/
extern "C" void evma__epoll()
{
bUseEpoll = 1;
}
/************
evma__kqueue
************/
extern "C" void evma__kqueue()
{
bUseKqueue = 1;
}
/**********************
evma_set_rlimit_nofile
**********************/
extern "C" int evma_set_rlimit_nofile (int nofiles)
{
return EventMachine_t::SetRlimitNofile (nofiles);
}
/*********************************
evma_send_file_data_to_connection
*********************************/
extern "C" int evma_send_file_data_to_connection (const char *binding, const char *filename)
{
/* This is a sugaring over send_data_to_connection that reads a file into a
* locally-allocated buffer, and sends the file data to the remote peer.
* Return the number of bytes written to the caller.
* TODO, needs to impose a limit on the file size. This is intended only for
* small files. (I don't know, maybe 8K or less.) For larger files, use interleaved
* I/O to avoid slowing the rest of the system down.
* TODO: we should return a code rather than barf, in case of file-not-found.
* TODO, does this compile on Windows?
* TODO, given that we want this to work only with small files, how about allocating
* the buffer on the stack rather than the heap?
*
* Modified 25Jul07. This now returns -1 on file-too-large; 0 for success, and a positive
* errno in case of other errors.
*
/* Contributed by Kirk Haines.
*/
char data[32*1024];
int r;
ensure_eventmachine("evma_send_file_data_to_connection");
int Fd = open (filename, O_RDONLY);
if (Fd < 0)
return errno;
// From here on, all early returns MUST close Fd.
struct stat st;
if (fstat (Fd, &st)) {
int e = errno;
close (Fd);
return e;
}
int filesize = st.st_size;
if (filesize <= 0) {
close (Fd);
return 0;
}
else if (filesize > sizeof(data)) {
close (Fd);
return -1;
}
r = read (Fd, data, filesize);
if (r != filesize) {
int e = errno;
close (Fd);
return e;
}
evma_send_data_to_connection (binding, data, r);
close (Fd);
return 0;
}
/*****************************************************************************
$Id$
File: cplusplus.cpp
Date: 27Jul07
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
namespace EM {
static map<string, Eventable*> Eventables;
static map<string, void(*)()> Timers;
}
/*******
EM::Run
*******/
void EM::Run (void (*start_func)())
{
evma__epoll();
evma_initialize_library (EM::Callback);
if (start_func)
AddTimer (0, start_func);
evma_run_machine();
evma_release_library();
}
/************
EM::AddTimer
************/
void EM::AddTimer (int milliseconds, void (*func)())
{
if (func) {
const char *sig = evma_install_oneshot_timer (milliseconds);
Timers.insert (make_pair (sig, func));
}
}
/***************
EM::StopReactor
***************/
void EM::StopReactor()
{
evma_stop_machine();
}
/********************
EM::Acceptor::Accept
********************/
void EM::Acceptor::Accept (const char *signature)
{
Connection *c = MakeConnection();
c->Signature = signature;
Eventables.insert (make_pair (c->Signature, c));
c->PostInit();
}
/************************
EM::Connection::SendData
************************/
void EM::Connection::SendData (const char *data)
{
if (data)
SendData (data, strlen (data));
}
/************************
EM::Connection::SendData
************************/
void EM::Connection::SendData (const char *data, int length)
{
evma_send_data_to_connection (Signature.c_str(), data, length);
}
/*********************
EM::Connection::Close
*********************/
void EM::Connection::Close (bool afterWriting)
{
evma_close_connection (Signature.c_str(), afterWriting);
}
/***********************
EM::Connection::Connect
***********************/
void EM::Connection::Connect (const char *host, int port)
{
Signature = evma_connect_to_server (host, port);
Eventables.insert( make_pair (Signature, this));
}
/*******************
EM::Acceptor::Start
*******************/
void EM::Acceptor::Start (const char *host, int port)
{
Signature = evma_create_tcp_server (host, port);
Eventables.insert( make_pair (Signature, this));
}
/************
EM::Callback
************/
void EM::Callback (const char *sig, int ev, const char *data, int length)
{
EM::Eventable *e;
void (*f)();
switch (ev) {
case EM_TIMER_FIRED:
f = Timers [data];
if (f)
(*f)();
Timers.erase (sig);
break;
case EM_CONNECTION_READ:
e = EM::Eventables [sig];
e->ReceiveData (data, length);
break;
case EM_CONNECTION_COMPLETED:
e = EM::Eventables [sig];
e->ConnectionCompleted();
break;
case EM_CONNECTION_ACCEPTED:
e = EM::Eventables [sig];
e->Accept (data);
break;
case EM_CONNECTION_UNBOUND:
e = EM::Eventables [sig];
e->Unbind();
EM::Eventables.erase (sig);
delete e;
break;
}
}
/*****************************************************************************
$Id$
File: ed.cpp
Date: 06Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
/********************
SetSocketNonblocking
********************/
bool SetSocketNonblocking (SOCKET sd)
{
#ifdef OS_UNIX
int val = fcntl (sd, F_GETFL, 0);
return (fcntl (sd, F_SETFL, val | O_NONBLOCK) != SOCKET_ERROR) ? true : false;
#endif
#ifdef OS_WIN32
unsigned long one = 1;
return (ioctlsocket (sd, FIONBIO, &one) == 0) ? true : false;
#endif
}
/****************************************
EventableDescriptor::EventableDescriptor
****************************************/
EventableDescriptor::EventableDescriptor (int sd, EventMachine_t *em):
bCloseNow (false),
bCloseAfterWriting (false),
MySocket (sd),
EventCallback (NULL),
LastRead (0),
LastWritten (0),
bCallbackUnbind (true),
MyEventMachine (em)
{
/* There are three ways to close a socket, all of which should
* automatically signal to the event machine that this object
* should be removed from the polling scheduler.
* First is a hard close, intended for bad errors or possible
* security violations. It immediately closes the connection
* and puts this object into an error state.
* Second is to set bCloseNow, which will cause the event machine
* to delete this object (and thus close the connection in our
* destructor) the next chance it gets. bCloseNow also inhibits
* the writing of new data on the socket (but not necessarily
* the reading of new data).
* The third way is to set bCloseAfterWriting, which inhibits
* the writing of new data and converts to bCloseNow as soon
* as everything in the outbound queue has been written.
* bCloseAfterWriting is really for use only by protocol handlers
* (for example, HTTP writes an HTML page and then closes the
* connection). All of the error states we generate internally
* cause an immediate close to be scheduled, which may have the
* effect of discarding outbound data.
*/
if (sd == INVALID_SOCKET)
throw std::runtime_error ("bad eventable descriptor");
if (MyEventMachine == NULL)
throw std::runtime_error ("bad em in eventable descriptor");
CreatedAt = gCurrentLoopTime;
#ifdef HAVE_EPOLL
EpollEvent.data.ptr = this;
#endif
}
/*****************************************
EventableDescriptor::~EventableDescriptor
*****************************************/
EventableDescriptor::~EventableDescriptor()
{
if (EventCallback && bCallbackUnbind)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_UNBOUND, NULL, 0);
Close();
}
/*************************************
EventableDescriptor::SetEventCallback
*************************************/
void EventableDescriptor::SetEventCallback (void(*cb)(const char*, int, const char*, int))
{
EventCallback = cb;
}
/**************************
EventableDescriptor::Close
**************************/
void EventableDescriptor::Close()
{
// Close the socket right now. Intended for emergencies.
if (MySocket != INVALID_SOCKET) {
shutdown (MySocket, 1);
closesocket (MySocket);
MySocket = INVALID_SOCKET;
}
}
/*********************************
EventableDescriptor::ShouldDelete
*********************************/
bool EventableDescriptor::ShouldDelete()
{
/* For use by a socket manager, which needs to know if this object
* should be removed from scheduling events and deleted.
* Has an immediate close been scheduled, or are we already closed?
* If either of these are the case, return true. In theory, the manager will
* then delete us, which in turn will make sure the socket is closed.
* Note, if bCloseAfterWriting is true, we check a virtual method to see
* if there is outbound data to write, and only request a close if there is none.
*/
return ((MySocket == INVALID_SOCKET) || bCloseNow || (bCloseAfterWriting && (GetOutboundDataSize() <= 0)));
}
/**********************************
EventableDescriptor::ScheduleClose
**********************************/
void EventableDescriptor::ScheduleClose (bool after_writing)
{
// KEEP THIS SYNCHRONIZED WITH ::IsCloseScheduled.
if (after_writing)
bCloseAfterWriting = true;
else
bCloseNow = true;
}
/*************************************
EventableDescriptor::IsCloseScheduled
*************************************/
bool EventableDescriptor::IsCloseScheduled()
{
// KEEP THIS SYNCHRONIZED WITH ::ScheduleClose.
return (bCloseNow || bCloseAfterWriting);
}
/******************************************
ConnectionDescriptor::ConnectionDescriptor
******************************************/
ConnectionDescriptor::ConnectionDescriptor (int sd, EventMachine_t *em):
EventableDescriptor (sd, em),
bConnectPending (false),
bNotifyReadable (false),
bNotifyWritable (false),
bReadAttemptedAfterClose (false),
bWriteAttemptedAfterClose (false),
OutboundDataSize (0),
#ifdef WITH_SSL
SslBox (NULL),
#endif
bIsServer (false),
LastIo (gCurrentLoopTime),
InactivityTimeout (0)
{
#ifdef HAVE_EPOLL
EpollEvent.events = EPOLLOUT;
#endif
// 22Jan09: Moved ArmKqueueWriter into SetConnectPending() to fix assertion failure in _WriteOutboundData()
}
/*******************************************
ConnectionDescriptor::~ConnectionDescriptor
*******************************************/
ConnectionDescriptor::~ConnectionDescriptor()
{
// Run down any stranded outbound data.
for (size_t i=0; i < OutboundPages.size(); i++)
OutboundPages[i].Free();
#ifdef WITH_SSL
if (SslBox)
delete SslBox;
#endif
}
/**************************************************
STATIC: ConnectionDescriptor::SendDataToConnection
**************************************************/
int ConnectionDescriptor::SendDataToConnection (const char *binding, const char *data, int data_length)
{
// TODO: This is something of a hack, or at least it's a static method of the wrong class.
// TODO: Poor polymorphism here. We should be calling one virtual method
// instead of hacking out the runtime information of the target object.
ConnectionDescriptor *cd = dynamic_cast <ConnectionDescriptor*> (Bindable_t::GetObject (binding));
if (cd)
return cd->SendOutboundData (data, data_length);
DatagramDescriptor *ds = dynamic_cast <DatagramDescriptor*> (Bindable_t::GetObject (binding));
if (ds)
return ds->SendOutboundData (data, data_length);
#ifdef OS_UNIX
PipeDescriptor *ps = dynamic_cast <PipeDescriptor*> (Bindable_t::GetObject (binding));
if (ps)
return ps->SendOutboundData (data, data_length);
#endif
return -1;
}
/*********************************************
STATIC: ConnectionDescriptor::CloseConnection
*********************************************/
void ConnectionDescriptor::CloseConnection (const char *binding, bool after_writing)
{
// TODO: This is something of a hack, or at least it's a static method of the wrong class.
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
if (ed)
ed->ScheduleClose (after_writing);
}
/***********************************************
STATIC: ConnectionDescriptor::ReportErrorStatus
***********************************************/
int ConnectionDescriptor::ReportErrorStatus (const char *binding)
{
// TODO: This is something of a hack, or at least it's a static method of the wrong class.
// TODO: Poor polymorphism here. We should be calling one virtual method
// instead of hacking out the runtime information of the target object.
ConnectionDescriptor *cd = dynamic_cast <ConnectionDescriptor*> (Bindable_t::GetObject (binding));
if (cd)
return cd->_ReportErrorStatus();
return -1;
}
/***************************************
ConnectionDescriptor::SetConnectPending
****************************************/
void ConnectionDescriptor::SetConnectPending(bool f)
{
bConnectPending = f;
#ifdef HAVE_KQUEUE
MyEventMachine->ArmKqueueWriter (this);
#endif
}
/**************************************
ConnectionDescriptor::SendOutboundData
**************************************/
int ConnectionDescriptor::SendOutboundData (const char *data, int length)
{
#ifdef WITH_SSL
if (SslBox) {
if (length > 0) {
int w = SslBox->PutPlaintext (data, length);
if (w < 0)
ScheduleClose (false);
else
_DispatchCiphertext();
}
// TODO: What's the correct return value?
return 1; // That's a wild guess, almost certainly wrong.
}
else
#endif
return _SendRawOutboundData (data, length);
}
/******************************************
ConnectionDescriptor::_SendRawOutboundData
******************************************/
int ConnectionDescriptor::_SendRawOutboundData (const char *data, int length)
{
/* This internal method is called to schedule bytes that
* will be sent out to the remote peer.
* It's not directly accessed by the caller, who hits ::SendOutboundData,
* which may or may not filter or encrypt the caller's data before
* sending it here.
*/
// Highly naive and incomplete implementation.
// There's no throttle for runaways (which should abort only this connection
// and not the whole process), and no coalescing of small pages.
// (Well, not so bad, small pages are coalesced in ::Write)
if (IsCloseScheduled())
//if (bCloseNow || bCloseAfterWriting)
return 0;
if (!data && (length > 0))
throw std::runtime_error ("bad outbound data");
char *buffer = (char *) malloc (length + 1);
if (!buffer)
throw std::runtime_error ("no allocation for outbound data");
memcpy (buffer, data, length);
buffer [length] = 0;
OutboundPages.push_back (OutboundPage (buffer, length));
OutboundDataSize += length;
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | EPOLLOUT);
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
#ifdef HAVE_KQUEUE
MyEventMachine->ArmKqueueWriter (this);
#endif
return length;
}
/***********************************
ConnectionDescriptor::SelectForRead
***********************************/
bool ConnectionDescriptor::SelectForRead()
{
/* A connection descriptor is always scheduled for read,
* UNLESS it's in a pending-connect state.
* On Linux, unlike Unix, a nonblocking socket on which
* connect has been called, does NOT necessarily select
* both readable and writable in case of error.
* The socket will select writable when the disposition
* of the connect is known. On the other hand, a socket
* which successfully connects and selects writable may
* indeed have some data available on it, so it will
* select readable in that case, violating expectations!
* So we will not poll for readability until the socket
* is known to be in a connected state.
*/
return bConnectPending ? false : true;
}
/************************************
ConnectionDescriptor::SelectForWrite
************************************/
bool ConnectionDescriptor::SelectForWrite()
{
/* Cf the notes under SelectForRead.
* In a pending-connect state, we ALWAYS select for writable.
* In a normal state, we only select for writable when we
* have outgoing data to send.
*/
if (bConnectPending || bNotifyWritable)
return true;
else {
return (GetOutboundDataSize() > 0);
}
}
/**************************
ConnectionDescriptor::Read
**************************/
void ConnectionDescriptor::Read()
{
/* Read and dispatch data on a socket that has selected readable.
* It's theoretically possible to get and dispatch incoming data on
* a socket that has already been scheduled for closing or close-after-writing.
* In those cases, we'll leave it up the to protocol handler to "do the
* right thing" (which probably means to ignore the incoming data).
*
* 22Aug06: Chris Ochs reports that on FreeBSD, it's possible to come
* here with the socket already closed, after the process receives
* a ctrl-C signal (not sure if that's TERM or INT on BSD). The application
* was one in which network connections were doing a lot of interleaved reads
* and writes.
* Since we always write before reading (in order to keep the outbound queues
* as light as possible), I think what happened is that an interrupt caused
* the socket to be closed in ConnectionDescriptor::Write. We'll then
* come here in the same pass through the main event loop, and won't get
* cleaned up until immediately after.
* We originally asserted that the socket was valid when we got here.
* To deal properly with the possibility that we are closed when we get here,
* I removed the assert. HOWEVER, the potential for an infinite loop scares me,
* so even though this is really clunky, I added a flag to assert that we never
* come here more than once after being closed. (FCianfrocca)
*/
int sd = GetSocket();
//assert (sd != INVALID_SOCKET); (original, removed 22Aug06)
if (sd == INVALID_SOCKET) {
assert (!bReadAttemptedAfterClose);
bReadAttemptedAfterClose = true;
return;
}
if (bNotifyReadable) {
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_NOTIFY_READABLE, NULL, 0);
return;
}
LastIo = gCurrentLoopTime;
int total_bytes_read = 0;
char readbuffer [16 * 1024 + 1];
for (int i=0; i < 10; i++) {
// Don't read just one buffer and then move on. This is faster
// if there is a lot of incoming.
// But don't read indefinitely. Give other sockets a chance to run.
// NOTICE, we're reading one less than the buffer size.
// That's so we can put a guard byte at the end of what we send
// to user code.
int r = recv (sd, readbuffer, sizeof(readbuffer) - 1, 0);
//cerr << "<R:" << r << ">";
if (r > 0) {
total_bytes_read += r;
LastRead = gCurrentLoopTime;
// Add a null-terminator at the the end of the buffer
// that we will send to the callback.
// DO NOT EVER CHANGE THIS. We want to explicitly allow users
// to be able to depend on this behavior, so they will have
// the option to do some things faster. Additionally it's
// a security guard against buffer overflows.
readbuffer [r] = 0;
_DispatchInboundData (readbuffer, r);
}
else if (r == 0) {
break;
}
else {
// Basically a would-block, meaning we've read everything there is to read.
break;
}
}
if (total_bytes_read == 0) {
// If we read no data on a socket that selected readable,
// it generally means the other end closed the connection gracefully.
ScheduleClose (false);
//bCloseNow = true;
}
}
/******************************************
ConnectionDescriptor::_DispatchInboundData
******************************************/
void ConnectionDescriptor::_DispatchInboundData (const char *buffer, int size)
{
#ifdef WITH_SSL
if (SslBox) {
SslBox->PutCiphertext (buffer, size);
int s;
char B [2048];
while ((s = SslBox->GetPlaintext (B, sizeof(B) - 1)) > 0) {
B [s] = 0;
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_READ, B, s);
}
// INCOMPLETE, s may indicate an SSL error that would force the connection down.
_DispatchCiphertext();
}
else {
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_READ, buffer, size);
}
#endif
#ifdef WITHOUT_SSL
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_READ, buffer, size);
#endif
}
/***************************
ConnectionDescriptor::Write
***************************/
void ConnectionDescriptor::Write()
{
/* A socket which is in a pending-connect state will select
* writable when the disposition of the connect is known.
* At that point, check to be sure there are no errors,
* and if none, then promote the socket out of the pending
* state.
* TODO: I haven't figured out how Windows signals errors on
* unconnected sockets. Maybe it does the untraditional but
* logical thing and makes the socket selectable for error.
* If so, it's unsupported here for the time being, and connect
* errors will have to be caught by the timeout mechanism.
*/
if (bConnectPending) {
int error;
socklen_t len;
len = sizeof(error);
#ifdef OS_UNIX
int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, &error, &len);
#endif
#ifdef OS_WIN32
int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, (char*)&error, &len);
#endif
if ((o == 0) && (error == 0)) {
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_COMPLETED, "", 0);
bConnectPending = false;
#ifdef HAVE_EPOLL
// The callback may have scheduled outbound data.
EpollEvent.events = EPOLLIN | (SelectForWrite() ? EPOLLOUT : 0);
#endif
#ifdef HAVE_KQUEUE
MyEventMachine->ArmKqueueReader (this);
// The callback may have scheduled outbound data.
if (SelectForWrite())
MyEventMachine->ArmKqueueWriter (this);
#endif
}
else
ScheduleClose (false);
//bCloseNow = true;
}
else {
if (bNotifyWritable) {
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_NOTIFY_WRITABLE, NULL, 0);
return;
}
_WriteOutboundData();
}
}
/****************************************
ConnectionDescriptor::_WriteOutboundData
****************************************/
void ConnectionDescriptor::_WriteOutboundData()
{
/* This is a helper function called by ::Write.
* It's possible for a socket to select writable and then no longer
* be writable by the time we get around to writing. The kernel might
* have used up its available output buffers between the select call
* and when we get here. So this condition is not an error.
*
* 20Jul07, added the same kind of protection against an invalid socket
* that is at the top of ::Read. Not entirely how this could happen in
* real life (connection-reset from the remote peer, perhaps?), but I'm
* doing it to address some reports of crashing under heavy loads.
*/
int sd = GetSocket();
//assert (sd != INVALID_SOCKET);
if (sd == INVALID_SOCKET) {
assert (!bWriteAttemptedAfterClose);
bWriteAttemptedAfterClose = true;
return;
}
LastIo = gCurrentLoopTime;
char output_buffer [16 * 1024];
size_t nbytes = 0;
while ((OutboundPages.size() > 0) && (nbytes < sizeof(output_buffer))) {
OutboundPage *op = &(OutboundPages[0]);
if ((nbytes + op->Length - op->Offset) < sizeof (output_buffer)) {
memcpy (output_buffer + nbytes, op->Buffer + op->Offset, op->Length - op->Offset);
nbytes += (op->Length - op->Offset);
op->Free();
OutboundPages.pop_front();
}
else {
int len = sizeof(output_buffer) - nbytes;
memcpy (output_buffer + nbytes, op->Buffer + op->Offset, len);
op->Offset += len;
nbytes += len;
}
}
// We should never have gotten here if there were no data to write,
// so assert that as a sanity check.
// Don't bother to make sure nbytes is less than output_buffer because
// if it were we probably would have crashed already.
assert (nbytes > 0);
assert (GetSocket() != INVALID_SOCKET);
int bytes_written = send (GetSocket(), output_buffer, nbytes, 0);
bool err = false;
if (bytes_written < 0) {
err = true;
bytes_written = 0;
}
assert (bytes_written >= 0);
OutboundDataSize -= bytes_written;
if ((size_t)bytes_written < nbytes) {
int len = nbytes - bytes_written;
char *buffer = (char*) malloc (len + 1);
if (!buffer)
throw std::runtime_error ("bad alloc throwing back data");
memcpy (buffer, output_buffer + bytes_written, len);
buffer [len] = 0;
OutboundPages.push_front (OutboundPage (buffer, len));
}
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | (SelectForWrite() ? EPOLLOUT : 0));
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
#ifdef HAVE_KQUEUE
if (SelectForWrite())
MyEventMachine->ArmKqueueWriter (this);
#endif
if (err) {
#ifdef OS_UNIX
if ((errno != EINPROGRESS) && (errno != EWOULDBLOCK) && (errno != EINTR))
#endif
#ifdef OS_WIN32
if ((errno != WSAEINPROGRESS) && (errno != WSAEWOULDBLOCK))
#endif
Close();
}
}
/****************************************
ConnectionDescriptor::_ReportErrorStatus
****************************************/
int ConnectionDescriptor::_ReportErrorStatus()
{
int error;
socklen_t len;
len = sizeof(error);
#ifdef OS_UNIX
int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, &error, &len);
#endif
#ifdef OS_WIN32
int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, (char*)&error, &len);
#endif
if ((o == 0) && (error == 0))
return 0;
else
return 1;
}
/******************************
ConnectionDescriptor::StartTls
******************************/
void ConnectionDescriptor::StartTls()
{
#ifdef WITH_SSL
if (SslBox)
throw std::runtime_error ("SSL/TLS already running on connection");
SslBox = new SslBox_t (bIsServer, PrivateKeyFilename, CertChainFilename);
_DispatchCiphertext();
#endif
#ifdef WITHOUT_SSL
throw std::runtime_error ("Encryption not available on this event-machine");
#endif
}
/*********************************
ConnectionDescriptor::SetTlsParms
*********************************/
void ConnectionDescriptor::SetTlsParms (const char *privkey_filename, const char *certchain_filename)
{
#ifdef WITH_SSL
if (SslBox)
throw std::runtime_error ("call SetTlsParms before calling StartTls");
if (privkey_filename && *privkey_filename)
PrivateKeyFilename = privkey_filename;
if (certchain_filename && *certchain_filename)
CertChainFilename = certchain_filename;
#endif
#ifdef WITHOUT_SSL
throw std::runtime_error ("Encryption not available on this event-machine");
#endif
}
/*****************************************
ConnectionDescriptor::_DispatchCiphertext
*****************************************/
#ifdef WITH_SSL
void ConnectionDescriptor::_DispatchCiphertext()
{
assert (SslBox);
char BigBuf [2048];
bool did_work;
do {
did_work = false;
// try to drain ciphertext
while (SslBox->CanGetCiphertext()) {
int r = SslBox->GetCiphertext (BigBuf, sizeof(BigBuf));
assert (r > 0);
_SendRawOutboundData (BigBuf, r);
did_work = true;
}
// Pump the SslBox, in case it has queued outgoing plaintext
// This will return >0 if data was written,
// 0 if no data was written, and <0 if there was a fatal error.
bool pump;
do {
pump = false;
int w = SslBox->PutPlaintext (NULL, 0);
if (w > 0) {
did_work = true;
pump = true;
}
else if (w < 0)
ScheduleClose (false);
} while (pump);
// try to put plaintext. INCOMPLETE, doesn't belong here?
// In SendOutboundData, we're spooling plaintext directly
// into SslBox. That may be wrong, we may need to buffer it
// up here!
/*
const char *ptr;
int ptr_length;
while (OutboundPlaintext.GetPage (&ptr, &ptr_length)) {
assert (ptr && (ptr_length > 0));
int w = SslMachine.PutPlaintext (ptr, ptr_length);
if (w > 0) {
OutboundPlaintext.DiscardBytes (w);
did_work = true;
}
else
break;
}
*/
} while (did_work);
}
#endif
/*******************************
ConnectionDescriptor::Heartbeat
*******************************/
void ConnectionDescriptor::Heartbeat()
{
/* Only allow a certain amount of time to go by while waiting
* for a pending connect. If it expires, then kill the socket.
* For a connected socket, close it if its inactivity timer
* has expired.
*/
if (bConnectPending) {
if ((gCurrentLoopTime - CreatedAt) >= PendingConnectTimeout)
ScheduleClose (false);
//bCloseNow = true;
}
else {
if (InactivityTimeout && ((gCurrentLoopTime - LastIo) >= InactivityTimeout))
ScheduleClose (false);
//bCloseNow = true;
}
}
/****************************************
LoopbreakDescriptor::LoopbreakDescriptor
****************************************/
LoopbreakDescriptor::LoopbreakDescriptor (int sd, EventMachine_t *parent_em):
EventableDescriptor (sd, parent_em)
{
/* This is really bad and ugly. Change someday if possible.
* We have to know about an event-machine (probably the one that owns us),
* so we can pass newly-created connections to it.
*/
bCallbackUnbind = false;
#ifdef HAVE_EPOLL
EpollEvent.events = EPOLLIN;
#endif
#ifdef HAVE_KQUEUE
MyEventMachine->ArmKqueueReader (this);
#endif
}
/*************************
LoopbreakDescriptor::Read
*************************/
void LoopbreakDescriptor::Read()
{
// TODO, refactor, this code is probably in the wrong place.
assert (MyEventMachine);
MyEventMachine->_ReadLoopBreaker();
}
/**************************
LoopbreakDescriptor::Write
**************************/
void LoopbreakDescriptor::Write()
{
// Why are we here?
throw std::runtime_error ("bad code path in loopbreak");
}
/**************************************
AcceptorDescriptor::AcceptorDescriptor
**************************************/
AcceptorDescriptor::AcceptorDescriptor (int sd, EventMachine_t *parent_em):
EventableDescriptor (sd, parent_em)
{
#ifdef HAVE_EPOLL
EpollEvent.events = EPOLLIN;
#endif
#ifdef HAVE_KQUEUE
MyEventMachine->ArmKqueueReader (this);
#endif
}
/***************************************
AcceptorDescriptor::~AcceptorDescriptor
***************************************/
AcceptorDescriptor::~AcceptorDescriptor()
{
}
/****************************************
STATIC: AcceptorDescriptor::StopAcceptor
****************************************/
void AcceptorDescriptor::StopAcceptor (const char *binding)
{
// TODO: This is something of a hack, or at least it's a static method of the wrong class.
AcceptorDescriptor *ad = dynamic_cast <AcceptorDescriptor*> (Bindable_t::GetObject (binding));
if (ad)
ad->ScheduleClose (false);
else
throw std::runtime_error ("failed to close nonexistent acceptor");
}
/************************
AcceptorDescriptor::Read
************************/
void AcceptorDescriptor::Read()
{
/* Accept up to a certain number of sockets on the listening connection.
* Don't try to accept all that are present, because this would allow a DoS attack
* in which no data were ever read or written. We should accept more than one,
* if available, to keep the partially accepted sockets from backing up in the kernel.
*/
/* Make sure we use non-blocking i/o on the acceptor socket, since we're selecting it
* for readability. According to Stevens UNP, it's possible for an acceptor to select readable
* and then block when we call accept. For example, the other end resets the connection after
* the socket selects readable and before we call accept. The kernel will remove the dead
* socket from the accept queue. If the accept queue is now empty, accept will block.
*/
struct sockaddr_in pin;
socklen_t addrlen = sizeof (pin);
for (int i=0; i < 10; i++) {
int sd = accept (GetSocket(), (struct sockaddr*)&pin, &addrlen);
if (sd == INVALID_SOCKET) {
// This breaks the loop when we've accepted everything on the kernel queue,
// up to 10 new connections. But what if the *first* accept fails?
// Does that mean anything serious is happening, beyond the situation
// described in the note above?
break;
}
// Set the newly-accepted socket non-blocking.
// On Windows, this may fail because, weirdly, Windows inherits the non-blocking
// attribute that we applied to the acceptor socket into the accepted one.
if (!SetSocketNonblocking (sd)) {
//int val = fcntl (sd, F_GETFL, 0);
//if (fcntl (sd, F_SETFL, val | O_NONBLOCK) == -1) {
shutdown (sd, 1);
closesocket (sd);
continue;
}
// Disable slow-start (Nagle algorithm). Eventually make this configurable.
int one = 1;
setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (char*) &one, sizeof(one));
ConnectionDescriptor *cd = new ConnectionDescriptor (sd, MyEventMachine);
if (!cd)
throw std::runtime_error ("no newly accepted connection");
cd->SetServerMode();
if (EventCallback) {
(*EventCallback) (GetBinding().c_str(), EM_CONNECTION_ACCEPTED, cd->GetBinding().c_str(), cd->GetBinding().size());
}
#ifdef HAVE_EPOLL
cd->GetEpollEvent()->events = EPOLLIN | (cd->SelectForWrite() ? EPOLLOUT : 0);
#endif
assert (MyEventMachine);
MyEventMachine->Add (cd);
#ifdef HAVE_KQUEUE
if (cd->SelectForWrite())
MyEventMachine->ArmKqueueWriter (cd);
MyEventMachine->ArmKqueueReader (cd);
#endif
}
}
/*************************
AcceptorDescriptor::Write
*************************/
void AcceptorDescriptor::Write()
{
// Why are we here?
throw std::runtime_error ("bad code path in acceptor");
}
/*****************************
AcceptorDescriptor::Heartbeat
*****************************/
void AcceptorDescriptor::Heartbeat()
{
// No-op
}
/*******************************
AcceptorDescriptor::GetSockname
*******************************/
bool AcceptorDescriptor::GetSockname (struct sockaddr *s)
{
bool ok = false;
if (s) {
socklen_t len = sizeof(*s);
int gp = getsockname (GetSocket(), s, &len);
if (gp == 0)
ok = true;
}
return ok;
}
/**************************************
DatagramDescriptor::DatagramDescriptor
**************************************/
DatagramDescriptor::DatagramDescriptor (int sd, EventMachine_t *parent_em):
EventableDescriptor (sd, parent_em),
OutboundDataSize (0),
LastIo (gCurrentLoopTime),
InactivityTimeout (0)
{
memset (&ReturnAddress, 0, sizeof(ReturnAddress));
/* Provisionally added 19Oct07. All datagram sockets support broadcasting.
* Until now, sending to a broadcast address would give EACCES (permission denied)
* on systems like Linux and BSD that require the SO_BROADCAST socket-option in order
* to accept a packet to a broadcast address. Solaris doesn't require it. I think
* Windows DOES require it but I'm not sure.
*
* Ruby does NOT do what we're doing here. In Ruby, you have to explicitly set SO_BROADCAST
* on a UDP socket in order to enable broadcasting. The reason for requiring the option
* in the first place is so that applications don't send broadcast datagrams by mistake.
* I imagine that could happen if a user of an application typed in an address that happened
* to be a broadcast address on that particular subnet.
*
* This is provisional because someone may eventually come up with a good reason not to
* do it for all UDP sockets. If that happens, then we'll need to add a usercode-level API
* to set the socket option, just like Ruby does. AND WE'LL ALSO BREAK CODE THAT DOESN'T
* EXPLICITLY SET THE OPTION.
*/
int oval = 1;
int sob = setsockopt (GetSocket(), SOL_SOCKET, SO_BROADCAST, (char*)&oval, sizeof(oval));
#ifdef HAVE_EPOLL
EpollEvent.events = EPOLLIN;
#endif
#ifdef HAVE_KQUEUE
MyEventMachine->ArmKqueueReader (this);
#endif
}
/***************************************
DatagramDescriptor::~DatagramDescriptor
***************************************/
DatagramDescriptor::~DatagramDescriptor()
{
// Run down any stranded outbound data.
for (size_t i=0; i < OutboundPages.size(); i++)
OutboundPages[i].Free();
}
/*****************************
DatagramDescriptor::Heartbeat
*****************************/
void DatagramDescriptor::Heartbeat()
{
// Close it if its inactivity timer has expired.
if (InactivityTimeout && ((gCurrentLoopTime - LastIo) >= InactivityTimeout))
ScheduleClose (false);
//bCloseNow = true;
}
/************************
DatagramDescriptor::Read
************************/
void DatagramDescriptor::Read()
{
int sd = GetSocket();
assert (sd != INVALID_SOCKET);
LastIo = gCurrentLoopTime;
// This is an extremely large read buffer.
// In many cases you wouldn't expect to get any more than 4K.
char readbuffer [16 * 1024];
for (int i=0; i < 10; i++) {
// Don't read just one buffer and then move on. This is faster
// if there is a lot of incoming.
// But don't read indefinitely. Give other sockets a chance to run.
// NOTICE, we're reading one less than the buffer size.
// That's so we can put a guard byte at the end of what we send
// to user code.
struct sockaddr_in sin;
socklen_t slen = sizeof (sin);
memset (&sin, 0, slen);
int r = recvfrom (sd, readbuffer, sizeof(readbuffer) - 1, 0, (struct sockaddr*)&sin, &slen);
//cerr << "<R:" << r << ">";
// In UDP, a zero-length packet is perfectly legal.
if (r >= 0) {
LastRead = gCurrentLoopTime;
// Add a null-terminator at the the end of the buffer
// that we will send to the callback.
// DO NOT EVER CHANGE THIS. We want to explicitly allow users
// to be able to depend on this behavior, so they will have
// the option to do some things faster. Additionally it's
// a security guard against buffer overflows.
readbuffer [r] = 0;
// Set up a "temporary" return address so that callers can "reply" to us
// from within the callback we are about to invoke. That means that ordinary
// calls to "send_data_to_connection" (which is of course misnamed in this
// case) will result in packets being sent back to the same place that sent
// us this one.
// There is a different call (evma_send_datagram) for cases where the caller
// actually wants to send a packet somewhere else.
memset (&ReturnAddress, 0, sizeof(ReturnAddress));
memcpy (&ReturnAddress, &sin, slen);
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_READ, readbuffer, r);
}
else {
// Basically a would-block, meaning we've read everything there is to read.
break;
}
}
}
/*************************
DatagramDescriptor::Write
*************************/
void DatagramDescriptor::Write()
{
/* It's possible for a socket to select writable and then no longer
* be writable by the time we get around to writing. The kernel might
* have used up its available output buffers between the select call
* and when we get here. So this condition is not an error.
* This code is very reminiscent of ConnectionDescriptor::_WriteOutboundData,
* but differs in the that the outbound data pages (received from the
* user) are _message-structured._ That is, we send each of them out
* one message at a time.
* TODO, we are currently suppressing the EMSGSIZE error!!!
*/
int sd = GetSocket();
assert (sd != INVALID_SOCKET);
LastIo = gCurrentLoopTime;
assert (OutboundPages.size() > 0);
// Send out up to 10 packets, then cycle the machine.
for (int i = 0; i < 10; i++) {
if (OutboundPages.size() <= 0)
break;
OutboundPage *op = &(OutboundPages[0]);
// The nasty cast to (char*) is needed because Windows is brain-dead.
int s = sendto (sd, (char*)op->Buffer, op->Length, 0, (struct sockaddr*)&(op->From), sizeof(op->From));
int e = errno;
OutboundDataSize -= op->Length;
op->Free();
OutboundPages.pop_front();
if (s == SOCKET_ERROR) {
#ifdef OS_UNIX
if ((e != EINPROGRESS) && (e != EWOULDBLOCK) && (e != EINTR)) {
#endif
#ifdef OS_WIN32
if ((e != WSAEINPROGRESS) && (e != WSAEWOULDBLOCK)) {
#endif
Close();
break;
}
}
}
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | (SelectForWrite() ? EPOLLOUT : 0));
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
}
/**********************************
DatagramDescriptor::SelectForWrite
**********************************/
bool DatagramDescriptor::SelectForWrite()
{
/* Changed 15Nov07, per bug report by Mark Zvillius.
* The outbound data size will be zero if there are zero-length outbound packets,
* so we now select writable in case the outbound page buffer is not empty.
* Note that the superclass ShouldDelete method still checks for outbound data size,
* which may be wrong.
*/
//return (GetOutboundDataSize() > 0); (Original)
return (OutboundPages.size() > 0);
}
/************************************
DatagramDescriptor::SendOutboundData
************************************/
int DatagramDescriptor::SendOutboundData (const char *data, int length)
{
// This is an exact clone of ConnectionDescriptor::SendOutboundData.
// That means it needs to move to a common ancestor.
if (IsCloseScheduled())
//if (bCloseNow || bCloseAfterWriting)
return 0;
if (!data && (length > 0))
throw std::runtime_error ("bad outbound data");
char *buffer = (char *) malloc (length + 1);
if (!buffer)
throw std::runtime_error ("no allocation for outbound data");
memcpy (buffer, data, length);
buffer [length] = 0;
OutboundPages.push_back (OutboundPage (buffer, length, ReturnAddress));
OutboundDataSize += length;
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | EPOLLOUT);
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
return length;
}
/****************************************
DatagramDescriptor::SendOutboundDatagram
****************************************/
int DatagramDescriptor::SendOutboundDatagram (const char *data, int length, const char *address, int port)
{
// This is an exact clone of ConnectionDescriptor::SendOutboundData.
// That means it needs to move to a common ancestor.
// TODO: Refactor this so there's no overlap with SendOutboundData.
if (IsCloseScheduled())
//if (bCloseNow || bCloseAfterWriting)
return 0;
if (!address || !*address || !port)
return 0;
sockaddr_in pin;
unsigned long HostAddr;
HostAddr = inet_addr (address);
if (HostAddr == INADDR_NONE) {
// The nasty cast to (char*) is because Windows is brain-dead.
hostent *hp = gethostbyname ((char*)address);
if (!hp)
return 0;
HostAddr = ((in_addr*)(hp->h_addr))->s_addr;
}
memset (&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = HostAddr;
pin.sin_port = htons (port);
if (!data && (length > 0))
throw std::runtime_error ("bad outbound data");
char *buffer = (char *) malloc (length + 1);
if (!buffer)
throw std::runtime_error ("no allocation for outbound data");
memcpy (buffer, data, length);
buffer [length] = 0;
OutboundPages.push_back (OutboundPage (buffer, length, pin));
OutboundDataSize += length;
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | EPOLLOUT);
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
return length;
}
/****************************************
STATIC: DatagramDescriptor::SendDatagram
****************************************/
int DatagramDescriptor::SendDatagram (const char *binding, const char *data, int length, const char *address, int port)
{
DatagramDescriptor *dd = dynamic_cast <DatagramDescriptor*> (Bindable_t::GetObject (binding));
if (dd)
return dd->SendOutboundDatagram (data, length, address, port);
else
return -1;
}
/*********************************
ConnectionDescriptor::GetPeername
*********************************/
bool ConnectionDescriptor::GetPeername (struct sockaddr *s)
{
bool ok = false;
if (s) {
socklen_t len = sizeof(*s);
int gp = getpeername (GetSocket(), s, &len);
if (gp == 0)
ok = true;
}
return ok;
}
/*********************************
ConnectionDescriptor::GetSockname
*********************************/
bool ConnectionDescriptor::GetSockname (struct sockaddr *s)
{
bool ok = false;
if (s) {
socklen_t len = sizeof(*s);
int gp = getsockname (GetSocket(), s, &len);
if (gp == 0)
ok = true;
}
return ok;
}
/**********************************************
ConnectionDescriptor::GetCommInactivityTimeout
**********************************************/
int ConnectionDescriptor::GetCommInactivityTimeout (int *value)
{
if (value) {
*value = InactivityTimeout;
return 1;
}
else {
// TODO, extended logging, got bad parameter.
return 0;
}
}
/**********************************************
ConnectionDescriptor::SetCommInactivityTimeout
**********************************************/
int ConnectionDescriptor::SetCommInactivityTimeout (int *value)
{
int out = 0;
if (value) {
if ((*value==0) || (*value >= 2)) {
// Replace the value and send the old one back to the caller.
int v = *value;
*value = InactivityTimeout;
InactivityTimeout = v;
out = 1;
}
else {
// TODO, extended logging, got bad value.
}
}
else {
// TODO, extended logging, got bad parameter.
}
return out;
}
/*******************************
DatagramDescriptor::GetPeername
*******************************/
bool DatagramDescriptor::GetPeername (struct sockaddr *s)
{
bool ok = false;
if (s) {
memset (s, 0, sizeof(struct sockaddr));
memcpy (s, &ReturnAddress, sizeof(ReturnAddress));
ok = true;
}
return ok;
}
/*******************************
DatagramDescriptor::GetSockname
*******************************/
bool DatagramDescriptor::GetSockname (struct sockaddr *s)
{
bool ok = false;
if (s) {
socklen_t len = sizeof(*s);
int gp = getsockname (GetSocket(), s, &len);
if (gp == 0)
ok = true;
}
return ok;
}
/********************************************
DatagramDescriptor::GetCommInactivityTimeout
********************************************/
int DatagramDescriptor::GetCommInactivityTimeout (int *value)
{
if (value) {
*value = InactivityTimeout;
return 1;
}
else {
// TODO, extended logging, got bad parameter.
return 0;
}
}
/********************************************
DatagramDescriptor::SetCommInactivityTimeout
********************************************/
int DatagramDescriptor::SetCommInactivityTimeout (int *value)
{
int out = 0;
if (value) {
if ((*value==0) || (*value >= 2)) {
// Replace the value and send the old one back to the caller.
int v = *value;
*value = InactivityTimeout;
InactivityTimeout = v;
out = 1;
}
else {
// TODO, extended logging, got bad value.
}
}
else {
// TODO, extended logging, got bad parameter.
}
return out;
}
/*****************************************************************************
$Id$
File: em.cpp
Date: 06Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
// THIS ENTIRE FILE WILL EVENTUALLY BE FOR UNIX BUILDS ONLY.
//#ifdef OS_UNIX
#include "project.h"
// Keep a global variable floating around
// with the current loop time as set by the Event Machine.
// This avoids the need for frequent expensive calls to time(NULL);
time_t gCurrentLoopTime;
#ifdef OS_WIN32
unsigned gTickCountTickover;
unsigned gLastTickCount;
#endif
/* The numer of max outstanding timers was once a const enum defined in em.h.
* Now we define it here so that users can change its value if necessary.
*/
static int MaxOutstandingTimers = 1000;
/* Internal helper to convert strings to internet addresses. IPv6-aware.
* Not reentrant or threadsafe, optimized for speed.
*/
static struct sockaddr *name2address (const char *server, int port, int *family, int *bind_size);
/***************************************
STATIC EventMachine_t::SetMaxTimerCount
***************************************/
void EventMachine_t::SetMaxTimerCount (int count)
{
/* Allow a user to increase the maximum number of outstanding timers.
* If this gets "too high" (a metric that is of course platform dependent),
* bad things will happen like performance problems and possible overuse
* of memory.
* The actual timer mechanism is very efficient so it's hard to know what
* the practical max, but 100,000 shouldn't be too problematical.
*/
if (count < 100)
count = 100;
MaxOutstandingTimers = count;
}
/******************************
EventMachine_t::EventMachine_t
******************************/
EventMachine_t::EventMachine_t (void (*event_callback)(const char*, int, const char*, int)):
EventCallback (event_callback),
NextHeartbeatTime (0),
LoopBreakerReader (-1),
LoopBreakerWriter (-1),
bEpoll (false),
bKqueue (false),
epfd (-1)
{
// Default time-slice is just smaller than one hundred mills.
Quantum.tv_sec = 0;
Quantum.tv_usec = 90000;
gTerminateSignalReceived = false;
// Make sure the current loop time is sane, in case we do any initializations of
// objects before we start running.
gCurrentLoopTime = time(NULL);
/* We initialize the network library here (only on Windows of course)
* and initialize "loop breakers." Our destructor also does some network-level
* cleanup. There's thus an implicit assumption that any given instance of EventMachine_t
* will only call ::Run once. Is that a good assumption? Should we move some of these
* inits and de-inits into ::Run?
*/
#ifdef OS_WIN32
WSADATA w;
WSAStartup (MAKEWORD (1, 1), &w);
#endif
_InitializeLoopBreaker();
}
/*******************************
EventMachine_t::~EventMachine_t
*******************************/
EventMachine_t::~EventMachine_t()
{
// Run down descriptors
size_t i;
for (i = 0; i < NewDescriptors.size(); i++)
delete NewDescriptors[i];
for (i = 0; i < Descriptors.size(); i++)
delete Descriptors[i];
close (LoopBreakerReader);
close (LoopBreakerWriter);
if (epfd != -1)
close (epfd);
if (kqfd != -1)
close (kqfd);
}
/*************************
EventMachine_t::_UseEpoll
*************************/
void EventMachine_t::_UseEpoll()
{
/* Temporary.
* Use an internal flag to switch in epoll-based functionality until we determine
* how it should be integrated properly and the extent of the required changes.
* A permanent solution needs to allow the integration of additional technologies,
* like kqueue and Solaris's events.
*/
#ifdef HAVE_EPOLL
bEpoll = true;
#endif
}
/**************************
EventMachine_t::_UseKqueue
**************************/
void EventMachine_t::_UseKqueue()
{
/* Temporary.
* See comments under _UseEpoll.
*/
#ifdef HAVE_KQUEUE
bKqueue = true;
#endif
}
/****************************
EventMachine_t::ScheduleHalt
****************************/
void EventMachine_t::ScheduleHalt()
{
/* This is how we stop the machine.
* This can be called by clients. Signal handlers will probably
* set the global flag.
* For now this means there can only be one EventMachine ever running at a time.
*
* IMPORTANT: keep this light, fast, and async-safe. Don't do anything frisky in here,
* because it may be called from signal handlers invoked from code that we don't
* control. At this writing (20Sep06), EM does NOT install any signal handlers of
* its own.
*
* We need a FAQ. And one of the questions is: how do I stop EM when Ctrl-C happens?
* The answer is to call evma_stop_machine, which calls here, from a SIGINT handler.
*/
gTerminateSignalReceived = true;
}
/*******************************
EventMachine_t::SetTimerQuantum
*******************************/
void EventMachine_t::SetTimerQuantum (int interval)
{
/* We get a timer-quantum expressed in milliseconds.
* Don't set a quantum smaller than 5 or larger than 2500.
*/
if ((interval < 5) || (interval > 2500))
throw std::runtime_error ("invalid timer-quantum");
Quantum.tv_sec = interval / 1000;
Quantum.tv_usec = (interval % 1000) * 1000;
}
/*************************************
(STATIC) EventMachine_t::SetuidString
*************************************/
void EventMachine_t::SetuidString (const char *username)
{
/* This method takes a caller-supplied username and tries to setuid
* to that user. There is no meaningful implementation (and no error)
* on Windows. On Unix, a failure to setuid the caller-supplied string
* causes a fatal abort, because presumably the program is calling here
* in order to fulfill a security requirement. If we fail silently,
* the user may continue to run with too much privilege.
*
* TODO, we need to decide on and document a way of generating C++ level errors
* that can be wrapped in documented Ruby exceptions, so users can catch
* and handle them. And distinguish it from errors that we WON'T let the Ruby
* user catch (like security-violations and resource-overallocation).
* A setuid failure here would be in the latter category.
*/
#ifdef OS_UNIX
if (!username || !*username)
throw std::runtime_error ("setuid_string failed: no username specified");
struct passwd *p = getpwnam (username);
if (!p)
throw std::runtime_error ("setuid_string failed: unknown username");
if (setuid (p->pw_uid) != 0)
throw std::runtime_error ("setuid_string failed: no setuid");
// Success.
#endif
}
/****************************************
(STATIC) EventMachine_t::SetRlimitNofile
****************************************/
int EventMachine_t::SetRlimitNofile (int nofiles)
{
#ifdef OS_UNIX
struct rlimit rlim;
getrlimit (RLIMIT_NOFILE, &rlim);
if (nofiles >= 0) {
rlim.rlim_cur = nofiles;
if (nofiles > rlim.rlim_max)
rlim.rlim_max = nofiles;
setrlimit (RLIMIT_NOFILE, &rlim);
// ignore the error return, for now at least.
// TODO, emit an error message someday when we have proper debug levels.
}
getrlimit (RLIMIT_NOFILE, &rlim);
return rlim.rlim_cur;
#endif
#ifdef OS_WIN32
// No meaningful implementation on Windows.
return 0;
#endif
}
/*********************************
EventMachine_t::SignalLoopBreaker
*********************************/
void EventMachine_t::SignalLoopBreaker()
{
#ifdef OS_UNIX
write (LoopBreakerWriter, "", 1);
#endif
#ifdef OS_WIN32
sendto (LoopBreakerReader, "", 0, 0, (struct sockaddr*)&(LoopBreakerTarget), sizeof(LoopBreakerTarget));
#endif
}
/**************************************
EventMachine_t::_InitializeLoopBreaker
**************************************/
void EventMachine_t::_InitializeLoopBreaker()
{
/* A "loop-breaker" is a socket-descriptor that we can write to in order
* to break the main select loop. Primarily useful for things running on
* threads other than the main EM thread, so they can trigger processing
* of events that arise exogenously to the EM.
* Keep the loop-breaker pipe out of the main descriptor set, otherwise
* its events will get passed on to user code.
*/
#ifdef OS_UNIX
int fd[2];
if (pipe (fd))
throw std::runtime_error ("no loop breaker");
LoopBreakerWriter = fd[1];
LoopBreakerReader = fd[0];
#endif
#ifdef OS_WIN32
int sd = socket (AF_INET, SOCK_DGRAM, 0);
if (sd == INVALID_SOCKET)
throw std::runtime_error ("no loop breaker socket");
SetSocketNonblocking (sd);
memset (&LoopBreakerTarget, 0, sizeof(LoopBreakerTarget));
LoopBreakerTarget.sin_family = AF_INET;
LoopBreakerTarget.sin_addr.s_addr = inet_addr ("127.0.0.1");
srand ((int)time(NULL));
int i;
for (i=0; i < 100; i++) {
int r = (rand() % 10000) + 20000;
LoopBreakerTarget.sin_port = htons (r);
if (bind (sd, (struct sockaddr*)&LoopBreakerTarget, sizeof(LoopBreakerTarget)) == 0)
break;
}
if (i == 100)
throw std::runtime_error ("no loop breaker");
LoopBreakerReader = sd;
#endif
}
/*******************
EventMachine_t::Run
*******************/
void EventMachine_t::Run()
{
#ifdef OS_WIN32
HookControlC (true);
#endif
#ifdef HAVE_EPOLL
if (bEpoll) {
epfd = epoll_create (MaxEpollDescriptors);
if (epfd == -1) {
char buf[200];
snprintf (buf, sizeof(buf)-1, "unable to create epoll descriptor: %s", strerror(errno));
throw std::runtime_error (buf);
}
int cloexec = fcntl (epfd, F_GETFD, 0);
assert (cloexec >= 0);
cloexec |= FD_CLOEXEC;
fcntl (epfd, F_SETFD, cloexec);
assert (LoopBreakerReader >= 0);
LoopbreakDescriptor *ld = new LoopbreakDescriptor (LoopBreakerReader, this);
assert (ld);
Add (ld);
}
#endif
#ifdef HAVE_KQUEUE
if (bKqueue) {
kqfd = kqueue();
if (kqfd == -1) {
char buf[200];
snprintf (buf, sizeof(buf)-1, "unable to create kqueue descriptor: %s", strerror(errno));
throw std::runtime_error (buf);
}
// cloexec not needed. By definition, kqueues are not carried across forks.
assert (LoopBreakerReader >= 0);
LoopbreakDescriptor *ld = new LoopbreakDescriptor (LoopBreakerReader, this);
assert (ld);
Add (ld);
}
#endif
while (true) {
gCurrentLoopTime = time(NULL);
if (!_RunTimers())
break;
/* _Add must precede _Modify because the same descriptor might
* be on both lists during the same pass through the machine,
* and to modify a descriptor before adding it would fail.
*/
_AddNewDescriptors();
_ModifyDescriptors();
if (!_RunOnce())
break;
if (gTerminateSignalReceived)
break;
}
#ifdef OS_WIN32
HookControlC (false);
#endif
}
/************************
EventMachine_t::_RunOnce
************************/
bool EventMachine_t::_RunOnce()
{
if (bEpoll)
return _RunEpollOnce();
else if (bKqueue)
return _RunKqueueOnce();
else
return _RunSelectOnce();
}
/*****************************
EventMachine_t::_RunEpollOnce
*****************************/
bool EventMachine_t::_RunEpollOnce()
{
#ifdef HAVE_EPOLL
assert (epfd != -1);
struct epoll_event ev [MaxEpollDescriptors];
int s;
#ifdef BUILD_FOR_RUBY
TRAP_BEG;
#endif
s = epoll_wait (epfd, ev, MaxEpollDescriptors, 50);
#ifdef BUILD_FOR_RUBY
TRAP_END;
#endif
if (s > 0) {
for (int i=0; i < s; i++) {
EventableDescriptor *ed = (EventableDescriptor*) ev[i].data.ptr;
if (ev[i].events & (EPOLLERR | EPOLLHUP))
ed->ScheduleClose (false);
if (ev[i].events & EPOLLIN)
ed->Read();
if (ev[i].events & EPOLLOUT) {
ed->Write();
epoll_ctl (epfd, EPOLL_CTL_MOD, ed->GetSocket(), ed->GetEpollEvent());
// Ignoring return value
}
}
}
else if (s < 0) {
// epoll_wait can fail on error in a handful of ways.
// If this happens, then wait for a little while to avoid busy-looping.
// If the error was EINTR, we probably caught SIGCHLD or something,
// so keep the wait short.
timeval tv = {0, ((errno == EINTR) ? 5 : 50) * 1000};
EmSelect (0, NULL, NULL, NULL, &tv);
}
{ // cleanup dying sockets
// vector::pop_back works in constant time.
// TODO, rip this out and only delete the descriptors we know have died,
// rather than traversing the whole list.
// Modified 05Jan08 per suggestions by Chris Heath. It's possible that
// an EventableDescriptor will have a descriptor value of -1. That will
// happen if EventableDescriptor::Close was called on it. In that case,
// don't call epoll_ctl to remove the socket's filters from the epoll set.
// According to the epoll docs, this happens automatically when the
// descriptor is closed anyway. This is different from the case where
// the socket has already been closed but the descriptor in the ED object
// hasn't yet been set to INVALID_SOCKET.
int i, j;
int nSockets = Descriptors.size();
for (i=0, j=0; i < nSockets; i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
if (ed->ShouldDelete()) {
if (ed->GetSocket() != INVALID_SOCKET) {
assert (bEpoll); // wouldn't be in this method otherwise.
assert (epfd != -1);
int e = epoll_ctl (epfd, EPOLL_CTL_DEL, ed->GetSocket(), ed->GetEpollEvent());
// ENOENT or EBADF are not errors because the socket may be already closed when we get here.
if (e && (errno != ENOENT) && (errno != EBADF)) {
char buf [200];
snprintf (buf, sizeof(buf)-1, "unable to delete epoll event: %s", strerror(errno));
throw std::runtime_error (buf);
}
}
ModifiedDescriptors.erase (ed);
delete ed;
}
else
Descriptors [j++] = ed;
}
while ((size_t)j < Descriptors.size())
Descriptors.pop_back();
}
// TODO, heartbeats.
// Added 14Sep07, its absence was noted by Brian Candler. But the comment was here, indicated
// that this got thought about and not done when EPOLL was originally written. Was there a reason
// not to do it, or was it an oversight? Certainly, running a heartbeat on 50,000 connections every
// two seconds can get to be a real bear, especially if all we're doing is timing out dead ones.
// Maybe there's a better way to do this. (Or maybe it's not that expensive after all.)
//
{ // dispatch heartbeats
if (gCurrentLoopTime >= NextHeartbeatTime) {
NextHeartbeatTime = gCurrentLoopTime + HeartbeatInterval;
for (int i=0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
ed->Heartbeat();
}
}
}
#ifdef BUILD_FOR_RUBY
if (!rb_thread_alone()) {
rb_thread_schedule();
}
#endif
return true;
#else
throw std::runtime_error ("epoll is not implemented on this platform");
#endif
}
/******************************
EventMachine_t::_RunKqueueOnce
******************************/
bool EventMachine_t::_RunKqueueOnce()
{
#ifdef HAVE_KQUEUE
assert (kqfd != -1);
const int maxKevents = 2000;
struct kevent Karray [maxKevents];
struct timespec ts = {0, 10000000}; // Too frequent. Use blocking_region
int k;
#ifdef BUILD_FOR_RUBY
TRAP_BEG;
#endif
k = kevent (kqfd, NULL, 0, Karray, maxKevents, &ts);
#ifdef BUILD_FOR_RUBY
TRAP_END;
#endif
struct kevent *ke = Karray;
while (k > 0) {
EventableDescriptor *ed = (EventableDescriptor*) (ke->udata);
assert (ed);
if (ke->filter == EVFILT_READ)
ed->Read();
else if (ke->filter == EVFILT_WRITE)
ed->Write();
else
cerr << "Discarding unknown kqueue event " << ke->filter << endl;
--k;
++ke;
}
{ // cleanup dying sockets
// vector::pop_back works in constant time.
// TODO, rip this out and only delete the descriptors we know have died,
// rather than traversing the whole list.
// In kqueue, closing a descriptor automatically removes its event filters.
int i, j;
int nSockets = Descriptors.size();
for (i=0, j=0; i < nSockets; i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
if (ed->ShouldDelete()) {
ModifiedDescriptors.erase (ed);
delete ed;
}
else
Descriptors [j++] = ed;
}
while ((size_t)j < Descriptors.size())
Descriptors.pop_back();
}
{ // dispatch heartbeats
if (gCurrentLoopTime >= NextHeartbeatTime) {
NextHeartbeatTime = gCurrentLoopTime + HeartbeatInterval;
for (int i=0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
ed->Heartbeat();
}
}
}
// TODO, replace this with rb_thread_blocking_region for 1.9 builds.
#ifdef BUILD_FOR_RUBY
if (!rb_thread_alone()) {
rb_thread_schedule();
}
#endif
return true;
#else
throw std::runtime_error ("kqueue is not implemented on this platform");
#endif
}
/*********************************
EventMachine_t::_ModifyEpollEvent
*********************************/
void EventMachine_t::_ModifyEpollEvent (EventableDescriptor *ed)
{
#ifdef HAVE_EPOLL
if (bEpoll) {
assert (epfd != -1);
assert (ed);
int e = epoll_ctl (epfd, EPOLL_CTL_MOD, ed->GetSocket(), ed->GetEpollEvent());
if (e) {
char buf [200];
snprintf (buf, sizeof(buf)-1, "unable to modify epoll event: %s", strerror(errno));
throw std::runtime_error (buf);
}
}
#endif
}
/**************************
SelectData_t::SelectData_t
**************************/
SelectData_t::SelectData_t()
{
maxsocket = 0;
FD_ZERO (&fdreads);
FD_ZERO (&fdwrites);
}
#ifdef BUILD_FOR_RUBY
/*****************
_SelectDataSelect
*****************/
#ifdef HAVE_TBR
static VALUE _SelectDataSelect (void *v)
{
SelectData_t *sd = (SelectData_t*)v;
sd->nSockets = select (sd->maxsocket+1, &(sd->fdreads), &(sd->fdwrites), NULL, &(sd->tv));
return Qnil;
}
#endif
/*********************
SelectData_t::_Select
*********************/
int SelectData_t::_Select()
{
#ifdef HAVE_TBR
rb_thread_blocking_region (_SelectDataSelect, (void*)this, RUBY_UBF_IO, 0);
return nSockets;
#endif
#ifndef HAVE_TBR
return EmSelect (maxsocket+1, &fdreads, &fdwrites, NULL, &tv);
#endif
}
#endif
/******************************
EventMachine_t::_RunSelectOnce
******************************/
bool EventMachine_t::_RunSelectOnce()
{
// Crank the event machine once.
// If there are no descriptors to process, then sleep
// for a few hundred mills to avoid busy-looping.
// Return T/F to indicate whether we should continue.
// This is based on a select loop. Alternately provide epoll
// if we know we're running on a 2.6 kernel.
// epoll will be effective if we provide it as an alternative,
// however it has the same problem interoperating with Ruby
// threads that select does.
//cerr << "X";
/* This protection is now obsolete, because we will ALWAYS
* have at least one descriptor (the loop-breaker) to read.
*/
/*
if (Descriptors.size() == 0) {
#ifdef OS_UNIX
timeval tv = {0, 200 * 1000};
EmSelect (0, NULL, NULL, NULL, &tv);
return true;
#endif
#ifdef OS_WIN32
Sleep (200);
return true;
#endif
}
*/
SelectData_t SelectData;
/*
fd_set fdreads, fdwrites;
FD_ZERO (&fdreads);
FD_ZERO (&fdwrites);
int maxsocket = 0;
*/
// Always read the loop-breaker reader.
// Changed 23Aug06, provisionally implemented for Windows with a UDP socket
// running on localhost with a randomly-chosen port. (*Puke*)
// Windows has a version of the Unix pipe() library function, but it doesn't
// give you back descriptors that are selectable.
FD_SET (LoopBreakerReader, &(SelectData.fdreads));
if (SelectData.maxsocket < LoopBreakerReader)
SelectData.maxsocket = LoopBreakerReader;
// prepare the sockets for reading and writing
size_t i;
for (i = 0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
int sd = ed->GetSocket();
assert (sd != INVALID_SOCKET);
if (ed->SelectForRead())
FD_SET (sd, &(SelectData.fdreads));
if (ed->SelectForWrite())
FD_SET (sd, &(SelectData.fdwrites));
if (SelectData.maxsocket < sd)
SelectData.maxsocket = sd;
}
{ // read and write the sockets
//timeval tv = {1, 0}; // Solaris fails if the microseconds member is >= 1000000.
//timeval tv = Quantum;
SelectData.tv = Quantum;
int s = SelectData._Select();
//rb_thread_blocking_region(xxx,(void*)&SelectData,RUBY_UBF_IO,0);
//int s = EmSelect (SelectData.maxsocket+1, &(SelectData.fdreads), &(SelectData.fdwrites), NULL, &(SelectData.tv));
//int s = SelectData.nSockets;
if (s > 0) {
/* Changed 01Jun07. We used to handle the Loop-breaker right here.
* Now we do it AFTER all the regular descriptors. There's an
* incredibly important and subtle reason for this. Code on
* loop breakers is sometimes used to cause the reactor core to
* cycle (for example, to allow outbound network buffers to drain).
* If a loop-breaker handler reschedules itself (say, after determining
* that the write buffers are still too full), then it will execute
* IMMEDIATELY if _ReadLoopBreaker is done here instead of after
* the other descriptors are processed. That defeats the whole purpose.
*/
for (i=0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
int sd = ed->GetSocket();
assert (sd != INVALID_SOCKET);
if (FD_ISSET (sd, &(SelectData.fdwrites)))
ed->Write();
if (FD_ISSET (sd, &(SelectData.fdreads)))
ed->Read();
}
if (FD_ISSET (LoopBreakerReader, &(SelectData.fdreads)))
_ReadLoopBreaker();
}
else if (s < 0) {
// select can fail on error in a handful of ways.
// If this happens, then wait for a little while to avoid busy-looping.
// If the error was EINTR, we probably caught SIGCHLD or something,
// so keep the wait short.
timeval tv = {0, ((errno == EINTR) ? 5 : 50) * 1000};
EmSelect (0, NULL, NULL, NULL, &tv);
}
}
{ // dispatch heartbeats
if (gCurrentLoopTime >= NextHeartbeatTime) {
NextHeartbeatTime = gCurrentLoopTime + HeartbeatInterval;
for (i=0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
ed->Heartbeat();
}
}
}
{ // cleanup dying sockets
// vector::pop_back works in constant time.
int i, j;
int nSockets = Descriptors.size();
for (i=0, j=0; i < nSockets; i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
if (ed->ShouldDelete())
delete ed;
else
Descriptors [j++] = ed;
}
while ((size_t)j < Descriptors.size())
Descriptors.pop_back();
}
return true;
}
/********************************
EventMachine_t::_ReadLoopBreaker
********************************/
void EventMachine_t::_ReadLoopBreaker()
{
/* The loop breaker has selected readable.
* Read it ONCE (it may block if we try to read it twice)
* and send a loop-break event back to user code.
*/
char buffer [1024];
read (LoopBreakerReader, buffer, sizeof(buffer));
if (EventCallback)
(*EventCallback)("", EM_LOOPBREAK_SIGNAL, "", 0);
}
/**************************
EventMachine_t::_RunTimers
**************************/
bool EventMachine_t::_RunTimers()
{
// These are caller-defined timer handlers.
// Return T/F to indicate whether we should continue the main loop.
// We rely on the fact that multimaps sort by their keys to avoid
// inspecting the whole list every time we come here.
// Just keep inspecting and processing the list head until we hit
// one that hasn't expired yet.
#ifdef OS_UNIX
struct timeval tv;
gettimeofday (&tv, NULL);
Int64 now = (((Int64)(tv.tv_sec)) * 1000000LL) + ((Int64)(tv.tv_usec));
#endif
#ifdef OS_WIN32
unsigned tick = GetTickCount();
if (tick < gLastTickCount)
gTickCountTickover += 1;
gLastTickCount = tick;
Int64 now = ((Int64)gTickCountTickover << 32) + (Int64)tick;
#endif
while (true) {
multimap<Int64,Timer_t>::iterator i = Timers.begin();
if (i == Timers.end())
break;
if (i->first > now)
break;
if (EventCallback)
(*EventCallback) ("", EM_TIMER_FIRED, i->second.GetBinding().c_str(), i->second.GetBinding().length());
Timers.erase (i);
}
return true;
}
/***********************************
EventMachine_t::InstallOneshotTimer
***********************************/
const char *EventMachine_t::InstallOneshotTimer (int milliseconds)
{
if (Timers.size() > MaxOutstandingTimers)
return false;
// Don't use the global loop-time variable here, because we might
// get called before the main event machine is running.
#ifdef OS_UNIX
struct timeval tv;
gettimeofday (&tv, NULL);
Int64 fire_at = (((Int64)(tv.tv_sec)) * 1000000LL) + ((Int64)(tv.tv_usec));
fire_at += ((Int64)milliseconds) * 1000LL;
#endif
#ifdef OS_WIN32
unsigned tick = GetTickCount();
if (tick < gLastTickCount)
gTickCountTickover += 1;
gLastTickCount = tick;
Int64 fire_at = ((Int64)gTickCountTickover << 32) + (Int64)tick;
fire_at += (Int64)milliseconds;
#endif
Timer_t t;
multimap<Int64,Timer_t>::iterator i =
Timers.insert (make_pair (fire_at, t));
return i->second.GetBindingChars();
}
/*******************************
EventMachine_t::ConnectToServer
*******************************/
const char *EventMachine_t::ConnectToServer (const char *server, int port)
{
/* We want to spend no more than a few seconds waiting for a connection
* to a remote host. So we use a nonblocking connect.
* Linux disobeys the usual rules for nonblocking connects.
* Per Stevens (UNP p.410), you expect a nonblocking connect to select
* both readable and writable on error, and not to return EINPROGRESS
* if the connect can be fulfilled immediately. Linux violates both
* of these expectations.
* Any kind of nonblocking connect on Linux returns EINPROGRESS.
* The socket will then return writable when the disposition of the
* connect is known, but it will not also be readable in case of
* error! Weirdly, it will be readable in case there is data to read!!!
* (Which can happen with protocols like SSH and SMTP.)
* I suppose if you were so inclined you could consider this logical,
* but it's not the way Unix has historically done it.
* So we ignore the readable flag and read getsockopt to see if there
* was an error connecting. A select timeout works as expected.
* In regard to getsockopt: Linux does the Berkeley-style thing,
* not the Solaris-style, and returns zero with the error code in
* the error parameter.
* Return the binding-text of the newly-created pending connection,
* or NULL if there was a problem.
*/
if (!server || !*server || !port)
return NULL;
int family, bind_size;
struct sockaddr *bind_as = name2address (server, port, &family, &bind_size);
if (!bind_as)
return NULL;
int sd = socket (family, SOCK_STREAM, 0);
if (sd == INVALID_SOCKET)
return NULL;
/*
sockaddr_in pin;
unsigned long HostAddr;
HostAddr = inet_addr (server);
if (HostAddr == INADDR_NONE) {
hostent *hp = gethostbyname ((char*)server); // Windows requires (char*)
if (!hp) {
// TODO: This gives the caller a fatal error. Not good.
// They can respond by catching RuntimeError (blecch).
// Possibly we need to fire an unbind event and provide
// a status code so user code can detect the cause of the
// failure.
return NULL;
}
HostAddr = ((in_addr*)(hp->h_addr))->s_addr;
}
memset (&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = HostAddr;
pin.sin_port = htons (port);
int sd = socket (AF_INET, SOCK_STREAM, 0);
if (sd == INVALID_SOCKET)
return NULL;
*/
// From here on, ALL error returns must close the socket.
// Set the new socket nonblocking.
if (!SetSocketNonblocking (sd)) {
closesocket (sd);
return NULL;
}
// Disable slow-start (Nagle algorithm).
int one = 1;
setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (char*) &one, sizeof(one));
const char *out = NULL;
#ifdef OS_UNIX
//if (connect (sd, (sockaddr*)&pin, sizeof pin) == 0) {
if (connect (sd, bind_as, bind_size) == 0) {
// This is a connect success, which Linux appears
// never to give when the socket is nonblocking,
// even if the connection is intramachine or to
// localhost.
/* Changed this branch 08Aug06. Evidently some kernels
* (FreeBSD for example) will actually return success from
* a nonblocking connect. This is a pretty simple case,
* just set up the new connection and clear the pending flag.
* Thanks to Chris Ochs for helping track this down.
* This branch never gets taken on Linux or (oddly) OSX.
* The original behavior was to throw an unimplemented,
* which the user saw as a fatal exception. Very unfriendly.
*
* Tweaked 10Aug06. Even though the connect disposition is
* known, we still set the connect-pending flag. That way
* some needed initialization will happen in the ConnectionDescriptor.
* (To wit, the ConnectionCompleted event gets sent to the client.)
*/
ConnectionDescriptor *cd = new ConnectionDescriptor (sd, this);
if (!cd)
throw std::runtime_error ("no connection allocated");
cd->SetConnectPending (true);
Add (cd);
out = cd->GetBinding().c_str();
}
else if (errno == EINPROGRESS) {
// Errno will generally always be EINPROGRESS, but on Linux
// we have to look at getsockopt to be sure what really happened.
int error;
socklen_t len;
len = sizeof(error);
int o = getsockopt (sd, SOL_SOCKET, SO_ERROR, &error, &len);
if ((o == 0) && (error == 0)) {
// Here, there's no disposition.
// Put the connection on the stack and wait for it to complete
// or time out.
ConnectionDescriptor *cd = new ConnectionDescriptor (sd, this);
if (!cd)
throw std::runtime_error ("no connection allocated");
cd->SetConnectPending (true);
Add (cd);
out = cd->GetBinding().c_str();
}
else {
/* This could be connection refused or some such thing.
* We will come here on Linux if a localhost connection fails.
* Changed 16Jul06: Originally this branch was a no-op, and
* we'd drop down to the end of the method, close the socket,
* and return NULL, which would cause the caller to GET A
* FATAL EXCEPTION. Now we keep the socket around but schedule an
* immediate close on it, so the caller will get a close-event
* scheduled on it. This was only an issue for localhost connections
* to non-listening ports. We may eventually need to revise this
* revised behavior, in case it causes problems like making it hard
* for people to know that a failure occurred.
*/
ConnectionDescriptor *cd = new ConnectionDescriptor (sd, this);
if (!cd)
throw std::runtime_error ("no connection allocated");
cd->ScheduleClose (false);
Add (cd);
out = cd->GetBinding().c_str();
}
}
else {
// The error from connect was something other then EINPROGRESS.
}
#endif
#ifdef OS_WIN32
//if (connect (sd, (sockaddr*)&pin, sizeof pin) == 0) {
if (connect (sd, bind_as, bind_size) == 0) {
// This is a connect success, which Windows appears
// never to give when the socket is nonblocking,
// even if the connection is intramachine or to
// localhost.
throw std::runtime_error ("unimplemented");
}
else if (WSAGetLastError() == WSAEWOULDBLOCK) {
// Here, there's no disposition.
// Windows appears not to surface refused connections or
// such stuff at this point.
// Put the connection on the stack and wait for it to complete
// or time out.
ConnectionDescriptor *cd = new ConnectionDescriptor (sd, this);
if (!cd)
throw std::runtime_error ("no connection allocated");
cd->SetConnectPending (true);
Add (cd);
out = cd->GetBinding().c_str();
}
else {
// The error from connect was something other then WSAEWOULDBLOCK.
}
#endif
if (out == NULL)
closesocket (sd);
return out;
}
/***********************************
EventMachine_t::ConnectToUnixServer
***********************************/
const char *EventMachine_t::ConnectToUnixServer (const char *server)
{
/* Connect to a Unix-domain server, which by definition is running
* on the same host.
* There is no meaningful implementation on Windows.
* There's no need to do a nonblocking connect, since the connection
* is always local and can always be fulfilled immediately.
*/
#ifdef OS_WIN32
throw std::runtime_error ("unix-domain connection unavailable on this platform");
return NULL;
#endif
// The whole rest of this function is only compiled on Unix systems.
#ifdef OS_UNIX
const char *out = NULL;
if (!server || !*server)
return NULL;
sockaddr_un pun;
memset (&pun, 0, sizeof(pun));
pun.sun_family = AF_LOCAL;
// You ordinarily expect the server name field to be at least 1024 bytes long,
// but on Linux it can be MUCH shorter.
if (strlen(server) >= sizeof(pun.sun_path))
throw std::runtime_error ("unix-domain server name is too long");
strcpy (pun.sun_path, server);
int fd = socket (AF_LOCAL, SOCK_STREAM, 0);
if (fd == INVALID_SOCKET)
return NULL;
// From here on, ALL error returns must close the socket.
// NOTE: At this point, the socket is still a blocking socket.
if (connect (fd, (struct sockaddr*)&pun, sizeof(pun)) != 0) {
closesocket (fd);
return NULL;
}
// Set the newly-connected socket nonblocking.
if (!SetSocketNonblocking (fd)) {
closesocket (fd);
return NULL;
}
// Set up a connection descriptor and add it to the event-machine.
// Observe, even though we know the connection status is connect-success,
// we still set the "pending" flag, so some needed initializations take
// place.
ConnectionDescriptor *cd = new ConnectionDescriptor (fd, this);
if (!cd)
throw std::runtime_error ("no connection allocated");
cd->SetConnectPending (true);
Add (cd);
out = cd->GetBinding().c_str();
if (out == NULL)
closesocket (fd);
return out;
#endif
}
/************************
EventMachine_t::AttachFD
************************/
const char *EventMachine_t::AttachFD (int fd, bool notify_readable, bool notify_writable)
{
#ifdef OS_UNIX
if (fcntl(fd, F_GETFL, 0) < 0)
throw std::runtime_error ("invalid file descriptor");
#endif
#ifdef OS_WIN32
// TODO: add better check for invalid file descriptors (see ioctlsocket or getsockopt)
if (fd == INVALID_SOCKET)
throw std::runtime_error ("invalid file descriptor");
#endif
{// Check for duplicate descriptors
size_t i;
for (i = 0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
if (ed->GetSocket() == fd)
throw std::runtime_error ("adding existing descriptor");
}
for (i = 0; i < NewDescriptors.size(); i++) {
EventableDescriptor *ed = NewDescriptors[i];
assert (ed);
if (ed->GetSocket() == fd)
throw std::runtime_error ("adding existing new descriptor");
}
}
ConnectionDescriptor *cd = new ConnectionDescriptor (fd, this);
if (!cd)
throw std::runtime_error ("no connection allocated");
cd->SetConnectPending (true);
cd->SetNotifyReadable (notify_readable);
cd->SetNotifyWritable (notify_writable);
Add (cd);
const char *out = NULL;
out = cd->GetBinding().c_str();
if (out == NULL)
closesocket (fd);
return out;
}
/************************
EventMachine_t::DetachFD
************************/
int EventMachine_t::DetachFD (EventableDescriptor *ed)
{
if (!ed)
throw std::runtime_error ("detaching bad descriptor");
#ifdef HAVE_EPOLL
if (bEpoll) {
if (ed->GetSocket() != INVALID_SOCKET) {
assert (bEpoll); // wouldn't be in this method otherwise.
assert (epfd != -1);
int e = epoll_ctl (epfd, EPOLL_CTL_DEL, ed->GetSocket(), ed->GetEpollEvent());
// ENOENT or EBADF are not errors because the socket may be already closed when we get here.
if (e && (errno != ENOENT) && (errno != EBADF)) {
char buf [200];
snprintf (buf, sizeof(buf)-1, "unable to delete epoll event: %s", strerror(errno));
throw std::runtime_error (buf);
}
}
}
#endif
#ifdef HAVE_KQUEUE
if (bKqueue) {
struct kevent k;
EV_SET (&k, ed->GetSocket(), EVFILT_READ, EV_DELETE, 0, 0, ed);
int t = kevent (kqfd, &k, 1, NULL, 0, NULL);
assert (t == 0);
}
#endif
{ // remove descriptor from lists
int i, j;
int nSockets = Descriptors.size();
for (i=0, j=0; i < nSockets; i++) {
EventableDescriptor *ted = Descriptors[i];
assert (ted);
if (ted != ed)
Descriptors [j++] = ted;
}
while ((size_t)j < Descriptors.size())
Descriptors.pop_back();
ModifiedDescriptors.erase (ed);
}
int fd = ed->GetSocket();
// We depend on ~EventableDescriptor not calling close() if the socket is invalid
ed->SetSocketInvalid();
delete ed;
return fd;
}
/************
name2address
************/
struct sockaddr *name2address (const char *server, int port, int *family, int *bind_size)
{
// THIS IS NOT RE-ENTRANT OR THREADSAFE. Optimize for speed.
// Check the more-common cases first.
// Return NULL if no resolution.
static struct sockaddr_in in4;
#ifndef __CYGWIN__
static struct sockaddr_in6 in6;
#endif
struct hostent *hp;
if (!server || !*server)
server = "0.0.0.0";
memset (&in4, 0, sizeof(in4));
if ( (in4.sin_addr.s_addr = inet_addr (server)) != INADDR_NONE) {
if (family)
*family = AF_INET;
if (bind_size)
*bind_size = sizeof(in4);
in4.sin_family = AF_INET;
in4.sin_port = htons (port);
return (struct sockaddr*)&in4;
}
#if defined(OS_UNIX) && !defined(__CYGWIN__)
memset (&in6, 0, sizeof(in6));
if (inet_pton (AF_INET6, server, in6.sin6_addr.s6_addr) > 0) {
if (family)
*family = AF_INET6;
if (bind_size)
*bind_size = sizeof(in6);
in6.sin6_family = AF_INET6;
in6.sin6_port = htons (port);
return (struct sockaddr*)&in6;
}
#endif
#ifdef OS_WIN32
// TODO, must complete this branch. Windows doesn't have inet_pton.
// A possible approach is to make a getaddrinfo call with the supplied
// server address, constraining the hints to ipv6 and seeing if we
// get any addresses.
// For the time being, Ipv6 addresses aren't supported on Windows.
#endif
hp = gethostbyname ((char*)server); // Windows requires the cast.
if (hp) {
in4.sin_addr.s_addr = ((in_addr*)(hp->h_addr))->s_addr;
if (family)
*family = AF_INET;
if (bind_size)
*bind_size = sizeof(in4);
in4.sin_family = AF_INET;
in4.sin_port = htons (port);
return (struct sockaddr*)&in4;
}
return NULL;
}
/*******************************
EventMachine_t::CreateTcpServer
*******************************/
const char *EventMachine_t::CreateTcpServer (const char *server, int port)
{
/* Create a TCP-acceptor (server) socket and add it to the event machine.
* Return the binding of the new acceptor to the caller.
* This binding will be referenced when the new acceptor sends events
* to indicate accepted connections.
*/
int family, bind_size;
struct sockaddr *bind_here = name2address (server, port, &family, &bind_size);
if (!bind_here)
return NULL;
const char *output_binding = NULL;
//struct sockaddr_in sin;
int sd_accept = socket (family, SOCK_STREAM, 0);
if (sd_accept == INVALID_SOCKET) {
goto fail;
}
/*
memset (&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons (port);
if (server && *server) {
sin.sin_addr.s_addr = inet_addr (server);
if (sin.sin_addr.s_addr == INADDR_NONE) {
hostent *hp = gethostbyname ((char*)server); // Windows requires the cast.
if (hp == NULL) {
//__warning ("hostname not resolved: ", server);
goto fail;
}
sin.sin_addr.s_addr = ((in_addr*)(hp->h_addr))->s_addr;
}
}
*/
{ // set reuseaddr to improve performance on restarts.
int oval = 1;
if (setsockopt (sd_accept, SOL_SOCKET, SO_REUSEADDR, (char*)&oval, sizeof(oval)) < 0) {
//__warning ("setsockopt failed while creating listener","");
goto fail;
}
}
{ // set CLOEXEC. Only makes sense on Unix
#ifdef OS_UNIX
int cloexec = fcntl (sd_accept, F_GETFD, 0);
assert (cloexec >= 0);
cloexec |= FD_CLOEXEC;
fcntl (sd_accept, F_SETFD, cloexec);
#endif
}
//if (bind (sd_accept, (struct sockaddr*)&sin, sizeof(sin))) {
if (bind (sd_accept, bind_here, bind_size)) {
//__warning ("binding failed");
goto fail;
}
if (listen (sd_accept, 100)) {
//__warning ("listen failed");
goto fail;
}
{
// Set the acceptor non-blocking.
// THIS IS CRUCIALLY IMPORTANT because we read it in a select loop.
if (!SetSocketNonblocking (sd_accept)) {
//int val = fcntl (sd_accept, F_GETFL, 0);
//if (fcntl (sd_accept, F_SETFL, val | O_NONBLOCK) == -1) {
goto fail;
}
}
{ // Looking good.
AcceptorDescriptor *ad = new AcceptorDescriptor (sd_accept, this);
if (!ad)
throw std::runtime_error ("unable to allocate acceptor");
Add (ad);
output_binding = ad->GetBinding().c_str();
}
return output_binding;
fail:
if (sd_accept != INVALID_SOCKET)
closesocket (sd_accept);
return NULL;
}
/**********************************
EventMachine_t::OpenDatagramSocket
**********************************/
const char *EventMachine_t::OpenDatagramSocket (const char *address, int port)
{
const char *output_binding = NULL;
int sd = socket (AF_INET, SOCK_DGRAM, 0);
if (sd == INVALID_SOCKET)
goto fail;
// from here on, early returns must close the socket!
struct sockaddr_in sin;
memset (&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons (port);
if (address && *address) {
sin.sin_addr.s_addr = inet_addr (address);
if (sin.sin_addr.s_addr == INADDR_NONE) {
hostent *hp = gethostbyname ((char*)address); // Windows requires the cast.
if (hp == NULL)
goto fail;
sin.sin_addr.s_addr = ((in_addr*)(hp->h_addr))->s_addr;
}
}
else
sin.sin_addr.s_addr = htonl (INADDR_ANY);
// Set the new socket nonblocking.
{
if (!SetSocketNonblocking (sd))
//int val = fcntl (sd, F_GETFL, 0);
//if (fcntl (sd, F_SETFL, val | O_NONBLOCK) == -1)
goto fail;
}
if (bind (sd, (struct sockaddr*)&sin, sizeof(sin)) != 0)
goto fail;
{ // Looking good.
DatagramDescriptor *ds = new DatagramDescriptor (sd, this);
if (!ds)
throw std::runtime_error ("unable to allocate datagram-socket");
Add (ds);
output_binding = ds->GetBinding().c_str();
}
return output_binding;
fail:
if (sd != INVALID_SOCKET)
closesocket (sd);
return NULL;
}
/*******************
EventMachine_t::Add
*******************/
void EventMachine_t::Add (EventableDescriptor *ed)
{
if (!ed)
throw std::runtime_error ("added bad descriptor");
ed->SetEventCallback (EventCallback);
NewDescriptors.push_back (ed);
}
/*******************************
EventMachine_t::ArmKqueueWriter
*******************************/
void EventMachine_t::ArmKqueueWriter (EventableDescriptor *ed)
{
#ifdef HAVE_KQUEUE
if (bKqueue) {
if (!ed)
throw std::runtime_error ("added bad descriptor");
struct kevent k;
EV_SET (&k, ed->GetSocket(), EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, ed);
int t = kevent (kqfd, &k, 1, NULL, 0, NULL);
assert (t == 0);
}
#endif
}
/*******************************
EventMachine_t::ArmKqueueReader
*******************************/
void EventMachine_t::ArmKqueueReader (EventableDescriptor *ed)
{
#ifdef HAVE_KQUEUE
if (bKqueue) {
if (!ed)
throw std::runtime_error ("added bad descriptor");
struct kevent k;
EV_SET (&k, ed->GetSocket(), EVFILT_READ, EV_ADD, 0, 0, ed);
int t = kevent (kqfd, &k, 1, NULL, 0, NULL);
assert (t == 0);
}
#endif
}
/**********************************
EventMachine_t::_AddNewDescriptors
**********************************/
void EventMachine_t::_AddNewDescriptors()
{
/* Avoid adding descriptors to the main descriptor list
* while we're actually traversing the list.
* Any descriptors that are added as a result of processing timers
* or acceptors should go on a temporary queue and then added
* while we're not traversing the main list.
* Also, it (rarely) happens that a newly-created descriptor
* is immediately scheduled to close. It might be a good
* idea not to bother scheduling these for I/O but if
* we do that, we might bypass some important processing.
*/
for (size_t i = 0; i < NewDescriptors.size(); i++) {
EventableDescriptor *ed = NewDescriptors[i];
if (ed == NULL)
throw std::runtime_error ("adding bad descriptor");
#if HAVE_EPOLL
if (bEpoll) {
assert (epfd != -1);
int e = epoll_ctl (epfd, EPOLL_CTL_ADD, ed->GetSocket(), ed->GetEpollEvent());
if (e) {
char buf [200];
snprintf (buf, sizeof(buf)-1, "unable to add new descriptor: %s", strerror(errno));
throw std::runtime_error (buf);
}
}
#endif
#if HAVE_KQUEUE
/*
if (bKqueue) {
// INCOMPLETE. Some descriptors don't want to be readable.
assert (kqfd != -1);
struct kevent k;
EV_SET (&k, ed->GetSocket(), EVFILT_READ, EV_ADD, 0, 0, ed);
int t = kevent (kqfd, &k, 1, NULL, 0, NULL);
assert (t == 0);
}
*/
#endif
Descriptors.push_back (ed);
}
NewDescriptors.clear();
}
/**********************************
EventMachine_t::_ModifyDescriptors
**********************************/
void EventMachine_t::_ModifyDescriptors()
{
/* For implementations which don't level check every descriptor on
* every pass through the machine, as select does.
* If we're not selecting, then descriptors need a way to signal to the
* machine that their readable or writable status has changed.
* That's what the ::Modify call is for. We do it this way to avoid
* modifying descriptors during the loop traversal, where it can easily
* happen that an object (like a UDP socket) gets data written on it by
* the application during #post_init. That would take place BEFORE the
* descriptor even gets added to the epoll descriptor, so the modify
* operation will crash messily.
* Another really messy possibility is for a descriptor to put itself
* on the Modified list, and then get deleted before we get here.
* Remember, deletes happen after the I/O traversal and before the
* next pass through here. So we have to make sure when we delete a
* descriptor to remove it from the Modified list.
*/
#ifdef HAVE_EPOLL
if (bEpoll) {
set<EventableDescriptor*>::iterator i = ModifiedDescriptors.begin();
while (i != ModifiedDescriptors.end()) {
assert (*i);
_ModifyEpollEvent (*i);
++i;
}
}
#endif
ModifiedDescriptors.clear();
}
/**********************
EventMachine_t::Modify
**********************/
void EventMachine_t::Modify (EventableDescriptor *ed)
{
if (!ed)
throw std::runtime_error ("modified bad descriptor");
ModifiedDescriptors.insert (ed);
}
/***********************************
EventMachine_t::_OpenFileForWriting
***********************************/
const char *EventMachine_t::_OpenFileForWriting (const char *filename)
{
/*
* Return the binding-text of the newly-opened file,
* or NULL if there was a problem.
*/
if (!filename || !*filename)
return NULL;
int fd = open (filename, O_CREAT|O_TRUNC|O_WRONLY|O_NONBLOCK, 0644);
FileStreamDescriptor *fsd = new FileStreamDescriptor (fd, this);
if (!fsd)
throw std::runtime_error ("no file-stream allocated");
Add (fsd);
return fsd->GetBinding().c_str();
}
/**************************************
EventMachine_t::CreateUnixDomainServer
**************************************/
const char *EventMachine_t::CreateUnixDomainServer (const char *filename)
{
/* Create a UNIX-domain acceptor (server) socket and add it to the event machine.
* Return the binding of the new acceptor to the caller.
* This binding will be referenced when the new acceptor sends events
* to indicate accepted connections.
* THERE IS NO MEANINGFUL IMPLEMENTATION ON WINDOWS.
*/
#ifdef OS_WIN32
throw std::runtime_error ("unix-domain server unavailable on this platform");
#endif
// The whole rest of this function is only compiled on Unix systems.
#ifdef OS_UNIX
const char *output_binding = NULL;
struct sockaddr_un s_sun;
int sd_accept = socket (AF_LOCAL, SOCK_STREAM, 0);
if (sd_accept == INVALID_SOCKET) {
goto fail;
}
if (!filename || !*filename)
goto fail;
unlink (filename);
bzero (&s_sun, sizeof(s_sun));
s_sun.sun_family = AF_LOCAL;
strncpy (s_sun.sun_path, filename, sizeof(s_sun.sun_path)-1);
// don't bother with reuseaddr for a local socket.
{ // set CLOEXEC. Only makes sense on Unix
#ifdef OS_UNIX
int cloexec = fcntl (sd_accept, F_GETFD, 0);
assert (cloexec >= 0);
cloexec |= FD_CLOEXEC;
fcntl (sd_accept, F_SETFD, cloexec);
#endif
}
if (bind (sd_accept, (struct sockaddr*)&s_sun, sizeof(s_sun))) {
//__warning ("binding failed");
goto fail;
}
if (listen (sd_accept, 100)) {
//__warning ("listen failed");
goto fail;
}
{
// Set the acceptor non-blocking.
// THIS IS CRUCIALLY IMPORTANT because we read it in a select loop.
if (!SetSocketNonblocking (sd_accept)) {
//int val = fcntl (sd_accept, F_GETFL, 0);
//if (fcntl (sd_accept, F_SETFL, val | O_NONBLOCK) == -1) {
goto fail;
}
}
{ // Looking good.
AcceptorDescriptor *ad = new AcceptorDescriptor (sd_accept, this);
if (!ad)
throw std::runtime_error ("unable to allocate acceptor");
Add (ad);
output_binding = ad->GetBinding().c_str();
}
return output_binding;
fail:
if (sd_accept != INVALID_SOCKET)
closesocket (sd_accept);
return NULL;
#endif // OS_UNIX
}
/*********************
EventMachine_t::Popen
*********************/
#if OBSOLETE
const char *EventMachine_t::Popen (const char *cmd, const char *mode)
{
#ifdef OS_WIN32
throw std::runtime_error ("popen is currently unavailable on this platform");
#endif
// The whole rest of this function is only compiled on Unix systems.
// Eventually we need this functionality (or a full-duplex equivalent) on Windows.
#ifdef OS_UNIX
const char *output_binding = NULL;
FILE *fp = popen (cmd, mode);
if (!fp)
return NULL;
// From here, all early returns must pclose the stream.
// According to the pipe(2) manpage, descriptors returned from pipe have both
// CLOEXEC and NONBLOCK clear. Do NOT set CLOEXEC. DO set nonblocking.
if (!SetSocketNonblocking (fileno (fp))) {
pclose (fp);
return NULL;
}
{ // Looking good.
PipeDescriptor *pd = new PipeDescriptor (fp, this);
if (!pd)
throw std::runtime_error ("unable to allocate pipe");
Add (pd);
output_binding = pd->GetBinding().c_str();
}
return output_binding;
#endif
}
#endif // OBSOLETE
/**************************
EventMachine_t::Socketpair
**************************/
const char *EventMachine_t::Socketpair (char * const*cmd_strings)
{
#ifdef OS_WIN32
throw std::runtime_error ("socketpair is currently unavailable on this platform");
#endif
// The whole rest of this function is only compiled on Unix systems.
// Eventually we need this functionality (or a full-duplex equivalent) on Windows.
#ifdef OS_UNIX
// Make sure the incoming array of command strings is sane.
if (!cmd_strings)
return NULL;
int j;
for (j=0; j < 100 && cmd_strings[j]; j++)
;
if ((j==0) || (j==100))
return NULL;
const char *output_binding = NULL;
int sv[2];
if (socketpair (AF_LOCAL, SOCK_STREAM, 0, sv) < 0)
return NULL;
// from here, all early returns must close the pair of sockets.
// Set the parent side of the socketpair nonblocking.
// We don't care about the child side, and most child processes will expect their
// stdout to be blocking. Thanks to Duane Johnson and Bill Kelly for pointing this out.
// Obviously DON'T set CLOEXEC.
if (!SetSocketNonblocking (sv[0])) {
close (sv[0]);
close (sv[1]);
return NULL;
}
pid_t f = fork();
if (f > 0) {
close (sv[1]);
PipeDescriptor *pd = new PipeDescriptor (sv[0], f, this);
if (!pd)
throw std::runtime_error ("unable to allocate pipe");
Add (pd);
output_binding = pd->GetBinding().c_str();
}
else if (f == 0) {
close (sv[0]);
dup2 (sv[1], STDIN_FILENO);
close (sv[1]);
dup2 (STDIN_FILENO, STDOUT_FILENO);
execvp (cmd_strings[0], cmd_strings+1);
exit (-1); // end the child process if the exec doesn't work.
}
else
throw std::runtime_error ("no fork");
return output_binding;
#endif
}
/****************************
EventMachine_t::OpenKeyboard
****************************/
const char *EventMachine_t::OpenKeyboard()
{
KeyboardDescriptor *kd = new KeyboardDescriptor (this);
if (!kd)
throw std::runtime_error ("no keyboard-object allocated");
Add (kd);
return kd->GetBinding().c_str();
}
//#endif // OS_UNIX
/*****************************************************************************
$Id$
File: emwin.cpp
Date: 05May06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
// THIS ENTIRE FILE IS FOR WINDOWS BUILDS ONLY
// INCOMPLETE AND DISABLED FOR NOW.
#ifdef xOS_WIN32
#include "project.h"
// Keep a global variable floating around
// with the current loop time as set by the Event Machine.
// This avoids the need for frequent expensive calls to time(NULL);
time_t gCurrentLoopTime;
/******************************
EventMachine_t::EventMachine_t
******************************/
EventMachine_t::EventMachine_t (void (*event_callback)(const char*, int, const char*, int)):
EventCallback (event_callback),
NextHeartbeatTime (0)
{
gTerminateSignalReceived = false;
Iocp = NULL;
}
/*******************************
EventMachine_t::~EventMachine_t
*******************************/
EventMachine_t::~EventMachine_t()
{
cerr << "EM __dt\n";
if (Iocp)
CloseHandle (Iocp);
}
/****************************
EventMachine_t::ScheduleHalt
****************************/
void EventMachine_t::ScheduleHalt()
{
/* This is how we stop the machine.
* This can be called by clients. Signal handlers will probably
* set the global flag.
* For now this means there can only be one EventMachine ever running at a time.
*/
gTerminateSignalReceived = true;
}
/*******************
EventMachine_t::Run
*******************/
void EventMachine_t::Run()
{
HookControlC (true);
Iocp = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL, 0, 0);
if (Iocp == NULL)
throw std::runtime_error ("no completion port");
DWORD nBytes, nCompletionKey;
LPOVERLAPPED Overlapped;
do {
gCurrentLoopTime = time(NULL);
// Have some kind of strategy that will dequeue maybe up to 10 completions
// without running the timers as long as they are available immediately.
// Otherwise in a busy server we're calling them every time through the loop.
if (!_RunTimers())
break;
if (GetQueuedCompletionStatus (Iocp, &nBytes, &nCompletionKey, &Overlapped, 1000)) {
}
cerr << "+";
} while (!gTerminateSignalReceived);
/*
while (true) {
gCurrentLoopTime = time(NULL);
if (!_RunTimers())
break;
_AddNewDescriptors();
if (!_RunOnce())
break;
if (gTerminateSignalReceived)
break;
}
*/
HookControlC (false);
}
/**************************
EventMachine_t::_RunTimers
**************************/
bool EventMachine_t::_RunTimers()
{
// These are caller-defined timer handlers.
// Return T/F to indicate whether we should continue the main loop.
// We rely on the fact that multimaps sort by their keys to avoid
// inspecting the whole list every time we come here.
// Just keep inspecting and processing the list head until we hit
// one that hasn't expired yet.
while (true) {
multimap<time_t,Timer_t>::iterator i = Timers.begin();
if (i == Timers.end())
break;
if (i->first > gCurrentLoopTime)
break;
if (EventCallback)
(*EventCallback) ("", EM_TIMER_FIRED, i->second.GetBinding().c_str(), i->second.GetBinding().length());
Timers.erase (i);
}
return true;
}
/***********************************
EventMachine_t::InstallOneshotTimer
***********************************/
const char *EventMachine_t::InstallOneshotTimer (int seconds)
{
if (Timers.size() > MaxOutstandingTimers)
return false;
// Don't use the global loop-time variable here, because we might
// get called before the main event machine is running.
Timer_t t;
Timers.insert (make_pair (time(NULL) + seconds, t));
return t.GetBinding().c_str();
}
/**********************************
EventMachine_t::OpenDatagramSocket
**********************************/
const char *EventMachine_t::OpenDatagramSocket (const char *address, int port)
{
cerr << "OPEN DATAGRAM SOCKET\n";
return "Unimplemented";
}
/*******************************
EventMachine_t::CreateTcpServer
*******************************/
const char *EventMachine_t::CreateTcpServer (const char *server, int port)
{
/* Create a TCP-acceptor (server) socket and add it to the event machine.
* Return the binding of the new acceptor to the caller.
* This binding will be referenced when the new acceptor sends events
* to indicate accepted connections.
*/
const char *output_binding = NULL;
struct sockaddr_in sin;
SOCKET sd_accept = socket (AF_INET, SOCK_STREAM, 0);
if (sd_accept == INVALID_SOCKET) {
goto fail;
}
memset (&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons (port);
if (server && *server) {
sin.sin_addr.s_addr = inet_addr (server);
if (sin.sin_addr.s_addr == INADDR_NONE) {
hostent *hp = gethostbyname (server);
if (hp == NULL) {
//__warning ("hostname not resolved: ", server);
goto fail;
}
sin.sin_addr.s_addr = ((in_addr*)(hp->h_addr))->s_addr;
}
}
// No need to set reuseaddr on Windows.
if (bind (sd_accept, (struct sockaddr*)&sin, sizeof(sin))) {
//__warning ("binding failed");
goto fail;
}
if (listen (sd_accept, 100)) {
//__warning ("listen failed");
goto fail;
}
{ // Looking good.
AcceptorDescriptor *ad = new AcceptorDescriptor (this, sd_accept);
if (!ad)
throw std::runtime_error ("unable to allocate acceptor");
Add (ad);
output_binding = ad->GetBinding().c_str();
CreateIoCompletionPort ((HANDLE)sd_accept, Iocp, NULL, 0);
SOCKET sd = socket (AF_INET, SOCK_STREAM, 0);
CreateIoCompletionPort ((HANDLE)sd, Iocp, NULL, 0);
AcceptEx (sd_accept, sd,
}
return output_binding;
fail:
if (sd_accept != INVALID_SOCKET)
closesocket (sd_accept);
return NULL;
}
/*******************************
EventMachine_t::ConnectToServer
*******************************/
const char *EventMachine_t::ConnectToServer (const char *server, int port)
{
if (!server || !*server || !port)
return NULL;
sockaddr_in pin;
unsigned long HostAddr;
HostAddr = inet_addr (server);
if (HostAddr == INADDR_NONE) {
hostent *hp = gethostbyname (server);
if (!hp)
return NULL;
HostAddr = ((in_addr*)(hp->h_addr))->s_addr;
}
memset (&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = HostAddr;
pin.sin_port = htons (port);
int sd = socket (AF_INET, SOCK_STREAM, 0);
if (sd == INVALID_SOCKET)
return NULL;
LPOVERLAPPED olap = (LPOVERLAPPED) calloc (1, sizeof (OVERLAPPED));
cerr << "I'm dying now\n";
throw runtime_error ("UNIMPLEMENTED!!!\n");
}
/*******************
EventMachine_t::Add
*******************/
void EventMachine_t::Add (EventableDescriptor *ed)
{
cerr << "ADD\n";
}
#endif // OS_WIN32
/*****************************************************************************
$Id$
File: epoll.cpp
Date: 06Jun07
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#ifdef HAVE_EPOLL
#include "project.h"
#endif // HAVE_EPOLL
/*****************************************************************************
$Id: mapper.cpp 4527 2007-07-04 10:21:34Z francis $
File: mapper.cpp
Date: 02Jul07
Copyright (C) 2007 by Francis Cianfrocca. All Rights Reserved.
Gmail: garbagecat10
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
//////////////////////////////////////////////////////////////////////
// UNIX implementation
//////////////////////////////////////////////////////////////////////
#ifdef OS_UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <iostream>
#include "unistd.h"
#include <string>
#include <cstring>
#include <stdexcept>
using namespace std;
#include "mapper.h"
/******************
Mapper_t::Mapper_t
******************/
Mapper_t::Mapper_t (const string &filename)
{
/* We ASSUME we can open the file.
* (More precisely, we assume someone else checked before we got here.)
*/
Fd = open (filename.c_str(), O_RDONLY);
if (Fd < 0)
throw runtime_error (strerror (errno));
struct stat st;
if (fstat (Fd, &st))
throw runtime_error (strerror (errno));
FileSize = st.st_size;
MapPoint = (const char*) mmap (0, FileSize, PROT_READ, MAP_SHARED, Fd, 0);
if (MapPoint == MAP_FAILED)
throw runtime_error (strerror (errno));
}
/*******************
Mapper_t::~Mapper_t
*******************/
Mapper_t::~Mapper_t()
{
Close();
}
/***************
Mapper_t::Close
***************/
void Mapper_t::Close()
{
// Can be called multiple times.
// Calls to GetChunk are invalid after a call to Close.
if (MapPoint) {
munmap ((void*)MapPoint, FileSize);
MapPoint = NULL;
}
if (Fd >= 0) {
close (Fd);
Fd = -1;
}
}
/******************
Mapper_t::GetChunk
******************/
const char *Mapper_t::GetChunk (unsigned start)
{
return MapPoint + start;
}
#endif // OS_UNIX
//////////////////////////////////////////////////////////////////////
// WINDOWS implementation
//////////////////////////////////////////////////////////////////////
#ifdef OS_WIN32
#include <windows.h>
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
#include "mapper.h"
/******************
Mapper_t::Mapper_t
******************/
Mapper_t::Mapper_t (const string &filename)
{
/* We ASSUME we can open the file.
* (More precisely, we assume someone else checked before we got here.)
*/
hFile = INVALID_HANDLE_VALUE;
hMapping = NULL;
MapPoint = NULL;
FileSize = 0;
hFile = CreateFile (filename.c_str(), GENERIC_READ|GENERIC_WRITE, FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
throw runtime_error ("File not found");
BY_HANDLE_FILE_INFORMATION i;
if (GetFileInformationByHandle (hFile, &i))
FileSize = i.nFileSizeLow;
hMapping = CreateFileMapping (hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
if (!hMapping)
throw runtime_error ("File not mapped");
MapPoint = (const char*) MapViewOfFile (hMapping, FILE_MAP_WRITE, 0, 0, 0);
if (!MapPoint)
throw runtime_error ("Mappoint not read");
}
/*******************
Mapper_t::~Mapper_t
*******************/
Mapper_t::~Mapper_t()
{
Close();
}
/***************
Mapper_t::Close
***************/
void Mapper_t::Close()
{
// Can be called multiple times.
// Calls to GetChunk are invalid after a call to Close.
if (MapPoint) {
UnmapViewOfFile (MapPoint);
MapPoint = NULL;
}
if (hMapping != NULL) {
CloseHandle (hMapping);
hMapping = NULL;
}
if (hFile != INVALID_HANDLE_VALUE) {
CloseHandle (hFile);
hMapping = INVALID_HANDLE_VALUE;
}
}
/******************
Mapper_t::GetChunk
******************/
const char *Mapper_t::GetChunk (unsigned start)
{
return MapPoint + start;
}
#endif // OS_WINDOWS
/*****************************************************************************
$Id: rubymain.cpp 4529 2007-07-04 11:32:22Z francis $
File: rubymain.cpp
Date: 02Jul07
Copyright (C) 2007 by Francis Cianfrocca. All Rights Reserved.
Gmail: garbagecat10
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include <iostream>
#include <stdexcept>
using namespace std;
#include <ruby.h>
#include "mapper.h"
static VALUE EmModule;
static VALUE FastFileReader;
static VALUE Mapper;
/*********
mapper_dt
*********/
static void mapper_dt (void *ptr)
{
if (ptr)
delete (Mapper_t*) ptr;
}
/**********
mapper_new
**********/
static VALUE mapper_new (VALUE self, VALUE filename)
{
Mapper_t *m = new Mapper_t (StringValuePtr (filename));
if (!m)
rb_raise (rb_eException, "No Mapper Object");
VALUE v = Data_Wrap_Struct (Mapper, 0, mapper_dt, (void*)m);
return v;
}
/****************
mapper_get_chunk
****************/
static VALUE mapper_get_chunk (VALUE self, VALUE start, VALUE length)
{
Mapper_t *m = NULL;
Data_Get_Struct (self, Mapper_t, m);
if (!m)
rb_raise (rb_eException, "No Mapper Object");
// TODO, what if some moron sends us a negative start value?
unsigned _start = NUM2INT (start);
unsigned _length = NUM2INT (length);
if ((_start + _length) > m->GetFileSize())
rb_raise (rb_eException, "Mapper Range Error");
const char *chunk = m->GetChunk (_start);
if (!chunk)
rb_raise (rb_eException, "No Mapper Chunk");
return rb_str_new (chunk, _length);
}
/************
mapper_close
************/
static VALUE mapper_close (VALUE self)
{
Mapper_t *m = NULL;
Data_Get_Struct (self, Mapper_t, m);
if (!m)
rb_raise (rb_eException, "No Mapper Object");
m->Close();
return Qnil;
}
/***********
mapper_size
***********/
static VALUE mapper_size (VALUE self)
{
Mapper_t *m = NULL;
Data_Get_Struct (self, Mapper_t, m);
if (!m)
rb_raise (rb_eException, "No Mapper Object");
return INT2NUM (m->GetFileSize());
}
/**********************
Init_fastfilereaderext
**********************/
extern "C" void Init_fastfilereaderext()
{
EmModule = rb_define_module ("EventMachine");
FastFileReader = rb_define_class_under (EmModule, "FastFileReader", rb_cObject);
Mapper = rb_define_class_under (FastFileReader, "Mapper", rb_cObject);
rb_define_module_function (Mapper, "new", (VALUE(*)(...))mapper_new, 1);
rb_define_method (Mapper, "size", (VALUE(*)(...))mapper_size, 0);
rb_define_method (Mapper, "close", (VALUE(*)(...))mapper_close, 0);
rb_define_method (Mapper, "get_chunk", (VALUE(*)(...))mapper_get_chunk, 2);
}
/*****************************************************************************
$Id$
File: files.cpp
Date: 26Aug06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
/******************************************
FileStreamDescriptor::FileStreamDescriptor
******************************************/
FileStreamDescriptor::FileStreamDescriptor (int fd, EventMachine_t *em):
EventableDescriptor (fd, em),
OutboundDataSize (0)
{
cerr << "#####";
}
/*******************************************
FileStreamDescriptor::~FileStreamDescriptor
*******************************************/
FileStreamDescriptor::~FileStreamDescriptor()
{
// Run down any stranded outbound data.
for (size_t i=0; i < OutboundPages.size(); i++)
OutboundPages[i].Free();
}
/**************************
FileStreamDescriptor::Read
**************************/
void FileStreamDescriptor::Read()
{
}
/***************************
FileStreamDescriptor::Write
***************************/
void FileStreamDescriptor::Write()
{
}
/*******************************
FileStreamDescriptor::Heartbeat
*******************************/
void FileStreamDescriptor::Heartbeat()
{
}
/***********************************
FileStreamDescriptor::SelectForRead
***********************************/
bool FileStreamDescriptor::SelectForRead()
{
cerr << "R?";
return false;
}
/************************************
FileStreamDescriptor::SelectForWrite
************************************/
bool FileStreamDescriptor::SelectForWrite()
{
cerr << "W?";
return false;
}
/*****************************************************************************
$Id$
File: kb.cpp
Date: 24Aug07
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
/**************************************
KeyboardDescriptor::KeyboardDescriptor
**************************************/
KeyboardDescriptor::KeyboardDescriptor (EventMachine_t *parent_em):
EventableDescriptor (0, parent_em),
bReadAttemptedAfterClose (false),
LastIo (gCurrentLoopTime),
InactivityTimeout (0)
{
#ifdef HAVE_EPOLL
EpollEvent.events = EPOLLIN;
#endif
#ifdef HAVE_KQUEUE
MyEventMachine->ArmKqueueReader (this);
#endif
}
/***************************************
KeyboardDescriptor::~KeyboardDescriptor
***************************************/
KeyboardDescriptor::~KeyboardDescriptor()
{
}
/*************************
KeyboardDescriptor::Write
*************************/
void KeyboardDescriptor::Write()
{
// Why are we here?
throw std::runtime_error ("bad code path in keyboard handler");
}
/*****************************
KeyboardDescriptor::Heartbeat
*****************************/
void KeyboardDescriptor::Heartbeat()
{
// no-op
}
/************************
KeyboardDescriptor::Read
************************/
void KeyboardDescriptor::Read()
{
char c;
read (GetSocket(), &c, 1);
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_READ, &c, 1);
}
#if 0
/******************************
PipeDescriptor::PipeDescriptor
******************************/
PipeDescriptor::PipeDescriptor (int fd, pid_t subpid, EventMachine_t *parent_em):
EventableDescriptor (fd, parent_em),
bReadAttemptedAfterClose (false),
LastIo (gCurrentLoopTime),
InactivityTimeout (0),
OutboundDataSize (0),
SubprocessPid (subpid)
{
#ifdef HAVE_EPOLL
EpollEvent.events = EPOLLIN;
#endif
}
/*******************************
PipeDescriptor::~PipeDescriptor
*******************************/
PipeDescriptor::~PipeDescriptor()
{
// Run down any stranded outbound data.
for (size_t i=0; i < OutboundPages.size(); i++)
OutboundPages[i].Free();
/* As a virtual destructor, we come here before the base-class
* destructor that closes our file-descriptor.
* We have to make sure the subprocess goes down (if it's not
* already down) and we have to reap the zombie.
*
* This implementation is PROVISIONAL and will surely be improved.
* The intention here is that we never block, hence the highly
* undesirable sleeps. But if we can't reap the subprocess even
* after sending it SIGKILL, then something is wrong and we
* throw a fatal exception, which is also not something we should
* be doing.
*
* Eventually the right thing to do will be to have the reactor
* core respond to SIGCHLD by chaining a handler on top of the
* one Ruby may have installed, and dealing with a list of dead
* children that are pending cleanup.
*
* Since we want to have a signal processor integrated into the
* client-visible API, let's wait until that is done before cleaning
* this up.
*/
struct timespec req = {0, 10000000};
kill (SubprocessPid, SIGTERM);
nanosleep (&req, NULL);
if (waitpid (SubprocessPid, NULL, WNOHANG) == 0) {
kill (SubprocessPid, SIGKILL);
nanosleep (&req, NULL);
if (waitpid (SubprocessPid, NULL, WNOHANG) == 0)
throw std::runtime_error ("unable to reap subprocess");
}
}
/********************
PipeDescriptor::Read
********************/
void PipeDescriptor::Read()
{
int sd = GetSocket();
if (sd == INVALID_SOCKET) {
assert (!bReadAttemptedAfterClose);
bReadAttemptedAfterClose = true;
return;
}
LastIo = gCurrentLoopTime;
int total_bytes_read = 0;
char readbuffer [16 * 1024];
for (int i=0; i < 10; i++) {
// Don't read just one buffer and then move on. This is faster
// if there is a lot of incoming.
// But don't read indefinitely. Give other sockets a chance to run.
// NOTICE, we're reading one less than the buffer size.
// That's so we can put a guard byte at the end of what we send
// to user code.
// Use read instead of recv, which on Linux gives a "socket operation
// on nonsocket" error.
int r = read (sd, readbuffer, sizeof(readbuffer) - 1);
//cerr << "<R:" << r << ">";
if (r > 0) {
total_bytes_read += r;
LastRead = gCurrentLoopTime;
// Add a null-terminator at the the end of the buffer
// that we will send to the callback.
// DO NOT EVER CHANGE THIS. We want to explicitly allow users
// to be able to depend on this behavior, so they will have
// the option to do some things faster. Additionally it's
// a security guard against buffer overflows.
readbuffer [r] = 0;
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_READ, readbuffer, r);
}
else if (r == 0) {
break;
}
else {
// Basically a would-block, meaning we've read everything there is to read.
break;
}
}
if (total_bytes_read == 0) {
// If we read no data on a socket that selected readable,
// it generally means the other end closed the connection gracefully.
ScheduleClose (false);
//bCloseNow = true;
}
}
/*********************
PipeDescriptor::Write
*********************/
void PipeDescriptor::Write()
{
int sd = GetSocket();
assert (sd != INVALID_SOCKET);
LastIo = gCurrentLoopTime;
char output_buffer [16 * 1024];
size_t nbytes = 0;
while ((OutboundPages.size() > 0) && (nbytes < sizeof(output_buffer))) {
OutboundPage *op = &(OutboundPages[0]);
if ((nbytes + op->Length - op->Offset) < sizeof (output_buffer)) {
memcpy (output_buffer + nbytes, op->Buffer + op->Offset, op->Length - op->Offset);
nbytes += (op->Length - op->Offset);
op->Free();
OutboundPages.pop_front();
}
else {
int len = sizeof(output_buffer) - nbytes;
memcpy (output_buffer + nbytes, op->Buffer + op->Offset, len);
op->Offset += len;
nbytes += len;
}
}
// We should never have gotten here if there were no data to write,
// so assert that as a sanity check.
// Don't bother to make sure nbytes is less than output_buffer because
// if it were we probably would have crashed already.
assert (nbytes > 0);
assert (GetSocket() != INVALID_SOCKET);
int bytes_written = write (GetSocket(), output_buffer, nbytes);
if (bytes_written > 0) {
OutboundDataSize -= bytes_written;
if ((size_t)bytes_written < nbytes) {
int len = nbytes - bytes_written;
char *buffer = (char*) malloc (len + 1);
if (!buffer)
throw std::runtime_error ("bad alloc throwing back data");
memcpy (buffer, output_buffer + bytes_written, len);
buffer [len] = 0;
OutboundPages.push_front (OutboundPage (buffer, len));
}
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | (SelectForWrite() ? EPOLLOUT : 0));
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
}
else {
#ifdef OS_UNIX
if ((errno != EINPROGRESS) && (errno != EWOULDBLOCK) && (errno != EINTR))
#endif
#ifdef OS_WIN32
if ((errno != WSAEINPROGRESS) && (errno != WSAEWOULDBLOCK))
#endif
Close();
}
}
/*************************
PipeDescriptor::Heartbeat
*************************/
void PipeDescriptor::Heartbeat()
{
// If an inactivity timeout is defined, then check for it.
if (InactivityTimeout && ((gCurrentLoopTime - LastIo) >= InactivityTimeout))
ScheduleClose (false);
//bCloseNow = true;
}
/*****************************
PipeDescriptor::SelectForRead
*****************************/
bool PipeDescriptor::SelectForRead()
{
/* Pipe descriptors, being local by definition, don't have
* a pending state, so this is simpler than for the
* ConnectionDescriptor object.
*/
return true;
}
/******************************
PipeDescriptor::SelectForWrite
******************************/
bool PipeDescriptor::SelectForWrite()
{
/* Pipe descriptors, being local by definition, don't have
* a pending state, so this is simpler than for the
* ConnectionDescriptor object.
*/
return (GetOutboundDataSize() > 0);
}
/********************************
PipeDescriptor::SendOutboundData
********************************/
int PipeDescriptor::SendOutboundData (const char *data, int length)
{
//if (bCloseNow || bCloseAfterWriting)
if (IsCloseScheduled())
return 0;
if (!data && (length > 0))
throw std::runtime_error ("bad outbound data");
char *buffer = (char *) malloc (length + 1);
if (!buffer)
throw std::runtime_error ("no allocation for outbound data");
memcpy (buffer, data, length);
buffer [length] = 0;
OutboundPages.push_back (OutboundPage (buffer, length));
OutboundDataSize += length;
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | EPOLLOUT);
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
return length;
}
/********************************
PipeDescriptor::GetSubprocessPid
********************************/
bool PipeDescriptor::GetSubprocessPid (pid_t *pid)
{
bool ok = false;
if (pid && (SubprocessPid > 0)) {
*pid = SubprocessPid;
ok = true;
}
return ok;
}
#endif
/*****************************************************************************
$Id$
File: page.cpp
Date: 30Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
/******************
PageList::PageList
******************/
PageList::PageList()
{
}
/*******************
PageList::~PageList
*******************/
PageList::~PageList()
{
while (HasPages())
PopFront();
}
/***************
PageList::Front
***************/
void PageList::Front (const char **page, int *length)
{
assert (page && length);
if (HasPages()) {
Page p = Pages.front();
*page = p.Buffer;
*length = p.Size;
}
else {
*page = NULL;
*length = 0;
}
}
/******************
PageList::PopFront
******************/
void PageList::PopFront()
{
if (HasPages()) {
Page p = Pages.front();
Pages.pop_front();
if (p.Buffer)
free ((void*)p.Buffer);
}
}
/******************
PageList::HasPages
******************/
bool PageList::HasPages()
{
return (Pages.size() > 0) ? true : false;
}
/**************
PageList::Push
**************/
void PageList::Push (const char *buf, int size)
{
if (buf && (size > 0)) {
char *copy = (char*) malloc (size);
if (!copy)
throw runtime_error ("no memory in pagelist");
memcpy (copy, buf, size);
Pages.push_back (Page (copy, size));
}
}
/*****************************************************************************
$Id$
File: pipe.cpp
Date: 30May07
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
#ifdef OS_UNIX
// THIS ENTIRE FILE IS ONLY COMPILED ON UNIX-LIKE SYSTEMS.
/******************************
PipeDescriptor::PipeDescriptor
******************************/
PipeDescriptor::PipeDescriptor (int fd, pid_t subpid, EventMachine_t *parent_em):
EventableDescriptor (fd, parent_em),
bReadAttemptedAfterClose (false),
LastIo (gCurrentLoopTime),
InactivityTimeout (0),
OutboundDataSize (0),
SubprocessPid (subpid)
{
#ifdef HAVE_EPOLL
EpollEvent.events = EPOLLIN;
#endif
#ifdef HAVE_KQUEUE
MyEventMachine->ArmKqueueReader (this);
#endif
}
/*******************************
PipeDescriptor::~PipeDescriptor
*******************************/
PipeDescriptor::~PipeDescriptor()
{
// Run down any stranded outbound data.
for (size_t i=0; i < OutboundPages.size(); i++)
OutboundPages[i].Free();
/* As a virtual destructor, we come here before the base-class
* destructor that closes our file-descriptor.
* We have to make sure the subprocess goes down (if it's not
* already down) and we have to reap the zombie.
*
* This implementation is PROVISIONAL and will surely be improved.
* The intention here is that we never block, hence the highly
* undesirable sleeps. But if we can't reap the subprocess even
* after sending it SIGKILL, then something is wrong and we
* throw a fatal exception, which is also not something we should
* be doing.
*
* Eventually the right thing to do will be to have the reactor
* core respond to SIGCHLD by chaining a handler on top of the
* one Ruby may have installed, and dealing with a list of dead
* children that are pending cleanup.
*
* Since we want to have a signal processor integrated into the
* client-visible API, let's wait until that is done before cleaning
* this up.
*
* Added a very ugly hack to support passing the subprocess's exit
* status to the user. It only makes logical sense for user code to access
* the subprocess exit status in the unbind callback. But unbind is called
* back during the EventableDescriptor destructor. So by that time there's
* no way to call back this object through an object binding, because it's
* already been cleaned up. We might have added a parameter to the unbind
* callback, but that would probably break a huge amount of existing code.
* So the hack-solution is to define an instance variable in the EventMachine
* object and stick the exit status in there, where it can easily be accessed
* with an accessor visible to user code.
* User code should ONLY access the exit status from within the unbind callback.
* Otherwise there's no guarantee it'll be valid.
* This hack won't make it impossible to run multiple EventMachines in a single
* process, but it will make it impossible to reliably nest unbind calls
* within other unbind calls. (Not sure if that's even possible.)
*/
assert (MyEventMachine);
// check if the process is already dead
if (waitpid (SubprocessPid, &(MyEventMachine->SubprocessExitStatus), WNOHANG) == 0) {
kill (SubprocessPid, SIGTERM);
// wait 0.25s for process to die
struct timespec req = {0, 250000000};
nanosleep (&req, NULL);
if (waitpid (SubprocessPid, &(MyEventMachine->SubprocessExitStatus), WNOHANG) == 0) {
kill (SubprocessPid, SIGKILL);
// wait 0.5s for process to die
struct timespec req = {0, 500000000};
nanosleep (&req, NULL);
if (waitpid (SubprocessPid, &(MyEventMachine->SubprocessExitStatus), WNOHANG) == 0)
throw std::runtime_error ("unable to reap subprocess");
}
}
}
/********************
PipeDescriptor::Read
********************/
void PipeDescriptor::Read()
{
int sd = GetSocket();
if (sd == INVALID_SOCKET) {
assert (!bReadAttemptedAfterClose);
bReadAttemptedAfterClose = true;
return;
}
LastIo = gCurrentLoopTime;
int total_bytes_read = 0;
char readbuffer [16 * 1024];
for (int i=0; i < 10; i++) {
// Don't read just one buffer and then move on. This is faster
// if there is a lot of incoming.
// But don't read indefinitely. Give other sockets a chance to run.
// NOTICE, we're reading one less than the buffer size.
// That's so we can put a guard byte at the end of what we send
// to user code.
// Use read instead of recv, which on Linux gives a "socket operation
// on nonsocket" error.
int r = read (sd, readbuffer, sizeof(readbuffer) - 1);
//cerr << "<R:" << r << ">";
if (r > 0) {
total_bytes_read += r;
LastRead = gCurrentLoopTime;
// Add a null-terminator at the the end of the buffer
// that we will send to the callback.
// DO NOT EVER CHANGE THIS. We want to explicitly allow users
// to be able to depend on this behavior, so they will have
// the option to do some things faster. Additionally it's
// a security guard against buffer overflows.
readbuffer [r] = 0;
if (EventCallback)
(*EventCallback)(GetBinding().c_str(), EM_CONNECTION_READ, readbuffer, r);
}
else if (r == 0) {
break;
}
else {
// Basically a would-block, meaning we've read everything there is to read.
break;
}
}
if (total_bytes_read == 0) {
// If we read no data on a socket that selected readable,
// it generally means the other end closed the connection gracefully.
ScheduleClose (false);
//bCloseNow = true;
}
}
/*********************
PipeDescriptor::Write
*********************/
void PipeDescriptor::Write()
{
int sd = GetSocket();
assert (sd != INVALID_SOCKET);
LastIo = gCurrentLoopTime;
char output_buffer [16 * 1024];
size_t nbytes = 0;
while ((OutboundPages.size() > 0) && (nbytes < sizeof(output_buffer))) {
OutboundPage *op = &(OutboundPages[0]);
if ((nbytes + op->Length - op->Offset) < sizeof (output_buffer)) {
memcpy (output_buffer + nbytes, op->Buffer + op->Offset, op->Length - op->Offset);
nbytes += (op->Length - op->Offset);
op->Free();
OutboundPages.pop_front();
}
else {
int len = sizeof(output_buffer) - nbytes;
memcpy (output_buffer + nbytes, op->Buffer + op->Offset, len);
op->Offset += len;
nbytes += len;
}
}
// We should never have gotten here if there were no data to write,
// so assert that as a sanity check.
// Don't bother to make sure nbytes is less than output_buffer because
// if it were we probably would have crashed already.
assert (nbytes > 0);
assert (GetSocket() != INVALID_SOCKET);
int bytes_written = write (GetSocket(), output_buffer, nbytes);
if (bytes_written > 0) {
OutboundDataSize -= bytes_written;
if ((size_t)bytes_written < nbytes) {
int len = nbytes - bytes_written;
char *buffer = (char*) malloc (len + 1);
if (!buffer)
throw std::runtime_error ("bad alloc throwing back data");
memcpy (buffer, output_buffer + bytes_written, len);
buffer [len] = 0;
OutboundPages.push_front (OutboundPage (buffer, len));
}
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | (SelectForWrite() ? EPOLLOUT : 0));
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
}
else {
#ifdef OS_UNIX
if ((errno != EINPROGRESS) && (errno != EWOULDBLOCK) && (errno != EINTR))
#endif
#ifdef OS_WIN32
if ((errno != WSAEINPROGRESS) && (errno != WSAEWOULDBLOCK))
#endif
Close();
}
}
/*************************
PipeDescriptor::Heartbeat
*************************/
void PipeDescriptor::Heartbeat()
{
// If an inactivity timeout is defined, then check for it.
if (InactivityTimeout && ((gCurrentLoopTime - LastIo) >= InactivityTimeout))
ScheduleClose (false);
//bCloseNow = true;
}
/*****************************
PipeDescriptor::SelectForRead
*****************************/
bool PipeDescriptor::SelectForRead()
{
/* Pipe descriptors, being local by definition, don't have
* a pending state, so this is simpler than for the
* ConnectionDescriptor object.
*/
return true;
}
/******************************
PipeDescriptor::SelectForWrite
******************************/
bool PipeDescriptor::SelectForWrite()
{
/* Pipe descriptors, being local by definition, don't have
* a pending state, so this is simpler than for the
* ConnectionDescriptor object.
*/
return (GetOutboundDataSize() > 0);
}
/********************************
PipeDescriptor::SendOutboundData
********************************/
int PipeDescriptor::SendOutboundData (const char *data, int length)
{
//if (bCloseNow || bCloseAfterWriting)
if (IsCloseScheduled())
return 0;
if (!data && (length > 0))
throw std::runtime_error ("bad outbound data");
char *buffer = (char *) malloc (length + 1);
if (!buffer)
throw std::runtime_error ("no allocation for outbound data");
memcpy (buffer, data, length);
buffer [length] = 0;
OutboundPages.push_back (OutboundPage (buffer, length));
OutboundDataSize += length;
#ifdef HAVE_EPOLL
EpollEvent.events = (EPOLLIN | EPOLLOUT);
assert (MyEventMachine);
MyEventMachine->Modify (this);
#endif
return length;
}
/********************************
PipeDescriptor::GetSubprocessPid
********************************/
bool PipeDescriptor::GetSubprocessPid (pid_t *pid)
{
bool ok = false;
if (pid && (SubprocessPid > 0)) {
*pid = SubprocessPid;
ok = true;
}
return ok;
}
#endif // OS_UNIX
/*****************************************************************************
$Id$
File: rubymain.cpp
Date: 06Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
#include "eventmachine.h"
#include <ruby.h>
/*******
Statics
*******/
static VALUE EmModule;
static VALUE EmConnection;
static VALUE Intern_at_signature;
static VALUE Intern_at_timers;
static VALUE Intern_at_conns;
static VALUE Intern_event_callback;
static VALUE Intern_run_deferred_callbacks;
static VALUE Intern_delete;
static VALUE Intern_call;
static VALUE Intern_receive_data;
static VALUE Intern_notify_readable;
static VALUE Intern_notify_writable;
/****************
t_event_callback
****************/
static void event_callback (const char *a1, int a2, const char *a3, int a4)
{
if (a2 == EM_CONNECTION_READ) {
VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
VALUE q = rb_hash_aref (t, rb_str_new2(a1));
if (q == Qnil)
rb_raise (rb_eRuntimeError, "no connection");
rb_funcall (q, Intern_receive_data, 1, rb_str_new (a3, a4));
}
else if (a2 == EM_CONNECTION_NOTIFY_READABLE) {
VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
VALUE q = rb_hash_aref (t, rb_str_new2(a1));
if (q == Qnil)
rb_raise (rb_eRuntimeError, "no connection");
rb_funcall (q, Intern_notify_readable, 0);
}
else if (a2 == EM_CONNECTION_NOTIFY_WRITABLE) {
VALUE t = rb_ivar_get (EmModule, Intern_at_conns);
VALUE q = rb_hash_aref (t, rb_str_new2(a1));
if (q == Qnil)
rb_raise (rb_eRuntimeError, "no connection");
rb_funcall (q, Intern_notify_writable, 0);
}
else if (a2 == EM_LOOPBREAK_SIGNAL) {
rb_funcall (EmModule, Intern_run_deferred_callbacks, 0);
}
else if (a2 == EM_TIMER_FIRED) {
VALUE t = rb_ivar_get (EmModule, Intern_at_timers);
VALUE q = rb_funcall (t, Intern_delete, 1, rb_str_new(a3, a4));
if (q == Qnil)
rb_raise (rb_eRuntimeError, "no timer");
rb_funcall (q, Intern_call, 0);
}
else
rb_funcall (EmModule, Intern_event_callback, 3, rb_str_new2(a1), (a2 << 1) | 1, rb_str_new(a3,a4));
}
/**************************
t_initialize_event_machine
**************************/
static VALUE t_initialize_event_machine (VALUE self)
{
evma_initialize_library (event_callback);
return Qnil;
}
/*****************************
t_run_machine_without_threads
*****************************/
static VALUE t_run_machine_without_threads (VALUE self)
{
evma_run_machine();
return Qnil;
}
/*******************
t_add_oneshot_timer
*******************/
static VALUE t_add_oneshot_timer (VALUE self, VALUE interval)
{
const char *f = evma_install_oneshot_timer (FIX2INT (interval));
if (!f || !*f)
rb_raise (rb_eRuntimeError, "no timer");
return rb_str_new2 (f);
}
/**************
t_start_server
**************/
static VALUE t_start_server (VALUE self, VALUE server, VALUE port)
{
const char *f = evma_create_tcp_server (StringValuePtr(server), FIX2INT(port));
if (!f || !*f)
rb_raise (rb_eRuntimeError, "no acceptor");
return rb_str_new2 (f);
}
/*************
t_stop_server
*************/
static VALUE t_stop_server (VALUE self, VALUE signature)
{
evma_stop_tcp_server (StringValuePtr (signature));
return Qnil;
}
/*******************
t_start_unix_server
*******************/
static VALUE t_start_unix_server (VALUE self, VALUE filename)
{
const char *f = evma_create_unix_domain_server (StringValuePtr(filename));
if (!f || !*f)
rb_raise (rb_eRuntimeError, "no unix-domain acceptor");
return rb_str_new2 (f);
}
/***********
t_send_data
***********/
static VALUE t_send_data (VALUE self, VALUE signature, VALUE data, VALUE data_length)
{
int b = evma_send_data_to_connection (StringValuePtr (signature), StringValuePtr (data), FIX2INT (data_length));
return INT2NUM (b);
}
/***********
t_start_tls
***********/
static VALUE t_start_tls (VALUE self, VALUE signature)
{
evma_start_tls (StringValuePtr (signature));
return Qnil;
}
/***************
t_set_tls_parms
***************/
static VALUE t_set_tls_parms (VALUE self, VALUE signature, VALUE privkeyfile, VALUE certchainfile)
{
/* set_tls_parms takes a series of positional arguments for specifying such things
* as private keys and certificate chains.
* It's expected that the parameter list will grow as we add more supported features.
* ALL of these parameters are optional, and can be specified as empty or NULL strings.
*/
evma_set_tls_parms (StringValuePtr (signature), StringValuePtr (privkeyfile), StringValuePtr (certchainfile) );
return Qnil;
}
/**************
t_get_peername
**************/
static VALUE t_get_peername (VALUE self, VALUE signature)
{
struct sockaddr s;
if (evma_get_peername (StringValuePtr (signature), &s)) {
return rb_str_new ((const char*)&s, sizeof(s));
}
return Qnil;
}
/**************
t_get_sockname
**************/
static VALUE t_get_sockname (VALUE self, VALUE signature)
{
struct sockaddr s;
if (evma_get_sockname (StringValuePtr (signature), &s)) {
return rb_str_new ((const char*)&s, sizeof(s));
}
return Qnil;
}
/********************
t_get_subprocess_pid
********************/
static VALUE t_get_subprocess_pid (VALUE self, VALUE signature)
{
pid_t pid;
if (evma_get_subprocess_pid (StringValuePtr (signature), &pid)) {
return INT2NUM (pid);
}
return Qnil;
}
/***********************
t_get_subprocess_status
***********************/
static VALUE t_get_subprocess_status (VALUE self, VALUE signature)
{
int status;
if (evma_get_subprocess_status (StringValuePtr (signature), &status)) {
return INT2NUM (status);
}
return Qnil;
}
/*****************************
t_get_comm_inactivity_timeout
*****************************/
static VALUE t_get_comm_inactivity_timeout (VALUE self, VALUE signature)
{
int timeout;
if (evma_get_comm_inactivity_timeout (StringValuePtr (signature), &timeout))
return INT2FIX (timeout);
return Qnil;
}
/*****************************
t_set_comm_inactivity_timeout
*****************************/
static VALUE t_set_comm_inactivity_timeout (VALUE self, VALUE signature, VALUE timeout)
{
int ti = FIX2INT (timeout);
if (evma_set_comm_inactivity_timeout (StringValuePtr (signature), &ti));
return Qtrue;
return Qnil;
}
/***************
t_send_datagram
***************/
static VALUE t_send_datagram (VALUE self, VALUE signature, VALUE data, VALUE data_length, VALUE address, VALUE port)
{
int b = evma_send_datagram (StringValuePtr (signature), StringValuePtr (data), FIX2INT (data_length), StringValuePtr(address), FIX2INT(port));
return INT2NUM (b);
}
/******************
t_close_connection
******************/
static VALUE t_close_connection (VALUE self, VALUE signature, VALUE after_writing)
{
evma_close_connection (StringValuePtr (signature), ((after_writing == Qtrue) ? 1 : 0));
return Qnil;
}
/********************************
t_report_connection_error_status
********************************/
static VALUE t_report_connection_error_status (VALUE self, VALUE signature)
{
int b = evma_report_connection_error_status (StringValuePtr (signature));
return INT2NUM (b);
}
/****************
t_connect_server
****************/
static VALUE t_connect_server (VALUE self, VALUE server, VALUE port)
{
// Avoid FIX2INT in this case, because it doesn't deal with type errors properly.
// Specifically, if the value of port comes in as a string rather than an integer,
// NUM2INT will throw a type error, but FIX2INT will generate garbage.
const char *f = evma_connect_to_server (StringValuePtr(server), NUM2INT(port));
if (!f || !*f)
rb_raise (rb_eRuntimeError, "no connection");
return rb_str_new2 (f);
}
/*********************
t_connect_unix_server
*********************/
static VALUE t_connect_unix_server (VALUE self, VALUE serversocket)
{
const char *f = evma_connect_to_unix_server (StringValuePtr(serversocket));
if (!f || !*f)
rb_raise (rb_eRuntimeError, "no connection");
return rb_str_new2 (f);
}
/***********
t_attach_fd
***********/
static VALUE t_attach_fd (VALUE self, VALUE file_descriptor, VALUE read_mode, VALUE write_mode)
{
const char *f = evma_attach_fd (NUM2INT(file_descriptor), (read_mode == Qtrue) ? 1 : 0, (write_mode == Qtrue) ? 1 : 0);
if (!f || !*f)
rb_raise (rb_eRuntimeError, "no connection");
return rb_str_new2 (f);
}
/***********
t_detach_fd
***********/
static VALUE t_detach_fd (VALUE self, VALUE signature)
{
return INT2NUM(evma_detach_fd (StringValuePtr(signature)));
}
/*****************
t_open_udp_socket
*****************/
static VALUE t_open_udp_socket (VALUE self, VALUE server, VALUE port)
{
const char *f = evma_open_datagram_socket (StringValuePtr(server), FIX2INT(port));
if (!f || !*f)
rb_raise (rb_eRuntimeError, "no datagram socket");
return rb_str_new2 (f);
}
/*****************
t_release_machine
*****************/
static VALUE t_release_machine (VALUE self)
{
evma_release_library();
return Qnil;
}
/******
t_stop
******/
static VALUE t_stop (VALUE self)
{
evma_stop_machine();
return Qnil;
}
/******************
t_signal_loopbreak
******************/
static VALUE t_signal_loopbreak (VALUE self)
{
evma_signal_loopbreak();
return Qnil;
}
/**************
t_library_type
**************/
static VALUE t_library_type (VALUE self)
{
return rb_eval_string (":extension");
}
/*******************
t_set_timer_quantum
*******************/
static VALUE t_set_timer_quantum (VALUE self, VALUE interval)
{
evma_set_timer_quantum (FIX2INT (interval));
return Qnil;
}
/********************
t_set_max_timer_count
********************/
static VALUE t_set_max_timer_count (VALUE self, VALUE ct)
{
evma_set_max_timer_count (FIX2INT (ct));
return Qnil;
}
/***************
t_setuid_string
***************/
static VALUE t_setuid_string (VALUE self, VALUE username)
{
evma_setuid_string (StringValuePtr (username));
return Qnil;
}
/*************
t__write_file
*************/
static VALUE t__write_file (VALUE self, VALUE filename)
{
const char *f = evma__write_file (StringValuePtr (filename));
if (!f || !*f)
rb_raise (rb_eRuntimeError, "file not opened");
return rb_str_new2 (f);
}
/**************
t_invoke_popen
**************/
static VALUE t_invoke_popen (VALUE self, VALUE cmd)
{
// 1.8.7+
#ifdef RARRAY_LEN
int len = RARRAY_LEN(cmd);
#else
int len = RARRAY (cmd)->len;
#endif
if (len > 98)
rb_raise (rb_eRuntimeError, "too many arguments to popen");
char *strings [100];
for (int i=0; i < len; i++) {
VALUE ix = INT2FIX (i);
VALUE s = rb_ary_aref (1, &ix, cmd);
strings[i] = StringValuePtr (s);
}
strings[len] = NULL;
const char *f = evma_popen (strings);
if (!f || !*f) {
char *err = strerror (errno);
char buf[100];
memset (buf, 0, sizeof(buf));
snprintf (buf, sizeof(buf)-1, "no popen: %s", (err?err:"???"));
rb_raise (rb_eRuntimeError, buf);
}
return rb_str_new2 (f);
}
/***************
t_read_keyboard
***************/
static VALUE t_read_keyboard (VALUE self)
{
const char *f = evma_open_keyboard();
if (!f || !*f)
rb_raise (rb_eRuntimeError, "no keyboard reader");
return rb_str_new2 (f);
}
/********
t__epoll
********/
static VALUE t__epoll (VALUE self)
{
// Temporary.
evma__epoll();
return Qnil;
}
/**********
t__epoll_p
**********/
static VALUE t__epoll_p (VALUE self)
{
#ifdef HAVE_EPOLL
return Qtrue;
#else
return Qfalse;
#endif
}
/*********
t__kqueue
*********/
static VALUE t__kqueue (VALUE self)
{
// Temporary.
evma__kqueue();
return Qnil;
}
/***********
t__kqueue_p
***********/
static VALUE t__kqueue_p (VALUE self)
{
#ifdef HAVE_KQUEUE
return Qtrue;
#else
return Qfalse;
#endif
}
/****************
t_send_file_data
****************/
static VALUE t_send_file_data (VALUE self, VALUE signature, VALUE filename)
{
/* The current implementation of evma_send_file_data_to_connection enforces a strict
* upper limit on the file size it will transmit (currently 32K). The function returns
* zero on success, -1 if the requested file exceeds its size limit, and a positive
* number for other errors.
* TODO: Positive return values are actually errno's, which is probably the wrong way to
* do this. For one thing it's ugly. For another, we can't be sure zero is never a real errno.
*/
int b = evma_send_file_data_to_connection (StringValuePtr(signature), StringValuePtr(filename));
if (b == -1)
rb_raise(rb_eRuntimeError, "File too large. send_file_data() supports files under 32k.");
if (b > 0) {
char *err = strerror (b);
char buf[1024];
memset (buf, 0, sizeof(buf));
snprintf (buf, sizeof(buf)-1, ": %s %s", StringValuePtr(filename),(err?err:"???"));
rb_raise (rb_eIOError, buf);
}
return INT2NUM (0);
}
/*******************
t_set_rlimit_nofile
*******************/
static VALUE t_set_rlimit_nofile (VALUE self, VALUE arg)
{
arg = (NIL_P(arg)) ? -1 : NUM2INT (arg);
return INT2NUM (evma_set_rlimit_nofile (arg));
}
/***************************
conn_get_outbound_data_size
***************************/
static VALUE conn_get_outbound_data_size (VALUE self)
{
VALUE sig = rb_ivar_get (self, Intern_at_signature);
return INT2NUM (evma_get_outbound_data_size (StringValuePtr(sig)));
}
/******************************
conn_associate_callback_target
******************************/
static VALUE conn_associate_callback_target (VALUE self, VALUE sig)
{
// No-op for the time being.
return Qnil;
}
/***************
t_get_loop_time
****************/
static VALUE t_get_loop_time (VALUE self)
{
VALUE cTime = rb_path2class("Time");
if (gCurrentLoopTime != 0) {
return rb_funcall(cTime,
rb_intern("at"),
1,
INT2NUM(gCurrentLoopTime));
}
return Qnil;
}
/*********************
Init_rubyeventmachine
*********************/
extern "C" void Init_rubyeventmachine()
{
// Tuck away some symbol values so we don't have to look 'em up every time we need 'em.
Intern_at_signature = rb_intern ("@signature");
Intern_at_timers = rb_intern ("@timers");
Intern_at_conns = rb_intern ("@conns");
Intern_event_callback = rb_intern ("event_callback");
Intern_run_deferred_callbacks = rb_intern ("run_deferred_callbacks");
Intern_delete = rb_intern ("delete");
Intern_call = rb_intern ("call");
Intern_receive_data = rb_intern ("receive_data");
Intern_notify_readable = rb_intern ("notify_readable");
Intern_notify_writable = rb_intern ("notify_writable");
// INCOMPLETE, we need to define class Connections inside module EventMachine
// run_machine and run_machine_without_threads are now identical.
// Must deprecate the without_threads variant.
EmModule = rb_define_module ("EventMachine");
EmConnection = rb_define_class_under (EmModule, "Connection", rb_cObject);
rb_define_class_under (EmModule, "ConnectionNotBound", rb_eException);
rb_define_class_under (EmModule, "NoHandlerForAcceptedConnection", rb_eException);
rb_define_class_under (EmModule, "UnknownTimerFired", rb_eException);
rb_define_module_function (EmModule, "initialize_event_machine", (VALUE(*)(...))t_initialize_event_machine, 0);
rb_define_module_function (EmModule, "run_machine", (VALUE(*)(...))t_run_machine_without_threads, 0);
rb_define_module_function (EmModule, "run_machine_without_threads", (VALUE(*)(...))t_run_machine_without_threads, 0);
rb_define_module_function (EmModule, "add_oneshot_timer", (VALUE(*)(...))t_add_oneshot_timer, 1);
rb_define_module_function (EmModule, "start_tcp_server", (VALUE(*)(...))t_start_server, 2);
rb_define_module_function (EmModule, "stop_tcp_server", (VALUE(*)(...))t_stop_server, 1);
rb_define_module_function (EmModule, "start_unix_server", (VALUE(*)(...))t_start_unix_server, 1);
rb_define_module_function (EmModule, "set_tls_parms", (VALUE(*)(...))t_set_tls_parms, 3);
rb_define_module_function (EmModule, "start_tls", (VALUE(*)(...))t_start_tls, 1);
rb_define_module_function (EmModule, "send_data", (VALUE(*)(...))t_send_data, 3);
rb_define_module_function (EmModule, "send_datagram", (VALUE(*)(...))t_send_datagram, 5);
rb_define_module_function (EmModule, "close_connection", (VALUE(*)(...))t_close_connection, 2);
rb_define_module_function (EmModule, "report_connection_error_status", (VALUE(*)(...))t_report_connection_error_status, 1);
rb_define_module_function (EmModule, "connect_server", (VALUE(*)(...))t_connect_server, 2);
rb_define_module_function (EmModule, "connect_unix_server", (VALUE(*)(...))t_connect_unix_server, 1);
rb_define_module_function (EmModule, "attach_fd", (VALUE (*)(...))t_attach_fd, 3);
rb_define_module_function (EmModule, "detach_fd", (VALUE (*)(...))t_detach_fd, 1);
rb_define_module_function (EmModule, "current_time", (VALUE(*)(...))t_get_loop_time, 0);
rb_define_module_function (EmModule, "open_udp_socket", (VALUE(*)(...))t_open_udp_socket, 2);
rb_define_module_function (EmModule, "read_keyboard", (VALUE(*)(...))t_read_keyboard, 0);
rb_define_module_function (EmModule, "release_machine", (VALUE(*)(...))t_release_machine, 0);
rb_define_module_function (EmModule, "stop", (VALUE(*)(...))t_stop, 0);
rb_define_module_function (EmModule, "signal_loopbreak", (VALUE(*)(...))t_signal_loopbreak, 0);
rb_define_module_function (EmModule, "library_type", (VALUE(*)(...))t_library_type, 0);
rb_define_module_function (EmModule, "set_timer_quantum", (VALUE(*)(...))t_set_timer_quantum, 1);
rb_define_module_function (EmModule, "set_max_timer_count", (VALUE(*)(...))t_set_max_timer_count, 1);
rb_define_module_function (EmModule, "setuid_string", (VALUE(*)(...))t_setuid_string, 1);
rb_define_module_function (EmModule, "invoke_popen", (VALUE(*)(...))t_invoke_popen, 1);
rb_define_module_function (EmModule, "send_file_data", (VALUE(*)(...))t_send_file_data, 2);
// Provisional:
rb_define_module_function (EmModule, "_write_file", (VALUE(*)(...))t__write_file, 1);
rb_define_module_function (EmModule, "get_peername", (VALUE(*)(...))t_get_peername, 1);
rb_define_module_function (EmModule, "get_sockname", (VALUE(*)(...))t_get_sockname, 1);
rb_define_module_function (EmModule, "get_subprocess_pid", (VALUE(*)(...))t_get_subprocess_pid, 1);
rb_define_module_function (EmModule, "get_subprocess_status", (VALUE(*)(...))t_get_subprocess_status, 1);
rb_define_module_function (EmModule, "get_comm_inactivity_timeout", (VALUE(*)(...))t_get_comm_inactivity_timeout, 1);
rb_define_module_function (EmModule, "set_comm_inactivity_timeout", (VALUE(*)(...))t_set_comm_inactivity_timeout, 2);
rb_define_module_function (EmModule, "set_rlimit_nofile", (VALUE(*)(...))t_set_rlimit_nofile, 1);
// Temporary:
rb_define_module_function (EmModule, "epoll", (VALUE(*)(...))t__epoll, 0);
rb_define_module_function (EmModule, "kqueue", (VALUE(*)(...))t__kqueue, 0);
rb_define_module_function (EmModule, "epoll?", (VALUE(*)(...))t__epoll_p, 0);
rb_define_module_function (EmModule, "kqueue?", (VALUE(*)(...))t__kqueue_p, 0);
rb_define_method (EmConnection, "get_outbound_data_size", (VALUE(*)(...))conn_get_outbound_data_size, 0);
rb_define_method (EmConnection, "associate_callback_target", (VALUE(*)(...))conn_associate_callback_target, 1);
rb_define_const (EmModule, "TimerFired", INT2NUM(100));
rb_define_const (EmModule, "ConnectionData", INT2NUM(101));
rb_define_const (EmModule, "ConnectionUnbound", INT2NUM(102));
rb_define_const (EmModule, "ConnectionAccepted", INT2NUM(103));
rb_define_const (EmModule, "ConnectionCompleted", INT2NUM(104));
rb_define_const (EmModule, "LoopbreakSignalled", INT2NUM(105));
rb_define_const (EmModule, "ConnectionNotifyReadable", INT2NUM(106));
rb_define_const (EmModule, "ConnectionNotifyWritable", INT2NUM(107));
}
/*****************************************************************************
$Id$
File: sigs.cpp
Date: 06Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
bool gTerminateSignalReceived;
/**************
SigtermHandler
**************/
void SigtermHandler (int sig)
{
// This is a signal-handler, don't do anything frisky. Interrupts are disabled.
// Set the terminate flag WITHOUT trying to lock a mutex- otherwise we can easily
// self-deadlock, especially if the event machine is looping quickly.
gTerminateSignalReceived = true;
}
/*********************
InstallSignalHandlers
*********************/
void InstallSignalHandlers()
{
#ifdef OS_UNIX
static bool bInstalled = false;
if (!bInstalled) {
bInstalled = true;
signal (SIGINT, SigtermHandler);
signal (SIGTERM, SigtermHandler);
signal (SIGPIPE, SIG_IGN);
}
#endif
}
/*******************
WintelSignalHandler
*******************/
#ifdef OS_WIN32
BOOL WINAPI WintelSignalHandler (DWORD control)
{
if (control == CTRL_C_EVENT)
gTerminateSignalReceived = true;
return TRUE;
}
#endif
/************
HookControlC
************/
#ifdef OS_WIN32
void HookControlC (bool hook)
{
if (hook) {
// INSTALL hook
SetConsoleCtrlHandler (WintelSignalHandler, TRUE);
}
else {
// UNINSTALL hook
SetConsoleCtrlHandler (WintelSignalHandler, FALSE);
}
}
#endif
/*****************************************************************************
$Id$
File: ssl.cpp
Date: 30Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#ifdef WITH_SSL
#include "project.h"
bool SslContext_t::bLibraryInitialized = false;
static void InitializeDefaultCredentials();
static EVP_PKEY *DefaultPrivateKey = NULL;
static X509 *DefaultCertificate = NULL;
static char PrivateMaterials[] = {
"-----BEGIN RSA PRIVATE KEY-----\n"
"MIICXAIBAAKBgQDCYYhcw6cGRbhBVShKmbWm7UVsEoBnUf0cCh8AX+MKhMxwVDWV\n"
"Igdskntn3cSJjRtmgVJHIK0lpb/FYHQB93Ohpd9/Z18pDmovfFF9nDbFF0t39hJ/\n"
"AqSzFB3GiVPoFFZJEE1vJqh+3jzsSF5K56bZ6azz38VlZgXeSozNW5bXkQIDAQAB\n"
"AoGALA89gIFcr6BIBo8N5fL3aNHpZXjAICtGav+kTUpuxSiaym9cAeTHuAVv8Xgk\n"
"H2Wbq11uz+6JMLpkQJH/WZ7EV59DPOicXrp0Imr73F3EXBfR7t2EQDYHPMthOA1D\n"
"I9EtCzvV608Ze90hiJ7E3guGrGppZfJ+eUWCPgy8CZH1vRECQQDv67rwV/oU1aDo\n"
"6/+d5nqjeW6mWkGqTnUU96jXap8EIw6B+0cUKskwx6mHJv+tEMM2748ZY7b0yBlg\n"
"w4KDghbFAkEAz2h8PjSJG55LwqmXih1RONSgdN9hjB12LwXL1CaDh7/lkEhq0PlK\n"
"PCAUwQSdM17Sl0Xxm2CZiekTSlwmHrtqXQJAF3+8QJwtV2sRJp8u2zVe37IeH1cJ\n"
"xXeHyjTzqZ2803fnjN2iuZvzNr7noOA1/Kp+pFvUZUU5/0G2Ep8zolPUjQJAFA7k\n"
"xRdLkzIx3XeNQjwnmLlncyYPRv+qaE3FMpUu7zftuZBnVCJnvXzUxP3vPgKTlzGa\n"
"dg5XivDRfsV+okY5uQJBAMV4FesUuLQVEKb6lMs7rzZwpeGQhFDRfywJzfom2TLn\n"
"2RdJQQ3dcgnhdVDgt5o1qkmsqQh8uJrJ9SdyLIaZQIc=\n"
"-----END RSA PRIVATE KEY-----\n"
"-----BEGIN CERTIFICATE-----\n"
"MIID6TCCA1KgAwIBAgIJANm4W/Tzs+s+MA0GCSqGSIb3DQEBBQUAMIGqMQswCQYD\n"
"VQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxETAPBgNVBAcTCE5ldyBZb3JrMRYw\n"
"FAYDVQQKEw1TdGVhbWhlYXQubmV0MRQwEgYDVQQLEwtFbmdpbmVlcmluZzEdMBsG\n"
"A1UEAxMUb3BlbmNhLnN0ZWFtaGVhdC5uZXQxKDAmBgkqhkiG9w0BCQEWGWVuZ2lu\n"
"ZWVyaW5nQHN0ZWFtaGVhdC5uZXQwHhcNMDYwNTA1MTcwNjAzWhcNMjQwMjIwMTcw\n"
"NjAzWjCBqjELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMREwDwYDVQQH\n"
"EwhOZXcgWW9yazEWMBQGA1UEChMNU3RlYW1oZWF0Lm5ldDEUMBIGA1UECxMLRW5n\n"
"aW5lZXJpbmcxHTAbBgNVBAMTFG9wZW5jYS5zdGVhbWhlYXQubmV0MSgwJgYJKoZI\n"
"hvcNAQkBFhllbmdpbmVlcmluZ0BzdGVhbWhlYXQubmV0MIGfMA0GCSqGSIb3DQEB\n"
"AQUAA4GNADCBiQKBgQDCYYhcw6cGRbhBVShKmbWm7UVsEoBnUf0cCh8AX+MKhMxw\n"
"VDWVIgdskntn3cSJjRtmgVJHIK0lpb/FYHQB93Ohpd9/Z18pDmovfFF9nDbFF0t3\n"
"9hJ/AqSzFB3GiVPoFFZJEE1vJqh+3jzsSF5K56bZ6azz38VlZgXeSozNW5bXkQID\n"
"AQABo4IBEzCCAQ8wHQYDVR0OBBYEFPJvPd1Fcmd8o/Tm88r+NjYPICCkMIHfBgNV\n"
"HSMEgdcwgdSAFPJvPd1Fcmd8o/Tm88r+NjYPICCkoYGwpIGtMIGqMQswCQYDVQQG\n"
"EwJVUzERMA8GA1UECBMITmV3IFlvcmsxETAPBgNVBAcTCE5ldyBZb3JrMRYwFAYD\n"
"VQQKEw1TdGVhbWhlYXQubmV0MRQwEgYDVQQLEwtFbmdpbmVlcmluZzEdMBsGA1UE\n"
"AxMUb3BlbmNhLnN0ZWFtaGVhdC5uZXQxKDAmBgkqhkiG9w0BCQEWGWVuZ2luZWVy\n"
"aW5nQHN0ZWFtaGVhdC5uZXSCCQDZuFv087PrPjAMBgNVHRMEBTADAQH/MA0GCSqG\n"
"SIb3DQEBBQUAA4GBAC1CXey/4UoLgJiwcEMDxOvW74plks23090iziFIlGgcIhk0\n"
"Df6hTAs7H3MWww62ddvR8l07AWfSzSP5L6mDsbvq7EmQsmPODwb6C+i2aF3EDL8j\n"
"uw73m4YIGI0Zw2XdBpiOGkx2H56Kya6mJJe/5XORZedh1wpI7zki01tHYbcy\n"
"-----END CERTIFICATE-----\n"};
/* These private materials were made with:
* openssl req -new -x509 -keyout cakey.pem -out cacert.pem -nodes -days 6500
* TODO: We need a full-blown capability to work with user-supplied
* keypairs and properly-signed certificates.
*/
/*****************
builtin_passwd_cb
*****************/
extern "C" int builtin_passwd_cb (char *buf, int bufsize, int rwflag, void *userdata)
{
strcpy (buf, "kittycat");
return 8;
}
/****************************
InitializeDefaultCredentials
****************************/
static void InitializeDefaultCredentials()
{
BIO *bio = BIO_new_mem_buf (PrivateMaterials, -1);
assert (bio);
if (DefaultPrivateKey) {
// we may come here in a restart.
EVP_PKEY_free (DefaultPrivateKey);
DefaultPrivateKey = NULL;
}
PEM_read_bio_PrivateKey (bio, &DefaultPrivateKey, builtin_passwd_cb, 0);
if (DefaultCertificate) {
// we may come here in a restart.
X509_free (DefaultCertificate);
DefaultCertificate = NULL;
}
PEM_read_bio_X509 (bio, &DefaultCertificate, NULL, 0);
BIO_free (bio);
}
/**************************
SslContext_t::SslContext_t
**************************/
SslContext_t::SslContext_t (bool is_server, const string &privkeyfile, const string &certchainfile):
pCtx (NULL),
PrivateKey (NULL),
Certificate (NULL)
{
/* TODO: the usage of the specified private-key and cert-chain filenames only applies to
* client-side connections at this point. Server connections currently use the default materials.
* That needs to be fixed asap.
* Also, in this implementation, server-side connections use statically defined X-509 defaults.
* One thing I'm really not clear on is whether or not you have to explicitly free X509 and EVP_PKEY
* objects when we call our destructor, or whether just calling SSL_CTX_free is enough.
*/
if (!bLibraryInitialized) {
bLibraryInitialized = true;
SSL_library_init();
OpenSSL_add_ssl_algorithms();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ERR_load_crypto_strings();
InitializeDefaultCredentials();
}
bIsServer = is_server;
pCtx = SSL_CTX_new (is_server ? SSLv23_server_method() : SSLv23_client_method());
if (!pCtx)
throw std::runtime_error ("no SSL context");
SSL_CTX_set_options (pCtx, SSL_OP_ALL);
//SSL_CTX_set_options (pCtx, (SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3));
if (is_server) {
// The SSL_CTX calls here do NOT allocate memory.
int e;
if (privkeyfile.length() > 0)
e = SSL_CTX_use_PrivateKey_file (pCtx, privkeyfile.c_str(), SSL_FILETYPE_PEM);
else
e = SSL_CTX_use_PrivateKey (pCtx, DefaultPrivateKey);
assert (e > 0);
if (certchainfile.length() > 0)
e = SSL_CTX_use_certificate_chain_file (pCtx, certchainfile.c_str());
else
e = SSL_CTX_use_certificate (pCtx, DefaultCertificate);
assert (e > 0);
}
SSL_CTX_set_cipher_list (pCtx, "ALL:!ADH:!LOW:!EXP:!DES-CBC3-SHA:@STRENGTH");
if (is_server) {
SSL_CTX_sess_set_cache_size (pCtx, 128);
SSL_CTX_set_session_id_context (pCtx, (unsigned char*)"eventmachine", 12);
}
else {
int e;
if (privkeyfile.length() > 0) {
e = SSL_CTX_use_PrivateKey_file (pCtx, privkeyfile.c_str(), SSL_FILETYPE_PEM);
assert (e > 0);
}
if (certchainfile.length() > 0) {
e = SSL_CTX_use_certificate_chain_file (pCtx, certchainfile.c_str());
assert (e > 0);
}
}
}
/***************************
SslContext_t::~SslContext_t
***************************/
SslContext_t::~SslContext_t()
{
if (pCtx)
SSL_CTX_free (pCtx);
if (PrivateKey)
EVP_PKEY_free (PrivateKey);
if (Certificate)
X509_free (Certificate);
}
/******************
SslBox_t::SslBox_t
******************/
SslBox_t::SslBox_t (bool is_server, const string &privkeyfile, const string &certchainfile):
bIsServer (is_server),
pSSL (NULL),
pbioRead (NULL),
pbioWrite (NULL)
{
/* TODO someday: make it possible to re-use SSL contexts so we don't have to create
* a new one every time we come here.
*/
Context = new SslContext_t (bIsServer, privkeyfile, certchainfile);
assert (Context);
pbioRead = BIO_new (BIO_s_mem());
assert (pbioRead);
pbioWrite = BIO_new (BIO_s_mem());
assert (pbioWrite);
pSSL = SSL_new (Context->pCtx);
assert (pSSL);
SSL_set_bio (pSSL, pbioRead, pbioWrite);
if (!bIsServer)
SSL_connect (pSSL);
}
/*******************
SslBox_t::~SslBox_t
*******************/
SslBox_t::~SslBox_t()
{
// Freeing pSSL will also free the associated BIOs, so DON'T free them separately.
if (pSSL) {
if (SSL_get_shutdown (pSSL) & SSL_RECEIVED_SHUTDOWN)
SSL_shutdown (pSSL);
else
SSL_clear (pSSL);
SSL_free (pSSL);
}
delete Context;
}
/***********************
SslBox_t::PutCiphertext
***********************/
bool SslBox_t::PutCiphertext (const char *buf, int bufsize)
{
assert (buf && (bufsize > 0));
assert (pbioRead);
int n = BIO_write (pbioRead, buf, bufsize);
return (n == bufsize) ? true : false;
}
/**********************
SslBox_t::GetPlaintext
**********************/
int SslBox_t::GetPlaintext (char *buf, int bufsize)
{
if (!SSL_is_init_finished (pSSL)) {
int e = bIsServer ? SSL_accept (pSSL) : SSL_connect (pSSL);
if (e < 0) {
int er = SSL_get_error (pSSL, e);
if (er != SSL_ERROR_WANT_READ) {
// Return -1 for a nonfatal error, -2 for an error that should force the connection down.
return (er == SSL_ERROR_SSL) ? (-2) : (-1);
}
else
return 0;
}
// If handshake finished, FALL THROUGH and return the available plaintext.
}
if (!SSL_is_init_finished (pSSL)) {
// We can get here if a browser abandons a handshake.
// The user can see a warning dialog and abort the connection.
cerr << "<SSL_incomp>";
return 0;
}
//cerr << "CIPH: " << SSL_get_cipher (pSSL) << endl;
int n = SSL_read (pSSL, buf, bufsize);
if (n >= 0) {
return n;
}
else {
if (SSL_get_error (pSSL, n) == SSL_ERROR_WANT_READ) {
return 0;
}
else {
return -1;
}
}
return 0;
}
/**************************
SslBox_t::CanGetCiphertext
**************************/
bool SslBox_t::CanGetCiphertext()
{
assert (pbioWrite);
return BIO_pending (pbioWrite) ? true : false;
}
/***********************
SslBox_t::GetCiphertext
***********************/
int SslBox_t::GetCiphertext (char *buf, int bufsize)
{
assert (pbioWrite);
assert (buf && (bufsize > 0));
return BIO_read (pbioWrite, buf, bufsize);
}
/**********************
SslBox_t::PutPlaintext
**********************/
int SslBox_t::PutPlaintext (const char *buf, int bufsize)
{
// The caller will interpret the return value as the number of bytes written.
// WARNING WARNING WARNING, are there any situations in which a 0 or -1 return
// from SSL_write means we should immediately retry? The socket-machine loop
// will probably wait for a time-out cycle (perhaps a second) before re-trying.
// THIS WOULD CAUSE A PERCEPTIBLE DELAY!
/* We internally queue any outbound plaintext that can't be dispatched
* because we're in the middle of a handshake or something.
* When we get called, try to send any queued data first, and then
* send the caller's data (or queue it). We may get called with no outbound
* data, which means we try to send the outbound queue and that's all.
*
* Return >0 if we wrote any data, 0 if we didn't, and <0 for a fatal error.
* Note that if we return 0, the connection is still considered live
* and we are signalling that we have accepted the outbound data (if any).
*/
OutboundQ.Push (buf, bufsize);
if (!SSL_is_init_finished (pSSL))
return 0;
bool fatal = false;
bool did_work = false;
while (OutboundQ.HasPages()) {
const char *page;
int length;
OutboundQ.Front (&page, &length);
assert (page && (length > 0));
int n = SSL_write (pSSL, page, length);
if (n > 0) {
did_work = true;
OutboundQ.PopFront();
}
else {
int er = SSL_get_error (pSSL, n);
if ((er != SSL_ERROR_WANT_READ) && (er != SSL_ERROR_WANT_WRITE))
fatal = true;
break;
}
}
if (did_work)
return 1;
else if (fatal)
return -1;
else
return 0;
}
#endif // WITH_SSL
|