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
|
/*
* Copyright 2025 Vsevolod Stakhov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "http_connection.h"
#include "http_private.h"
#include "http_message.h"
#include "utlist.h"
#include "util.h"
#include "printf.h"
#include "logger.h"
#include "ref.h"
#include "ottery.h"
#include "keypair_private.h"
#include "cryptobox.h"
#include "libutil/libev_helper.h"
#include "libserver/ssl_util.h"
#include "libserver/url.h"
#include "contrib/mumhash/mum.h"
#include "contrib/http-parser/http_parser.h"
#include "unix-std.h"
#include <openssl/err.h>
#define ENCRYPTED_VERSION " HTTP/1.0"
struct _rspamd_http_privbuf {
rspamd_fstring_t *data;
const char *zc_buf;
gsize zc_remain;
ref_entry_t ref;
};
enum rspamd_http_priv_flags {
RSPAMD_HTTP_CONN_FLAG_ENCRYPTED = 1u << 0u,
RSPAMD_HTTP_CONN_FLAG_NEW_HEADER = 1u << 1u,
RSPAMD_HTTP_CONN_FLAG_RESETED = 1u << 2u,
RSPAMD_HTTP_CONN_FLAG_TOO_LARGE = 1u << 3u,
RSPAMD_HTTP_CONN_FLAG_ENCRYPTION_NEEDED = 1u << 4u,
RSPAMD_HTTP_CONN_FLAG_PROXY = 1u << 5u,
RSPAMD_HTTP_CONN_FLAG_PROXY_REQUEST = 1u << 6u,
RSPAMD_HTTP_CONN_OWN_SOCKET = 1u << 7u,
RSPAMD_HTTP_CONN_FLAG_EARLY_RESPONSE = 1u << 8u, /* Server sent early response during write */
RSPAMD_HTTP_CONN_FLAG_INNER_COMPLETE = 1u << 9u, /* Decrypted inner message was completed */
/* Bytes of a message arrived when no message was expected: after a reply */
RSPAMD_HTTP_CONN_FLAG_UNSOLICITED = 1u << 10u,
/* An interim (1xx) reply is being read: the final one follows it */
RSPAMD_HTTP_CONN_FLAG_INTERIM = 1u << 11u,
};
#define IS_CONN_ENCRYPTED(c) ((c)->flags & RSPAMD_HTTP_CONN_FLAG_ENCRYPTED)
#define IS_CONN_RESETED(c) ((c)->flags & RSPAMD_HTTP_CONN_FLAG_RESETED)
static gssize rspamd_http_try_read(int fd,
struct rspamd_http_connection *conn,
struct rspamd_http_connection_private *priv,
struct _rspamd_http_privbuf *pbuf,
const char **buf_ptr);
struct rspamd_http_connection_private {
struct rspamd_http_context *ctx;
struct rspamd_ssl_connection *ssl;
struct _rspamd_http_privbuf *buf;
struct rspamd_keypair_cache *cache;
struct rspamd_cryptobox_pubkey *peer_key;
struct rspamd_cryptobox_keypair *local_key;
struct rspamd_http_header *header;
struct http_parser parser;
struct http_parser_settings parser_cb;
struct rspamd_io_ev ev;
ev_tstamp timeout; /* legacy/global timeout (fallback) */
/* Staged timeouts (seconds); 0 means use ctx/defaults */
ev_tstamp connect_timeout;
ev_tstamp ssl_timeout;
ev_tstamp write_timeout;
ev_tstamp read_timeout;
struct rspamd_http_message *msg;
/* How many messages were given to the finish handler on this connection */
unsigned int completed;
struct iovec *out;
unsigned int outlen;
enum rspamd_http_priv_flags flags;
gsize wr_pos;
gsize wr_total;
/* Keepalive tuning and telemetry */
double created_ts; /* when connection object was created */
double last_used_ts; /* last time returned to pool */
unsigned int reuse_count; /* number of reuses from keepalive */
double ka_ttl_override; /* per-request TTL */
double ka_idle_override; /* per-request idle timeout */
unsigned int ka_max_reuse_override; /* per-request max reuse */
/* Internal state */
bool first_write_done;
};
static const rspamd_ftok_t key_header = {
.begin = "Key",
.len = 3};
static const rspamd_ftok_t date_header = {
.begin = "Date",
.len = 4};
static const rspamd_ftok_t last_modified_header = {
.begin = "Last-Modified",
.len = 13};
static void rspamd_http_event_handler(int fd, short what, gpointer ud);
static void rspamd_http_ssl_err_handler(gpointer ud, GError *err);
#define HTTP_ERROR http_error_quark()
GQuark
http_error_quark(void)
{
return g_quark_from_static_string("http-error-quark");
}
static void
rspamd_http_privbuf_dtor(gpointer ud)
{
struct _rspamd_http_privbuf *p = (struct _rspamd_http_privbuf *) ud;
if (p->data) {
rspamd_fstring_free(p->data);
}
g_free(p);
}
static const char *
rspamd_http_code_to_str(int code)
{
if (code == 200) {
return "OK";
}
else if (code == 404) {
return "Not found";
}
else if (code == 403 || code == 401) {
return "Not authorized";
}
else if (code >= 400 && code < 500) {
return "Bad request";
}
else if (code >= 300 && code < 400) {
return "See Other";
}
else if (code >= 500 && code < 600) {
return "Internal server error";
}
return "Unknown error";
}
static void
rspamd_http_parse_key(rspamd_ftok_t *data, struct rspamd_http_connection *conn,
struct rspamd_http_connection_private *priv)
{
unsigned char *decoded_id;
const char *eq_pos;
gsize id_len, pk_len;
struct rspamd_cryptobox_pubkey *pk;
if (priv->local_key == NULL) {
/* In this case we cannot do anything, e.g. we cannot decrypt payload */
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
}
else {
/* Check sanity of what we have */
eq_pos = memchr(data->begin, '=', data->len);
if (eq_pos != NULL) {
decoded_id = rspamd_decode_base32(data->begin, eq_pos - data->begin,
&id_len, RSPAMD_BASE32_DEFAULT);
/*
* The key is the rest of the value, and an empty one must not reach
* rspamd_pubkey_from_base32: it takes a length of 0 for a
* NUL-terminated string, which a header value is not.
*/
pk_len = data->begin + data->len - eq_pos - 1;
if (decoded_id != NULL && id_len >= RSPAMD_KEYPAIR_SHORT_ID_LEN &&
pk_len > 0) {
pk = rspamd_pubkey_from_base32(eq_pos + 1, pk_len,
RSPAMD_KEYPAIR_KEX);
if (pk != NULL) {
/*
* Keep a peer key that is already set: a client has
* its server key moved in before the reply is read,
* and an unauthenticated header must not replace it.
* A repeated Key header is ignored the same way.
*/
if (priv->msg->peer_key == NULL &&
memcmp(rspamd_keypair_get_id(priv->local_key),
decoded_id,
RSPAMD_KEYPAIR_SHORT_ID_LEN) == 0) {
priv->msg->peer_key = pk;
if (priv->cache && priv->msg->peer_key) {
rspamd_keypair_cache_process(priv->cache,
priv->local_key,
priv->msg->peer_key);
}
}
else {
rspamd_pubkey_unref(pk);
}
}
}
priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
g_free(decoded_id);
}
}
}
static inline void
rspamd_http_check_special_header(struct rspamd_http_connection *conn,
struct rspamd_http_connection_private *priv)
{
if (rspamd_ftok_casecmp(&priv->header->name, &date_header) == 0) {
priv->msg->date = rspamd_http_parse_date(priv->header->value.begin,
priv->header->value.len);
}
else if (rspamd_ftok_casecmp(&priv->header->name, &key_header) == 0) {
rspamd_http_parse_key(&priv->header->value, conn, priv);
}
else if (rspamd_ftok_casecmp(&priv->header->name, &last_modified_header) == 0) {
priv->msg->last_modified = rspamd_http_parse_date(
priv->header->value.begin,
priv->header->value.len);
}
}
static int
rspamd_http_on_url(http_parser *parser, const char *at, size_t length)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
priv = conn->priv;
if (priv->msg == NULL) {
/*
* A callback can arrive after the message it belongs to is gone:
* completing a message runs application code, and with keepalive the
* connection is reset right there, so whatever the peer sent after that
* message still reaches the parser. Those bytes belong to no message
* and must not be parsed into one that is no longer there.
*/
return 0;
}
priv->msg->url = rspamd_fstring_append(priv->msg->url, at, length);
return 0;
}
static int
rspamd_http_on_status(http_parser *parser, const char *at, size_t length)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
priv = conn->priv;
if (priv->msg == NULL) {
/* Arrived after the message was released, see rspamd_http_on_url */
conn->priv->flags |= RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
return 0;
}
if (parser->status_code != 200) {
if (priv->msg->status == NULL) {
priv->msg->status = rspamd_fstring_new();
}
priv->msg->status = rspamd_fstring_append(priv->msg->status, at, length);
}
return 0;
}
static void rspamd_http_drop_header(struct rspamd_http_connection_private *priv);
static void
rspamd_http_finish_header(struct rspamd_http_connection *conn,
struct rspamd_http_connection_private *priv)
{
struct rspamd_http_header *hdr;
khiter_t k;
int r;
if (!(priv->flags & RSPAMD_HTTP_CONN_FLAG_NEW_HEADER)) {
/*
* The field never got a value. The parser refuses a line without
* ':', but should a field still end this way, it is not a header,
* and without the ": " separator the value length below would wrap
*/
rspamd_http_drop_header(priv);
return;
}
priv->header->combined = rspamd_fstring_append(priv->header->combined,
"\r\n", 2);
priv->header->value.len = priv->header->combined->len -
priv->header->name.len - 4;
priv->header->value.begin = priv->header->combined->str +
priv->header->name.len + 2;
priv->header->name.begin = priv->header->combined->str;
k = kh_put(rspamd_http_headers_hash, priv->msg->headers, &priv->header->name,
&r);
if (r != 0) {
kh_value(priv->msg->headers, k) = priv->header;
hdr = NULL;
}
else {
hdr = kh_value(priv->msg->headers, k);
}
DL_APPEND(hdr, priv->header);
rspamd_http_check_special_header(conn, priv);
}
static void
rspamd_http_init_header(struct rspamd_http_connection_private *priv)
{
priv->header = g_malloc0(sizeof(struct rspamd_http_header));
priv->header->combined = rspamd_fstring_new();
}
static int
rspamd_http_on_header_field(http_parser *parser,
const char *at,
size_t length)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
priv = conn->priv;
if (priv->msg == NULL) {
/* Arrived after the message was released, see rspamd_http_on_url */
conn->priv->flags |= RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
return 0;
}
if (priv->header == NULL) {
rspamd_http_init_header(priv);
}
else if (priv->flags & RSPAMD_HTTP_CONN_FLAG_NEW_HEADER) {
rspamd_http_finish_header(conn, priv);
rspamd_http_init_header(priv);
}
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
priv->header->combined = rspamd_fstring_append(priv->header->combined,
at, length);
return 0;
}
static int
rspamd_http_on_header_value(http_parser *parser,
const char *at,
size_t length)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
priv = conn->priv;
if (priv->msg == NULL) {
/* Arrived after the message was released, see rspamd_http_on_url */
conn->priv->flags |= RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
return 0;
}
if (priv->header == NULL) {
/* Should not happen */
return -1;
}
if (!(priv->flags & RSPAMD_HTTP_CONN_FLAG_NEW_HEADER)) {
priv->flags |= RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
priv->header->combined = rspamd_fstring_append(priv->header->combined,
": ", 2);
priv->header->name.len = priv->header->combined->len - 2;
}
priv->header->combined = rspamd_fstring_append(priv->header->combined,
at, length);
return 0;
}
/*
* Cap on the body storage that a peer's own declaration may pre-allocate when
* no message limit is configured to bound it. The declared length is only ever
* a hint for the initial size and the storage grows geometrically afterwards,
* so a low cap costs at most a few reallocations on a genuinely large body.
*/
#define RSPAMD_HTTP_BODY_PREALLOC_MAX ((uint64_t) 1024 * 1024)
/*
* How much body the peer has announced but not sent yet: what is left of
* `Content-Length` for identity encoding, and what is left of the *current
* chunk* for chunked encoding. Nothing has been received to back it up, so it
* may only be used as a hint. ULLONG_MAX is the parser's "not announced" value.
*/
static inline uint64_t
rspamd_http_body_announced(http_parser *parser)
{
if (parser->content_length == ULLONG_MAX) {
return 0;
}
return parser->content_length;
}
/*
* Enforces `max_size` over what has been received plus what is still announced.
* Counting the announcement refuses an oversized body as early as its first
* fragment, before anything has been read or allocated for it, which is what
* `on_headers_complete` already does when the length is known up front.
*/
static gboolean
rspamd_http_body_within_limit(struct rspamd_http_connection *conn,
struct rspamd_http_message *msg,
http_parser *parser,
size_t length)
{
uint64_t received;
if (conn->max_size == 0) {
return TRUE;
}
received = (uint64_t) msg->body_buf.len + length;
if (received > conn->max_size) {
return FALSE;
}
if (rspamd_http_body_announced(parser) > conn->max_size - received) {
return FALSE;
}
return TRUE;
}
/*
* Initial size for the body storage. Deliberately not the announced length on
* its own: with chunked encoding that is a chunk size the peer picked, so using
* it unbounded lets a peer of its choosing size an allocation here.
*/
static gsize
rspamd_http_body_prealloc(struct rspamd_http_connection *conn,
http_parser *parser,
size_t length)
{
uint64_t hint = rspamd_http_body_announced(parser);
if (conn->max_size > 0 && hint > conn->max_size) {
hint = conn->max_size;
}
if (hint > RSPAMD_HTTP_BODY_PREALLOC_MAX) {
hint = RSPAMD_HTTP_BODY_PREALLOC_MAX;
}
/* Whatever is already in hand has to fit regardless of the cap */
if (hint < length) {
hint = length;
}
return (gsize) hint;
}
/*
* Releases a header that is still being parsed. Ownership of a header moves to
* the message only in `rspamd_http_finish_header`, so one that never got there
* -- an unterminated trailer, a connection torn down mid-header -- is ours to
* free and would otherwise be leaked per message.
*/
static void
rspamd_http_drop_header(struct rspamd_http_connection_private *priv)
{
if (priv->header != NULL) {
rspamd_fstring_free(priv->header->combined);
g_free(priv->header);
priv->header = NULL;
}
}
static int
rspamd_http_on_headers_complete(http_parser *parser)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
struct rspamd_http_message *msg;
int ret;
priv = conn->priv;
msg = priv->msg;
if (msg == NULL) {
/* Arrived after the message was released, see rspamd_http_on_url */
conn->priv->flags |= RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
return 0;
}
if (priv->header != NULL) {
rspamd_http_finish_header(conn, priv);
priv->header = NULL;
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
}
if (conn->type == RSPAMD_HTTP_CLIENT && parser->type == HTTP_RESPONSE &&
parser->status_code >= 100 && parser->status_code < 200 &&
parser->status_code != 101) {
/*
* An interim reply (100 Continue, 103 Early Hints): it is not the
* answer to the request, which follows it on this connection
*/
priv->flags |= RSPAMD_HTTP_CONN_FLAG_INTERIM;
return 0;
}
if (msg->method == HTTP_HEAD) {
/* We don't care about the rest */
rspamd_ev_watcher_stop(priv->ctx->event_loop, &priv->ev);
msg->code = parser->status_code;
rspamd_http_connection_ref(conn);
priv->completed++;
ret = conn->finish_handler(conn, msg);
if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
rspamd_http_context_push_keepalive(conn->priv->ctx, conn,
msg, conn->priv->ctx->event_loop);
/* push_keepalive() may decline pooling and leave conn->finished == TRUE */
if (!conn->finished) {
rspamd_http_connection_reset(conn);
}
}
else {
conn->finished = TRUE;
}
rspamd_http_connection_unref(conn);
return ret;
}
/*
* HTTP parser sets content length to (-1) when it doesn't know the real
* length, for example, in case of chunked encoding.
*
* Hence, we skip body setup here
*/
if (parser->content_length != ULLONG_MAX && parser->content_length != 0 &&
msg->method != HTTP_HEAD) {
if (conn->max_size > 0 &&
parser->content_length > conn->max_size) {
/* Too large message */
priv->flags |= RSPAMD_HTTP_CONN_FLAG_TOO_LARGE;
return -1;
}
/*
* The announced length is bounded here exactly as it is in the body
* callback: nothing of the body has arrived yet, so this is still only
* the peer's word for how much room to make.
*/
if (!rspamd_http_message_set_body(msg, NULL,
rspamd_http_body_prealloc(conn, parser,
0))) {
return -1;
}
}
if (parser->flags & F_SPAMC) {
msg->flags |= RSPAMD_HTTP_FLAG_SPAMC;
}
msg->method = parser->method;
msg->code = parser->status_code;
return 0;
}
static void
rspamd_http_switch_zc(struct _rspamd_http_privbuf *pbuf,
struct rspamd_http_message *msg,
http_parser *parser)
{
gsize window;
if (msg->body_buf.begin == NULL ||
msg->body_buf.allocated_len <= msg->body_buf.len) {
/*
* There is no mapping to write into (e.g. growing it has just failed),
* so stay with the private buffer instead of pointing at nothing
*/
pbuf->zc_buf = NULL;
pbuf->zc_remain = 0;
return;
}
window = msg->body_buf.allocated_len - msg->body_buf.len;
/*
* A zero-copy read lands inside the message's own body storage, which means
* the parser is then handed memory the message owns. That is only safe
* while every byte in the window is still body: a callback that completes
* the message may replace its body, freeing exactly this storage, and the
* parser would walk into the bytes that followed the message inside it.
*
* So the window never reaches past what the peer has announced is still to
* come -- the rest of the current chunk under chunked framing, the rest of
* Content-Length otherwise. The parser then has nothing left to look at by
* the time a message completes, so it does not matter what the callback
* does with the storage. With nothing announced there is nothing safe to
* read into here, and reads go back to the private buffer, which the event
* handler holds across the parse. ULLONG_MAX means the body runs to EOF, so
* nothing can follow it and the whole window is body.
*
* Holding the message instead would not do: it is not reliably refcounted,
* rspamd_proxy frees one outright from its finish handler.
*/
if (parser->content_length != ULLONG_MAX) {
if (parser->content_length == 0) {
pbuf->zc_buf = NULL;
pbuf->zc_remain = 0;
return;
}
if (parser->content_length < window) {
window = parser->content_length;
}
}
pbuf->zc_buf = msg->body_buf.begin + msg->body_buf.len;
pbuf->zc_remain = window;
}
static int
rspamd_http_on_body(http_parser *parser, const char *at, size_t length)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
struct rspamd_http_message *msg;
struct _rspamd_http_privbuf *pbuf;
const char *p;
priv = conn->priv;
msg = priv->msg;
pbuf = priv->buf;
p = at;
if (msg == NULL) {
/* Arrived after the message was released, see rspamd_http_on_url */
conn->priv->flags |= RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
return 0;
}
if (conn->finished) {
return 0;
}
if (!rspamd_http_body_within_limit(conn, msg, parser, length)) {
/* Body length overflow */
priv->flags |= RSPAMD_HTTP_CONN_FLAG_TOO_LARGE;
return -1;
}
if (!(msg->flags & RSPAMD_HTTP_FLAG_HAS_BODY)) {
if (!rspamd_http_message_set_body(msg, NULL,
rspamd_http_body_prealloc(conn, parser,
length))) {
return -1;
}
}
if (!pbuf->zc_buf) {
if (!rspamd_http_message_append_body(msg, at, length)) {
return -1;
}
/* We might have some leftover in our private buffer */
if (pbuf->data->len == length) {
/* Switch to zero-copy mode */
rspamd_http_switch_zc(pbuf, msg, parser);
}
}
else {
if (msg->body_buf.begin == NULL ||
msg->body_buf.allocated_len < msg->body_buf.len ||
msg->body_buf.allocated_len - msg->body_buf.len < length) {
/*
* The parser cannot have read more than the mapping we handed to
* it, so this is not expected to happen; bail out rather than write
* past the end of the body storage
*/
return -1;
}
if (msg->body_buf.begin + msg->body_buf.len != at) {
/* Likely chunked encoding */
memmove((char *) msg->body_buf.begin + msg->body_buf.len, at, length);
p = msg->body_buf.begin + msg->body_buf.len;
}
/* Adjust zero-copy buf */
msg->body_buf.len += length;
if (!(msg->flags & RSPAMD_HTTP_FLAG_SHMEM)) {
msg->body_buf.c.normal->len += length;
}
/*
* Re-armed through the same bound as the initial switch, so that the
* window cannot creep past the end of the body as the body grows
*/
rspamd_http_switch_zc(pbuf, msg, parser);
}
if ((conn->opts & RSPAMD_HTTP_BODY_PARTIAL) && !IS_CONN_ENCRYPTED(priv)) {
/* Incremental update is impossible for encrypted requests so far */
return (conn->body_handler(conn, msg, p, length));
}
return 0;
}
static int
rspamd_http_on_body_decrypted(http_parser *parser, const char *at, size_t length)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
priv = conn->priv;
if (priv->header != NULL) {
rspamd_http_finish_header(conn, priv);
priv->header = NULL;
}
if (conn->finished) {
return 0;
}
if (priv->msg->body_buf.len == 0) {
priv->msg->body_buf.begin = at;
priv->msg->method = parser->method;
priv->msg->code = parser->status_code;
}
else if (priv->msg->body_buf.begin + priv->msg->body_buf.len != at) {
/*
* Chunked encoding inside the encrypted message: the fragments are
* separated by the chunk framing, so the body is not contiguous as it
* lies. Only `begin` and `len` are reported to the caller, hence the
* fragments are packed together here, exactly as the plaintext path
* does. The plaintext buffer is ours and the destination is always
* behind the fragment being moved.
*/
memmove((char *) priv->msg->body_buf.begin + priv->msg->body_buf.len,
at, length);
}
priv->msg->body_buf.len += length;
return 0;
}
/*
* The inner message needs an explicit completion callback: without one, an
* inner body that stops in the middle of its framing consumes every byte of
* the plaintext without the parser ever reporting an error, and would pass
* for a complete message.
*
* The parser is stopped here as well, so that the caller can tell where the
* inner message ended. One encrypted envelope carries exactly one message;
* without the stop, a second message in the same plaintext would keep parsing
* into the very same `priv->msg`, and an incomplete one would consume the rest
* of the plaintext while the completion of the first still vouched for it. The
* parser is a local one, used for this plaintext only, so stopping it affects
* nothing else.
*/
static int
rspamd_http_on_message_complete_decrypted(http_parser *parser)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv = conn->priv;
if (priv->msg == NULL) {
/* Arrived after the message was released, see rspamd_http_on_url */
conn->priv->flags |= RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
return 0;
}
if (priv->header != NULL) {
rspamd_http_finish_header(conn, priv);
priv->header = NULL;
}
priv->flags |= RSPAMD_HTTP_CONN_FLAG_INNER_COMPLETE;
http_parser_pause(parser, 1);
return 0;
}
static int
rspamd_http_on_headers_complete_decrypted(http_parser *parser)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
struct rspamd_http_message *msg;
int ret;
priv = conn->priv;
msg = priv->msg;
if (msg == NULL) {
/* Arrived after the message was released, see rspamd_http_on_url */
conn->priv->flags |= RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
return 0;
}
if (priv->header != NULL) {
rspamd_http_finish_header(conn, priv);
priv->header = NULL;
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
}
if (parser->flags & F_SPAMC) {
priv->msg->flags |= RSPAMD_HTTP_FLAG_SPAMC;
}
if (msg->method == HTTP_HEAD) {
/* We don't care about the rest */
rspamd_ev_watcher_stop(priv->ctx->event_loop, &priv->ev);
msg->code = parser->status_code;
rspamd_http_connection_ref(conn);
priv->completed++;
ret = conn->finish_handler(conn, msg);
if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
rspamd_http_context_push_keepalive(conn->priv->ctx, conn,
msg, conn->priv->ctx->event_loop);
/* push_keepalive() may decline pooling and leave conn->finished == TRUE */
if (!conn->finished) {
rspamd_http_connection_reset(conn);
}
}
else {
conn->finished = TRUE;
}
rspamd_http_connection_unref(conn);
return ret;
}
priv->msg->method = parser->method;
priv->msg->code = parser->status_code;
return 0;
}
static int
rspamd_http_decrypt_message(struct rspamd_http_connection *conn,
struct rspamd_http_connection_private *priv,
struct rspamd_cryptobox_pubkey *peer_key)
{
unsigned char *nonce, *m;
const unsigned char *nm;
gsize dec_len;
struct rspamd_http_message *msg = priv->msg;
struct rspamd_http_header *hdr, *hcur, *hcurtmp;
struct http_parser decrypted_parser;
struct http_parser_settings decrypted_cb;
size_t nparsed;
nonce = msg->body_buf.str;
m = msg->body_buf.str + crypto_box_noncebytes() +
crypto_box_macbytes();
dec_len = msg->body_buf.len - crypto_box_noncebytes() - crypto_box_macbytes();
if ((nm = rspamd_pubkey_get_nm(peer_key, priv->local_key)) == NULL) {
nm = rspamd_pubkey_calculate_nm(peer_key, priv->local_key);
}
if (!rspamd_cryptobox_decrypt_nm_inplace(m, dec_len, nonce,
nm, m - crypto_box_macbytes())) {
msg_err("cannot verify encrypted message, first bytes of the input: %*xs",
(int) MIN(msg->body_buf.len, 64), msg->body_buf.begin);
return -1;
}
/* Cleanup message */
kh_foreach_value (msg->headers, hdr, {
DL_FOREACH_SAFE (hdr, hcur, hcurtmp) {
rspamd_fstring_free (hcur->combined);
g_free (hcur);
}
});
kh_destroy(rspamd_http_headers_hash, msg->headers);
msg->headers = kh_init(rspamd_http_headers_hash);
if (msg->url != NULL) {
msg->url = rspamd_fstring_assign(msg->url, "", 0);
}
msg->body_buf.len = 0;
memset(&decrypted_parser, 0, sizeof(decrypted_parser));
http_parser_init(&decrypted_parser,
conn->type == RSPAMD_HTTP_SERVER ? HTTP_REQUEST : HTTP_RESPONSE);
memset(&decrypted_cb, 0, sizeof(decrypted_cb));
decrypted_cb.on_url = rspamd_http_on_url;
decrypted_cb.on_status = rspamd_http_on_status;
decrypted_cb.on_header_field = rspamd_http_on_header_field;
decrypted_cb.on_header_value = rspamd_http_on_header_value;
decrypted_cb.on_headers_complete = rspamd_http_on_headers_complete_decrypted;
decrypted_cb.on_body = rspamd_http_on_body_decrypted;
decrypted_cb.on_message_complete = rspamd_http_on_message_complete_decrypted;
decrypted_parser.data = conn;
decrypted_parser.content_length = dec_len;
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_INNER_COMPLETE;
nparsed = http_parser_execute(&decrypted_parser, &decrypted_cb, m, dec_len);
if (decrypted_parser.http_errno == HPE_PAUSED) {
/* Stopped by us at the end of the inner message, not an error */
http_parser_pause(&decrypted_parser, 0);
}
if (decrypted_parser.http_errno != HPE_OK) {
msg_err("HTTP parser error: %s when parsing encrypted request",
http_errno_description(decrypted_parser.http_errno));
return -1;
}
if (!(priv->flags & RSPAMD_HTTP_CONN_FLAG_INNER_COMPLETE)) {
msg_err("incomplete encrypted request: the inner message ends in the "
"middle of its framing");
return -1;
}
/*
* The parser stops on the last byte of the inner message, so this is also
* what says that the message ended exactly where the plaintext does, with
* no second message behind it
*/
if (nparsed != (size_t) dec_len) {
msg_err("encrypted request has %z trailing bytes after the inner message",
(size_t) (dec_len - nparsed));
return -1;
}
return 0;
}
static int
rspamd_http_on_message_complete(http_parser *parser)
{
struct rspamd_http_connection *conn =
(struct rspamd_http_connection *) parser->data;
struct rspamd_http_connection_private *priv;
int ret = 0;
if (conn->finished) {
return 0;
}
priv = conn->priv;
if (priv->msg == NULL) {
/* Arrived after the message was released, see rspamd_http_on_url */
conn->priv->flags |= RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
return 0;
}
/*
* Trailers use the ordinary header callbacks, but the end of the trailer
* section arrives here instead of at `on_headers_complete`: the last
* trailer has to be finished explicitly or it is both lost and leaked.
*/
if (priv->header != NULL) {
rspamd_http_finish_header(conn, priv);
priv->header = NULL;
}
if (priv->flags & RSPAMD_HTTP_CONN_FLAG_INTERIM) {
/*
* The end of an interim reply: go on reading the final one. The
* parser is started anew: it takes a reply with no keep-alive in it
* for the last message of its connection, and an interim one says
* nothing of that
*/
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_INTERIM;
http_parser_init(parser, HTTP_RESPONSE);
return 0;
}
if ((conn->opts & RSPAMD_HTTP_REQUIRE_ENCRYPTION) && !IS_CONN_ENCRYPTED(priv)) {
priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTION_NEEDED;
msg_err("unencrypted connection when encryption has been requested");
return -1;
}
if ((conn->opts & RSPAMD_HTTP_BODY_PARTIAL) == 0 && IS_CONN_ENCRYPTED(priv)) {
if (priv->local_key == NULL || priv->msg->peer_key == NULL ||
priv->msg->body_buf.len < crypto_box_noncebytes() +
crypto_box_macbytes()) {
msg_err("cannot decrypt message");
return -1;
}
/* We have keys, so we can decrypt message */
ret = rspamd_http_decrypt_message(conn, priv, priv->msg->peer_key);
if (ret != 0) {
return ret;
}
if (conn->body_handler != NULL) {
rspamd_http_connection_ref(conn);
ret = conn->body_handler(conn,
priv->msg,
priv->msg->body_buf.begin,
priv->msg->body_buf.len);
rspamd_http_connection_unref(conn);
}
}
else if ((conn->opts & RSPAMD_HTTP_BODY_PARTIAL) == 0 && conn->body_handler) {
g_assert(conn->body_handler != NULL);
rspamd_http_connection_ref(conn);
ret = conn->body_handler(conn,
priv->msg,
priv->msg->body_buf.begin,
priv->msg->body_buf.len);
rspamd_http_connection_unref(conn);
}
if (ret == 0) {
rspamd_ev_watcher_stop(priv->ctx->event_loop, &priv->ev);
rspamd_http_connection_ref(conn);
priv->completed++;
ret = conn->finish_handler(conn, priv->msg);
if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
rspamd_http_context_push_keepalive(conn->priv->ctx, conn,
priv->msg, conn->priv->ctx->event_loop);
/* push_keepalive() may decline pooling and leave conn->finished == TRUE */
if (!conn->finished) {
rspamd_http_connection_reset(conn);
}
}
else {
conn->finished = TRUE;
}
rspamd_http_connection_unref(conn);
}
return ret;
}
static void
rspamd_http_simple_client_helper(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv;
gpointer ssl;
int request_method;
GString *prev_host = NULL;
priv = conn->priv;
ssl = priv->ssl;
priv->ssl = NULL;
/* Preserve data */
if (priv->msg) {
request_method = priv->msg->method;
/* Preserve host for keepalive */
prev_host = priv->msg->host;
priv->msg->host = NULL;
}
rspamd_http_connection_reset(conn);
priv->ssl = ssl;
/* Plan read message */
if (conn->opts & RSPAMD_HTTP_CLIENT_SHARED) {
rspamd_http_connection_read_message_shared(conn, conn->ud,
(priv->read_timeout > 0 ? priv->read_timeout : conn->priv->timeout));
}
else {
rspamd_http_connection_read_message(conn, conn->ud,
(priv->read_timeout > 0 ? priv->read_timeout : conn->priv->timeout));
}
if (priv->msg) {
priv->msg->method = request_method;
priv->msg->host = prev_host;
}
else {
if (prev_host) {
g_string_free(prev_host, TRUE);
}
}
}
static inline void
rspamd_http_connection_stop_watcher(struct rspamd_http_connection_private *priv);
static void
rspamd_http_write_helper(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv;
struct iovec *start;
unsigned int niov, i;
int flags = 0;
gsize remain;
gssize r;
GError *err;
struct iovec *cur_iov;
struct msghdr msg;
priv = conn->priv;
if (priv->wr_pos == priv->wr_total) {
goto call_finish_handler;
}
start = &priv->out[0];
niov = priv->outlen;
remain = priv->wr_pos;
/* We know that niov is small enough for that */
if (priv->ssl) {
/* Might be recursive! */
cur_iov = g_malloc(niov * sizeof(struct iovec));
}
else {
cur_iov = alloca(niov * sizeof(struct iovec));
}
memcpy(cur_iov, priv->out, niov * sizeof(struct iovec));
for (i = 0; i < priv->outlen && remain > 0; i++) {
/* Find out the first iov required */
start = &cur_iov[i];
if (start->iov_len <= remain) {
remain -= start->iov_len;
start = &cur_iov[i + 1];
niov--;
}
else {
start->iov_base = (void *) ((char *) start->iov_base + remain);
start->iov_len -= remain;
remain = 0;
}
}
memset(&msg, 0, sizeof(msg));
msg.msg_iov = start;
msg.msg_iovlen = MIN(IOV_MAX, niov);
g_assert(niov > 0);
#ifdef MSG_NOSIGNAL
flags = MSG_NOSIGNAL;
#endif
if (priv->ssl) {
r = rspamd_ssl_writev(priv->ssl, msg.msg_iov, msg.msg_iovlen);
g_free(cur_iov);
}
else {
r = sendmsg(conn->fd, &msg, flags);
}
if (r == -1) {
int saved_errno = errno;
if (!priv->ssl) {
/* Check if server sent an early response (e.g., 413) */
if (saved_errno == EPIPE || saved_errno == ECONNRESET ||
saved_errno == ENOTCONN) {
struct _rspamd_http_privbuf *pbuf = priv->buf;
const char *d;
gssize read_res;
REF_RETAIN(pbuf);
read_res = rspamd_http_try_read(conn->fd, conn, priv, pbuf, &d);
if (read_res > 0) {
msg_debug("got early server response (%z bytes) during write, processing",
read_res);
if (http_parser_execute(&priv->parser, &priv->parser_cb,
d, read_res) != (size_t) read_res ||
priv->parser.http_errno != 0) {
err = g_error_new(HTTP_ERROR, 400,
"HTTP parser error on early response: %s",
http_errno_description(priv->parser.http_errno));
rspamd_http_connection_stop_watcher(priv);
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
g_error_free(err);
}
REF_RELEASE(pbuf);
return;
}
REF_RELEASE(pbuf);
}
err = g_error_new(HTTP_ERROR, 500, "IO write error: %s", strerror(saved_errno));
rspamd_http_connection_stop_watcher(priv);
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
g_error_free(err);
}
return;
}
else {
priv->wr_pos += r;
}
if (priv->wr_pos >= priv->wr_total) {
goto call_finish_handler;
}
else {
/* Want to write more */
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_RESETED;
if (priv->ssl && r > 0) {
/* We can write more data... */
rspamd_http_write_helper(conn);
return;
}
}
return;
call_finish_handler:
rspamd_ev_watcher_stop(priv->ctx->event_loop, &priv->ev);
if ((conn->opts & RSPAMD_HTTP_CLIENT_SIMPLE) == 0) {
rspamd_http_connection_ref(conn);
conn->finished = TRUE;
conn->finish_handler(conn, priv->msg);
rspamd_http_connection_unref(conn);
}
else {
if (priv->flags & RSPAMD_HTTP_CONN_FLAG_EARLY_RESPONSE) {
/* Early response already being processed */
rspamd_ev_watcher_reschedule(priv->ctx->event_loop, &priv->ev, EV_READ);
}
else {
/* Plan read message */
priv->first_write_done = true;
rspamd_http_simple_client_helper(conn);
}
}
}
static gssize
rspamd_http_try_read(int fd,
struct rspamd_http_connection *conn,
struct rspamd_http_connection_private *priv,
struct _rspamd_http_privbuf *pbuf,
const char **buf_ptr)
{
gssize r;
char *data;
gsize len;
struct rspamd_http_message *msg;
msg = priv->msg;
if (pbuf->zc_buf == NULL) {
data = priv->buf->data->str;
len = priv->buf->data->allocated;
}
else {
data = (char *) pbuf->zc_buf;
len = pbuf->zc_remain;
if (len == 0) {
if (rspamd_http_message_grow_body(priv->msg,
priv->buf->data->allocated)) {
rspamd_http_switch_zc(pbuf, msg, &priv->parser);
data = (char *) pbuf->zc_buf;
len = pbuf->zc_remain;
}
if (pbuf->zc_buf == NULL || len == 0) {
/*
* There is no room left in the body storage and no way to get
* any (growing it has just failed). Read into the private
* buffer instead: appending it to the body then fails in the
* parser callback and the error is reported through the usual
* path, whereas here we would have written past the mapping.
*/
pbuf->zc_buf = NULL;
pbuf->zc_remain = 0;
data = priv->buf->data->str;
len = priv->buf->data->allocated;
}
}
}
if (priv->ssl) {
r = rspamd_ssl_read(priv->ssl, data, len);
}
else {
r = read(fd, data, len);
}
if (r <= 0) {
return r;
}
else {
if (pbuf->zc_buf == NULL) {
priv->buf->data->len = r;
}
else {
pbuf->zc_remain -= r;
pbuf->zc_buf += r;
}
}
if (buf_ptr) {
*buf_ptr = data;
}
return r;
}
static void
rspamd_http_ssl_err_handler(gpointer ud, GError *err)
{
struct rspamd_http_connection *conn = (struct rspamd_http_connection *) ud;
struct rspamd_http_connection_private *priv = conn->priv;
/* Error is terminal, stop watcher before delegating to user handler */
rspamd_http_connection_stop_watcher(priv);
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
}
static inline void
rspamd_http_connection_stop_watcher(struct rspamd_http_connection_private *priv)
{
rspamd_ev_watcher_stop(priv->ctx->event_loop, &priv->ev);
}
static void
rspamd_http_event_handler(int fd, short what, gpointer ud)
{
struct rspamd_http_connection *conn = (struct rspamd_http_connection *) ud;
struct rspamd_http_connection_private *priv;
struct _rspamd_http_privbuf *pbuf;
const char *d;
gssize r;
GError *err;
priv = conn->priv;
pbuf = priv->buf;
REF_RETAIN(pbuf);
rspamd_http_connection_ref(conn);
/* To tell if a message is completed by what is read here */
const unsigned int completed = priv->completed;
if (what & EV_READ) {
/* Check for early response while still sending request (client only) */
if (conn->type == RSPAMD_HTTP_CLIENT &&
priv->wr_pos < priv->wr_total && priv->wr_total > 0) {
/* Check for connection errors (io_uring reports POLLERR as EV_READ) */
if (!priv->first_write_done) {
int sock_err = 0;
socklen_t sock_err_len = sizeof(sock_err);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &sock_err, &sock_err_len) == 0 &&
sock_err != 0) {
err = g_error_new(HTTP_ERROR, 500,
"Connection failed: %s", strerror(sock_err));
rspamd_http_connection_stop_watcher(priv);
conn->error_handler(conn, err);
g_error_free(err);
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
}
msg_debug("received early server response while still writing request "
"(sent %uz of %uz bytes)",
priv->wr_pos, priv->wr_total);
priv->wr_pos = priv->wr_total;
priv->flags |= RSPAMD_HTTP_CONN_FLAG_EARLY_RESPONSE;
}
read_again:
r = rspamd_http_try_read(fd, conn, priv, pbuf, &d);
if (r > 0) {
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_UNSOLICITED;
if (http_parser_execute(&priv->parser, &priv->parser_cb,
d, r) != (size_t) r ||
priv->parser.http_errno != 0) {
if (priv->completed != completed) {
/*
* The message was read and given to its owner, who is
* done with this exchange: what follows the message is
* not an error of that request. Such a connection is
* not one to reuse
*/
msg_info("got garbage after the end of a message, close the connection");
rspamd_http_context_drop_keepalive(priv->ctx, conn);
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
if (priv->flags & RSPAMD_HTTP_CONN_FLAG_TOO_LARGE) {
err = g_error_new(HTTP_ERROR, 413,
"Request entity too large: %zu",
(size_t) priv->parser.content_length);
}
else if (priv->flags & RSPAMD_HTTP_CONN_FLAG_ENCRYPTION_NEEDED) {
err = g_error_new(HTTP_ERROR, 400,
"Encryption required");
}
else if (priv->parser.http_errno == HPE_CLOSED_CONNECTION) {
msg_err("got garbage after end of the message, ignore it");
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
else {
if (priv->parser.http_errno > HPE_CB_status) {
err = g_error_new(HTTP_ERROR, 400,
"HTTP parser error: %s",
http_errno_description(priv->parser.http_errno));
}
else {
err = g_error_new(HTTP_ERROR, 500,
"HTTP parser internal error: %s",
http_errno_description(priv->parser.http_errno));
}
}
if (!conn->finished) {
rspamd_http_connection_stop_watcher(priv);
conn->error_handler(conn, err);
}
else {
msg_err("got error after HTTP request is finished: %e", err);
}
g_error_free(err);
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
/*
* SSL_read returns at most the room left in our buffer and keeps
* the rest of the TLS record decrypted inside OpenSSL: the socket
* will not become readable for it again, so drain it now. Parser
* callbacks can finish or reset the connection and replace its
* read buffer, stop then.
*/
if (priv->completed != completed &&
(priv->flags & RSPAMD_HTTP_CONN_FLAG_UNSOLICITED)) {
/* Bytes of something else after the message, in the same read */
msg_info("got data after the end of a message, close the connection");
rspamd_http_context_drop_keepalive(priv->ctx, conn);
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
if (priv->ssl && !conn->finished && !IS_CONN_RESETED(priv) &&
priv->buf == pbuf && priv->msg != NULL &&
rspamd_ssl_pending(priv->ssl) > 0) {
goto read_again;
}
}
else if (r == 0) {
/* We can still call http parser */
http_parser_execute(&priv->parser, &priv->parser_cb, d, r);
if (priv->completed != completed) {
/*
* A message that ends where the stream ends is complete, and
* its owner has it. The connection is over, whatever its
* headers said about keeping it
*/
rspamd_http_context_drop_keepalive(priv->ctx, conn);
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
if (!conn->finished) {
err = g_error_new(HTTP_ERROR,
400,
"IO read error: unexpected EOF");
rspamd_http_connection_stop_watcher(priv);
conn->error_handler(conn, err);
g_error_free(err);
}
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
else {
if (!priv->ssl) {
if (!conn->finished) {
err = g_error_new(HTTP_ERROR,
500,
"HTTP IO read error: %s",
strerror(errno));
rspamd_http_connection_stop_watcher(priv);
conn->error_handler(conn, err);
g_error_free(err);
}
else {
msg_err("got error after HTTP request is finished: %s",
strerror(errno));
}
}
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
}
else if (what & EV_TIMEOUT) {
if (!priv->ssl) {
/* Let's try to read from the socket first */
r = rspamd_http_try_read(fd, conn, priv, pbuf, &d);
if (r > 0) {
if (http_parser_execute(&priv->parser, &priv->parser_cb,
d, r) != (size_t) r ||
priv->parser.http_errno != 0) {
err = g_error_new(HTTP_ERROR, 400,
"HTTP parser error: %s",
http_errno_description(priv->parser.http_errno));
if (!conn->finished) {
rspamd_http_connection_stop_watcher(priv);
conn->error_handler(conn, err);
}
else {
msg_err("got error after HTTP request is finished: %e", err);
}
g_error_free(err);
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
/*
* The one-shot timer has already expired, so if the drained
* data did not complete the message, the connection would be
* left with no deadline at all: report a timeout instead
*/
if (!conn->finished && !IS_CONN_RESETED(priv)) {
err = g_error_new(HTTP_ERROR, 408,
"IO timeout: incomplete message at deadline");
rspamd_http_connection_stop_watcher(priv);
conn->error_handler(conn, err);
g_error_free(err);
}
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
else {
err = g_error_new(HTTP_ERROR, 408,
"IO timeout");
rspamd_http_connection_stop_watcher(priv);
conn->error_handler(conn, err);
g_error_free(err);
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
}
else {
/* In case of SSL we disable this logic as we already came from SSL handler */
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
return;
}
}
else if (what & EV_WRITE) {
/* The socket is connected (and TLS handshaking has finished). Switch
* to the write deadline once, without extending it on later writes.
* Keep the existing deadline when only a single timeout is used. */
if (priv->ev.timeout != priv->timeout) {
rspamd_ev_watcher_stop(priv->ctx->event_loop, &priv->ev);
rspamd_ev_watcher_start(priv->ctx->event_loop, &priv->ev, priv->timeout);
}
rspamd_http_write_helper(conn);
}
REF_RELEASE(pbuf);
rspamd_http_connection_unref(conn);
}
static void
rspamd_http_parser_reset(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv = conn->priv;
http_parser_init(&priv->parser,
conn->type == RSPAMD_HTTP_SERVER ? HTTP_REQUEST : HTTP_RESPONSE);
priv->parser_cb.on_url = rspamd_http_on_url;
priv->parser_cb.on_status = rspamd_http_on_status;
priv->parser_cb.on_header_field = rspamd_http_on_header_field;
priv->parser_cb.on_header_value = rspamd_http_on_header_value;
priv->parser_cb.on_headers_complete = rspamd_http_on_headers_complete;
priv->parser_cb.on_body = rspamd_http_on_body;
priv->parser_cb.on_message_complete = rspamd_http_on_message_complete;
}
static struct rspamd_http_connection *
rspamd_http_connection_new_common(struct rspamd_http_context *ctx,
int fd,
rspamd_http_body_handler_t body_handler,
rspamd_http_error_handler_t error_handler,
rspamd_http_finish_handler_t finish_handler,
unsigned opts,
enum rspamd_http_connection_type type,
enum rspamd_http_priv_flags priv_flags,
struct upstream *proxy_upstream)
{
struct rspamd_http_connection *conn;
struct rspamd_http_connection_private *priv;
g_assert(error_handler != NULL && finish_handler != NULL);
if (ctx == NULL) {
ctx = rspamd_http_context_default();
}
conn = g_malloc0(sizeof(struct rspamd_http_connection));
conn->opts = opts;
conn->type = type;
conn->body_handler = body_handler;
conn->error_handler = error_handler;
conn->finish_handler = finish_handler;
conn->fd = fd;
conn->ref = 1;
conn->finished = FALSE;
/* Init priv */
priv = g_malloc0(sizeof(struct rspamd_http_connection_private));
conn->priv = priv;
priv->ctx = ctx;
/* Initialize staged timeouts and keepalive telemetry */
priv->connect_timeout = ctx->config.connect_timeout;
priv->ssl_timeout = ctx->config.ssl_timeout;
priv->write_timeout = ctx->config.write_timeout;
priv->read_timeout = ctx->config.read_timeout;
priv->created_ts = (ctx->event_loop ? ev_now(ctx->event_loop) : rspamd_get_ticks(FALSE));
priv->last_used_ts = 0;
priv->reuse_count = 0;
priv->ka_ttl_override = 0;
priv->ka_idle_override = 0;
priv->ka_max_reuse_override = 0;
priv->first_write_done = false;
priv->flags = priv_flags;
if (type == RSPAMD_HTTP_SERVER) {
priv->cache = ctx->server_kp_cache;
}
else {
priv->cache = ctx->client_kp_cache;
if (ctx->client_kp) {
priv->local_key = rspamd_keypair_ref(ctx->client_kp);
}
}
rspamd_http_parser_reset(conn);
priv->parser.data = conn;
return conn;
}
struct rspamd_http_connection *
rspamd_http_connection_new_server(struct rspamd_http_context *ctx,
int fd,
rspamd_http_body_handler_t body_handler,
rspamd_http_error_handler_t error_handler,
rspamd_http_finish_handler_t finish_handler,
unsigned opts)
{
return rspamd_http_connection_new_common(ctx, fd, body_handler,
error_handler, finish_handler, opts, RSPAMD_HTTP_SERVER, 0, NULL);
}
struct rspamd_http_connection *
rspamd_http_connection_new_client_socket(struct rspamd_http_context *ctx,
rspamd_http_body_handler_t body_handler,
rspamd_http_error_handler_t error_handler,
rspamd_http_finish_handler_t finish_handler,
unsigned opts,
int fd)
{
return rspamd_http_connection_new_common(ctx, fd, body_handler,
error_handler, finish_handler, opts, RSPAMD_HTTP_CLIENT, 0, NULL);
}
struct rspamd_http_connection *
rspamd_http_connection_new_client(struct rspamd_http_context *ctx,
rspamd_http_body_handler_t body_handler,
rspamd_http_error_handler_t error_handler,
rspamd_http_finish_handler_t finish_handler,
unsigned opts,
rspamd_inet_addr_t *addr)
{
int fd;
if (ctx == NULL) {
ctx = rspamd_http_context_default();
}
if (ctx->http_proxies) {
struct upstream *up = rspamd_upstream_get(ctx->http_proxies,
RSPAMD_UPSTREAM_ROUND_ROBIN, NULL, 0);
if (up) {
rspamd_inet_addr_t *proxy_addr = rspamd_upstream_addr_next(up);
fd = rspamd_inet_address_connect(proxy_addr, SOCK_STREAM, TRUE);
if (fd == -1) {
msg_info("cannot connect to http proxy %s: %s",
rspamd_inet_address_to_string_pretty(proxy_addr),
strerror(errno));
rspamd_upstream_fail(up, TRUE, strerror(errno));
return NULL;
}
/* The selected proxy upstream is handed off to new_common but
* never tracked through the request lifecycle here; retire the
* inflight counter at connect-success time so P2C scoring stays
* accurate. Wiring per-request success/failure is left for a
* follow-up. */
rspamd_upstream_release(up);
return rspamd_http_connection_new_common(ctx, fd, body_handler,
error_handler, finish_handler, opts,
RSPAMD_HTTP_CLIENT,
RSPAMD_HTTP_CONN_OWN_SOCKET | RSPAMD_HTTP_CONN_FLAG_PROXY,
up);
}
else {
/*
* Proxies are configured but none usable right now (all dead or
* pending DNS resolution). Surface this so the admin knows
* traffic is going direct instead of silently bypassing the
* configured proxy chain.
*/
msg_info("no http proxy upstream available "
"(all dead or pending DNS); falling back to direct connect");
}
}
/* Unproxied version */
fd = rspamd_inet_address_connect(addr, SOCK_STREAM, TRUE);
if (fd == -1) {
msg_info("cannot connect make http connection to %s: %s",
rspamd_inet_address_to_string_pretty(addr),
strerror(errno));
return NULL;
}
return rspamd_http_connection_new_common(ctx, fd, body_handler,
error_handler, finish_handler, opts,
RSPAMD_HTTP_CLIENT,
RSPAMD_HTTP_CONN_OWN_SOCKET,
NULL);
}
struct rspamd_http_connection *
rspamd_http_connection_new_client_keepalive(struct rspamd_http_context *ctx,
rspamd_http_body_handler_t body_handler,
rspamd_http_error_handler_t error_handler,
rspamd_http_finish_handler_t finish_handler,
unsigned opts,
rspamd_inet_addr_t *addr,
const char *host)
{
struct rspamd_http_connection *conn;
if (ctx == NULL) {
ctx = rspamd_http_context_default();
}
unsigned int ssl_flags = 0;
if (opts & RSPAMD_HTTP_CLIENT_SSL) {
ssl_flags |= RSPAMD_HTTP_KEEPALIVE_SSL;
if (opts & RSPAMD_HTTP_CLIENT_SSL_NOVERIFY) {
ssl_flags |= RSPAMD_HTTP_KEEPALIVE_SSL_NOVERIFY;
}
}
conn = rspamd_http_context_check_keepalive(ctx, addr, host, ssl_flags);
if (conn) {
struct rspamd_http_connection_private *priv = conn->priv;
/*
* What the request before set for itself does not go on to this
* one: its limits, its timeouts, the key of its peer
*/
if (priv->peer_key) {
rspamd_pubkey_unref(priv->peer_key);
priv->peer_key = NULL;
}
priv->connect_timeout = 0;
priv->ssl_timeout = 0;
priv->write_timeout = 0;
priv->read_timeout = 0;
priv->flags &= ~(RSPAMD_HTTP_CONN_FLAG_UNSOLICITED | RSPAMD_HTTP_CONN_FLAG_INTERIM);
conn->max_size = 0;
return conn;
}
conn = rspamd_http_connection_new_client(ctx,
body_handler, error_handler, finish_handler,
opts | RSPAMD_HTTP_CLIENT_SIMPLE | RSPAMD_HTTP_CLIENT_KEEP_ALIVE,
addr);
if (conn) {
rspamd_http_context_prepare_keepalive(ctx, conn, addr, host, ssl_flags);
}
return conn;
}
void rspamd_http_connection_reset(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv;
struct rspamd_http_message *msg;
priv = conn->priv;
msg = priv->msg;
/* Clear request */
if (msg != NULL) {
if (msg->peer_key) {
priv->peer_key = msg->peer_key;
msg->peer_key = NULL;
}
rspamd_http_message_unref(msg);
priv->msg = NULL;
}
conn->finished = FALSE;
/* Clear priv */
rspamd_http_drop_header(priv);
rspamd_ev_watcher_stop(priv->ctx->event_loop, &priv->ev);
if (!(priv->flags & RSPAMD_HTTP_CONN_FLAG_RESETED)) {
rspamd_http_parser_reset(conn);
}
if (priv->buf != NULL) {
REF_RELEASE(priv->buf);
priv->buf = NULL;
}
if (priv->out != NULL) {
g_free(priv->out);
priv->out = NULL;
}
priv->flags |= RSPAMD_HTTP_CONN_FLAG_RESETED;
}
struct rspamd_http_message *
rspamd_http_connection_steal_msg(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv;
struct rspamd_http_message *msg;
priv = conn->priv;
msg = priv->msg;
/* Clear request */
if (msg != NULL) {
if (msg->peer_key) {
priv->peer_key = msg->peer_key;
msg->peer_key = NULL;
}
priv->msg = NULL;
}
return msg;
}
struct rspamd_http_message *
rspamd_http_connection_copy_msg(struct rspamd_http_message *msg, GError **err)
{
struct rspamd_http_message *new_msg;
struct rspamd_http_header *hdr, *nhdr, *nhdrs, *hcur;
const char *old_body;
gsize old_len;
struct stat st;
union _rspamd_storage_u *storage;
new_msg = rspamd_http_new_message(msg->type);
new_msg->flags = msg->flags;
if (msg->body_buf.len > 0) {
if (msg->flags & RSPAMD_HTTP_FLAG_SHMEM) {
gsize body_off = 0;
/* Avoid copying by just mapping a shared segment */
new_msg->flags |= RSPAMD_HTTP_FLAG_SHMEM_IMMUTABLE;
storage = &new_msg->body_buf.c;
storage->shared.name = NULL;
storage->shared.shm_fd = dup(msg->body_buf.c.shared.shm_fd);
new_msg->body_buf.str = MAP_FAILED;
if (storage->shared.shm_fd == -1) {
rspamd_http_message_unref(new_msg);
g_set_error(err, http_error_quark(), errno,
"cannot dup shmem fd: %d: %s",
msg->body_buf.c.shared.shm_fd, strerror(errno));
return NULL;
}
if (fstat(storage->shared.shm_fd, &st) == -1) {
g_set_error(err, http_error_quark(), errno,
"cannot stat shmem fd: %d: %s",
storage->shared.shm_fd, strerror(errno));
rspamd_http_message_unref(new_msg);
return NULL;
}
if (RSPAMD_HTTP_BODY_IS_MAPPED(msg) &&
msg->body_buf.begin >= msg->body_buf.str) {
body_off = msg->body_buf.begin - msg->body_buf.str;
}
if (st.st_size <= 0 ||
(gsize) st.st_size < body_off ||
msg->body_buf.len > (gsize) st.st_size - body_off) {
g_set_error(err, http_error_quark(), EINVAL,
"shmem fd %d does not fit the body: %zu bytes at "
"offset %zu of %lld",
storage->shared.shm_fd, msg->body_buf.len,
body_off, (long long) st.st_size);
rspamd_http_message_unref(new_msg);
return NULL;
}
/* We don't own segment, so do not try to touch it */
if (msg->body_buf.c.shared.name) {
storage->shared.name = msg->body_buf.c.shared.name;
REF_RETAIN(storage->shared.name);
}
/*
* The segment belongs to the original message and stays mutable:
* it can be both resized and rewritten whilst this copy keeps it
* mapped. `allocated_len` therefore records the length passed to
* mmap below (the only length that may ever be unmapped) and
* consumers of this body must snapshot the bytes they need rather
* than parsing them in place.
*/
new_msg->body_buf.str = mmap(NULL, st.st_size,
PROT_READ, MAP_SHARED,
storage->shared.shm_fd, 0);
if (new_msg->body_buf.str == MAP_FAILED) {
g_set_error(err, http_error_quark(), errno,
"cannot mmap shmem fd: %d: %s",
storage->shared.shm_fd, strerror(errno));
rspamd_http_message_unref(new_msg);
return NULL;
}
new_msg->body_buf.begin = new_msg->body_buf.str + body_off;
new_msg->body_buf.len = msg->body_buf.len;
new_msg->body_buf.allocated_len = st.st_size;
}
else {
old_body = rspamd_http_message_get_body(msg, &old_len);
if (!rspamd_http_message_set_body(new_msg, old_body, old_len)) {
g_set_error(err, http_error_quark(), errno,
"cannot set body for message, length: %zd",
old_len);
rspamd_http_message_unref(new_msg);
return NULL;
}
}
}
if (msg->url) {
if (new_msg->url) {
new_msg->url = rspamd_fstring_append(new_msg->url, msg->url->str,
msg->url->len);
}
else {
new_msg->url = rspamd_fstring_new_init(msg->url->str,
msg->url->len);
}
}
if (msg->host) {
new_msg->host = g_string_new_len(msg->host->str, msg->host->len);
}
new_msg->method = msg->method;
new_msg->port = msg->port;
new_msg->date = msg->date;
new_msg->last_modified = msg->last_modified;
new_msg->header_cnt = msg->header_cnt;
kh_foreach_value(msg->headers, hdr, {
nhdrs = NULL;
DL_FOREACH(hdr, hcur)
{
nhdr = g_malloc(sizeof(struct rspamd_http_header));
nhdr->combined = rspamd_fstring_new_init(hcur->combined->str,
hcur->combined->len);
nhdr->name.begin = nhdr->combined->str +
(hcur->name.begin - hcur->combined->str);
nhdr->name.len = hcur->name.len;
nhdr->value.begin = nhdr->combined->str +
(hcur->value.begin - hcur->combined->str);
nhdr->value.len = hcur->value.len;
nhdr->order = hcur->order;
DL_APPEND(nhdrs, nhdr);
}
int r;
khiter_t k = kh_put(rspamd_http_headers_hash, new_msg->headers,
&nhdrs->name, &r);
if (r != 0) {
kh_value(new_msg->headers, k) = nhdrs;
}
else {
DL_CONCAT(kh_value(new_msg->headers, k), nhdrs);
}
});
return new_msg;
}
void rspamd_http_connection_free(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv;
priv = conn->priv;
if (priv != NULL) {
rspamd_http_connection_reset(conn);
if (priv->ssl) {
rspamd_ssl_connection_free(priv->ssl);
priv->ssl = NULL;
}
if (priv->local_key) {
rspamd_keypair_unref(priv->local_key);
}
if (priv->peer_key) {
rspamd_pubkey_unref(priv->peer_key);
}
if (priv->flags & RSPAMD_HTTP_CONN_OWN_SOCKET) {
/* Fd is owned by a connection */
close(conn->fd);
}
if (conn->keepalive_addr) {
rspamd_inet_address_free(conn->keepalive_addr);
conn->keepalive_addr = NULL;
}
g_free(priv);
}
g_free(conn);
}
static void
rspamd_http_connection_read_message_common(struct rspamd_http_connection *conn,
gpointer ud, ev_tstamp timeout,
int flags)
{
struct rspamd_http_connection_private *priv = conn->priv;
struct rspamd_http_message *req;
conn->ud = ud;
req = rspamd_http_new_message(
conn->type == RSPAMD_HTTP_SERVER ? HTTP_REQUEST : HTTP_RESPONSE);
priv->msg = req;
req->flags = flags;
if (flags & RSPAMD_HTTP_FLAG_SHMEM) {
req->body_buf.c.shared.shm_fd = -1;
}
if (priv->peer_key) {
priv->msg->peer_key = priv->peer_key;
priv->peer_key = NULL;
priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
}
/* Use read-stage timeout override if set; else fallback */
priv->timeout = (priv->read_timeout > 0 ? priv->read_timeout : timeout);
rspamd_http_drop_header(priv);
priv->buf = g_malloc0(sizeof(*priv->buf));
REF_INIT_RETAIN(priv->buf, rspamd_http_privbuf_dtor);
priv->buf->data = rspamd_fstring_sized_new(8192);
priv->flags |= RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
if (!priv->ssl) {
rspamd_ev_watcher_init(&priv->ev, conn->fd, EV_READ,
rspamd_http_event_handler, conn);
rspamd_ev_watcher_start(priv->ctx->event_loop, &priv->ev, priv->timeout);
}
else {
rspamd_ssl_connection_restore_handlers(priv->ssl,
rspamd_http_event_handler,
rspamd_http_ssl_err_handler,
conn,
EV_READ, priv->timeout);
}
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_RESETED;
}
void rspamd_http_connection_read_message(struct rspamd_http_connection *conn,
gpointer ud, ev_tstamp timeout)
{
rspamd_http_connection_read_message_common(conn, ud, timeout, 0);
}
void rspamd_http_connection_read_message_shared(struct rspamd_http_connection *conn,
gpointer ud, ev_tstamp timeout)
{
rspamd_http_connection_read_message_common(conn, ud, timeout,
RSPAMD_HTTP_FLAG_SHMEM);
}
/*
* Comparator for sorting header nodes by their insertion order. Used when
* RSPAMD_HTTP_FLAG_ORDERED_HEADERS is set so headers leave on the wire in the
* exact order the caller added them, instead of hash bucket order. Each header
* gets a unique `order` value, so qsort's instability never bites here.
*/
static int
rspamd_http_header_cmp_order(const void *a, const void *b)
{
const struct rspamd_http_header *ha = *(struct rspamd_http_header *const *) a;
const struct rspamd_http_header *hb = *(struct rspamd_http_header *const *) b;
if (ha->order < hb->order) {
return -1;
}
else if (ha->order > hb->order) {
return 1;
}
return 0;
}
static void
rspamd_http_connection_encrypt_message(
struct rspamd_http_connection *conn,
struct rspamd_http_message *msg,
struct rspamd_http_connection_private *priv,
unsigned char *pbody,
unsigned int bodylen,
unsigned char *pmethod,
unsigned int methodlen,
unsigned int preludelen,
int hdrcount,
unsigned char *np,
unsigned char *mp,
struct rspamd_cryptobox_pubkey *peer_key)
{
struct rspamd_cryptobox_segment *segments;
unsigned char *crlfp;
const unsigned char *nm;
int i, cnt;
unsigned int outlen;
struct rspamd_http_header *hdr, *hcur;
crlfp = mp + crypto_box_macbytes();
outlen = priv->out[0].iov_len + priv->out[1].iov_len;
/*
* Create segments from the following:
* Method, [URL], CRLF, nheaders, CRLF, body segment(s)
*/
gsize body_seg_count = (msg->body_iov_count > 0) ? msg->body_iov_count : (pbody ? 1 : 0);
segments = g_new(struct rspamd_cryptobox_segment, hdrcount + 4 + body_seg_count);
segments[0].data = pmethod;
segments[0].len = methodlen;
if (conn->type != RSPAMD_HTTP_SERVER) {
segments[1].data = msg->url->str;
segments[1].len = msg->url->len;
/* space + HTTP version + crlf */
segments[2].data = crlfp;
segments[2].len = preludelen - 2;
crlfp += segments[2].len;
i = 3;
}
else {
/* Here we send just CRLF */
segments[1].data = crlfp;
segments[1].len = 2;
crlfp += segments[1].len;
i = 2;
}
if (msg->flags & RSPAMD_HTTP_FLAG_ORDERED_HEADERS) {
struct rspamd_http_header **hdrs_sorted;
unsigned int nhdrs = 0;
hdrs_sorted = g_malloc(sizeof(*hdrs_sorted) * (hdrcount + 1));
kh_foreach_value (msg->headers, hdr, {
DL_FOREACH (hdr, hcur) {
hdrs_sorted[nhdrs++] = hcur;
}
});
qsort(hdrs_sorted, nhdrs, sizeof(*hdrs_sorted),
rspamd_http_header_cmp_order);
for (unsigned int j = 0; j < nhdrs; j++) {
segments[i].data = hdrs_sorted[j]->combined->str;
segments[i++].len = hdrs_sorted[j]->combined->len;
}
g_free(hdrs_sorted);
}
else
{
kh_foreach_value (msg->headers, hdr, {
DL_FOREACH (hdr, hcur) {
segments[i].data = hcur->combined->str;
segments[i++].len = hcur->combined->len;
}
});
}
/* crlfp should point now at the second crlf */
segments[i].data = crlfp;
segments[i++].len = 2;
if (msg->body_iov_count > 0) {
for (gsize j = 0; j < msg->body_iov_count; j++) {
segments[i].data = msg->body_iov[j].iov_base;
segments[i++].len = msg->body_iov[j].iov_len;
}
}
else if (pbody) {
segments[i].data = pbody;
segments[i++].len = bodylen;
}
cnt = i;
if ((nm = rspamd_pubkey_get_nm(peer_key, priv->local_key)) == NULL) {
nm = rspamd_pubkey_calculate_nm(peer_key, priv->local_key);
}
rspamd_cryptobox_encryptv_nm_inplace(segments, cnt, np, nm, mp);
/*
* iov[0] = base HTTP request
* iov[1] = CRLF
* iov[2] = nonce
* iov[3] = mac
* iov[4..i] = encrypted HTTP request/reply
*/
priv->out[2].iov_base = np;
priv->out[2].iov_len = crypto_box_noncebytes();
priv->out[3].iov_base = mp;
priv->out[3].iov_len = crypto_box_macbytes();
outlen += crypto_box_noncebytes() +
crypto_box_macbytes();
for (i = 0; i < cnt; i++) {
priv->out[i + 4].iov_base = segments[i].data;
priv->out[i + 4].iov_len = segments[i].len;
outlen += segments[i].len;
}
priv->wr_total = outlen;
g_free(segments);
}
static void
rspamd_http_detach_shared(struct rspamd_http_message *msg)
{
rspamd_fstring_t *cpy_str;
if (msg->body_buf.begin != NULL && msg->body_buf.len > 0) {
cpy_str = rspamd_fstring_new_init(msg->body_buf.begin,
msg->body_buf.len);
}
else {
cpy_str = rspamd_fstring_new();
}
rspamd_http_message_set_body_from_fstring_steal(msg, cpy_str);
}
int rspamd_http_message_write_header(const char *mime_type, gboolean encrypted,
char *repbuf, gsize replen, gsize bodylen, gsize enclen, const char *host,
struct rspamd_http_connection *conn, struct rspamd_http_message *msg,
rspamd_fstring_t **buf,
struct rspamd_http_connection_private *priv,
struct rspamd_cryptobox_pubkey *peer_key)
{
char datebuf[64];
int meth_len = 0;
const char *server_conn_header, *client_conn_header;
/* Set up connection header strings based on flags and connection type */
if (msg->flags & RSPAMD_HTTP_FLAG_HAS_CONNECTION_HEADER) {
server_conn_header = "";
client_conn_header = "";
}
else {
server_conn_header = "Connection: close\r\n";
if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
client_conn_header = "Connection: keep-alive\r\n";
}
else {
client_conn_header = "Connection: close\r\n";
}
}
if (conn->type == RSPAMD_HTTP_SERVER) {
/* Format reply */
if (msg->method < HTTP_SYMBOLS) {
rspamd_ftok_t status;
rspamd_http_date_format(datebuf, sizeof(datebuf), msg->date);
if (mime_type == NULL) {
mime_type =
encrypted ? "application/octet-stream" : "text/plain";
}
if (msg->status == NULL || msg->status->len == 0) {
if (msg->code == 200) {
RSPAMD_FTOK_ASSIGN(&status, "OK");
}
else if (msg->code == 404) {
RSPAMD_FTOK_ASSIGN(&status, "Not Found");
}
else if (msg->code == 403) {
RSPAMD_FTOK_ASSIGN(&status, "Forbidden");
}
else if (msg->code >= 500 && msg->code < 600) {
RSPAMD_FTOK_ASSIGN(&status, "Internal Server Error");
}
else {
RSPAMD_FTOK_ASSIGN(&status, "Undefined Error");
}
}
else {
status.begin = msg->status->str;
status.len = msg->status->len;
}
if (encrypted) {
/* Internal reply (encrypted) */
if (mime_type) {
meth_len =
rspamd_snprintf(repbuf, replen,
"HTTP/1.1 %d %T\r\n"
"%s"
"Server: %s\r\n"
"Date: %s\r\n"
"Content-Length: %z\r\n"
"Content-Type: %s", /* NO \r\n at the end ! */
msg->code, &status,
server_conn_header,
priv->ctx->config.server_hdr,
datebuf,
bodylen, mime_type);
}
else {
meth_len =
rspamd_snprintf(repbuf, replen,
"HTTP/1.1 %d %T\r\n"
"%s"
"Server: %s\r\n"
"Date: %s\r\n"
"Content-Length: %z", /* NO \r\n at the end ! */
msg->code, &status,
server_conn_header,
priv->ctx->config.server_hdr,
datebuf,
bodylen);
}
enclen += meth_len;
/* External reply */
rspamd_printf_fstring(buf,
"HTTP/1.1 200 OK\r\n"
"%s"
"Server: %s\r\n"
"Date: %s\r\n"
"Content-Length: %z\r\n"
"Content-Type: application/octet-stream\r\n",
server_conn_header,
priv->ctx->config.server_hdr,
datebuf, enclen);
}
else {
if (mime_type) {
meth_len =
rspamd_printf_fstring(buf,
"HTTP/1.1 %d %T\r\n"
"%s"
"Server: %s\r\n"
"Date: %s\r\n"
"Content-Length: %z\r\n"
"Content-Type: %s\r\n",
msg->code, &status,
server_conn_header,
priv->ctx->config.server_hdr,
datebuf,
bodylen, mime_type);
}
else {
meth_len =
rspamd_printf_fstring(buf,
"HTTP/1.1 %d %T\r\n"
"%s"
"Server: %s\r\n"
"Date: %s\r\n"
"Content-Length: %z\r\n",
msg->code, &status,
server_conn_header,
priv->ctx->config.server_hdr,
datebuf,
bodylen);
}
}
}
else {
/* Legacy spamd reply */
if (msg->flags & RSPAMD_HTTP_FLAG_SPAMC) {
gsize real_bodylen;
goffset eoh_pos;
GString tmp;
/* Unfortunately, spamc protocol is deadly brain damaged */
tmp.str = (char *) msg->body_buf.begin;
tmp.len = msg->body_buf.len;
if (rspamd_string_find_eoh(&tmp, &eoh_pos) != -1 &&
bodylen > eoh_pos) {
real_bodylen = bodylen - eoh_pos;
}
else {
real_bodylen = bodylen;
}
rspamd_printf_fstring(buf, "SPAMD/1.1 0 EX_OK\r\n"
"Content-length: %z\r\n",
real_bodylen);
}
else {
rspamd_printf_fstring(buf, "RSPAMD/1.3 0 EX_OK\r\n");
}
}
}
else {
/* Client request */
/* Format request */
enclen += RSPAMD_FSTRING_LEN(msg->url) +
strlen(http_method_str(msg->method)) + 1;
if (host == NULL && msg->host == NULL) {
/* Fallback to HTTP/1.0 */
if (encrypted) {
rspamd_printf_fstring(buf,
"%s %s HTTP/1.0\r\n"
"Content-Length: %z\r\n"
"Content-Type: application/octet-stream\r\n"
"%s",
"POST",
"/post",
enclen,
client_conn_header);
}
else {
rspamd_printf_fstring(buf,
"%s %V HTTP/1.0\r\n"
"Content-Length: %z\r\n"
"%s",
http_method_str(msg->method),
msg->url,
bodylen,
client_conn_header);
if (bodylen > 0) {
if (mime_type == NULL) {
mime_type = "text/plain";
}
rspamd_printf_fstring(buf,
"Content-Type: %s\r\n",
mime_type);
}
}
}
else {
/* Normal HTTP/1.1 with Host */
if (host == NULL) {
host = msg->host->str;
}
if (encrypted) {
/* TODO: Add proxy support to HTTPCrypt */
if (rspamd_http_message_is_standard_port(msg)) {
rspamd_printf_fstring(buf,
"%s %s HTTP/1.1\r\n"
"%s"
"Host: %s\r\n"
"Content-Length: %z\r\n"
"Content-Type: application/octet-stream\r\n",
"POST",
"/post",
client_conn_header,
host,
enclen);
}
else {
rspamd_printf_fstring(buf,
"%s %s HTTP/1.1\r\n"
"%s"
"Host: %s:%d\r\n"
"Content-Length: %z\r\n"
"Content-Type: application/octet-stream\r\n",
"POST",
"/post",
client_conn_header,
host,
msg->port,
enclen);
}
}
else {
if (conn->priv->flags & RSPAMD_HTTP_CONN_FLAG_PROXY) {
/* Write proxied request */
if ((msg->flags & RSPAMD_HTTP_FLAG_HAS_HOST_HEADER)) {
rspamd_printf_fstring(buf,
"%s %s://%s:%d/%V HTTP/1.1\r\n"
"%s"
"Content-Length: %z\r\n",
http_method_str(msg->method),
(conn->opts & RSPAMD_HTTP_CLIENT_SSL) ? "https" : "http",
host,
msg->port,
msg->url,
client_conn_header,
bodylen);
}
else {
if (rspamd_http_message_is_standard_port(msg)) {
rspamd_printf_fstring(buf,
"%s %s://%s:%d/%V HTTP/1.1\r\n"
"%s"
"Host: %s\r\n"
"Content-Length: %z\r\n",
http_method_str(msg->method),
(conn->opts & RSPAMD_HTTP_CLIENT_SSL) ? "https" : "http",
host,
msg->port,
msg->url,
client_conn_header,
host,
bodylen);
}
else {
rspamd_printf_fstring(buf,
"%s %s://%s:%d/%V HTTP/1.1\r\n"
"%s"
"Host: %s:%d\r\n"
"Content-Length: %z\r\n",
http_method_str(msg->method),
(conn->opts & RSPAMD_HTTP_CLIENT_SSL) ? "https" : "http",
host,
msg->port,
msg->url,
client_conn_header,
host,
msg->port,
bodylen);
}
}
}
else {
/* Unproxied version */
if ((msg->flags & RSPAMD_HTTP_FLAG_HAS_HOST_HEADER)) {
rspamd_printf_fstring(buf,
"%s %V HTTP/1.1\r\n"
"%s"
"Content-Length: %z\r\n",
http_method_str(msg->method),
msg->url,
client_conn_header,
bodylen);
}
else {
if (rspamd_http_message_is_standard_port(msg)) {
rspamd_printf_fstring(buf,
"%s %V HTTP/1.1\r\n"
"%s"
"Host: %s\r\n"
"Content-Length: %z\r\n",
http_method_str(msg->method),
msg->url,
client_conn_header,
host,
bodylen);
}
else {
rspamd_printf_fstring(buf,
"%s %V HTTP/1.1\r\n"
"%s"
"Host: %s:%d\r\n"
"Content-Length: %z\r\n",
http_method_str(msg->method),
msg->url,
client_conn_header,
host,
msg->port,
bodylen);
}
}
}
if (bodylen > 0) {
if (mime_type != NULL) {
rspamd_printf_fstring(buf,
"Content-Type: %s\r\n",
mime_type);
}
}
}
}
if (encrypted) {
GString *b32_key, *b32_id;
b32_key = rspamd_keypair_print(priv->local_key,
RSPAMD_KEYPAIR_ENCODING_DEFAULT,
RSPAMD_KEYPAIR_PUBKEY);
b32_id = rspamd_pubkey_print(peer_key,
RSPAMD_KEYPAIR_ENCODING_DEFAULT,
RSPAMD_KEYPAIR_ID_SHORT);
/* XXX: add some fuzz here */
rspamd_printf_fstring(&*buf, "Key: %v=%v\r\n", b32_id, b32_key);
g_string_free(b32_key, TRUE);
g_string_free(b32_id, TRUE);
}
}
return meth_len;
}
static gboolean
rspamd_http_connection_write_message_common(struct rspamd_http_connection *conn,
struct rspamd_http_message *msg,
const char *host,
const char *mime_type,
gpointer ud,
ev_tstamp timeout,
gboolean allow_shared)
{
struct rspamd_http_connection_private *priv = conn->priv;
struct rspamd_http_header *hdr, *hcur;
char repbuf[512], *pbody;
int i, hdrcount, meth_len = 0, preludelen = 0;
gsize bodylen, enclen = 0;
rspamd_fstring_t *buf;
gboolean encrypted = FALSE;
unsigned char nonce[rspamd_cryptobox_MAX_NONCEBYTES], mac[rspamd_cryptobox_MAX_MACBYTES];
unsigned char *np = NULL, *mp = NULL, *meth_pos = NULL;
struct rspamd_cryptobox_pubkey *peer_key = NULL;
GError *err;
conn->ud = ud;
priv->msg = msg;
/* Use write-stage timeout override if set */
priv->timeout = (priv->write_timeout > 0 ? priv->write_timeout : timeout);
rspamd_http_drop_header(priv);
priv->buf = g_malloc0(sizeof(*priv->buf));
REF_INIT_RETAIN(priv->buf, rspamd_http_privbuf_dtor);
priv->buf->data = rspamd_fstring_sized_new(512);
buf = priv->buf->data;
if ((msg->flags & RSPAMD_HTTP_FLAG_WANT_SSL) && !(conn->opts & RSPAMD_HTTP_CLIENT_SSL)) {
err = g_error_new(HTTP_ERROR, 400,
"SSL connection requested but not created properly, internal error");
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
g_error_free(err);
return FALSE;
}
if (priv->peer_key && priv->local_key) {
if (priv->msg->peer_key != NULL) {
/* The message has a key of its own: that is the one to use */
rspamd_pubkey_unref(priv->peer_key);
}
else {
priv->msg->peer_key = priv->peer_key;
}
priv->peer_key = NULL;
priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
}
if (msg->peer_key != NULL) {
if (priv->local_key == NULL) {
/* Automatically generate a temporary keypair */
priv->local_key = rspamd_keypair_new(RSPAMD_KEYPAIR_KEX);
}
encrypted = TRUE;
/*
* The reply to an encrypted request must be encrypted as well. The
* read path sets this for a reply read after the request is sent, but
* a client also parses a reply that comes while it is still writing
*/
priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
if (priv->cache) {
rspamd_keypair_cache_process(priv->cache,
priv->local_key, priv->msg->peer_key);
}
}
if (encrypted && (msg->flags &
(RSPAMD_HTTP_FLAG_SHMEM_IMMUTABLE | RSPAMD_HTTP_FLAG_SHMEM))) {
/* We cannot use immutable body to encrypt message in place */
allow_shared = FALSE;
rspamd_http_detach_shared(msg);
}
/*
* `Shm`, `Shm-Offset` and `Shm-Length` describe our own segment and are
* generated internally, so they are a reserved triplet: any instance that
* came from a peer is dropped here. Otherwise the internally generated
* values would be appended behind the peer supplied ones and a receiver
* reading the first instance of each header would open a segment and an
* offset of somebody else's choice.
*/
rspamd_http_message_remove_header(msg, "Shm");
rspamd_http_message_remove_header(msg, "Shm-Offset");
rspamd_http_message_remove_header(msg, "Shm-Length");
if (allow_shared) {
char tmpbuf[64];
if (!(msg->flags & RSPAMD_HTTP_FLAG_SHMEM) ||
msg->body_buf.c.shared.name == NULL) {
allow_shared = FALSE;
}
else {
gsize shm_offset = 0;
if (RSPAMD_HTTP_BODY_IS_MAPPED(msg) &&
msg->body_buf.begin >= msg->body_buf.str) {
shm_offset = msg->body_buf.begin - msg->body_buf.str;
}
/* Insert exactly one internally generated triplet */
rspamd_http_message_add_header(msg, "Shm",
msg->body_buf.c.shared.name->shm_name);
rspamd_snprintf(tmpbuf, sizeof(tmpbuf), "%uz", shm_offset);
rspamd_http_message_add_header(msg, "Shm-Offset",
tmpbuf);
rspamd_snprintf(tmpbuf, sizeof(tmpbuf), "%uz",
msg->body_buf.len);
rspamd_http_message_add_header(msg, "Shm-Length",
tmpbuf);
}
}
if (priv->ctx->config.user_agent && conn->type == RSPAMD_HTTP_CLIENT) {
rspamd_ftok_t srch;
khiter_t k;
int r;
RSPAMD_FTOK_ASSIGN(&srch, "User-Agent");
k = kh_put(rspamd_http_headers_hash, msg->headers, &srch, &r);
if (r != 0) {
hdr = g_malloc0(sizeof(struct rspamd_http_header));
unsigned int vlen = strlen(priv->ctx->config.user_agent);
hdr->combined = rspamd_fstring_sized_new(srch.len + vlen + 4);
rspamd_printf_fstring(&hdr->combined, "%T: %*s\r\n", &srch, vlen,
priv->ctx->config.user_agent);
hdr->name.begin = hdr->combined->str;
hdr->name.len = srch.len;
hdr->value.begin = hdr->combined->str + srch.len + 2;
hdr->value.len = vlen;
hdr->order = msg->header_cnt++;
hdr->prev = hdr; /* for utlists */
kh_value(msg->headers, k) = hdr;
/* as we searched using static buffer */
kh_key(msg->headers, k) = &hdr->name;
}
}
if (encrypted) {
if (msg->body_iov_count > 0) {
pbody = NULL;
bodylen = msg->body_buf.len;
msg->method = HTTP_POST;
}
else if (msg->body_buf.len == 0) {
pbody = NULL;
bodylen = 0;
msg->method = HTTP_GET;
}
else {
pbody = (char *) msg->body_buf.begin;
bodylen = msg->body_buf.len;
msg->method = HTTP_POST;
}
if (conn->type == RSPAMD_HTTP_SERVER) {
/*
* iov[0] = base reply
* iov[1] = CRLF
* iov[2] = nonce
* iov[3] = mac
* iov[4] = encrypted reply
* iov[6] = encrypted crlf
* iov[7..n] = encrypted headers
* iov[n + 1] = encrypted crlf
* [iov[n + 2..] = encrypted body segment(s)]
*/
priv->outlen = 7;
enclen = crypto_box_noncebytes() +
crypto_box_macbytes() +
4 + /* 2 * CRLF */
bodylen;
}
else {
/*
* iov[0] = base request
* iov[1] = CRLF
* iov[2] = nonce
* iov[3] = mac
* iov[4] = encrypted method + space
* iov[5] = encrypted url
* iov[7] = encrypted prelude
* iov[8..n] = encrypted headers
* iov[n + 1] = encrypted crlf
* [iov[n + 2..] = encrypted body segment(s)]
*/
priv->outlen = 8;
if (bodylen > 0) {
if (mime_type != NULL) {
preludelen = rspamd_snprintf(repbuf, sizeof(repbuf), "%s\r\n"
"Content-Length: %z\r\n"
"Content-Type: %s\r\n"
"\r\n",
ENCRYPTED_VERSION, bodylen,
mime_type);
}
else {
preludelen = rspamd_snprintf(repbuf, sizeof(repbuf), "%s\r\n"
"Content-Length: %z\r\n"
""
"\r\n",
ENCRYPTED_VERSION, bodylen);
}
}
else {
preludelen = rspamd_snprintf(repbuf, sizeof(repbuf),
"%s\r\n\r\n",
ENCRYPTED_VERSION);
}
enclen = crypto_box_noncebytes() +
crypto_box_macbytes() +
preludelen + /* version [content-length] + 2 * CRLF */
bodylen;
}
if (bodylen > 0) {
if (msg->body_iov_count > 0) {
priv->outlen += msg->body_iov_count;
}
else {
priv->outlen++;
}
}
}
else {
if (msg->method < HTTP_SYMBOLS) {
if (msg->body_iov_count > 0) {
pbody = NULL;
bodylen = msg->body_buf.len;
priv->outlen = 2 + msg->body_iov_count;
if (msg->method == HTTP_INVALID) {
msg->method = HTTP_POST;
}
}
else if (msg->body_buf.len == 0 || allow_shared) {
pbody = NULL;
bodylen = 0;
priv->outlen = 2;
if (msg->method == HTTP_INVALID) {
msg->method = HTTP_GET;
}
}
else {
pbody = (char *) msg->body_buf.begin;
bodylen = msg->body_buf.len;
priv->outlen = 3;
if (msg->method == HTTP_INVALID) {
msg->method = HTTP_POST;
}
}
}
else if (msg->body_buf.len > 0) {
allow_shared = FALSE;
pbody = (char *) msg->body_buf.begin;
bodylen = msg->body_buf.len;
priv->outlen = 2;
}
else {
/* Invalid body for spamc method */
abort();
}
}
peer_key = msg->peer_key;
priv->wr_total = bodylen + 2;
hdrcount = 0;
if (msg->method < HTTP_SYMBOLS) {
kh_foreach_value (msg->headers, hdr, {
DL_FOREACH (hdr, hcur) {
/* <name: value\r\n> */
priv->wr_total += hcur->combined->len;
enclen += hcur->combined->len;
priv->outlen ++;
hdrcount ++;
}
});
}
/* Allocate iov */
priv->out = g_malloc0(sizeof(struct iovec) * priv->outlen);
priv->wr_pos = 0;
meth_len = rspamd_http_message_write_header(mime_type, encrypted,
repbuf, sizeof(repbuf), bodylen, enclen,
host, conn, msg,
&buf, priv, peer_key);
priv->wr_total += buf->len;
/* Setup external request body */
priv->out[0].iov_base = buf->str;
priv->out[0].iov_len = buf->len;
/* Buf will be used eventually for encryption */
if (encrypted) {
int meth_offset, nonce_offset, mac_offset;
ottery_rand_bytes(nonce, crypto_box_noncebytes());
memset(mac, 0, crypto_box_macbytes());
meth_offset = buf->len;
if (conn->type == RSPAMD_HTTP_SERVER) {
buf = rspamd_fstring_append(buf, repbuf, meth_len);
}
else {
meth_len = strlen(http_method_str(msg->method)) + 1; /* + space */
buf = rspamd_fstring_append(buf, http_method_str(msg->method),
meth_len - 1);
buf = rspamd_fstring_append(buf, " ", 1);
}
nonce_offset = buf->len;
buf = rspamd_fstring_append(buf, nonce, crypto_box_noncebytes());
mac_offset = buf->len;
buf = rspamd_fstring_append(buf, mac, crypto_box_macbytes());
/* Need to be encrypted */
if (conn->type == RSPAMD_HTTP_SERVER) {
buf = rspamd_fstring_append(buf, "\r\n\r\n", 4);
}
else {
buf = rspamd_fstring_append(buf, repbuf, preludelen);
}
meth_pos = buf->str + meth_offset;
np = buf->str + nonce_offset;
mp = buf->str + mac_offset;
}
/* During previous writes, buf might be reallocated and changed */
priv->buf->data = buf;
if (encrypted) {
/* Finish external HTTP request */
priv->out[1].iov_base = "\r\n";
priv->out[1].iov_len = 2;
/* Encrypt the real request */
rspamd_http_connection_encrypt_message(conn, msg, priv, pbody, bodylen,
meth_pos, meth_len, preludelen, hdrcount, np, mp, peer_key);
}
else {
i = 1;
if (msg->method < HTTP_SYMBOLS) {
if (msg->flags & RSPAMD_HTTP_FLAG_ORDERED_HEADERS) {
struct rspamd_http_header **hdrs_sorted;
unsigned int nhdrs = 0;
hdrs_sorted = g_malloc(sizeof(*hdrs_sorted) * (hdrcount + 1));
kh_foreach_value (msg->headers, hdr, {
DL_FOREACH (hdr, hcur) {
hdrs_sorted[nhdrs++] = hcur;
}
});
qsort(hdrs_sorted, nhdrs, sizeof(*hdrs_sorted),
rspamd_http_header_cmp_order);
for (unsigned int j = 0; j < nhdrs; j++) {
priv->out[i].iov_base = hdrs_sorted[j]->combined->str;
priv->out[i++].iov_len = hdrs_sorted[j]->combined->len;
}
g_free(hdrs_sorted);
}
else
{
kh_foreach_value (msg->headers, hdr, {
DL_FOREACH (hdr, hcur) {
priv->out[i].iov_base = hcur->combined->str;
priv->out[i++].iov_len = hcur->combined->len;
}
});
}
priv->out[i].iov_base = "\r\n";
priv->out[i++].iov_len = 2;
}
else
{
/* No CRLF for compatibility reply */
priv->wr_total -= 2;
}
if (msg->body_iov_count > 0) {
for (gsize j = 0; j < msg->body_iov_count; j++) {
priv->out[i].iov_base = msg->body_iov[j].iov_base;
priv->out[i++].iov_len = msg->body_iov[j].iov_len;
}
}
else if (pbody != NULL) {
priv->out[i].iov_base = pbody;
priv->out[i++].iov_len = bodylen;
}
}
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_RESETED;
if ((priv->flags & RSPAMD_HTTP_CONN_FLAG_PROXY) && (conn->opts & RSPAMD_HTTP_CLIENT_SSL)) {
/* We need to disable SSL flag! */
err = g_error_new(HTTP_ERROR, 400, "cannot use proxy for SSL connections");
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
g_error_free(err);
return FALSE;
}
rspamd_ev_watcher_stop(priv->ctx->event_loop, &priv->ev);
if (conn->opts & RSPAMD_HTTP_CLIENT_SSL) {
gpointer ssl_ctx = (msg->flags & RSPAMD_HTTP_FLAG_SSL_NOVERIFY) ? priv->ctx->ssl_ctx_noverify : priv->ctx->ssl_ctx;
if (!ssl_ctx) {
err = g_error_new(HTTP_ERROR, 400, "ssl message requested "
"with no ssl ctx");
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
g_error_free(err);
return FALSE;
}
else {
if (!priv->ssl) {
priv->ssl = rspamd_ssl_connection_new(ssl_ctx, priv->ctx->event_loop,
!(msg->flags & RSPAMD_HTTP_FLAG_SSL_NOVERIFY),
conn->log_tag);
g_assert(priv->ssl != NULL);
/* Use ssl_timeout for handshake if provided */
ev_tstamp ssl_to = (priv->ssl_timeout > 0 ? priv->ssl_timeout : (priv->connect_timeout > 0 ? priv->connect_timeout : priv->timeout));
if (!rspamd_ssl_connect_fd(priv->ssl, conn->fd, host, &priv->ev,
ssl_to, rspamd_http_event_handler,
rspamd_http_ssl_err_handler, conn)) {
err = g_error_new(HTTP_ERROR, 400,
"ssl connection error: ssl error=%s, errno=%s",
ERR_error_string(ERR_get_error(), NULL),
strerror(errno));
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
g_error_free(err);
return FALSE;
}
}
else {
/* Just restore SSL handlers */
rspamd_ssl_connection_restore_handlers(priv->ssl,
rspamd_http_event_handler,
rspamd_http_ssl_err_handler,
conn,
EV_WRITE | EV_READ, priv->timeout);
}
}
}
else if (priv->ssl) {
/* Server-side SSL: connection already established, restore handlers */
rspamd_ssl_connection_restore_handlers(priv->ssl,
rspamd_http_event_handler,
rspamd_http_ssl_err_handler,
conn,
EV_WRITE, priv->timeout);
}
else {
/* Watch for READ too on client to detect early server responses */
short ev_flags = (conn->type == RSPAMD_HTTP_CLIENT) ? (EV_WRITE | EV_READ) : EV_WRITE;
rspamd_ev_watcher_init(&priv->ev, conn->fd, ev_flags,
rspamd_http_event_handler, conn);
/* Use connect_timeout on initial EV_WRITE stage if provided */
ev_tstamp start_to = (priv->connect_timeout > 0 ? priv->connect_timeout : priv->timeout);
rspamd_ev_watcher_start(priv->ctx->event_loop, &priv->ev, start_to);
}
return TRUE;
}
gboolean
rspamd_http_connection_write_message(struct rspamd_http_connection *conn,
struct rspamd_http_message *msg,
const char *host,
const char *mime_type,
gpointer ud,
ev_tstamp timeout)
{
return rspamd_http_connection_write_message_common(conn, msg, host, mime_type,
ud, timeout, FALSE);
}
gboolean
rspamd_http_connection_write_message_shared(struct rspamd_http_connection *conn,
struct rspamd_http_message *msg,
const char *host,
const char *mime_type,
gpointer ud,
ev_tstamp timeout)
{
return rspamd_http_connection_write_message_common(conn, msg, host, mime_type,
ud, timeout, TRUE);
}
void rspamd_http_connection_set_max_size(struct rspamd_http_connection *conn,
gsize sz)
{
conn->max_size = sz;
}
void rspamd_http_connection_set_key(struct rspamd_http_connection *conn,
struct rspamd_cryptobox_keypair *key)
{
struct rspamd_http_connection_private *priv = conn->priv;
g_assert(key != NULL);
priv->local_key = rspamd_keypair_ref(key);
}
void rspamd_http_connection_own_socket(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv = conn->priv;
priv->flags |= RSPAMD_HTTP_CONN_OWN_SOCKET;
}
const struct rspamd_cryptobox_pubkey *
rspamd_http_connection_get_peer_key(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv = conn->priv;
if (priv->peer_key) {
return priv->peer_key;
}
else if (priv->msg) {
return priv->msg->peer_key;
}
return NULL;
}
gboolean
rspamd_http_connection_is_encrypted(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv = conn->priv;
if (priv->peer_key != NULL) {
return TRUE;
}
else if (priv->msg) {
return priv->msg->peer_key != NULL;
}
return FALSE;
}
GHashTable *
rspamd_http_message_parse_query(struct rspamd_http_message *msg)
{
GHashTable *res;
rspamd_fstring_t *key = NULL, *value = NULL;
rspamd_ftok_t *key_tok = NULL, *value_tok = NULL;
const char *p, *c, *end;
struct http_parser_url u;
enum {
parse_key,
parse_eqsign,
parse_value,
parse_ampersand
} state = parse_key;
res = g_hash_table_new_full(rspamd_ftok_icase_hash,
rspamd_ftok_icase_equal,
rspamd_fstring_mapped_ftok_free,
rspamd_fstring_mapped_ftok_free);
if (msg->url && msg->url->len > 0) {
http_parser_parse_url(msg->url->str, msg->url->len, TRUE, &u);
if (u.field_set & (1 << UF_QUERY)) {
p = msg->url->str + u.field_data[UF_QUERY].off;
c = p;
end = p + u.field_data[UF_QUERY].len;
while (p <= end) {
switch (state) {
case parse_key:
if ((p == end || *p == '&') && p > c) {
/* We have a single parameter without a value */
key = rspamd_fstring_new_init(c, p - c);
key_tok = rspamd_ftok_map(key);
key_tok->len = rspamd_url_decode(key->str, key->str,
key->len);
value = rspamd_fstring_new_init("", 0);
value_tok = rspamd_ftok_map(value);
g_hash_table_replace(res, key_tok, value_tok);
state = parse_ampersand;
}
else if (*p == '=' && p > c) {
/* We have something like key=value */
key = rspamd_fstring_new_init(c, p - c);
key_tok = rspamd_ftok_map(key);
key_tok->len = rspamd_url_decode(key->str, key->str,
key->len);
state = parse_eqsign;
}
else {
p++;
}
break;
case parse_eqsign:
if (*p != '=') {
c = p;
state = parse_value;
}
else {
p++;
}
break;
case parse_value:
if ((p == end || *p == '&') && p >= c) {
g_assert(key != NULL);
if (p > c) {
value = rspamd_fstring_new_init(c, p - c);
value_tok = rspamd_ftok_map(value);
value_tok->len = rspamd_url_decode(value->str,
value->str,
value->len);
/* Detect quotes for value */
if (value_tok->begin[0] == '"') {
memmove(value->str, value->str + 1,
value_tok->len - 1);
value_tok->len--;
}
if (value_tok->begin[value_tok->len - 1] == '"') {
value_tok->len--;
}
}
else {
value = rspamd_fstring_new_init("", 0);
value_tok = rspamd_ftok_map(value);
}
g_hash_table_replace(res, key_tok, value_tok);
key = value = NULL;
key_tok = value_tok = NULL;
state = parse_ampersand;
}
else {
p++;
}
break;
case parse_ampersand:
if (p != end && *p != '&') {
c = p;
state = parse_key;
}
else {
p++;
}
break;
}
}
}
if (state != parse_ampersand && key != NULL) {
rspamd_fstring_free(key);
}
}
return res;
}
struct rspamd_http_message *
rspamd_http_message_ref(struct rspamd_http_message *msg)
{
REF_RETAIN(msg);
return msg;
}
void rspamd_http_message_unref(struct rspamd_http_message *msg)
{
REF_RELEASE(msg);
}
void rspamd_http_connection_disable_encryption(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv;
priv = conn->priv;
if (priv) {
if (priv->local_key) {
rspamd_keypair_unref(priv->local_key);
}
if (priv->peer_key) {
rspamd_pubkey_unref(priv->peer_key);
}
priv->local_key = NULL;
priv->peer_key = NULL;
priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
}
}
void rspamd_http_connection_set_timeouts(struct rspamd_http_connection *conn,
ev_tstamp connect_timeout,
ev_tstamp ssl_timeout,
ev_tstamp write_timeout,
ev_tstamp read_timeout)
{
struct rspamd_http_connection_private *priv = conn->priv;
if (connect_timeout > 0) {
priv->connect_timeout = connect_timeout;
}
if (ssl_timeout > 0) {
priv->ssl_timeout = ssl_timeout;
}
if (write_timeout > 0) {
priv->write_timeout = write_timeout;
}
if (read_timeout > 0) {
priv->read_timeout = read_timeout;
}
}
void rspamd_http_connection_set_keepalive_tuning(struct rspamd_http_connection *conn,
double connection_ttl,
double idle_timeout,
unsigned int max_reuse)
{
struct rspamd_http_connection_private *priv = conn->priv;
if (connection_ttl > 0) {
priv->ka_ttl_override = connection_ttl;
}
if (idle_timeout > 0) {
priv->ka_idle_override = idle_timeout;
}
if (max_reuse > 0) {
priv->ka_max_reuse_override = max_reuse;
}
}
void rspamd_http_connection_keepalive_note_put(struct rspamd_http_connection *conn,
double now_ts)
{
struct rspamd_http_connection_private *priv = conn->priv;
priv->last_used_ts = now_ts;
}
void rspamd_http_connection_keepalive_note_reuse(struct rspamd_http_connection *conn)
{
struct rspamd_http_connection_private *priv = conn->priv;
priv->reuse_count++;
}
gboolean rspamd_http_connection_keepalive_is_valid(struct rspamd_http_connection *conn,
double now_ts,
double default_ttl,
unsigned int default_max_reuse)
{
struct rspamd_http_connection_private *priv = conn->priv;
double ttl = (priv->ka_ttl_override > 0 ? priv->ka_ttl_override : default_ttl);
unsigned int max_reuse = (priv->ka_max_reuse_override > 0 ? priv->ka_max_reuse_override : default_max_reuse);
if (ttl > 0 && now_ts - priv->created_ts > ttl) {
return FALSE;
}
if (max_reuse > 0 && priv->reuse_count >= max_reuse) {
return FALSE;
}
return TRUE;
}
double rspamd_http_connection_keepalive_idle_timeout(struct rspamd_http_connection *conn,
double default_idle)
{
struct rspamd_http_connection_private *priv = conn->priv;
return (priv->ka_idle_override > 0 ? priv->ka_idle_override : default_idle);
}
static void
rspamd_http_ssl_accept_handler(int fd, short what, gpointer ud)
{
struct rspamd_http_connection *conn = (struct rspamd_http_connection *) ud;
struct rspamd_http_connection_private *priv = conn->priv;
/* SSL handshake complete, start reading HTTP message */
rspamd_http_connection_read_message_common(conn, conn->ud, priv->timeout, 0);
}
static void
rspamd_http_ssl_accept_shared_handler(int fd, short what, gpointer ud)
{
struct rspamd_http_connection *conn = (struct rspamd_http_connection *) ud;
struct rspamd_http_connection_private *priv = conn->priv;
/* SSL handshake complete, start reading HTTP message with shared body */
rspamd_http_connection_read_message_common(conn, conn->ud, priv->timeout,
RSPAMD_HTTP_FLAG_SHMEM);
}
static gboolean
rspamd_http_connection_accept_ssl_common(struct rspamd_http_connection *conn,
gpointer ssl_ctx,
gpointer ud,
ev_tstamp timeout,
rspamd_ssl_handler_t accept_handler)
{
struct rspamd_http_connection_private *priv = conn->priv;
GError *err;
g_assert(conn != NULL);
g_assert(ssl_ctx != NULL);
conn->ud = ud;
priv->timeout = timeout;
priv->ssl = rspamd_ssl_connection_new(ssl_ctx, priv->ctx->event_loop,
FALSE, conn->log_tag);
if (priv->ssl == NULL) {
err = g_error_new(HTTP_ERROR, 400, "cannot create SSL connection");
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
g_error_free(err);
return FALSE;
}
if (!rspamd_ssl_accept_fd(priv->ssl, conn->fd, &priv->ev,
timeout, accept_handler,
rspamd_http_ssl_err_handler, conn)) {
err = g_error_new(HTTP_ERROR, 400,
"ssl accept error: ssl error=%s, errno=%s",
ERR_error_string(ERR_get_error(), NULL),
strerror(errno));
rspamd_http_connection_ref(conn);
conn->error_handler(conn, err);
rspamd_http_connection_unref(conn);
g_error_free(err);
return FALSE;
}
return TRUE;
}
gboolean
rspamd_http_connection_accept_ssl(struct rspamd_http_connection *conn,
gpointer ssl_ctx,
gpointer ud,
ev_tstamp timeout)
{
return rspamd_http_connection_accept_ssl_common(conn, ssl_ctx, ud, timeout,
rspamd_http_ssl_accept_handler);
}
gboolean
rspamd_http_connection_accept_ssl_shared(struct rspamd_http_connection *conn,
gpointer ssl_ctx,
gpointer ud,
ev_tstamp timeout)
{
return rspamd_http_connection_accept_ssl_common(conn, ssl_ctx, ud, timeout,
rspamd_http_ssl_accept_shared_handler);
}
|