belle
/
include
/
belle.hh
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
/*
88888888
888888888888
88888888888888
8888888888888888
888888888888888888
888888 8888 888888
88888 88 88888
888888 8888 888888
88888888888888888888
88888888888888888888
8888888888888888888888
8888888888888888888888888888
88888888888888888888888888888888
88888888888888888888
888888888888888888888888
888888 8888888888 888888
888 8888 8888 888
888 888
OCTOBANANA
Belle
0.5.1
An HTTP / Websocket library in C++17 using Boost.Beast and Boost.ASIO.
https://octobanana.com/software/belle
Licensed under the MIT License
Copyright (c) 2018 Brett Robinson <https://octobanana.com/>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef OB_BELLE_HH
#define OB_BELLE_HH
#define OB_BELLE_VERSION_MAJOR 0
#define OB_BELLE_VERSION_MINOR 5
#define OB_BELLE_VERSION_PATCH 1
// Config Begin
// compile with -DOB_BELLE_CONFIG_<OPT> or
// comment out defines to alter the library
// ssl support
#ifndef OB_BELLE_CONFIG_SSL_OFF
#define OB_BELLE_CONFIG_SSL_ON
#endif // OB_BELLE_CONFIG_SSL_OFF
// client support
#ifndef OB_BELLE_CONFIG_CLIENT_OFF
#define OB_BELLE_CONFIG_CLIENT_ON
#endif // OB_BELLE_CONFIG_CLIENT_OFF
// server support
#ifndef OB_BELLE_CONFIG_SERVER_OFF
#define OB_BELLE_CONFIG_SERVER_ON
#endif // OB_BELLE_CONFIG_SERVER_OFF
// Config End
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/websocket.hpp>
#ifdef OB_BELLE_CONFIG_SSL_ON
#include <boost/beast/websocket/ssl.hpp>
#endif // OB_BELLE_CONFIG_SSL_ON
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/bind_executor.hpp>
#ifdef OB_BELLE_CONFIG_CLIENT_ON
#include <boost/asio/connect.hpp>
#endif // OB_BELLE_CONFIG_CLIENT_ON
#ifdef OB_BELLE_CONFIG_SSL_ON
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#endif // OB_BELLE_CONFIG_SSL_ON
#include <boost/config.hpp>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <cstddef>
#include <cstdint>
#include <csignal>
#include <string>
#include <sstream>
#include <iomanip>
#include <vector>
#include <array>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <regex>
#include <memory>
#include <chrono>
#include <utility>
#include <initializer_list>
#include <optional>
#include <limits>
#include <type_traits>
#include <thread>
namespace OB::Belle
{
// aliases
namespace net = boost::asio;
namespace beast = boost::beast;
namespace http = boost::beast::http;
namespace websocket = boost::beast::websocket;
#ifdef OB_BELLE_CONFIG_SSL_ON
namespace ssl = boost::asio::ssl;
#endif // OB_BELLE_CONFIG_SSL_ON
using tcp = boost::asio::ip::tcp;
using error_code = boost::system::error_code;
using Method = boost::beast::http::verb;
using Status = boost::beast::http::status;
using Header = boost::beast::http::field;
using Headers = boost::beast::http::fields;
// Ordered_Map: an insert ordered map
// enables fast random lookup and insert ordered iterators
// unordered map stores key value pairs
// queue holds insert ordered iterators to each key in the unordered map
template<typename K, typename V>
class Ordered_Map
{
public:
// map iterators
using m_iterator = typename std::unordered_map<K, V>::iterator;
using m_const_iterator = typename std::unordered_map<K, V>::const_iterator;
// index iterators
using i_iterator = typename std::deque<m_iterator>::iterator;
using i_const_iterator = typename std::deque<m_const_iterator>::const_iterator;
Ordered_Map()
{
}
Ordered_Map(std::initializer_list<std::pair<K, V>> const& lst)
{
for (auto const& [key, val] : lst)
{
_it.emplace_back(_map.insert({key, val}).first);
}
}
~Ordered_Map()
{
}
Ordered_Map& operator()(K const& k, V const& v)
{
auto it = _map.insert_or_assign(k, v);
if (it.second)
{
_it.emplace_back(it.first);
}
return *this;
}
i_iterator operator[](std::size_t index)
{
return _it[index];
}
i_const_iterator const operator[](std::size_t index) const
{
return _it[index];
}
V& at(K const& k)
{
return _map.at(k);
}
V const& at(K const& k) const
{
return _map.at(k);
}
m_iterator find(K const& k)
{
return _map.find(k);
}
m_const_iterator find(K const& k) const
{
return _map.find(k);
}
std::size_t size() const
{
return _it.size();
}
bool empty() const
{
return _it.empty();
}
Ordered_Map& clear()
{
_it.clear();
_map.clear();
return *this;
}
Ordered_Map& erase(K const& k)
{
auto it = _map.find(k);
if (it != _map.end())
{
for (auto e = _it.begin(); e < _it.end(); ++e)
{
if ((*e) == it)
{
_it.erase(e);
break;
}
}
_map.erase(it);
}
return *this;
}
i_iterator begin()
{
return _it.begin();
}
i_const_iterator begin() const
{
return _it.begin();
}
i_const_iterator cbegin() const
{
return _it.cbegin();
}
i_iterator end()
{
return _it.end();
}
i_const_iterator end() const
{
return _it.end();
}
i_const_iterator cend() const
{
return _it.cend();
}
m_iterator map_begin()
{
return _map.begin();
}
m_const_iterator map_begin() const
{
return _map.begin();
}
m_const_iterator map_cbegin() const
{
return _map.cbegin();
}
m_iterator map_end()
{
return _map.end();
}
m_const_iterator map_end() const
{
return _map.end();
}
m_const_iterator map_cend() const
{
return _map.cend();
}
private:
std::unordered_map<K, V> _map;
std::deque<m_iterator> _it;
}; // class Ordered_Map
namespace Detail
{
// prototypes
inline std::string lowercase(std::string str);
inline std::optional<std::string> extension(std::string const& path);
inline std::vector<std::string> split(std::string const& str, std::string const& delim,
std::size_t size = std::numeric_limits<std::size_t>::max());
// string to lowercase
inline std::string lowercase(std::string str)
{
auto const to_lower = [](char& c)
{
if (c >= 'A' && c <= 'Z')
{
c += 'a' - 'A';
}
return c;
};
for (char& c : str)
{
c = to_lower(c);
}
return str;
}
// find extension if present in a string path
inline std::optional<std::string> extension(std::string const& path)
{
if (path.empty() || path.size() < 2)
{
return {};
}
auto const pos = path.rfind(".");
if (pos == std::string::npos || pos == path.size() - 1)
{
return {};
}
return path.substr(pos + 1);
}
// split a string by a delimiter 'n' times
inline std::vector<std::string> split(std::string const& str,
std::string const& delim, std::size_t times)
{
std::vector<std::string> vtok;
std::size_t start {0};
auto end = str.find(delim);
while ((times-- > 0) && (end != std::string::npos))
{
vtok.emplace_back(str.substr(start, end - start));
start = end + delim.length();
end = str.find(delim, start);
}
vtok.emplace_back(str.substr(start, end));
return vtok;
}
// convert object into a string
template<typename T>
inline std::string to_string(T const& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
#ifdef OB_BELLE_CONFIG_SSL_ON
// TODO switch to boost::beast::ssl_stream when it moves out of experimental
template<typename Next_Layer>
class ssl_stream : public ssl::stream_base
{
// This class (ssl_stream) is a derivative work based on Boost.Beast,
// orignal copyright below:
/*
Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
using stream_type = ssl::stream<Next_Layer>;
public:
using native_handle_type = typename stream_type::native_handle_type;
using impl_struct = typename stream_type::impl_struct;
using next_layer_type = typename stream_type::next_layer_type;
using lowest_layer_type = typename stream_type::lowest_layer_type;
using executor_type = typename stream_type::executor_type;
ssl_stream(Next_Layer&& arg, ssl::context& ctx) :
_ptr {std::make_unique<stream_type>(std::move(arg), ctx)}
{
}
executor_type get_executor() noexcept
{
return _ptr->get_executor();
}
native_handle_type native_handle()
{
return _ptr->native_handle();
}
next_layer_type const& next_layer() const
{
return _ptr->next_layer();
}
next_layer_type& next_layer()
{
return _ptr->next_layer();
}
lowest_layer_type& lowest_layer()
{
return _ptr->lowest_layer();
}
lowest_layer_type const& lowest_layer() const
{
return _ptr->lowest_layer();
}
void set_verify_mode(ssl::verify_mode v)
{
_ptr->set_verify_mode(v);
}
void set_verify_mode(ssl::verify_mode v, error_code& ec)
{
_ptr->set_verify_mode(v, ec);
}
void set_verify_depth(int depth)
{
_ptr->set_verify_depth(depth);
}
void set_verify_depth(int depth, error_code& ec)
{
_ptr->set_verify_depth(depth, ec);
}
template<typename VerifyCallback>
void set_verify_callback(VerifyCallback callback)
{
_ptr->set_verify_callback(callback);
}
template<typename VerifyCallback>
void set_verify_callback(VerifyCallback callback, error_code& ec)
{
_ptr->set_verify_callback(callback, ec);
}
void handshake(handshake_type type)
{
_ptr->handshake(type);
}
void handshake(handshake_type type, error_code& ec)
{
_ptr->handshake(type, ec);
}
template<typename ConstBufferSequence>
void handshake(handshake_type type, ConstBufferSequence const& buffers)
{
_ptr->handshake(type, buffers);
}
template<typename ConstBufferSequence>
void handshake(handshake_type type, ConstBufferSequence const& buffers, error_code& ec)
{
_ptr->handshake(type, buffers, ec);
}
template<typename HandshakeHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(HandshakeHandler, void(error_code))
async_handshake(handshake_type type, BOOST_ASIO_MOVE_ARG(HandshakeHandler) handler)
{
return _ptr->async_handshake(type, BOOST_ASIO_MOVE_CAST(HandshakeHandler)(handler));
}
template<typename ConstBufferSequence, typename BufferedHandshakeHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(BufferedHandshakeHandler, void (error_code, std::size_t))
async_handshake(handshake_type type, ConstBufferSequence const& buffers,
BOOST_ASIO_MOVE_ARG(BufferedHandshakeHandler) handler)
{
return _ptr->async_handshake(type, buffers, BOOST_ASIO_MOVE_CAST(BufferedHandshakeHandler)(handler));
}
void shutdown()
{
_ptr->shutdown();
}
void shutdown(error_code& ec)
{
_ptr->shutdown(ec);
}
template<typename ShutdownHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ShutdownHandler, void (error_code))
async_shutdown(BOOST_ASIO_MOVE_ARG(ShutdownHandler) handler)
{
return _ptr->async_shutdown(BOOST_ASIO_MOVE_CAST(ShutdownHandler)(handler));
}
template<typename ConstBufferSequence>
std::size_t write_some(ConstBufferSequence const& buffers)
{
return _ptr->write_some(buffers);
}
template<typename ConstBufferSequence>
std::size_t write_some(ConstBufferSequence const& buffers, error_code& ec)
{
return _ptr->write_some(buffers, ec);
}
template<typename ConstBufferSequence, typename WriteHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (error_code, std::size_t))
async_write_some(ConstBufferSequence const& buffers,
BOOST_ASIO_MOVE_ARG(WriteHandler) handler)
{
return _ptr->async_write_some(buffers, BOOST_ASIO_MOVE_CAST(WriteHandler)(handler));
}
template<typename MutableBufferSequence>
std::size_t read_some(MutableBufferSequence const& buffers)
{
return _ptr->read_some(buffers);
}
template<typename MutableBufferSequence>
std::size_t read_some(MutableBufferSequence const& buffers, error_code& ec)
{
return _ptr->read_some(buffers, ec);
}
template<typename MutableBufferSequence, typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void(error_code, std::size_t))
async_read_some(MutableBufferSequence const& buffers,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler)
{
return _ptr->async_read_some(buffers, BOOST_ASIO_MOVE_CAST(ReadHandler)(handler));
}
template<typename SyncStream>
friend void teardown(websocket::role_type,
ssl_stream<SyncStream>& stream, error_code& ec);
template<typename AsyncStream, typename TeardownHandler>
friend void async_teardown(websocket::role_type,
ssl_stream<AsyncStream>& stream, TeardownHandler&& handler);
private:
std::unique_ptr<stream_type> _ptr;
}; // class ssl_stream
template<typename SyncStream>
inline void teardown(websocket::role_type role,
ssl_stream<SyncStream>& stream, error_code& ec)
{
websocket::teardown(role, *stream._ptr, ec);
}
template<typename AsyncStream, typename TeardownHandler>
inline void async_teardown(websocket::role_type role,
ssl_stream<AsyncStream>& stream, TeardownHandler&& handler)
{
websocket::async_teardown(role, *stream._ptr, std::forward<TeardownHandler>(handler));
}
#endif // OB_BELLE_CONFIG_SSL_ON
} // namespace Detail
std::unordered_map<std::string, std::string> const mime_types
{
{"html", "text/html"},
{"htm", "text/html"},
{"shtml", "text/html"},
{"css", "text/css"},
{"xml", "text/xml"},
{"gif", "image/gif"},
{"jpg", "image/jpg"},
{"jpeg", "image/jpg"},
{"js", "application/javascript"},
{"atom", "application/atom+xml"},
{"rss", "application/rss+xml"},
{"mml", "text/mathml"},
{"txt", "text/plain"},
{"jad", "text/vnd.sun.j2me.app-descriptor"},
{"wml", "text/vnd.wap.wml"},
{"htc", "text/x-component"},
{"png", "image/png"},
{"tif", "image/tiff"},
{"tiff", "image/tiff"},
{"wbmp", "image/vnd.wap.wbmp"},
{"ico", "image/x-icon"},
{"jng", "image/x-jng"},
{"bmp", "image/x-ms-bmp"},
{"svg", "image/svg+xml"},
{"svgz", "image/svg+xml"},
{"webp", "image/webp"},
{"woff", "application/font-woff"},
{"jar", "application/java-archive"},
{"war", "application/java-archive"},
{"ear", "application/java-archive"},
{"json", "application/json"},
{"hqx", "application/mac-binhex40"},
{"doc", "application/msword"},
{"pdf", "application/pdf"},
{"ps", "application/postscript"},
{"eps", "application/postscript"},
{"ai", "application/postscript"},
{"rtf", "application/rtf"},
{"m3u8", "application/vnd.apple.mpegurl"},
{"xls", "application/vnd.ms-excel"},
{"eot", "application/vnd.ms-fontobject"},
{"ppt", "application/vnd.ms-powerpoint"},
{"wmlc", "application/vnd.wap.wmlc"},
{"kml", "application/vnd.google-earth.kml+xml"},
{"kmz", "application/vnd.google-earth.kmz"},
{"7z", "application/x-7z-compressed"},
{"cco", "application/x-cocoa"},
{"jardiff", "application/x-java-archive-diff"},
{"jnlp", "application/x-java-jnlp-file"},
{"run", "application/x-makeself"},
{"pm", "application/x-perl"},
{"pl", "application/x-perl"},
{"pdb", "application/x-pilot"},
{"prc", "application/x-pilot"},
{"rar", "application/x-rar-compressed"},
{"rpm", "application/x-redhat-package-manager"},
{"sea", "application/x-sea"},
{"swf", "application/x-shockwave-flash"},
{"sit", "application/x-stuffit"},
{"tk", "application/x-tcl"},
{"tcl", "application/x-tcl"},
{"crt", "application/x-x509-ca-cert"},
{"pem", "application/x-x509-ca-cert"},
{"der", "application/x-x509-ca-cert"},
{"xpi", "application/x-xpinstall"},
{"xhtml", "application/xhtml+xml"},
{"xspf", "application/xspf+xml"},
{"zip", "application/zip"},
{"dll", "application/octet-stream"},
{"exe", "application/octet-stream"},
{"bin", "application/octet-stream"},
{"deb", "application/octet-stream"},
{"dmg", "application/octet-stream"},
{"img", "application/octet-stream"},
{"iso", "application/octet-stream"},
{"msm", "application/octet-stream"},
{"msp", "application/octet-stream"},
{"msi", "application/octet-stream"},
{"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{"kar", "audio/midi"},
{"midi", "audio/midi"},
{"mid", "audio/midi"},
{"mp3", "audio/mpeg"},
{"ogg", "audio/ogg"},
{"m4a", "audio/x-m4a"},
{"ra", "audio/x-realaudio"},
{"3gp", "video/3gpp"},
{"3gpp", "video/3gpp"},
{"ts", "video/mp2t"},
{"mp4", "video/mp4"},
{"mpg", "video/mpeg"},
{"mpeg", "video/mpeg"},
{"mov", "video/quicktime"},
{"webm", "video/webm"},
{"flv", "video/x-flv"},
{"m4v", "video/x-m4v"},
{"mng", "video/x-mng"},
{"asf", "video/x-ms-asf"},
{"asx", "video/x-ms-asf"},
{"wmv", "video/x-ms-wmv"},
{"avi", "video/x-msvideo"},
};
// prototypes
inline std::string mime_type(std::string const& path);
// find the mime type of a string path
inline std::string mime_type(std::string const& path)
{
if (auto ext = Detail::extension(path))
{
auto const str = Detail::lowercase(ext.value());
if (mime_types.find(str) != mime_types.end())
{
return mime_types.at(str);
}
}
return "application/octet-stream";
}
class Request : public http::request<http::string_body>
{
using Base = http::request<http::string_body>;
public:
using Path = std::vector<std::string>;
using Params = std::unordered_multimap<std::string, std::string>;
// inherit base constructors
using http::request<http::string_body>::message;
// default constructor
Request() = default;
// copy constructor
Request(Request const&) = default;
// move constructor
Request(Request&&) = default;
// copy assignment
Request& operator=(Request const&) = default;
// move assignment
Request& operator=(Request&& rhs) = default;
// default deconstructor
~Request() = default;
Request&& move() noexcept
{
return std::move(*this);
}
// get the path
Path& path()
{
return _path;
}
// get the query parameters
Params& params()
{
return _params;
}
// serialize path and query parameters to the target
void params_serialize()
{
std::string path {target().to_string()};
_path.clear();
_path.emplace_back(path);
if (! _params.empty())
{
path += "?";
auto it = _params.begin();
for (; it != _params.end(); ++it)
{
path += url_encode(it->first) + "=" + url_encode(it->second) + "&";
}
path.pop_back();
}
target(path);
}
// parse the query parameters from the target
void params_parse()
{
std::string path {target().to_string()};
// separate the query params
auto params = Detail::split(path, "?", 1);
// set params
if (params.size() == 2)
{
auto kv = Detail::split(params.at(1), "&");
for (auto const& e : kv)
{
if (e.empty())
{
continue;
}
auto k_v = Detail::split(e, "=", 1);
if (k_v.size() == 1)
{
_params.emplace(url_decode(e), "");
}
else if (k_v.size() == 2)
{
_params.emplace(url_decode(k_v.at(0)), url_decode(k_v.at(1)));
}
continue;
}
}
}
private:
std::string hex_encode(char const c)
{
char s[3];
if (c & 0x80)
{
std::snprintf(&s[0], 3, "%02X",
static_cast<unsigned int>(c & 0xff)
);
}
else
{
std::snprintf(&s[0], 3, "%02X",
static_cast<unsigned int>(c)
);
}
return std::string(s);
}
char hex_decode(std::string const& s)
{
unsigned int n;
std::sscanf(s.data(), "%x", &n);
return static_cast<char>(n);
}
std::string url_encode(std::string const& str)
{
std::string res;
res.reserve(str.size());
for (auto const& e : str)
{
if (e == ' ')
{
res += "+";
}
else if (std::isalnum(static_cast<unsigned char>(e)) ||
e == '-' || e == '_' || e == '.' || e == '~')
{
res += e;
}
else
{
res += "%" + hex_encode(e);
}
}
return res;
}
std::string url_decode(std::string const& str)
{
std::string res;
res.reserve(str.size());
for (std::size_t i = 0; i < str.size(); ++i)
{
if (str[i] == '+')
{
res += " ";
}
else if (str[i] == '%' && i + 2 < str.size() &&
std::isxdigit(static_cast<unsigned char>(str[i + 1])) &&
std::isxdigit(static_cast<unsigned char>(str[i + 2])))
{
res += hex_decode(str.substr(i + 1, 2));
i += 2;
}
else
{
res += str[i];
}
}
return res;
}
Path _path {};
Params _params {};
}; // Request
// store a type erased websocket
struct Websocket_Session
{
// default deconstructor
virtual ~Websocket_Session() = default;
// send a message
virtual void send(std::string const&&) = 0;
}; // struct Websocket_Session
#ifdef OB_BELLE_CONFIG_SERVER_ON
class Server
{
public:
// NOTE Channel implementation is NOT thread safe
class Channel
{
public:
Channel()
{
}
void join(Websocket_Session& socket_)
{
_sockets.insert(&socket_);
}
void leave(Websocket_Session& socket_)
{
_sockets.erase(&socket_);
}
void broadcast(std::string const&& str_) const
{
for(auto const e : _sockets)
{
e->send(std::move(str_));
}
}
std::size_t size() const
{
return _sockets.size();
}
private:
std::unordered_set<Websocket_Session*> _sockets;
}; // class Channel
// NOTE Channels implementation is NOT thread safe
using Channels = std::unordered_map<std::string, Channel>;
template<typename Body>
struct Http_Ctx_Basic
{
Request req {};
http::response<Body> res {};
std::shared_ptr<void> data {nullptr};
}; // class Http_Ctx_Basic
using Http_Ctx = Http_Ctx_Basic<http::string_body>;
class Websocket_Ctx
{
public:
Websocket_Ctx(Websocket_Session& socket_, Request&& req_,
Channels& channels_) :
socket {&socket_},
req {std::move(req_)},
channels {channels_}
{
}
~Websocket_Ctx()
{
}
void send(std::string const&& str_) const
{
socket->send(std::move(str_));
}
void broadcast(std::string const&& str_) const
{
for (auto const& e : channels)
{
e.second.broadcast(std::move(str_));
}
}
Websocket_Session* socket;
Request req;
Channels& channels;
std::string msg {};
std::shared_ptr<void> data {nullptr};
}; // class Websocket_Ctx
// callbacks
using fn_on_signal = std::function<void(error_code, int)>;
using fn_on_http = std::function<void(Http_Ctx&)>;
using fn_on_websocket = std::function<void(Websocket_Ctx&)>;
struct fns_on_websocket
{
fns_on_websocket(fn_on_websocket const& begin_,
fn_on_websocket const& data_, fn_on_websocket const& end_) :
begin {begin_},
data {data_},
end {end_}
{
}
fn_on_websocket begin {};
fn_on_websocket data {};
fn_on_websocket end {};
}; // struct fns_on_websocket
// aliases
using Http_Routes =
Ordered_Map<std::string, std::unordered_map<int, fn_on_http>>;
using Websocket_Routes =
std::vector<std::pair<std::string, fns_on_websocket>>;
private:
struct Attr
{
#ifdef OB_BELLE_CONFIG_SSL_ON
// use ssl
bool ssl {false};
// ssl context
ssl::context ssl_context {ssl::context::tlsv12_server};
#endif // OB_BELLE_CONFIG_SSL_ON
// the public directory for serving static files
std::string public_dir {};
// default index filename for the public directory
std::string index_file {"index.html"};
// socket timeout
std::chrono::seconds timeout {10};
// serve static files from public directory
bool http_static {true};
// serve dynamic content
bool http_dynamic {true};
// upgrade http to websocket connection
bool websocket {true};
// default http headers
Headers http_headers {};
// http routes
Http_Routes http_routes {};
// websocket routes
Websocket_Routes websocket_routes {};
// callbacks for http
fn_on_http on_http_error {};
fn_on_http on_http_connect {};
fn_on_http on_http_disconnect {};
// callbacks for websocket
fn_on_websocket on_websocket_error {};
fn_on_websocket on_websocket_connect {};
fn_on_websocket on_websocket_disconnect {};
// websocket channels
Channels channels {};
}; // struct Attr
template<typename Derived>
class Websocket_Base : public Websocket_Session
{
Derived& derived()
{
return static_cast<Derived&>(*this);
}
public:
Websocket_Base(net::io_context& io_, std::shared_ptr<Attr> const attr_,
Request&& req_, fns_on_websocket const& on_websocket_) :
_attr {attr_},
_ctx {static_cast<Derived&>(*this), std::move(req_), _attr->channels},
_on_websocket {on_websocket_},
_strand {io_.get_executor()}
{
}
~Websocket_Base()
{
// leave channel
_attr->channels.at(_ctx.req.path().at(0)).leave(derived());
if (_on_websocket.end)
{
try
{
// run user function
_on_websocket.end(_ctx);
}
catch (...)
{
this->handle_error();
}
}
if (_attr->on_websocket_disconnect)
{
try
{
// run user function
_attr->on_websocket_disconnect(_ctx);
}
catch (...)
{
this->handle_error();
}
}
}
void send(std::string const&& str_)
{
auto const pstr = std::make_shared<std::string const>(std::move(str_));
_que.emplace_back(pstr);
if (_que.size() > 1)
{
return;
}
derived().socket().async_write(net::buffer(*_que.front()),
[self = derived().shared_from_this()](error_code ec, std::size_t bytes)
{
self->on_write(ec, bytes);
}
);
}
void handle_error()
{
if (_attr->on_websocket_error)
{
try
{
// run user function
_attr->on_websocket_error(_ctx);
}
catch (...)
{
}
}
}
void do_accept()
{
derived().socket().control_callback(
[this](websocket::frame_type type, boost::beast::string_view data)
{
this->on_control_callback(type, data);
}
);
derived().socket().async_accept_ex(_ctx.req,
[&](auto& res)
{
for (auto const& e : _attr->http_headers)
{
res.insert(e.name_string(), e.value());
}
},
net::bind_executor(_strand,
[self = derived().shared_from_this()](error_code ec)
{
self->on_accept(ec);
}
)
);
}
void on_accept(error_code ec_)
{
if (ec_ == net::error::operation_aborted)
{
return;
}
if (ec_)
{
// TODO log here
return;
}
// join channel
if (_attr->channels.find(_ctx.req.path().at(0)) == _attr->channels.end())
{
_attr->channels[_ctx.req.path().at(0)] = Channel();
}
_attr->channels.at(_ctx.req.path().at(0)).join(derived());
if (_attr->on_websocket_connect)
{
try
{
// run user function
_attr->on_websocket_connect(_ctx);
}
catch (...)
{
this->handle_error();
}
}
if (_on_websocket.begin)
{
try
{
// run user function
_on_websocket.begin(_ctx);
}
catch (...)
{
this->handle_error();
}
}
this->do_read();
}
void on_control_callback(websocket::frame_type type_, boost::beast::string_view data_)
{
boost::ignore_unused(type_, data_);
}
void do_read()
{
derived().socket().async_read(_buf,
net::bind_executor(_strand,
[self = derived().shared_from_this()](error_code ec, std::size_t bytes)
{
self->on_read(ec, bytes);
}
)
);
}
void on_read(error_code ec_, std::size_t bytes_)
{
boost::ignore_unused(bytes_);
// socket closed by the timer
if (ec_ == net::error::operation_aborted)
{
return;
}
// socket closed
if (ec_ == websocket::error::closed)
{
return;
}
if (ec_)
{
// TODO log here
return;
}
if (_on_websocket.data)
{
try
{
_ctx.msg = boost::beast::buffers_to_string(_buf.data());
// run user function
_on_websocket.data(_ctx);
}
catch (...)
{
handle_error();
}
}
// clear the request object
_ctx.req.clear();
// clear the buffers
_buf.consume(_buf.size());
this->do_read();
}
void on_write(error_code ec_, std::size_t bytes_)
{
boost::ignore_unused(bytes_);
// happens when the timer closes the socket
if (ec_ == net::error::operation_aborted)
{
return;
}
if (ec_)
{
// TODO log here
return;
}
// remove sent message from the queue
_que.pop_front();
if (_que.empty())
{
return;
}
derived().socket().async_write(net::buffer(*_que.front()),
[self = derived().shared_from_this()](error_code ec, std::size_t bytes)
{
self->on_write(ec, bytes);
}
);
}
std::shared_ptr<Attr> const _attr;
Websocket_Ctx _ctx;
fns_on_websocket const& _on_websocket;
net::strand<net::io_context::executor_type> _strand;
boost::beast::multi_buffer _buf;
std::deque<std::shared_ptr<std::string const>> _que {};
}; // class Websocket_Base
class Websocket :
public Websocket_Base<Websocket>,
public std::enable_shared_from_this<Websocket>
{
public:
Websocket(tcp::socket&& socket_, std::shared_ptr<Attr> const attr_,
Request&& req_, fns_on_websocket const& on_websocket_) :
Websocket_Base<Websocket> {socket_.get_executor().context(), attr_,
std::move(req_), on_websocket_},
_socket {std::move(socket_)}
{
}
~Websocket()
{
}
websocket::stream<tcp::socket>& socket()
{
return _socket;
}
void run()
{
this->do_accept();
}
void do_timeout()
{
this->do_shutdown();
}
void do_shutdown()
{
_socket.async_close(websocket::close_code::normal,
net::bind_executor(this->_strand,
[self = this->shared_from_this()](error_code ec)
{
self->on_shutdown(ec);
}
)
);
}
void on_shutdown(error_code ec_)
{
if (ec_)
{
// TODO log here
return;
}
}
private:
websocket::stream<tcp::socket> _socket;
}; // class Websocket
#ifdef OB_BELLE_CONFIG_SSL_ON
class Websockets :
public Websocket_Base<Websockets>,
public std::enable_shared_from_this<Websockets>
{
public:
Websockets(Detail::ssl_stream<tcp::socket>&& socket_, std::shared_ptr<Attr> const attr_,
Request&& req_, fns_on_websocket const& on_websocket_) :
Websocket_Base<Websockets> {socket_.get_executor().context(), attr_,
std::move(req_), on_websocket_},
_socket {std::move(socket_)}
{
}
~Websockets()
{
}
websocket::stream<Detail::ssl_stream<tcp::socket>>& socket()
{
return _socket;
}
void run()
{
this->do_accept();
}
void do_timeout()
{
this->do_shutdown();
}
void do_shutdown()
{
_socket.async_close(websocket::close_code::normal,
net::bind_executor(this->_strand,
[self = this->shared_from_this()](error_code ec)
{
self->on_shutdown(ec);
}
)
);
}
void on_shutdown(error_code ec_)
{
if (ec_)
{
// TODO log here
return;
}
}
private:
websocket::stream<Detail::ssl_stream<tcp::socket>> _socket;
}; // class Websockets
#endif // OB_BELLE_CONFIG_SSL_ON
template<typename Derived, typename Websocket_Type>
class Http_Base
{
Derived& derived()
{
return static_cast<Derived&>(*this);
}
public:
Http_Base(net::io_context& io_, std::shared_ptr<Attr> const attr_) :
_strand {io_.get_executor()},
_timer {io_, (std::chrono::steady_clock::time_point::max)()},
_attr {attr_}
{
}
~Http_Base()
{
}
// TODO remove shim once visual studio supports generic lambdas
#ifdef _MSC_VER
template<typename Self, typename Res>
static void constexpr send(Self self, Res&& res)
#else
// generic lambda for sending different types of responses
static auto constexpr send = [](auto self, auto&& res) -> void
#endif // _MSC_VER
{
using item_type = std::remove_reference_t<decltype(res)>;
auto ptr = std::make_shared<item_type>(std::move(res));
self->_res = ptr;
http::async_write(self->derived().socket(), *ptr,
net::bind_executor(self->_strand,
[self, close = ptr->need_eof()]
(error_code ec, std::size_t bytes)
{
self->on_write(ec, bytes, close);
}
)
);
};
int serve_static()
{
if (! _attr->http_static || _attr->public_dir.empty())
{
return 404;
}
if ((_ctx.req.method() != http::verb::get) && (_ctx.req.method() != http::verb::head))
{
return 404;
}
std::string path {_attr->public_dir + _ctx.req.target().to_string()};
if (path.back() == '/')
{
path += _attr->index_file;
}
error_code ec;
http::file_body::value_type body;
body.open(path.data(), beast::file_mode::scan, ec);
if (ec)
{
return 404;
}
// head request
if (_ctx.req.method() == http::verb::head)
{
http::response<http::empty_body> res {};
res.base() = http::response_header<>(_attr->http_headers);
res.version(_ctx.req.version());
res.keep_alive(_ctx.req.keep_alive());
res.content_length(body.size());
res.set(Header::content_type, mime_type(path));
send(derived().shared_from_this(), std::move(res));
return 0;
}
// get request
auto const size = body.size();
http::response<http::file_body> res {
std::piecewise_construct,
std::make_tuple(std::move(body)),
std::make_tuple(_attr->http_headers)
};
res.version(_ctx.req.version());
res.keep_alive(_ctx.req.keep_alive());
res.content_length(size);
res.set(Header::content_type, mime_type(path));
send(derived().shared_from_this(), std::move(res));
return 0;
}
int serve_dynamic()
{
if (! _attr->http_dynamic || _attr->http_routes.empty())
{
return 404;
}
// regex variables
std::smatch rx_match {};
std::regex_constants::syntax_option_type const rx_opts {std::regex::ECMAScript};
std::regex_constants::match_flag_type const rx_flgs {std::regex_constants::match_not_null};
// the request path
std::string path {_ctx.req.target().to_string()};
// separate the query parameters
auto params = Detail::split(path, "?", 1);
path = params.at(0);
// iterate over routes
for (auto const& regex_method : _attr->http_routes)
{
bool method_match {false};
auto match = (*regex_method).second.find(0);
if (match != (*regex_method).second.end())
{
method_match = true;
}
else
{
match = (*regex_method).second.find(static_cast<int>(_ctx.req.method()));
if (match != (*regex_method).second.end())
{
method_match = true;
}
}
if (method_match)
{
std::regex rx_str {(*regex_method).first, rx_opts};
if (std::regex_match(path, rx_match, rx_str, rx_flgs))
{
// set the path
for (auto const& e : rx_match)
{
_ctx.req.path().emplace_back(e.str());
}
// parse target params
_ctx.req.params_parse();
// set callback function
auto const& user_func = match->second;
try
{
// run user function
user_func(_ctx);
_ctx.res.content_length(_ctx.res.body().size());
send(derived().shared_from_this(), std::move(_ctx.res));
return 0;
}
catch (int const e)
{
return e;
}
catch (unsigned int const e)
{
return static_cast<int>(e);
}
catch (Status const e)
{
return static_cast<int>(e);
}
catch (std::exception const&)
{
return 500;
}
catch (...)
{
return 500;
}
}
}
}
return 404;
}
void serve_error(int err)
{
_ctx.res.result(static_cast<unsigned int>(err));
if (_attr->on_http_error)
{
try
{
// run user function
_attr->on_http_error(_ctx);
_ctx.res.content_length(_ctx.res.body().size());
send(derived().shared_from_this(), std::move(_ctx.res));
return;
}
catch (int const e)
{
_ctx.res.result(static_cast<unsigned int>(e));
}
catch (unsigned int const e)
{
_ctx.res.result(e);
}
catch (Status const e)
{
_ctx.res.result(e);
}
catch (std::exception const&)
{
_ctx.res.result(500);
}
catch (...)
{
_ctx.res.result(500);
}
}
_ctx.res.set(Header::content_type, "text/plain");
_ctx.res.body() = "Error: " + std::to_string(_ctx.res.result_int());
_ctx.res.content_length(_ctx.res.body().size());
send(derived().shared_from_this(), std::move(_ctx.res));
};
void handle_request()
{
// set default response values
_ctx.res.version(_ctx.req.version());
_ctx.res.keep_alive(_ctx.req.keep_alive());
if (_ctx.req.target().empty())
{
_ctx.req.target() = "/";
}
if (_ctx.req.target().at(0) != '/' ||
_ctx.req.target().find("..") != boost::beast::string_view::npos)
{
this->serve_error(404);
return;
}
// serve dynamic content
auto dyna = this->serve_dynamic();
// success
if (dyna == 0)
{
return;
}
// error
if (dyna != 404)
{
this->serve_error(dyna);
return;
}
// serve static content
auto stat = this->serve_static();
if (stat != 0)
{
this->serve_error(stat);
return;
}
}
bool handle_websocket()
{
// the request path
std::string path {_ctx.req.target().to_string()};
// separate the query parameters
auto params = Detail::split(path, "?", 1);
path = params.at(0);
// regex variables
std::smatch rx_match {};
std::regex_constants::syntax_option_type const rx_opts {std::regex::ECMAScript};
std::regex_constants::match_flag_type const rx_flgs {std::regex_constants::match_not_null};
// check for matching route
for (auto const& [regex, callback] : _attr->websocket_routes)
{
std::regex rx_str {regex, rx_opts};
if (std::regex_match(path, rx_match, rx_str, rx_flgs))
{
// set the path
for (auto const& e : rx_match)
{
_ctx.req.path().emplace_back(e.str());
}
// parse target params
_ctx.req.params_parse();
// create websocket
std::make_shared<Websocket_Type>
(derived().socket_move(), _attr, std::move(_ctx.req), callback)
->run();
return true;
}
}
return false;
}
void cancel_timer()
{
// set the timer to expire immediately
_timer.expires_at((std::chrono::steady_clock::time_point::min)());
}
void do_timer()
{
// wait on the timer
_timer.async_wait(
net::bind_executor(_strand,
[self = derived().shared_from_this()](error_code ec)
{
self->on_timer(ec);
}
)
);
}
void on_timer(error_code ec_ = {})
{
if (ec_ && ec_ != net::error::operation_aborted)
{
// TODO log here
return;
}
// check if socket has been upgraded or closed
if (_timer.expires_at() == (std::chrono::steady_clock::time_point::min)())
{
return;
}
// check expiry
if (_timer.expiry() <= std::chrono::steady_clock::now())
{
derived().do_timeout();
return;
}
}
void do_read()
{
_timer.expires_after(_attr->timeout);
_res = nullptr;
_ctx = {};
_ctx.res.base() = http::response_header<>(_attr->http_headers);
http::async_read(derived().socket(), _buf, _ctx.req,
net::bind_executor(_strand,
[self = derived().shared_from_this()](error_code ec, std::size_t bytes)
{
self->on_read(ec, bytes);
}
)
);
}
void on_read(error_code ec_, std::size_t bytes_)
{
boost::ignore_unused(bytes_);
// the timer has closed the socket
if (ec_ == net::error::operation_aborted)
{
return;
}
// the connection has been closed
if (ec_ == http::error::end_of_stream)
{
derived().do_shutdown();
return;
}
if (ec_)
{
// TODO log here
return;
}
// check for websocket upgrade
if (websocket::is_upgrade(_ctx.req))
{
if (! _attr->websocket || _attr->websocket_routes.empty())
{
derived().do_shutdown();
return;
}
// upgrade to websocket
if (handle_websocket())
{
this->cancel_timer();
return;
}
else
{
derived().do_shutdown();
return;
}
}
if (_attr->on_http_connect)
{
try
{
// run user func
_attr->on_http_connect(_ctx);
}
catch (...)
{
}
}
this->handle_request();
if (_attr->on_http_disconnect)
{
try
{
// run user func
_attr->on_http_disconnect(_ctx);
}
catch (...)
{
}
}
}
void on_write(error_code ec_, std::size_t bytes_, bool close_)
{
boost::ignore_unused(bytes_);
// the timer has closed the socket
if (ec_ == net::error::operation_aborted)
{
return;
}
if (ec_)
{
// TODO log here
return;
}
if (close_)
{
derived().do_shutdown();
return;
}
// read another request
this->do_read();
}
net::strand<net::io_context::executor_type> _strand;
net::steady_timer _timer;
boost::beast::flat_buffer _buf;
std::shared_ptr<Attr> const _attr;
Http_Ctx _ctx {};
std::shared_ptr<void> _res {nullptr};
bool _close {false};
}; // class Http_Base
class Http :
public Http_Base<Http, Websocket>,
public std::enable_shared_from_this<Http>
{
public:
Http(tcp::socket socket_, std::shared_ptr<Attr> const attr_) :
Http_Base<Http, Websocket> {socket_.get_executor().context(), attr_},
_socket {std::move(socket_)}
{
}
~Http()
{
}
tcp::socket& socket()
{
return _socket;
}
tcp::socket&& socket_move()
{
return std::move(_socket);
}
void run()
{
this->do_timer();
this->do_read();
}
void do_timeout()
{
this->do_shutdown();
}
void do_shutdown()
{
error_code ec;
// send a tcp shutdown
_socket.shutdown(tcp::socket::shutdown_send, ec);
this->cancel_timer();
if (ec)
{
// TODO log here
return;
}
}
private:
tcp::socket _socket;
}; // class Http
#ifdef OB_BELLE_CONFIG_SSL_ON
class Https :
public Http_Base<Https, Websockets>,
public std::enable_shared_from_this<Https>
{
public:
Https(tcp::socket&& socket_, std::shared_ptr<Attr> const attr_) :
Http_Base<Https, Websockets> {socket_.get_executor().context(), attr_},
_socket {std::move(socket_), attr_->ssl_context}
{
this->_close = true;
}
~Https()
{
}
Detail::ssl_stream<tcp::socket>& socket()
{
return _socket;
}
Detail::ssl_stream<tcp::socket>&& socket_move()
{
return std::move(_socket);
}
void run()
{
this->do_timer();
this->do_handshake();
}
void do_timeout()
{
// timed out on handshake or shutdown
if (this->_close)
{
return;
}
// reset the timer
this->_timer.expires_at((std::chrono::steady_clock::time_point::max)());
this->do_timer();
this->do_shutdown();
}
void do_handshake()
{
this->_timer.expires_after(this->_attr->timeout);
_socket.async_handshake(ssl::stream_base::server,
net::bind_executor(this->_strand,
[self = this->shared_from_this()](error_code ec)
{
self->on_handshake(ec);
}
)
);
}
void on_handshake(error_code ec_)
{
// the timer has closed the socket
if (ec_ == net::error::operation_aborted)
{
return;
}
if (ec_)
{
// TODO log here
return;
}
this->_close = false;
this->do_read();
}
void do_shutdown()
{
this->_timer.expires_after(this->_attr->timeout);
this->_close = true;
// shutdown the socket
_socket.async_shutdown(
net::bind_executor(this->_strand,
[self = this->shared_from_this()](error_code ec)
{
self->on_shutdown(ec);
}
)
);
}
void on_shutdown(error_code ec_)
{
this->cancel_timer();
// the timer has closed the socket
if (ec_ == net::error::operation_aborted)
{
return;
}
if (ec_)
{
// TODO log here
return;
}
}
private:
Detail::ssl_stream<tcp::socket> _socket;
}; // class Https
#endif // OB_BELLE_CONFIG_SSL_ON
template<typename Session>
class Listener : public std::enable_shared_from_this<Listener<Session>>
{
public:
Listener(net::io_context& io_, tcp::endpoint endpoint_, std::shared_ptr<Attr> const attr_) :
_acceptor {io_},
_socket {io_},
_attr {attr_}
{
error_code ec;
// open the acceptor
_acceptor.open(endpoint_.protocol(), ec);
if (ec)
{
// TODO log here
return;
}
// allow address reuse
_acceptor.set_option(net::socket_base::reuse_address(true), ec);
if (ec)
{
// TODO log here
return;
}
// bind to the server address
_acceptor.bind(endpoint_, ec);
if (ec)
{
// TODO log here
return;
}
// start listening for connections
_acceptor.listen(net::socket_base::max_listen_connections, ec);
if (ec)
{
// TODO log here
return;
}
}
void run()
{
if (! _acceptor.is_open())
{
// TODO log here
return;
}
do_accept();
}
private:
void do_accept()
{
_acceptor.async_accept(_socket,
[self = this->shared_from_this()](error_code ec)
{
self->on_accept(ec);
}
);
}
void on_accept(error_code ec_)
{
if (ec_)
{
// TODO log here
}
else
{
// create an Http obj and run it
std::make_shared<Session>(std::move(_socket), _attr)->run();
}
// accept another connection
do_accept();
}
private:
tcp::acceptor _acceptor;
tcp::socket _socket;
std::shared_ptr<Attr> const _attr;
}; // class Listener
public:
// default constructor
Server()
{
}
// constructor with address and port
Server(std::string address_, unsigned short port_) :
_address {address_},
_port {port_}
{
}
#ifdef OB_BELLE_CONFIG_SSL_ON
// constructor with address, port, and ssl
Server(std::string address_, unsigned short port_, bool ssl_) :
_address {address_},
_port {port_}
{
_attr->ssl = true;
}
#endif // OB_BELLE_CONFIG_SSL_ON
// destructor
~Server()
{
}
// set the listening address
Server& address(std::string address_)
{
_address = address_;
return *this;
}
// get the listening address
std::string address()
{
return _address;
}
// set the listening port
Server& port(unsigned short port_)
{
_port = port_;
return *this;
}
// get the listening port
unsigned short port()
{
return _port;
}
// set the public directory for serving static files
Server& public_dir(std::string public_dir_)
{
if (! public_dir_.empty() && public_dir_.back() == '/')
{
public_dir_.pop_back();
}
if (public_dir_.empty())
{
public_dir_ = ".";
}
_attr->public_dir = public_dir_;
return *this;
}
// get the public directory for serving static files
std::string public_dir()
{
return _attr->public_dir;
}
// set the default index filename
Server& index_file(std::string index_file_)
{
if (index_file_.empty())
{
_attr->index_file = "index.html";
}
else
{
_attr->index_file = index_file_;
}
return *this;
}
// get the default index filename
std::string index_file()
{
return _attr->index_file;
}
// set the number of threads
Server& threads(unsigned int threads_)
{
_threads = std::max<unsigned int>(1, threads_);
return *this;
}
// get the number of threads
unsigned int threads()
{
return _threads;
}
#ifdef OB_BELLE_CONFIG_SSL_ON
// set ssl
Server& ssl(bool ssl_)
{
_attr->ssl = ssl_;
return *this;
}
// get ssl
bool ssl()
{
return _attr->ssl;
}
// get the ssl context
ssl::context& ssl_context()
{
return _attr->ssl_context;
}
// set the ssl context
Server& ssl_context(ssl::context&& ctx_)
{
_attr->ssl_context = std::move(ctx_);
return *this;
}
#endif // OB_BELLE_CONFIG_SSL_ON
// set http static
Server& http_static(bool val_)
{
_attr->http_static = val_;
return *this;
}
// get http static
bool http_static()
{
return _attr->http_static;
}
// set http dynamic
Server& http_dynamic(bool val_)
{
_attr->http_dynamic = val_;
return *this;
}
// get http dynamic
bool http_dynamic()
{
return _attr->http_dynamic;
}
// set http static and dynamic
Server& http(bool val_)
{
_attr->http_static = val_;
_attr->http_dynamic = val_;
return *this;
}
// set websocket upgrade
Server& websocket(bool val_)
{
_attr->websocket = val_;
return *this;
}
// get websocket upgrade
bool websocket()
{
return _attr->websocket;
}
// set the socket timeout
Server& timeout(std::chrono::seconds timeout_)
{
_attr->timeout = timeout_;
return *this;
}
// get the socket timeout
std::chrono::seconds timeout()
{
return _attr->timeout;
}
// get the io_context
net::io_context& io()
{
return _io;
}
// set signals to capture
Server& signals(std::vector<int> signals_)
{
for (auto const& e : signals_)
{
_signals.add(e);
}
return *this;
}
// set signal callback
// called when a captured signal is received
Server& on_signal(fn_on_signal on_signal_)
{
_on_signal = on_signal_;
_signals.async_wait(
[this](error_code const& ec, int sig)
{
this->_on_signal(ec, sig);
}
);
return *this;
}
// set http callback matching a single method
// called after http read
Server& on_http(std::string route_, Method method_, fn_on_http on_http_)
{
if (_attr->http_routes.find(route_) == _attr->http_routes.map_end())
{
_attr->http_routes(route_, {{static_cast<int>(method_), on_http_}});
}
else
{
_attr->http_routes.at(route_)[static_cast<int>(method_)] = on_http_;
}
return *this;
}
// set http callback matching multiple methods
// called after http read
Server& on_http(std::string route_, std::vector<Method> methods_, fn_on_http on_http_)
{
for (auto const& e : methods_)
{
if (_attr->http_routes.find(route_) == _attr->http_routes.map_end())
{
_attr->http_routes(route_, {{static_cast<int>(e), on_http_}});
}
else
{
_attr->http_routes.at(route_)[static_cast<int>(e)] = on_http_;
}
}
return *this;
}
// set http callback matching all methods
// called after http read
Server& on_http(std::string route_, fn_on_http on_http_)
{
if (_attr->http_routes.find(route_) == _attr->http_routes.map_end())
{
_attr->http_routes(route_, {{0, on_http_}});
}
else
{
_attr->http_routes.at(route_)[0] = on_http_;
}
return *this;
}
// set http error callback
// called when an exception or error occurs
Server& on_http_error(fn_on_http on_http_error_)
{
_attr->on_http_error = on_http_error_;
return *this;
}
// set http connect callback
// called at the very beginning of every http connection
Server& on_http_connect(fn_on_http on_http_connect_)
{
_attr->on_http_connect = on_http_connect_;
return *this;
}
// set http disconnect callback
// called at the very end of every http connection
Server& on_http_disconnect(fn_on_http on_http_disconnect_)
{
_attr->on_http_disconnect = on_http_disconnect_;
return *this;
}
// set websocket data callback
// data: called after every websocket read
Server& on_websocket(std::string route_, fn_on_websocket data_)
{
_attr->websocket_routes.emplace_back(
std::make_pair(route_, fns_on_websocket(nullptr, data_, nullptr)));
return *this;
}
// set websocket begin, data, and end callbacks
// begin: called once after connected
// data: called after every websocket read
// end: called once after disconnected
Server& on_websocket(std::string route_,
fn_on_websocket begin_, fn_on_websocket data_, fn_on_websocket end_)
{
_attr->websocket_routes.emplace_back(
std::make_pair(route_, fns_on_websocket(begin_, data_, end_)));
return *this;
}
// set websocket error callback
// called when an exception or error occurs
Server& on_websocket_error(fn_on_websocket on_websocket_error_)
{
_attr->on_websocket_error = on_websocket_error_;
return *this;
}
// set websocket connect callback
// called once at the very beginning after connected
Server& on_websocket_connect(fn_on_websocket on_websocket_connect_)
{
_attr->on_websocket_connect = on_websocket_connect_;
return *this;
}
// set websocket disconnect callback
// called once at the very end after disconnected
Server& on_websocket_disconnect(fn_on_websocket on_websocket_disconnect_)
{
_attr->on_websocket_disconnect = on_websocket_disconnect_;
return *this;
}
// get http routes
Http_Routes& http_routes()
{
return _attr->http_routes;
}
// get websocket routes
Websocket_Routes& websocket_routes()
{
return _attr->websocket_routes;
}
// set default http headers
Server& http_headers(Headers const& headers_)
{
_attr->http_headers = headers_;
return *this;
}
// get default http headers
Headers& http_headers()
{
return _attr->http_headers;
}
// get websocket channels
Channels& channels()
{
return _attr->channels;
}
// check if address:port is already in use
static bool available(std::string const& address_, unsigned short port_)
{
error_code ec;
net::io_context io;
tcp::acceptor acceptor(io);
auto endpoint = tcp::endpoint(net::ip::make_address(address_), port_);
acceptor.open(endpoint.protocol(), ec);
if (ec)
{
return false;
}
acceptor.bind(endpoint, ec);
if (ec)
{
return false;
}
return true;
};
// check if address:port is already in use
bool available() const
{
error_code ec;
net::io_context io;
tcp::acceptor acceptor(io);
auto endpoint = tcp::endpoint(net::ip::make_address(_address), _port);
acceptor.open(endpoint.protocol(), ec);
if (ec)
{
return false;
}
acceptor.bind(endpoint, ec);
if (ec)
{
return false;
}
return true;
};
// start the server
void listen(std::string address_ = "", unsigned short port_ = 0)
{
// set the listening address
if (! address_.empty())
{
_address = address_;
}
// set the listening port
if (port_ != 0)
{
_port = port_;
}
// set default server header value if not present
if (_attr->http_headers.find(Header::server) == _attr->http_headers.end())
{
_attr->http_headers.set(Header::server, "Belle");
}
// websocket channels are not threadsafe, limit to 1 thread
if (_attr->websocket && _threads > 1)
{
_threads = 1;
}
// create the listener
#ifdef OB_BELLE_CONFIG_SSL_ON
if (_attr->ssl)
{
// use https
std::make_shared<Listener<Https>>
(_io, tcp::endpoint(net::ip::make_address(_address), _port), _attr)
->run();
}
else
#endif // OB_BELLE_CONFIG_SSL_ON
{
// use http
std::make_shared<Listener<Http>>
(_io, tcp::endpoint(net::ip::make_address(_address), _port), _attr)
->run();
}
// thread pool
std::vector<std::thread> io_threads;
// create and start threads if needed
if (_threads > 1)
{
io_threads.reserve(static_cast<std::size_t>(_threads) - 1);
for (unsigned int i = 1; i < _threads; ++i)
{
io_threads.emplace_back(
[this]()
{
// run the io context on the new thread
this->_io.run();
}
);
}
}
// run the io context on the current thread
_io.run();
// wait on threads to return
for (auto& t : io_threads)
{
t.join();
}
}
private:
// hold the server attributes shared by each socket connection
std::shared_ptr<Attr> const _attr {std::make_shared<Attr>()};
// the address to listen on
std::string _address {"127.0.0.1"};
// the port to listen on
unsigned short _port {8080};
// the number of threads to run on
unsigned int _threads {1};
// the io context
net::io_context _io {};
// signals
net::signal_set _signals {_io};
// callback for signals
fn_on_signal _on_signal {};
}; // class Server
#endif // OB_BELLE_CONFIG_SERVER_ON
#ifdef OB_BELLE_CONFIG_CLIENT_ON
class Client
{
public:
struct Http_Ctx
{
// http request
Request* req {nullptr};
// http response
http::response<http::string_body> res {};
}; // struct Http_Ctx
struct Error_Ctx
{
// error code
error_code const& ec;
}; // struct Error_Ctx
// callbacks
using fn_on_http = std::function<void(Http_Ctx&)>;
using fn_on_http_error = std::function<void(Error_Ctx&)>;
struct Req_Ctx
{
// http request object
Request req {};
// http callback
fn_on_http on_http {};
}; // struct Req_Ctx
struct Attr
{
#ifdef OB_BELLE_CONFIG_SSL_ON
// use ssl
bool ssl {false};
// ssl context
ssl::context ssl_context {ssl::context::tlsv12_client};
#endif // OB_BELLE_CONFIG_SSL_ON
// socket timeout
std::chrono::seconds timeout {10};
// address to connect to
std::string address {"127.0.0.1"};
// port to connect to
unsigned short port {8080};
// http request queue
std::deque<Req_Ctx> que;
// http error callback
fn_on_http_error on_http_error {};
}; // struct Attr
template<typename Derived>
class Http_Base
{
Derived& derived()
{
return static_cast<Derived&>(*this);
}
public:
Http_Base(net::io_context& io_, std::shared_ptr<Attr> const attr_) :
_resolver {io_},
_strand {io_.get_executor()},
_timer {io_, (std::chrono::steady_clock::time_point::max)()},
_attr {attr_}
{
}
~Http_Base()
{
}
void cancel_timer()
{
// set the timer to expire immediately
_timer.expires_at((std::chrono::steady_clock::time_point::min)());
}
void do_timer()
{
// wait on the timer
_timer.async_wait(
net::bind_executor(_strand,
[self = derived().shared_from_this()](error_code ec)
{
self->on_timer(ec);
}
)
);
}
void on_timer(error_code ec_)
{
if (ec_ && ec_ != net::error::operation_aborted)
{
Error_Ctx err {ec_};
_attr->on_http_error(err);
return;
}
// check if socket has been closed
if (_timer.expires_at() == (std::chrono::steady_clock::time_point::min)())
{
return;
}
// check expiry
if (_timer.expiry() <= std::chrono::steady_clock::now())
{
derived().do_close();
return;
}
if (_close)
{
return;
}
}
void do_resolve()
{
_timer.expires_after(_attr->timeout);
// domain name server lookup
_resolver.async_resolve(_attr->address,
Detail::to_string(_attr->port),
net::bind_executor(_strand,
[self = derived().shared_from_this()]
(error_code ec, tcp::resolver::results_type results)
{
self->on_resolve(ec, results);
}
)
);
}
void on_resolve(error_code ec_, tcp::resolver::results_type results_)
{
if (ec_)
{
cancel_timer();
Error_Ctx err {ec_};
_attr->on_http_error(err);
return;
}
// connect to the endpoint
net::async_connect(derived().socket().lowest_layer(),
results_.begin(), results_.end(),
net::bind_executor(_strand,
[self = derived().shared_from_this()](error_code ec, auto)
{
self->derived().on_connect(ec);
}
)
);
}
void prepare_request()
{
_ctx = {};
_ctx.req = &_attr->que.front().req;
// serialize target and params
_ctx.req->params_serialize();
// set default user-agent header value if not present
if (_ctx.req->find(Header::user_agent) == _ctx.req->end())
{
_ctx.req->set(Header::user_agent, "Belle");
}
// set default host header value if not present
if (_ctx.req->find(Header::host) == _ctx.req->end())
{
_ctx.req->set(Header::host, _attr->address);
}
// set connection close if last request in the queue
if (_attr->que.size() == 1)
{
_ctx.req->keep_alive(false);
}
// prepare the payload
_ctx.req->prepare_payload();
}
void do_write()
{
prepare_request();
_timer.expires_after(_attr->timeout);
// Send the HTTP request
http::async_write(derived().socket(), *_ctx.req,
net::bind_executor(_strand,
[self = derived().shared_from_this()](error_code ec, std::size_t bytes)
{
self->on_write(ec, bytes);
}
)
);
}
void on_write(error_code ec_, std::size_t bytes_)
{
boost::ignore_unused(bytes_);
if (ec_)
{
cancel_timer();
Error_Ctx err {ec_};
_attr->on_http_error(err);
return;
}
do_read();
}
void do_read()
{
// Receive the HTTP response
http::async_read(derived().socket(), _buf, _ctx.res,
net::bind_executor(_strand,
[self = derived().shared_from_this()](error_code ec, std::size_t bytes)
{
self->on_read(ec, bytes);
}
)
);
}
void on_read(error_code ec_, std::size_t bytes_)
{
boost::ignore_unused(bytes_);
if (ec_)
{
cancel_timer();
Error_Ctx err {ec_};
_attr->on_http_error(err);
return;
}
// run user function
_attr->que.front().on_http(_ctx);
// remove request from queue
_attr->que.pop_front();
if (_attr->que.empty())
{
derived().do_close();
}
else
{
do_write();
}
}
tcp::resolver _resolver;
net::strand<net::io_context::executor_type> _strand;
net::steady_timer _timer;
std::shared_ptr<Attr> const _attr;
Http_Ctx _ctx {};
beast::flat_buffer _buf {};
bool _close {false};
}; // class Http_Base
class Http :
public Http_Base<Http>,
public std::enable_shared_from_this<Http>
{
public:
Http(net::io_context& io_, std::shared_ptr<Attr> attr_) :
Http_Base<Http>(io_, attr_),
_socket {io_}
{
}
~Http()
{
}
tcp::socket& socket()
{
return _socket;
}
tcp::socket&& socket_move()
{
return std::move(_socket);
}
void run()
{
do_timer();
do_resolve();
}
void on_connect(error_code ec_)
{
if (ec_)
{
cancel_timer();
Error_Ctx err {ec_};
_attr->on_http_error(err);
return;
}
do_write();
}
void do_close()
{
error_code ec;
// shutdown the socket
_socket.shutdown(tcp::socket::shutdown_both, ec);
_socket.close(ec);
// ignore not_connected error
if (ec && ec != boost::system::errc::not_connected)
{
cancel_timer();
Error_Ctx err {ec};
_attr->on_http_error(err);
return;
}
// the connection is now closed
}
private:
tcp::socket _socket;
}; // class Http
#ifdef OB_BELLE_CONFIG_SSL_ON
class Https :
public Http_Base<Https>,
public std::enable_shared_from_this<Https>
{
public:
Https(net::io_context& io_, std::shared_ptr<Attr> attr_) :
Http_Base<Https>(io_, attr_),
_socket {std::move(tcp::socket(io_)), attr_->ssl_context}
{
_close = true;
}
~Https()
{
}
Detail::ssl_stream<tcp::socket>& socket()
{
return _socket;
}
Detail::ssl_stream<tcp::socket>&& socket_move()
{
return std::move(_socket);
}
void run()
{
// start the timer
do_timer();
// set server name indication
// use SSL_ctrl instead of SSL_set_tlsext_host_name macro
// to avoid old style C cast to char*
// if (! SSL_set_tlsext_host_name(_socket.native_handle(), _attr->address.data()))
if (! SSL_ctrl(_socket.native_handle(), SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, _attr->address.data()))
{
error_code ec
{
static_cast<int>(ERR_get_error()),
net::error::get_ssl_category()
};
cancel_timer();
Error_Ctx err {ec};
_attr->on_http_error(err);
return;
}
do_resolve();
}
void on_connect(error_code ec_)
{
if (ec_)
{
cancel_timer();
Error_Ctx err {ec_};
_attr->on_http_error(err);
return;
}
do_handshake();
}
void do_handshake()
{
// perform the ssl handshake
_socket.async_handshake(ssl::stream_base::client,
net::bind_executor(_strand,
[self = this->shared_from_this()](error_code ec)
{
self->on_handshake(ec);
}
)
);
}
void on_handshake(error_code ec_)
{
if (ec_)
{
cancel_timer();
Error_Ctx err {ec_};
_attr->on_http_error(err);
return;
}
_close = false;
do_write();
}
void do_close()
{
if (_close)
{
return;
}
_close = true;
// shutdown the socket
_socket.async_shutdown(
net::bind_executor(_strand,
[self = this->shared_from_this()](error_code ec)
{
self->on_shutdown(ec);
}
)
);
}
void on_shutdown(error_code ec_)
{
cancel_timer();
// ignore eof error
if (ec_ == net::error::eof)
{
ec_.assign(0, ec_.category());
}
// ignore not_connected error
if (ec_ && ec_ != boost::system::errc::not_connected)
{
return;
}
// close the socket
_socket.next_layer().close(ec_);
// ignore not_connected error
if (ec_ && ec_ != boost::system::errc::not_connected)
{
return;
}
// the connection is now closed
}
private:
Detail::ssl_stream<tcp::socket> _socket;
}; // class Https
#endif // OB_BELLE_CONFIG_SSL_ON
// default constructor
Client()
{
}
// constructor with address and port
Client(std::string address_, unsigned short port_)
{
_attr->address = address_;
_attr->port = port_;
}
#ifdef OB_BELLE_CONFIG_SSL_ON
// constructor with address, port, and ssl
Client(std::string address_, unsigned short port_, bool ssl_)
{
_attr->address = address_;
_attr->port = port_;
_attr->ssl = ssl_;
}
#endif // OB_BELLE_CONFIG_SSL_ON
// destructor
~Client()
{
}
// set the address to connect to
Client& address(std::string address_)
{
_attr->address = address_;
return *this;
}
// get the address to connect to
std::string address()
{
return _attr->address;
}
// set the port to connect to
Client& port(unsigned short port_)
{
_attr->port = port_;
return *this;
}
// get the port to connect to
unsigned short port()
{
return _attr->port;
}
// set the socket timeout
Client& timeout(std::chrono::seconds timeout_)
{
_attr->timeout = timeout_;
return *this;
}
// get the socket timeout
std::chrono::seconds timeout()
{
return _attr->timeout;
}
// set the max timeout
Client& timeout_max(std::chrono::milliseconds timeout_max_)
{
_timeout_max = timeout_max_;
return *this;
}
// get the max timeout
std::chrono::milliseconds timeout_max()
{
return _timeout_max;
}
// get request queue
std::deque<Req_Ctx>& queue()
{
return _attr->que;
}
// get the io_context
net::io_context& io()
{
return _io;
}
#ifdef OB_BELLE_CONFIG_SSL_ON
// set ssl
Client& ssl(bool ssl_)
{
_attr->ssl = ssl_;
return *this;
}
// get ssl
bool ssl()
{
return _attr->ssl;
}
// get the ssl context
ssl::context& ssl_context()
{
return _attr->ssl_context;
}
// set the ssl context
Client& ssl_context(ssl::context&& ctx_)
{
_attr->ssl_context = std::move(ctx_);
return *this;
}
#endif // OB_BELLE_CONFIG_SSL_ON
Client& on_http(Request const& req_, fn_on_http on_http_)
{
_attr->que.emplace_back(Req_Ctx());
auto& ctx = _attr->que.back();
ctx.req = req_;
ctx.on_http = on_http_;
return *this;
}
Client& on_http(Request&& req_, fn_on_http on_http_)
{
_attr->que.emplace_back(Req_Ctx());
auto& ctx = _attr->que.back();
ctx.req = std::move(req_);
ctx.on_http = on_http_;
return *this;
}
Client& on_http(std::string const& target_, fn_on_http on_http_)
{
this->on_http_impl(Method::get, target_, Request::Params(), Headers(), {}, on_http_);
return *this;
}
Client& on_http(std::string const& target_, Request::Params const& params_, fn_on_http on_http_)
{
this->on_http_impl(Method::get, target_, params_, Headers(), {}, on_http_);
return *this;
}
Client& on_http(std::string const& target_, Headers const& headers_, fn_on_http on_http_)
{
this->on_http_impl(Method::get, target_, Request::Params(), headers_, {}, on_http_);
return *this;
}
Client& on_http(std::string const& target_, Request::Params const& params_, Headers const& headers_, fn_on_http on_http_)
{
this->on_http_impl(Method::get, target_, params_, headers_, {}, on_http_);
return *this;
}
Client& on_http(Method method_, std::string const& target_,
std::string const& body_, fn_on_http on_http_)
{
this->on_http_impl(method_, target_, Request::Params(), Headers(), body_, on_http_);
return *this;
}
Client& on_http(Method method_, std::string const& target_,
Request::Params const& params_,
std::string const& body_, fn_on_http on_http_)
{
this->on_http_impl(method_, target_, params_, Headers(), body_, on_http_);
return *this;
}
Client& on_http(Method method_, std::string const& target_,
Headers const& headers_,
std::string const& body_, fn_on_http on_http_)
{
this->on_http_impl(method_, target_, Request::Params(), headers_, body_, on_http_);
return *this;
}
Client& on_http(Method method_, std::string const& target_,
Request::Params const& params_, Headers const& headers_,
std::string const& body_, fn_on_http on_http_)
{
this->on_http_impl(method_, target_, params_, headers_, body_, on_http_);
return *this;
}
Client& on_http_error(fn_on_http_error on_http_error_)
{
_attr->on_http_error = on_http_error_;
return *this;
}
std::size_t connect()
{
if (_attr->que.empty())
{
return 0;
}
#ifdef OB_BELLE_CONFIG_SSL_ON
if (_attr->ssl)
{
// use https
std::make_shared<Https>(_io, _attr)->run();
}
else
#endif // OB_BELLE_CONFIG_SSL_ON
{
// use http
std::make_shared<Http>(_io, _attr)->run();
}
std::size_t size_begin {_attr->que.size()};
if (_timeout_max > std::chrono::milliseconds(0))
{
// run for max 'n' amount of time
_io.run_until(std::chrono::steady_clock::now() + _timeout_max);
}
else
{
_io.run();
}
// reset the io_context
_io.restart();
std::size_t size_end {_attr->que.size()};
return size_begin - size_end;
}
private:
Client& on_http_impl(Method method_, std::string const& target_,
Request::Params const& params_, Headers const& headers_,
std::string const& body_, fn_on_http on_http_)
{
_attr->que.emplace_back(Req_Ctx());
auto& ctx = _attr->que.back();
Request req {method_, target_, 11, body_, headers_};
req.params() = params_;
ctx.req = std::move(req);
ctx.on_http = on_http_;
return *this;
}
// hold the client attributes
std::shared_ptr<Attr> const _attr {std::make_shared<Attr>()};
// the io context
net::io_context _io {};
// timeout all requests after specified number of milliseconds
std::chrono::milliseconds _timeout_max {0};
}; // class Client
#endif // OB_BELLE_CONFIG_CLIENT_ON
} // namespace OB::Belle
#endif // OB_BELLE_HH