1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
//! Protocol Server: acceptor → parse → app → encode → write 的完整链路
//!
//! 本模块实现了多协议 Web 服务器的核心调度逻辑,负责:
//! - TCP/TLS 连接的接受与协议自动检测(ALPN / H2 preface)
//! - HTTP/1.1 流式解析与 keep-alive 管理
//! - 请求规范化 → App 处理 → 响应编码的全链路编排
//! - 所有错误统一映射到 [`ServerError`],fail-closed 不 panic
use std::fmt;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use rustc_hash::FxHashMap;
use zenith_api::{CanonicalRequest, CanonicalResponse, Protocol, Transport, MAX_PATH_LEN, MAX_QUERY_LEN};
use zenith_cache::{CacheEngine, CacheHit, CacheKeyBuilder};
use zenith_capability::{Capability, PermissionSet};
use zenith_foundation::current_time_ms;
use zenith_foundation::sync::{lock_recover, read_recover, write_recover};
use zenith_http1::parser::Http1Parser;
use zenith_http1::types::{Http1Config, Http1Error, HttpRequest as Http1Request};
use zenith_http2::connection::{ConnectionConfig, FrameAction, Http2Connection};
use zenith_http2::error::{Http2Error, Http2ErrorCode};
use zenith_http2::frame::{Frame, FrameType, PREFACE, PREFACE_LEN, Setting, SettingId};
use zenith_http2::hpack::HeaderField;
use zenith_http2::response::Http2ResponseEncoder;
use zenith_http3::frame::Http3Error;
use zenith_net::transport::acceptor::AcceptError;
use zenith_observability::audit::{AuditEvent, AuditLogger, Severity};
use zenith_observability::metrics::MetricsCollector;
#[cfg(feature = "runtime")]
use zenith_runtime::supervisor::{NodeSupervisor, SupervisorState};
#[cfg(feature = "runtime")]
use zenith_runtime::changeset::{ChangeSet, ChangeSetOutcome, ChangeSetState};
#[cfg(feature = "runtime")]
use zenith_runtime::{TaskOffloadChannel, TaskPayload, TaskRequest, TaskResult};
use zenith_tls::acceptor::{AcceptedTlsConn, TlsAcceptError, TlsAcceptor, TlsStream, TlsStreamError};
use zenith_tls::cert_manager::{CertGeneration, CertRotateError};
use zenith_tls::fingerprint::Ja3Fingerprint;
use zenith_waf::{WafEngine, WafResult};
use zenith_proxy::{ForwardConfig, LoadBalanceStrategy, ProxyConfig, ProxyEngine};
use zenith_forward::ForwardEngine;
use crate::app::App;
use crate::error::escape_json_string;
use crate::middleware::IdentityMiddleware;
use crate::normalize::*;
use crate::quic_server::{QuicServerConfig, QuicTransportServer};
/// 将 ASCII 字符串小写化写入调用方栈缓冲(热路径零堆分配)。
///
/// 非 ASCII 或超长出 fail-closed 返回空串(DNS/主机名契约均为 ASCII);
/// ASCII 输入的 UTF-8 有效性在构造上恒成立(UTF-8 含 ASCII 子集)。
#[inline]
fn lower_ascii_into<'b>(s: &str, buf: &'b mut [u8; 256]) -> &'b str {
if s.len() > buf.len() || !s.is_ascii() {
return "";
}
for (i, b) in s.bytes().enumerate() {
buf[i] = b.to_ascii_lowercase();
}
std::str::from_utf8(&buf[..s.len()]).unwrap_or("")
}
/// 将 &str 拷贝入定长栈缓冲并返回借用(脱离原所有者生命周期,零堆分配)。
///
/// 超长输入 fail-closed 截断;若截断恰好切断 UTF-8 多字节序列,
/// from_utf8 失败 → 返回空串(双重 fail-closed)。
/// 注:CanonicalRequest 已按 `MAX_PATH_LEN` / `MAX_QUERY_LEN` 限长,正常请求不触发截断。
#[inline]
fn copy_str_into<'b>(s: &str, buf: &'b mut [u8]) -> &'b str {
let n = s.len().min(buf.len());
buf[..n].copy_from_slice(&s.as_bytes()[..n]);
std::str::from_utf8(&buf[..n]).unwrap_or("")
}
/// 从请求头提取 host(Host 头优先,其次 :authority),小写化写入栈缓冲。
/// 借用语义:零堆分配,返回 &str 生命周期绑定 `buf`。
#[inline]
fn req_host<'b>(header_map: &FxHashMap<&str, &str>, buf: &'b mut [u8; 256]) -> &'b str {
let raw = header_map
.get("host")
.or_else(|| header_map.get(":authority"))
.copied()
.unwrap_or("");
lower_ascii_into(raw, buf)
}
/// 提取 Host/:authority 中显式给出的端口(RFC 3986 §3.2.3)。
///
/// - 主机名 / IPv4:`host:port`(前缀含其他 `:` 即视为未括号化 IPv6,放弃端口语义)
/// - 括号化 IPv6:仅 `]:` 之后视为端口(`[::1]:8443` → 8443)
/// - 端口非纯数字或缺失 → None(宽松默认:跳过端口一致性检查)
#[inline]
fn host_explicit_port(host: &str) -> Option<u16> {
let port_str = if host.starts_with('[') {
let i = host.rfind("]:")?;
&host[i + 2..]
} else {
let (name, port) = host.rsplit_once(':')?;
// 未括号化 IPv6(多冒号)无权威端口语义,放弃
if name.contains(':') {
return None;
}
port
};
if !port_str.is_empty() && port_str.bytes().all(|b| b.is_ascii_digit()) {
port_str.parse::<u16>().ok()
} else {
None
}
}
// 逐跳头判定:委托 zenith-proxy 单一实现(请求侧与响应侧语义一致)
use zenith_proxy::is_hop_by_hop;
// ─────────────────────────────────────────────────────────────────────────────
// 1. ServerError 枚举
// ─────────────────────────────────────────────────────────────────────────────
/// 服务器全链路错误类型
///
/// 覆盖从连接接受到响应发送的所有可能失败场景。
/// 所有变体都提供可观测的上下文,便于日志与监控。
#[derive(Debug)]
pub enum ServerError {
/// 请求/响应规范化层错误
Normalize(ProtocolNormalizeError),
/// HTTP/1.1 解析或协议错误
Http1(Http1Error),
/// HTTP/2 帧/HPACK/流状态机错误
Http2(Http2Error),
/// HTTP/3 帧/QPACK/流状态机错误(RFC 9114)
Http3(Http3Error),
/// 连接接受层错误(TCP bind/accept)
Accept(AcceptError),
/// TLS 握手/证书/SNI 解析/连接表错误
Tls(TlsAcceptError),
/// TLS 加密流读写/握手过程中的错误(真实加解密链路)
TlsStream(TlsStreamError),
/// 底层 I/O 错误(read/write/flush)
Io(std::io::Error),
/// 协议级逻辑错误(状态机非法转移等)
Protocol(String),
/// 对端在完整请求前关闭连接
ConnectionClosed,
/// 操作超时(空闲超时、握手超时等)
Timeout,
/// 内部不变量违反(理论上不应发生)
Internal(String),
}
impl fmt::Display for ServerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Normalize(e) => write!(f, "normalize error: {e}"),
Self::Http1(e) => write!(f, "http1 error: {e}"),
Self::Http2(e) => write!(f, "http2 error: {e}"),
Self::Http3(e) => write!(f, "http3 error: {e}"),
Self::Accept(e) => write!(f, "accept error: {e}"),
Self::Tls(e) => write!(f, "tls error: {e}"),
Self::TlsStream(e) => write!(f, "tls stream error: {e}"),
Self::Io(e) => write!(f, "io error: {e}"),
Self::Protocol(m) => write!(f, "protocol error: {m}"),
Self::ConnectionClosed => write!(f, "connection closed by peer"),
Self::Timeout => write!(f, "operation timed out"),
Self::Internal(m) => write!(f, "internal server error: {m}"),
}
}
}
impl std::error::Error for ServerError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Normalize(e) => Some(e),
Self::Http1(e) => Some(e),
Self::Http2(e) => Some(e),
Self::Http3(e) => Some(e),
Self::Accept(e) => Some(e),
Self::Tls(e) => Some(e),
Self::TlsStream(e) => Some(e),
Self::Io(e) => Some(e),
_ => None,
}
}
}
impl From<ProtocolNormalizeError> for ServerError {
#[inline]
fn from(e: ProtocolNormalizeError) -> Self {
Self::Normalize(e)
}
}
impl From<Http2Error> for ServerError {
#[inline]
fn from(e: Http2Error) -> Self {
Self::Http2(e)
}
}
impl From<Http3Error> for ServerError {
#[inline]
fn from(e: Http3Error) -> Self {
Self::Http3(e)
}
}
impl From<std::io::Error> for ServerError {
#[inline]
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
impl From<Http1Error> for ServerError {
#[inline]
fn from(e: Http1Error) -> Self {
Self::Http1(e)
}
}
impl From<AcceptError> for ServerError {
#[inline]
fn from(e: AcceptError) -> Self {
Self::Accept(e)
}
}
impl From<TlsAcceptError> for ServerError {
#[inline]
fn from(e: TlsAcceptError) -> Self {
Self::Tls(e)
}
}
impl From<TlsStreamError> for ServerError {
#[inline]
fn from(e: TlsStreamError) -> Self {
Self::TlsStream(e)
}
}
// ─────────────────────────────────────────────────────────────────────────────
// 2. ServerConfig 配置
// ─────────────────────────────────────────────────────────────────────────────
/// TLS 指纹黑名单匹配策略(可按需自由选择,支持运行时热更新)。
///
/// 说明:JA3 对 ClientHello 扩展/套件的**原始顺序**敏感——同一客户端(如
/// curl 8.20.0)每次连接会因扩展顺序随机化而得到不同的 JA3 哈希,但字段
/// 集合不变、JA4 稳定。因此:
/// - [`FingerprintMatch::Ja3`]:仅按 JA3 哈希前缀匹配(原始语义,最严格但可能漏同一客户端)
/// - [`FingerprintMatch::Ja4`]:仅按 JA4 哈希前缀匹配(对顺序稳定)
/// - [`FingerprintMatch::Ja3OrJa4`]:命中两者任一即阻断(默认,兼顾兼容与稳定性)
/// - [`FingerprintMatch::Ja3AndJa4`]:两者都命中才阻断(最宽松)
///
/// 该策略通过 `with_fingerprint_match` 在配置期设定,或经
/// `update_runtime(|rt| rt.set_fingerprint_match(...))` 在运行期热更新(对新连接生效)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FingerprintMatch {
/// 仅按 JA3 哈希前缀匹配
Ja3,
/// 仅按 JA4 哈希前缀匹配(对扩展顺序稳定)
Ja4,
/// 命中 JA3 或 JA4 任一前缀即阻断(默认)
Ja3OrJa4,
/// 需 JA3 与 JA4 都命中前缀才阻断
Ja3AndJa4,
}
impl Default for FingerprintMatch {
fn default() -> Self {
FingerprintMatch::Ja3OrJa4
}
}
/// 协议服务器配置
///
/// 所有参数均有安全默认值,可通过 `with_xxx` builder 方法定制。
/// 数值参数使用饱和语义(超过 `MAX` 的配置在运行时被裁剪并返回错误)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerConfig {
/// 单条 HTTP/1.1 连接最多处理的请求数(keep-alive 上限)
pub http1_max_requests_per_conn: u32,
/// HTTP/1.1 空闲超时(毫秒),防止 Slowloris 攻击
pub http1_idle_timeout_ms: u64,
/// HTTP/2 最大帧大小(RFC 7540 §6.5.2,范围 16384..=16777215)
pub http2_max_frame_size: u32,
/// HTTP/2 单连接并发流上限
pub http2_max_concurrent_streams: u32,
/// HTTP/3 头部字段段最大字节数(QPACK 解码上限)
pub http3_max_field_section_size: u64,
/// 读缓冲区大小(字节)
pub read_buffer_size: usize,
/// 写缓冲区初始容量(字节)
pub write_buffer_size: usize,
/// 最大请求体大小(字节),超过返回 413
pub max_body_size: usize,
/// 审计日志落盘路径(JSON Lines;None = 仅内存环形缓冲)
pub audit_log_path: Option<String>,
/// 服务器监听地址(AGENT §4.5 四元一致性之"传输层目的地址")。
///
/// 配置后,`:authority`/`Host` 的显式端口必须与其端口一致,
/// 不一致返回 421 Misdirected Request;authority 无显式端口时跳过
/// 端口检查(宽松默认语义)。None = 不启用端口一致性检查(零开销)。
pub bind_addr: Option<SocketAddr>,
/// 虚拟主机白名单(小写域名),启用 [`crate::middleware::IdentityMiddleware`]
/// 默认装配(AGENT §4.5 纵深默认闭环)。
///
/// 非空时:authority/Host 必须在白名单内(恒定时间比较),否则返回
/// 421 Misdirected Request。空列表 = pass-through 零开销(默认)。
pub allowed_hosts: Vec<String>,
/// /metrics 端点认证令牌(None 时端点不可访问,返回 404;
/// Some(token) 时校验 `Authorization: Bearer {token}` 头)
pub metrics_auth_token: Option<String>,
/// 是否启用内置 WAF(默认 `false`,严格按需)。
///
/// 作为**依赖库**,Zenith 不强制默认开启任何安全中间件;需要 WAF 时由
/// 调用方显式开启。开启后走内置 5 检测器(SQLi/XSS/SSRF/命令注入/路径穿越)
/// + 自定义规则。若需完全自定义规则或按 host 差异化,请用独立
/// `zenith_stack::waf::WafEngine` 在自定义中间件层实现。
pub waf_enabled: bool,
/// 按 host 强制启用 WAF 的白名单(小写域名)。即使 `waf_enabled=false`,
/// 命中此列表的 host 仍启用 WAF。用于"仅特定域开 WAF、其余关闭"。
pub waf_enabled_hosts: Vec<String>,
/// 按 host 跳过 WAF 的黑名单(小写域名)。即使 `waf_enabled=true`,
/// 命中此列表的 host 也跳过 WAF。用于"全局开、个别域放行"。
pub waf_disabled_hosts: Vec<String>,
/// 是否启用 TLS 指纹安全控制(JA3/JA4 黑名单 + 速率限制)。
///
/// 默认 `false`(严格按需)。内置管线默认**不**做任何指纹拦截/限流——
/// 依赖库不写死此类访问控制;需要时由调用方显式开启。
pub fingerprint_security_enabled: bool,
/// TLS 指纹黑名单匹配策略(可按需选择,支持运行时热更新)。
///
/// 仅当 [`Self::fingerprint_security_enabled`] 为 `true` 时生效。
/// 默认 [`FingerprintMatch::Ja3OrJa4`]。
pub fingerprint_match: FingerprintMatch,
/// 反向代理运行参数(连接池 / 超时 / 健康阈值,全部可配置)。
pub proxy: ProxyConfig,
/// L4 转发引擎运行参数(并发会话上限 / 单会话带宽,全部可配置,支持运行时热更新)。
pub forward: zenith_forward::ForwardConfig,
/// 内置缓存引擎条目上限
pub cache_max_entries: usize,
/// 内置缓存引擎字节上限
pub cache_max_size_bytes: usize,
/// TLS 指纹速率限制:每个时间窗口内每个 JA3 指纹允许的最大请求数。
///
/// 仅当 [`Self::fingerprint_security_enabled`] 为 `true` 时生效。
pub fingerprint_rate_limit_requests: u32,
/// TLS 指纹速率限制时间窗口(毫秒)。
///
/// 仅当 [`Self::fingerprint_security_enabled`] 为 `true` 时生效。
pub fingerprint_rate_limit_window_ms: u64,
/// WAF 大 body 卸载阈值(字节)
pub waf_offload_body_threshold: usize,
/// WAF 卸载执行期限(毫秒)
pub waf_offload_deadline_ms: u64,
/// L4 UDP 转发会话数上限
pub udp_max_sessions: usize,
/// L4 UDP 转发会话空闲超时(毫秒)
pub udp_session_idle_timeout_ms: u64,
/// L4 UDP 转发会话清理超时(毫秒)
pub udp_session_cleanup_timeout_ms: u64,
/// L4 转发会话超时(毫秒)
pub forward_session_timeout_ms: u64,
/// Supervisor 连续 5xx 熔断阈值
pub supervisor_max_consecutive_5xx: u64,
}
impl Default for ServerConfig {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl ServerConfig {
/// 使用安全默认值创建配置
#[inline]
pub fn new() -> Self {
Self {
http1_max_requests_per_conn: 100,
http1_idle_timeout_ms: 30_000,
http2_max_frame_size: 16_384,
http2_max_concurrent_streams: 100,
http3_max_field_section_size: 1_048_576,
read_buffer_size: 65_536,
write_buffer_size: 65_536,
max_body_size: 16_777_216,
audit_log_path: None,
bind_addr: None,
allowed_hosts: Vec::new(),
metrics_auth_token: None,
waf_enabled: false,
waf_enabled_hosts: Vec::new(),
waf_disabled_hosts: Vec::new(),
fingerprint_security_enabled: false,
fingerprint_match: FingerprintMatch::default(),
proxy: ProxyConfig::default(),
forward: zenith_forward::ForwardConfig::default(),
cache_max_entries: 65_536,
cache_max_size_bytes: 16 * 1024 * 1024,
fingerprint_rate_limit_requests: 100,
fingerprint_rate_limit_window_ms: 60_000,
waf_offload_body_threshold: 65_536,
waf_offload_deadline_ms: 5_000,
udp_max_sessions: 4096,
udp_session_idle_timeout_ms: 60_000,
udp_session_cleanup_timeout_ms: 300_000,
forward_session_timeout_ms: 300_000,
supervisor_max_consecutive_5xx: 10,
}
}
/// 设置监听地址(启用 :authority/Host 显式端口一致性检查 → 421;AGENT §4.5)
#[inline]
pub fn with_bind_addr(mut self, addr: SocketAddr) -> Self {
self.bind_addr = Some(addr);
self
}
/// 设置虚拟主机白名单(启用 IdentityMiddleware 默认装配;AGENT §4.5)
#[inline]
pub fn with_allowed_hosts<I, S>(mut self, hosts: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.allowed_hosts = hosts.into_iter().map(Into::into).collect();
self
}
/// 设置审计日志落盘路径(JSON Lines 追加写;None = 仅内存环形缓冲)
#[inline]
pub fn with_audit_log_path(mut self, path: impl Into<String>) -> Self {
self.audit_log_path = Some(path.into());
self
}
/// 设置单连接最大请求数(keep-alive)
#[inline]
pub fn with_http1_max_requests_per_conn(mut self, n: u32) -> Self {
self.http1_max_requests_per_conn = n;
self
}
/// 设置 HTTP/1.1 空闲超时(毫秒)
#[inline]
pub fn with_http1_idle_timeout_ms(mut self, ms: u64) -> Self {
self.http1_idle_timeout_ms = ms;
self
}
/// 设置 HTTP/2 最大帧大小
#[inline]
pub fn with_http2_max_frame_size(mut self, size: u32) -> Self {
self.http2_max_frame_size = size;
self
}
/// 设置 HTTP/2 最大并发流数
#[inline]
pub fn with_http2_max_concurrent_streams(mut self, n: u32) -> Self {
self.http2_max_concurrent_streams = n;
self
}
/// 设置 HTTP/3 最大头部字段段大小
#[inline]
pub fn with_http3_max_field_section_size(mut self, size: u64) -> Self {
self.http3_max_field_section_size = size;
self
}
/// 设置读缓冲区大小(字节)
#[inline]
pub fn with_read_buffer_size(mut self, size: usize) -> Self {
self.read_buffer_size = size;
self
}
/// 设置写缓冲区容量(字节)
#[inline]
pub fn with_write_buffer_size(mut self, size: usize) -> Self {
self.write_buffer_size = size;
self
}
/// 设置最大请求体大小(字节)
#[inline]
pub fn with_max_body_size(mut self, size: usize) -> Self {
self.max_body_size = size;
self
}
/// 启用/关闭内置 WAF(默认关闭,严格按需)。
///
/// 作为依赖库,Zenith 不默认开启安全中间件;显式调用 `with_waf(true)` 才启用。
#[inline]
pub fn with_waf(mut self, enabled: bool) -> Self {
self.waf_enabled = enabled;
self
}
/// 设置按 host 强制启用 WAF 的白名单(小写域名)。即使 `waf_enabled=false`,
/// 命中此列表的 host 仍启用 WAF。
#[inline]
pub fn with_waf_enabled_hosts<I, S>(mut self, hosts: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.waf_enabled_hosts = hosts
.into_iter()
.map(|h| h.into().to_ascii_lowercase())
.collect();
self
}
/// 设置按 host 跳过 WAF 的黑名单(小写域名)。即使 `waf_enabled=true`,
/// 命中此列表的 host 也跳过 WAF。
#[inline]
pub fn with_waf_disabled_hosts<I, S>(mut self, hosts: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.waf_disabled_hosts = hosts
.into_iter()
.map(|h| h.into().to_ascii_lowercase())
.collect();
self
}
/// 启用/关闭 TLS 指纹安全控制(JA3/JA4 黑名单 + 速率限制,默认关闭)。
#[inline]
pub fn with_fingerprint_security(mut self, enabled: bool) -> Self {
self.fingerprint_security_enabled = enabled;
self
}
/// 设置 TLS 指纹黑名单匹配策略(可按需自由选择,支持运行时热更新)。
///
/// 仅在 [`Self::with_fingerprint_security(true)`] 开启后生效。
#[inline]
pub fn with_fingerprint_match(mut self, mode: FingerprintMatch) -> Self {
self.fingerprint_match = mode;
self
}
/// 设置反向代理运行参数(连接池 / 超时 / 健康阈值全部可配置)。
#[inline]
pub fn with_proxy(mut self, proxy: ProxyConfig) -> Self {
self.proxy = proxy;
self
}
/// 设置内置缓存引擎条目上限
#[inline]
pub fn with_cache_max_entries(mut self, v: usize) -> Self {
self.cache_max_entries = v;
self
}
/// 设置内置缓存引擎字节上限
#[inline]
pub fn with_cache_max_size_bytes(mut self, v: usize) -> Self {
self.cache_max_size_bytes = v;
self
}
/// 设置 TLS 指纹速率限制:每个时间窗口内每个 JA3 指纹的最大请求数
#[inline]
pub fn with_fingerprint_rate_limit_requests(mut self, n: u32) -> Self {
self.fingerprint_rate_limit_requests = n;
self
}
/// 设置 TLS 指纹速率限制时间窗口(毫秒)
#[inline]
pub fn with_fingerprint_rate_limit_window_ms(mut self, ms: u64) -> Self {
self.fingerprint_rate_limit_window_ms = ms;
self
}
/// 设置 WAF 大 body 卸载阈值(字节)
#[inline]
pub fn with_waf_offload_body_threshold(mut self, v: usize) -> Self {
self.waf_offload_body_threshold = v;
self
}
/// 设置 WAF 卸载执行期限(毫秒)
#[inline]
pub fn with_waf_offload_deadline_ms(mut self, v: u64) -> Self {
self.waf_offload_deadline_ms = v;
self
}
/// 设置 L4 UDP 转发会话数上限
#[inline]
pub fn with_udp_max_sessions(mut self, v: usize) -> Self {
self.udp_max_sessions = v;
self
}
/// 设置 L4 UDP 转发会话空闲超时(毫秒)
#[inline]
pub fn with_udp_session_idle_timeout_ms(mut self, v: u64) -> Self {
self.udp_session_idle_timeout_ms = v;
self
}
/// 设置 L4 UDP 转发会话清理超时(毫秒)
#[inline]
pub fn with_udp_session_cleanup_timeout_ms(mut self, v: u64) -> Self {
self.udp_session_cleanup_timeout_ms = v;
self
}
/// 设置 L4 转发会话超时(毫秒)
#[inline]
pub fn with_forward_session_timeout_ms(mut self, v: u64) -> Self {
self.forward_session_timeout_ms = v;
self
}
/// 设置 L4 转发引擎运行参数(并发会话上限 / 单会话带宽,构建期)
#[inline]
pub fn with_forward_config(mut self, config: zenith_forward::ForwardConfig) -> Self {
self.forward = config;
self
}
/// 设置 Supervisor 连续 5xx 熔断阈值
#[inline]
pub fn with_supervisor_max_consecutive_5xx(mut self, v: u64) -> Self {
self.supervisor_max_consecutive_5xx = v;
self
}
}
// ─────────────────────────────────────────────────────────────────────────────
// 3. ProtocolServer 主结构体
// ─────────────────────────────────────────────────────────────────────────────
/// 多协议服务器核心
///
/// 持有应用实例 [`App`] 与运行时配置,负责单连接的完整生命周期:
/// acceptor → parse → normalize → app → encode → write。
///
/// # 设计
/// - 协议版本特定的编码器按连接创建,因此此处仅保存构造工厂所需的配置
/// - App 通过不可变引用调用,支持多线程无锁共享(Send + Sync)
///
/// web 域在 NodeSupervisor 中的 domain_id(单进程 web 服务器唯一域)
#[cfg(feature = "runtime")]
const WEB_DOMAIN_ID: u64 = 0;
/// WAF 卸载任务在 TaskPayload::Custom 中的 kind 标识
#[cfg(feature = "runtime")]
const WAF_OFFLOAD_TASK_KIND: u32 = 0x5741_4601;
/// WAF 卸载请求载荷(经 serde_json 序列化后由 TaskPayload::Custom 携带)
#[cfg(feature = "runtime")]
#[derive(serde::Serialize, serde::Deserialize)]
struct WafOffloadRequest {
method: String,
path: String,
query: String,
headers: Vec<(String, String)>,
body: Vec<u8>,
}
/// WAF 卸载结果载荷(消费线程回写,提交方解码)
#[cfg(feature = "runtime")]
#[derive(serde::Serialize, serde::Deserialize)]
struct WafOffloadResponse {
has_threat: bool,
severity: String,
triggered_rules: Vec<String>,
}
/// 任务卸载消费线程:真实 drain TaskOffloadChannel 并执行 WAF 检查任务
///
/// 生命周期跟随 SecurityPipeline 的最后一个 Arc 引用:
/// drop 时置退出标志并 join 消费线程(带超时防护,超时则 detach,
/// 禁止服务器关闭路径被阻塞)。
#[cfg(feature = "runtime")]
#[derive(Debug)]
struct OffloadWorker {
/// 退出标志(消费循环每次迭代检查)
shutdown: Arc<std::sync::atomic::AtomicBool>,
/// 消费线程句柄(Option 以便 drop 时 take 后 join)
handle: std::sync::Mutex<Option<std::thread::JoinHandle<()>>>,
}
#[cfg(feature = "runtime")]
impl OffloadWorker {
/// 创建并 spawn 消费线程
fn spawn(channel: Arc<TaskOffloadChannel<1024>>, waf: Arc<std::sync::RwLock<WafEngine>>) -> Self {
let shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false));
let shutdown_in_thread = Arc::clone(&shutdown);
let spawned = std::thread::Builder::new()
.name("zenith-waf-offload".to_string())
.spawn(move || Self::run(&channel, &waf, &shutdown_in_thread));
match spawned {
Ok(h) => Self {
shutdown,
handle: std::sync::Mutex::new(Some(h)),
},
Err(e) => {
// fail-visible:线程创建失败不 panic;后续卸载提交因无人消费
// 必然超时并回退内联执行,检查语义不丢失
tracing::error!(error = %e, "WAF offload consumer thread spawn failed");
Self {
shutdown,
handle: std::sync::Mutex::new(None),
}
}
}
}
/// 消费循环:取任务 → 执行 → 回写结果;退出前 drain 残余任务
fn run(
channel: &TaskOffloadChannel<1024>,
waf: &std::sync::RwLock<WafEngine>,
shutdown: &std::sync::atomic::AtomicBool,
) {
use std::sync::atomic::Ordering;
// 混合等待策略:连续空取时先自旋(忙时微秒级接单,提交方等待开销最小),
// 64 次连续空转后退化为 sleep(闲时零 CPU 浪费)
let mut empty_streak: u32 = 0;
loop {
match channel.fetch() {
Some(req) => {
empty_streak = 0;
let result = execute_offload_task(waf, &req);
// 结果队列满(提交方已超时回退)时丢弃结果;
// pending/completed 计数由 complete 内部保持配对
let _ = channel.complete(result);
}
None => {
if shutdown.load(Ordering::Acquire) {
break;
}
empty_streak += 1;
if empty_streak < 64 {
std::hint::spin_loop();
} else {
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
}
}
}
}
#[cfg(feature = "runtime")]
impl Drop for OffloadWorker {
fn drop(&mut self) {
use std::sync::atomic::Ordering;
self.shutdown.store(true, Ordering::Release);
let mut guard = lock_recover(&self.handle);
if let Some(handle) = guard.take() {
// 超时防护:消费循环每 1ms 检查一次退出标志,正常 100ms 内必退出;
// 超时则放弃 join(detach),禁止 drop 阻塞服务器关闭
let deadline = Instant::now() + std::time::Duration::from_millis(100);
while !handle.is_finished() && Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(1));
}
if handle.is_finished() {
let _ = handle.join();
}
}
}
}
/// 执行一条卸载任务(消费线程侧)
///
/// 已过截止时间的任务跳过执行(提交方必然已回退内联),
/// 但仍回写 Timeout 结果保持 pending/completed 计数配对。
#[cfg(feature = "runtime")]
fn execute_offload_task(waf: &std::sync::RwLock<WafEngine>, req: &TaskRequest) -> TaskResult {
let result = match &req.payload {
TaskPayload::Custom { kind, data } if *kind == WAF_OFFLOAD_TASK_KIND => {
if req.submitted_at.elapsed() > std::time::Duration::from_millis(req.deadline_ms) {
Err(zenith_runtime::TaskError::Timeout {
task_id: req.task_id,
elapsed_ms: req.submitted_at.elapsed().as_millis() as u32,
})
} else {
match serde_json::from_slice::<WafOffloadRequest>(data) {
Ok(waf_req) => {
// 卸载载荷为反序列化的 owned String:在其作用域内构造借用头图,
// 检查完成后随帧释放(owned 仅存在于大 body 冷路径)
let owned_headers: FxHashMap<String, String> =
waf_req.headers.into_iter().collect();
let headers: FxHashMap<&str, &str> = owned_headers
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
let waf_result = {
let engine = read_recover(waf);
engine.check_request(
&waf_req.method,
&waf_req.path,
&headers,
&waf_req.body,
&waf_req.query,
)
};
let offload_resp = WafOffloadResponse {
has_threat: waf_result.has_threat,
severity: waf_result.severity.as_str().to_string(),
triggered_rules: waf_result.triggered_rules,
};
match serde_json::to_vec(&offload_resp) {
Ok(bytes) => Ok(zenith_runtime::TaskOutput {
data: bytes,
status_code: 200,
elapsed_ms: req.submitted_at.elapsed().as_millis() as u32,
}),
Err(e) => Err(zenith_runtime::TaskError::Internal(format!(
"waf offload response encode: {e}"
))),
}
}
Err(e) => Err(zenith_runtime::TaskError::Internal(format!(
"waf offload request decode: {e}"
))),
}
}
}
other => Err(zenith_runtime::TaskError::InvalidPayload { kind: other.kind() }),
};
TaskResult {
task_id: req.task_id,
domain_id: req.domain_id,
result,
}
}
/// 反向代理路由条目:(路径前缀, 引擎(独立持锁), 转发配置)
type ProxyRoute = (String, Arc<std::sync::Mutex<ProxyEngine>>, ForwardConfig);
/// 指纹速率限制分片数(2 的幂,取模可用位与路由)
const FP_RATE_LIMIT_SHARDS: usize = 64;
/// 指纹速率限制分片表(64 分片独立 Mutex,按 JA3 哈希位与路由)
type FpRateLimitShards =
Arc<[std::sync::Mutex<FxHashMap<String, (u64, u32)>>; FP_RATE_LIMIT_SHARDS]>;
/// 按 JA3 指纹哈希路由到目标分片(FxHash + 位与,零分配)
#[inline]
fn fp_rate_limit_shard_index(ja3_hash: &str) -> usize {
use std::hash::{Hash, Hasher};
let mut h = rustc_hash::FxHasher::default();
ja3_hash.hash(&mut h);
(h.finish() as usize) & (FP_RATE_LIMIT_SHARDS - 1)
}
/// 协议级成功计数名(L7 转发闭环观测:按实际使用协议细分)
///
/// `protocol_used` 由 [`zenith_proxy::forward::ForwardLease::protocol_used`] 回填:
/// `http/1.1` / `https` / `h2` / `h3`;Auto 上游由内部 ALPN 决策归入对应协议。
fn proxy_success_metric(proto: Option<&'static str>) -> &'static str {
match proto {
Some("http/1.1") => "proxy_upstream_success_h1",
Some("https") => "proxy_upstream_success_https",
Some("h2") => "proxy_upstream_success_h2",
Some("h3") => "proxy_upstream_success_h3",
_ => "proxy_upstream_success_unknown",
}
}
/// 协议级失败计数名(L7 转发闭环观测)
fn proxy_error_metric(proto: Option<&'static str>) -> &'static str {
match proto {
Some("http/1.1") => "proxy_upstream_error_h1",
Some("https") => "proxy_upstream_error_https",
Some("h2") => "proxy_upstream_error_h2",
Some("h3") => "proxy_upstream_error_h3",
_ => "proxy_upstream_error_unknown",
}
}
// ── L4 UDP 转发:per-client 会话映射表(双线程模型) ──────────────────────
/// 单客户端 UDP 转发会话
///
/// 每个客户端源地址持有一个专属上游 socket(临时端口绑定):
/// - 回包 peer 唯一性 → 天然多客户端正确分拣(修复旧实现 `last_client`
/// 单客户端缺陷)
/// - 白名单/配额经 [`ForwardEngine::create_session`] 每客户端登记(fail-closed)
struct UdpClientSession {
/// 该客户端专属上游 socket(`0.0.0.0:0` 或 `[::]:0` 临时端口)
upstream_sock: std::net::UdpSocket,
/// ForwardEngine 会话 ID(记账 / close / cleanup 关联)
session_id: u64,
/// 最后活跃时刻(空闲回收)
last_active: Instant,
/// 客户端 → 上游 字节累计
rx: u64,
/// 上游 → 客户端 字节累计
tx: u64,
}
/// UDP 临时错误判定:不应终止转发线程
///
/// Windows 上 ICMP port unreachable 以 `ConnectionReset` 呈报——旧实现
/// break 会整体停摆转发(修复);`WouldBlock/TimedOut/Interrupted` 为
/// 非阻塞轮询的正常空转。
fn is_transient_udp_error(kind: std::io::ErrorKind) -> bool {
matches!(
kind,
std::io::ErrorKind::WouldBlock
| std::io::ErrorKind::TimedOut
| std::io::ErrorKind::Interrupted
| std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
)
}
/// 创建客户端 UDP 会话(白名单/配额/上限/bind 任一失败 → `false`,已计数 + 审计)
///
/// fail-closed:
/// 1. 并发上限(`udp_max_sessions`)→ 拒绝(`udp_sessions_denied`)
/// 2. `ForwardEngine::create_session` 白名单 + 配额 → 拒绝(`udp_sessions_denied`)
/// 3. 专属上游 socket 绑定失败 → `forward_relay_error`
///
/// 成功时插入映射表并返回 `true`(调用方随后 `get_mut` 取用)。
fn create_udp_session(
sessions: &mut FxHashMap<SocketAddr, UdpClientSession>,
security: &SecurityPipeline,
client: SocketAddr,
upstream_addr: SocketAddr,
) -> bool {
// 并发上限(防映射表无限增长 → 资源耗尽)
if sessions.len() >= security.runtime.udp_max_sessions.load(Ordering::Relaxed) as usize {
security.record_counter("udp_sessions_denied", 1);
security.audit(
"FORWARD_DENIED",
&format!("udp client={client} reason=max_sessions"),
);
return false;
}
// ForwardEngine 会话登记(白名单 + 配额,fail-closed)
let session_id = {
let mut engine = lock_recover(&security.forward_engine);
match engine.create_session(
zenith_forward::ForwardProtocol::Udp,
client,
upstream_addr,
) {
Some(id) => id,
None => {
security.record_counter("udp_sessions_denied", 1);
security.audit(
"FORWARD_DENIED",
&format!("udp client={client} reason=whitelist_or_quota"),
);
return false;
}
}
};
// 专属上游 socket(地址族与客户端匹配)
let bind_addr = if client.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" };
let upstream_sock = match std::net::UdpSocket::bind(bind_addr) {
Ok(s) => s,
Err(e) => {
security.record_counter("forward_relay_error", 1);
security.audit("FORWARD_ERROR", &format!("udp client={client} bind: {e}"));
return false;
}
};
let _ = upstream_sock.set_nonblocking(true);
security.record_counter("forward_sessions_total", 1);
security.record_counter("udp_sessions_created", 1);
security.audit(
"FORWARD_ACCEPT",
&format!("udp client={client} session={session_id}"),
);
sessions.insert(
client,
UdpClientSession {
upstream_sock,
session_id,
last_active: Instant::now(),
rx: 0,
tx: 0,
},
);
true
}
/// 回收单个 UDP 会话:分方向记账 + close + cleanup(唯一出口)
///
/// 先释放 sessions 锁取出条目,再取 engine 锁记账(锁序:sessions → engine,
/// 与 c2u 路径一致,无环)。
fn reap_udp_session(
security: &SecurityPipeline,
sessions: &std::sync::Mutex<FxHashMap<SocketAddr, UdpClientSession>>,
client: SocketAddr,
reason: &str,
) {
let removed = {
let mut guard = lock_recover(sessions);
guard.remove(&client)
};
let Some(s) = removed else { return };
let mut engine = lock_recover(&security.forward_engine);
if let Some(es) = engine.get_session_mut(s.session_id) {
es.record_rx(s.rx);
es.record_tx(s.tx);
}
engine.close_session(s.session_id);
engine.cleanup_closed(security.runtime.udp_session_cleanup_timeout_ms.load(Ordering::Relaxed));
security.record_counter("udp_sessions_reaped", 1);
security.audit(
"FORWARD_CLOSE",
&format!(
"udp client={client} session={} reason={reason} rx={} tx={}",
s.session_id, s.rx, s.tx
),
);
}
/// 清空全部 UDP 会话(u2c 线程退出统一收尾:记账 + close + cleanup)
fn drain_udp_sessions(
security: &SecurityPipeline,
sessions: &std::sync::Mutex<FxHashMap<SocketAddr, UdpClientSession>>,
) {
let drained = {
let mut guard = lock_recover(sessions);
let mut out: Vec<(SocketAddr, UdpClientSession)> = Vec::with_capacity(guard.len());
for (client, s) in guard.drain() {
out.push((client, s));
}
out
};
let mut engine = lock_recover(&security.forward_engine);
for (client, s) in drained {
if let Some(es) = engine.get_session_mut(s.session_id) {
es.record_rx(s.rx);
es.record_tx(s.tx);
}
engine.close_session(s.session_id);
security.audit(
"FORWARD_CLOSE",
&format!("udp client={client} session={} reason=shutdown", s.session_id),
);
}
engine.cleanup_closed(security.runtime.udp_session_cleanup_timeout_ms.load(Ordering::Relaxed));
}
/// 指纹决策结果 (简化版, 供 SecurityPipeline 使用)
#[derive(Debug, Clone)]
pub enum FingerprintDecision {
/// 放行
Allow,
/// 拒绝 (附带原因)
Block(String),
/// 速率限制 (附带重试毫秒数)
RateLimit(u32),
}
/// L7 HTTP 指纹快照 (头部顺序 / UA / Cookie 模式)
#[derive(Debug, Clone)]
pub struct HttpFingerprintSnapshot {
/// 头部名称顺序 (按接收顺序)
pub header_names: Vec<String>,
/// User-Agent 值
pub user_agent: Option<Vec<u8>>,
/// Cookie 值
pub cookie: Option<Vec<u8>>,
}
/// 采集 L7 HTTP 指纹
#[allow(dead_code)]
fn collect_l7_fingerprint(req: &CanonicalRequest) -> HttpFingerprintSnapshot {
// Header order
let header_names: Vec<String> = req
.headers_iter()
.iter()
.filter_map(|h| std::str::from_utf8(&h.name[..h.name_len as usize]).ok())
.map(|s| s.to_string())
.collect();
// UA
let user_agent = req
.find_header("user-agent")
.map(|h| h.value[..h.value_len as usize].to_vec());
// Cookie
let cookie = req
.find_header("cookie")
.map(|h| h.value[..h.value_len as usize].to_vec());
HttpFingerprintSnapshot {
header_names,
user_agent,
cookie,
}
}
/// 全链路安全与运行时管道
///
/// 集成 WAF + Cache + Metrics + Capability + Supervisor + ChangeSet + Forward + Proxy 七大横切关注点
/// 以及 TLS 指纹识别(JA3/JA4)用于访问控制
///
/// 请求处理顺序:
/// 1. Capability 权限校验(请求是否具备所需能力)
/// 2. TLS 指纹检查(是否在拒绝列表中 / 是否超过速率限制)
/// 3. WAF 恶意请求检测(SQL 注入 / XSS / SSRF / 命令注入 / 路径穿越)
/// 4. Cache 命中检测(命中则跳过 App 直接返回缓存响应)
/// 5. Supervisor 状态检查(运行中/降级/故障)
/// 6. App 业务处理
/// 7. ForwardEngine 上游转发(如配置了上游)
/// 8. Cache 存储 + 指标记录 + 审计日志
pub struct SecurityPipeline {
/// WAF 引擎:RwLock 读多写少(规则集只读检查并发,热更新走写锁);
/// 引擎内部计数器已原子化,check_request 仅需 &self
waf: Arc<std::sync::RwLock<WafEngine>>,
cache: Arc<std::sync::Mutex<CacheEngine>>,
metrics: Arc<std::sync::Mutex<MetricsCollector>>,
/// 能力权限集合(基于角色的最小权限)
permissions: PermissionSet,
/// 三级 Supervisor 节点(Node → Domain → Queue)
#[cfg(feature = "runtime")]
supervisor: Arc<std::sync::Mutex<NodeSupervisor>>,
/// ChangeSet 热更新引擎
#[cfg(feature = "runtime")]
changeset: Arc<std::sync::Mutex<ChangeSet>>,
/// 任务卸载通道(无锁,O(1) 投递)
#[cfg(feature = "runtime")]
task_channel: Arc<TaskOffloadChannel<1024>>,
/// 卸载消费线程(真实 drain 通道执行 WAF 检查;生命周期跟随本管道)
#[cfg(feature = "runtime")]
offload_worker: Arc<OffloadWorker>,
/// 卸载提交序列化锁(单提交者语义:结果队列无需按 task_id 路由)
#[cfg(feature = "runtime")]
offload_submit_lock: Arc<std::sync::Mutex<()>>,
/// 卸载任务 ID 分配器(单调递增)
#[cfg(feature = "runtime")]
offload_next_task_id: Arc<std::sync::atomic::AtomicU64>,
/// 转发引擎(L4 TCP/UDP 转发)
forward_engine: Arc<std::sync::Mutex<ForwardEngine>>,
/// 审计日志(环形缓冲 + 可选 JSON Lines 文件落盘)
audit_log: Arc<std::sync::Mutex<AuditLogger>>,
/// TLS 指纹识别(JA3/JA4)记录
fingerprints: Arc<std::sync::Mutex<Vec<Ja3Fingerprint>>>,
/// TLS 指纹拒绝列表(JA3 哈希值前缀匹配)
fingerprint_blocklist: Arc<std::sync::Mutex<Vec<String>>>,
/// TLS 指纹速率限制(JA3 hash → (窗口开始时间ms, 请求计数))
///
/// 64 分片独立 Mutex(与 zenith-cache 分片模式一致):按 fingerprint
/// 哈希取模路由,消除跨请求全局单锁争用;每桶窗口语义不变。
fingerprint_rate_limits: FpRateLimitShards,
/// 反向代理路由表(路径前缀 → 代理引擎 + 转发配置;经内部锁支持运行时注册)。
/// 引擎独立持锁:try_proxy 仅在匹配/借出/归还的短临界区持有引擎锁,
/// 网络 I/O 完全无锁(上游慢响应不冻结同管道其他代理请求)。
proxy_routes: Arc<std::sync::Mutex<Vec<ProxyRoute>>>,
/// 连续 5xx 计数器(超阈值触发 Supervisor Failed 熔断)
consecutive_5xx: Arc<std::sync::atomic::AtomicU64>,
/// 运行时热更新配置(无锁标量 + 仅 host 名单用 RwLock)。
///
/// ## 性能设计(热路径零锁/零竞争)
/// - 所有**标量旋钮**用 `AtomicU64`/`AtomicBool`:热路径单次原子加载
/// (一条指令,等价于普通读),**无锁、无竞争**。
/// - 仅两个 **host 名单**(`waf_enabled_hosts` / `waf_disabled_hosts`)
/// 可能含动态集合成员,用 `Arc<RwLock<Vec<String>>>`;但这些名单仅当
/// WAF 实际启用(`waf_enabled` 原子为 true)时才被读取,默认关闭时
/// `waf_enabled_for_host` 走原子快速路径,**完全不触碰锁**。
///
/// 热更新(写)频率极低,采用 `store`/写锁,不影响读热路径。
/// 本字段经 `SecurityPipeline::clone` 共享,运行时更新对所有副本立即生效。
runtime: Arc<RuntimeConfig>,
/// 反向代理运行参数(连接池/超时/健康阈值,全部可配置,支持运行时热更新)。
///
/// 经 `Arc<RwLock<ProxyConfig>>` 共享:`update_proxy_config`/`set_proxy_config`
/// 写低频;`add_proxy_route` 与请求路径在锁内读取当前值,热更新后对后续路由/
/// 请求立即生效,无需重建引擎/服务器。
proxy: Arc<std::sync::RwLock<ProxyConfig>>,
}
/// 运行时热更新配置(无锁标量 + 仅 host 名单用 RwLock)
///
/// 作为依赖库,这些运行参数支持**运行时热更新**(无需重建服务器):
/// 标量值经 `AtomicU64`/`AtomicBool` 无锁读写,host 名单经 `RwLock` 于
/// WAF 启用时读取。通过 [`SecurityPipeline::update_runtime`] 或
/// [`ProtocolServer::update_runtime`] 施加修改,对所有共享副本立即生效。
#[derive(Debug)]
pub struct RuntimeConfig {
/// 内置 WAF 是否启用(默认 false,严格按需)
waf_enabled: AtomicBool,
/// 按 host 强制启用 WAF 的白名单(小写域名)
waf_enabled_hosts: RwLock<Vec<String>>,
/// 按 host 跳过 WAF 的黑名单(小写域名)
waf_disabled_hosts: RwLock<Vec<String>>,
/// TLS 指纹安全控制(JA3/JA4 黑名单 + 速率限制)是否启用(默认关闭)
fingerprint_security_enabled: AtomicBool,
/// TLS 指纹黑名单匹配策略(运行期热更新,读写锁保护)
fingerprint_match: RwLock<FingerprintMatch>,
/// TLS 指纹速率限制:每个窗口内每个 JA3 指纹最大请求数
fingerprint_rate_limit_requests: AtomicU64,
/// TLS 指纹速率限制时间窗口(毫秒)
fingerprint_rate_limit_window_ms: AtomicU64,
/// WAF 大 body 卸载阈值(字节)
waf_offload_body_threshold: AtomicU64,
/// WAF 卸载执行期限(毫秒)
waf_offload_deadline_ms: AtomicU64,
/// L4 UDP 转发会话数上限
udp_max_sessions: AtomicU64,
/// L4 UDP 转发会话空闲超时(毫秒)
udp_session_idle_timeout_ms: AtomicU64,
/// L4 UDP 转发会话清理超时(毫秒)
udp_session_cleanup_timeout_ms: AtomicU64,
/// L4 转发会话超时(毫秒)
forward_session_timeout_ms: AtomicU64,
/// Supervisor 连续 5xx 熔断阈值
supervisor_max_consecutive_5xx: AtomicU64,
/// 单条 HTTP/1.1 连接最多处理的请求数(keep-alive 上限)
http1_max_requests_per_conn: AtomicU64,
/// HTTP/1.1 空闲超时(毫秒),防止 Slowloris 攻击
http1_idle_timeout_ms: AtomicU64,
/// 最大请求体大小(字节),超过返回 413
max_body_size: AtomicU64,
/// 读缓冲区大小(字节)
read_buffer_size: AtomicU64,
/// 写缓冲区初始容量(字节)
write_buffer_size: AtomicU64,
/// HTTP/2 最大帧大小(RFC 7540 §6.5.2,范围 16384..=16777215,可运行时热更新)
http2_max_frame_size: AtomicU64,
/// HTTP/2 单连接并发流上限(可运行时热更新)
http2_max_concurrent_streams: AtomicU64,
/// HTTP/3 头部字段段最大字节数(QPACK 解码上限,可运行时热更新)
http3_max_field_section_size: AtomicU64,
/// /metrics 端点认证令牌(None = 端点不可访问;可运行时热更新)
metrics_auth_token: RwLock<Option<String>>,
/// 监听地址(启用 :authority/Host 显式端口一致性检查 → 421;可运行时热更新)。
///
/// 注意:实际 socket 监听由调用方持有;本值驱动内置的端口一致性检查和
/// 逻辑标识,热更新后对**新连接**生效(每连接读取一次)。
bind_addr: RwLock<Option<SocketAddr>>,
/// 监听地址快速路径开关(`bind_addr.is_some()`):默认关闭时热路径仅一次
/// `AtomicBool::load` 即跳过端口检查,**零锁**;仅启用时才触碰 `bind_addr` 读锁。
bind_enabled: AtomicBool,
}
impl RuntimeConfig {
/// 从 `ServerConfig` 初始化运行时配置(原子化存储)
fn from_server_config(config: &ServerConfig) -> Self {
Self {
waf_enabled: AtomicBool::new(config.waf_enabled),
waf_enabled_hosts: RwLock::new(config.waf_enabled_hosts.clone()),
waf_disabled_hosts: RwLock::new(config.waf_disabled_hosts.clone()),
fingerprint_security_enabled: AtomicBool::new(config.fingerprint_security_enabled),
fingerprint_match: RwLock::new(config.fingerprint_match),
fingerprint_rate_limit_requests: AtomicU64::new(config.fingerprint_rate_limit_requests as u64),
fingerprint_rate_limit_window_ms: AtomicU64::new(config.fingerprint_rate_limit_window_ms),
waf_offload_body_threshold: AtomicU64::new(config.waf_offload_body_threshold as u64),
waf_offload_deadline_ms: AtomicU64::new(config.waf_offload_deadline_ms),
udp_max_sessions: AtomicU64::new(config.udp_max_sessions as u64),
udp_session_idle_timeout_ms: AtomicU64::new(config.udp_session_idle_timeout_ms),
udp_session_cleanup_timeout_ms: AtomicU64::new(config.udp_session_cleanup_timeout_ms),
forward_session_timeout_ms: AtomicU64::new(config.forward_session_timeout_ms),
supervisor_max_consecutive_5xx: AtomicU64::new(config.supervisor_max_consecutive_5xx),
http1_max_requests_per_conn: AtomicU64::new(config.http1_max_requests_per_conn as u64),
http1_idle_timeout_ms: AtomicU64::new(config.http1_idle_timeout_ms),
max_body_size: AtomicU64::new(config.max_body_size as u64),
read_buffer_size: AtomicU64::new(config.read_buffer_size as u64),
write_buffer_size: AtomicU64::new(config.write_buffer_size as u64),
http2_max_frame_size: AtomicU64::new(config.http2_max_frame_size as u64),
http2_max_concurrent_streams: AtomicU64::new(config.http2_max_concurrent_streams as u64),
http3_max_field_section_size: AtomicU64::new(config.http3_max_field_section_size),
metrics_auth_token: RwLock::new(config.metrics_auth_token.clone()),
bind_addr: RwLock::new(config.bind_addr),
bind_enabled: AtomicBool::new(config.bind_addr.is_some()),
}
}
/// 读取当前配置快照(调试/观测用;热路径不调用本方法)
pub fn snapshot(&self) -> RuntimeSnapshot {
RuntimeSnapshot {
waf_enabled: self.waf_enabled.load(Ordering::Acquire),
waf_enabled_hosts: read_recover(&self.waf_enabled_hosts).clone(),
waf_disabled_hosts: read_recover(&self.waf_disabled_hosts).clone(),
fingerprint_security_enabled: self.fingerprint_security_enabled.load(Ordering::Acquire),
fingerprint_rate_limit_requests: self.fingerprint_rate_limit_requests.load(Ordering::Acquire) as u32,
fingerprint_rate_limit_window_ms: self.fingerprint_rate_limit_window_ms.load(Ordering::Acquire),
waf_offload_body_threshold: self.waf_offload_body_threshold.load(Ordering::Acquire) as usize,
waf_offload_deadline_ms: self.waf_offload_deadline_ms.load(Ordering::Acquire),
udp_max_sessions: self.udp_max_sessions.load(Ordering::Acquire) as usize,
udp_session_idle_timeout_ms: self.udp_session_idle_timeout_ms.load(Ordering::Acquire),
udp_session_cleanup_timeout_ms: self.udp_session_cleanup_timeout_ms.load(Ordering::Acquire),
forward_session_timeout_ms: self.forward_session_timeout_ms.load(Ordering::Acquire),
supervisor_max_consecutive_5xx: self.supervisor_max_consecutive_5xx.load(Ordering::Acquire),
http1_max_requests_per_conn: self.http1_max_requests_per_conn.load(Ordering::Acquire) as u32,
http1_idle_timeout_ms: self.http1_idle_timeout_ms.load(Ordering::Acquire),
max_body_size: self.max_body_size.load(Ordering::Acquire) as usize,
read_buffer_size: self.read_buffer_size.load(Ordering::Acquire) as usize,
write_buffer_size: self.write_buffer_size.load(Ordering::Acquire) as usize,
http2_max_frame_size: self.http2_max_frame_size.load(Ordering::Acquire) as u32,
http2_max_concurrent_streams: self
.http2_max_concurrent_streams
.load(Ordering::Acquire) as u32,
http3_max_field_section_size: self
.http3_max_field_section_size
.load(Ordering::Acquire),
metrics_auth_token: read_recover(&self.metrics_auth_token).clone(),
bind_addr: *read_recover(&self.bind_addr),
}
}
}
/// [`RuntimeConfig::snapshot`] 返回的运行时配置只读快照
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeSnapshot {
/// 内置 WAF 是否启用
pub waf_enabled: bool,
/// 按 host 强制启用 WAF 的白名单(小写域名)
pub waf_enabled_hosts: Vec<String>,
/// 按 host 跳过 WAF 的黑名单(小写域名)
pub waf_disabled_hosts: Vec<String>,
/// TLS 指纹安全控制是否启用
pub fingerprint_security_enabled: bool,
/// TLS 指纹速率限制:每个窗口内每个 JA3 指纹最大请求数
pub fingerprint_rate_limit_requests: u32,
/// TLS 指纹速率限制时间窗口(毫秒)
pub fingerprint_rate_limit_window_ms: u64,
/// WAF 大 body 卸载阈值(字节)
pub waf_offload_body_threshold: usize,
/// WAF 卸载执行期限(毫秒)
pub waf_offload_deadline_ms: u64,
/// L4 UDP 转发会话数上限
pub udp_max_sessions: usize,
/// L4 UDP 转发会话空闲超时(毫秒)
pub udp_session_idle_timeout_ms: u64,
/// L4 UDP 转发会话清理超时(毫秒)
pub udp_session_cleanup_timeout_ms: u64,
/// L4 转发会话超时(毫秒)
pub forward_session_timeout_ms: u64,
/// Supervisor 连续 5xx 熔断阈值
pub supervisor_max_consecutive_5xx: u64,
/// 单条 HTTP/1.1 连接最多处理的请求数(keep-alive 上限)
pub http1_max_requests_per_conn: u32,
/// HTTP/1.1 空闲超时(毫秒)
pub http1_idle_timeout_ms: u64,
/// 最大请求体大小(字节)
pub max_body_size: usize,
/// 读缓冲区大小(字节)
pub read_buffer_size: usize,
/// 写缓冲区初始容量(字节)
pub write_buffer_size: usize,
/// HTTP/2 最大帧大小(RFC 7540,范围 16384..=16777215)
pub http2_max_frame_size: u32,
/// HTTP/2 单连接并发流上限
pub http2_max_concurrent_streams: u32,
/// HTTP/3 头部字段段最大字节数(QPACK 解码上限)
pub http3_max_field_section_size: u64,
/// /metrics 端点认证令牌(None = 端点不可访问)
pub metrics_auth_token: Option<String>,
/// 监听地址(enable :authority/Host 显式端口一致性检查;None = 不检查)
pub bind_addr: Option<SocketAddr>,
}
/// 运行时热更新描述符:对 [`RuntimeConfig`] 各旋钮施加修改的便捷句柄。
///
/// 由 [`SecurityPipeline::update_runtime`] / [`ProtocolServer::update_runtime`]
/// 传入闭包。标量经 `AtomicU64::store`(Relaxed,写频率极低),host 名单经
/// `RwLock` 写锁施加,全部无需重建服务器。
pub struct RuntimeConfigRef<'a> {
config: &'a RuntimeConfig,
}
impl fmt::Debug for RuntimeConfigRef<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RuntimeConfigRef").finish_non_exhaustive()
}
}
impl RuntimeConfigRef<'_> {
/// 全局开关:启用/关闭内置 WAF
#[inline]
pub fn set_waf_enabled(&self, enabled: bool) {
self.config.waf_enabled.store(enabled, Ordering::Relaxed);
}
/// 按 host 强制启用 WAF(追加到白名单,幂等)
#[inline]
pub fn enable_waf_for_host(&self, host: &str) {
let host = host.to_ascii_lowercase();
let mut list = write_recover(&self.config.waf_enabled_hosts);
if !list.iter().any(|h| h.eq_ignore_ascii_case(&host)) {
list.push(host);
}
}
/// 按 host 移除 WAF 强制启用(从白名单删除)
#[inline]
pub fn disable_waf_for_host(&self, host: &str) {
let mut list = write_recover(&self.config.waf_enabled_hosts);
list.retain(|h| !h.eq_ignore_ascii_case(host));
}
/// 按 host 跳过 WAF(追加到黑名单,幂等)
#[inline]
pub fn bypass_waf_for_host(&self, host: &str) {
let host = host.to_ascii_lowercase();
let mut list = write_recover(&self.config.waf_disabled_hosts);
if !list.iter().any(|h| h.eq_ignore_ascii_case(&host)) {
list.push(host);
}
}
/// 按 host 恢复 WAF(从黑名单删除)
#[inline]
pub fn unbypass_waf_for_host(&self, host: &str) {
let mut list = write_recover(&self.config.waf_disabled_hosts);
list.retain(|h| !h.eq_ignore_ascii_case(host));
}
/// 一键覆写 host 黑白名单(原子替换整个集合)
#[inline]
pub fn set_waf_host_lists(&self, enabled: Vec<String>, disabled: Vec<String>) {
*write_recover(&self.config.waf_enabled_hosts) = enabled;
*write_recover(&self.config.waf_disabled_hosts) = disabled;
}
/// 启用/关闭 TLS 指纹安全控制(黑名单 + 速率限制)
#[inline]
pub fn set_fingerprint_security(&self, enabled: bool) {
self.config
.fingerprint_security_enabled
.store(enabled, Ordering::Relaxed);
}
/// 运行时热更新 TLS 指纹黑名单匹配策略(对新连接生效)。
///
/// 可按需自由在 JA3 / JA4 / 两者任一 / 两者都命中 之间切换。
#[inline]
pub fn set_fingerprint_match(&self, mode: FingerprintMatch) {
*write_recover(&self.config.fingerprint_match) = mode;
}
/// 设置 TLS 指纹速率限制(每窗口每 JA3 最大请求数 + 窗口毫秒)
#[inline]
pub fn set_fingerprint_rate_limit(&self, requests: u32, window_ms: u64) {
self.config
.fingerprint_rate_limit_requests
.store(requests as u64, Ordering::Relaxed);
self.config
.fingerprint_rate_limit_window_ms
.store(window_ms, Ordering::Relaxed);
}
/// 设置 WAF 大 body 卸载阈值(字节)与执行期限(毫秒)
#[inline]
pub fn set_waf_offload(&self, body_threshold: usize, deadline_ms: u64) {
self.config
.waf_offload_body_threshold
.store(body_threshold as u64, Ordering::Relaxed);
self.config
.waf_offload_deadline_ms
.store(deadline_ms, Ordering::Relaxed);
}
/// 设置 L4 UDP 转发会话数上限
#[inline]
pub fn set_udp_max_sessions(&self, n: usize) {
self.config.udp_max_sessions.store(n as u64, Ordering::Relaxed);
}
/// 设置 L4 UDP 转发会话空闲超时(毫秒)
#[inline]
pub fn set_udp_session_idle_timeout_ms(&self, ms: u64) {
self.config
.udp_session_idle_timeout_ms
.store(ms, Ordering::Relaxed);
}
/// 设置 L4 UDP 转发会话清理超时(毫秒)
#[inline]
pub fn set_udp_session_cleanup_timeout_ms(&self, ms: u64) {
self.config
.udp_session_cleanup_timeout_ms
.store(ms, Ordering::Relaxed);
}
/// 设置 L4 转发会话超时(毫秒)
#[inline]
pub fn set_forward_session_timeout_ms(&self, ms: u64) {
self.config
.forward_session_timeout_ms
.store(ms, Ordering::Relaxed);
}
/// 设置 Supervisor 连续 5xx 熔断阈值
#[inline]
pub fn set_supervisor_max_consecutive_5xx(&self, n: u64) {
self.config
.supervisor_max_consecutive_5xx
.store(n, Ordering::Relaxed);
}
/// 设置单条 HTTP/1.1 连接最多处理的请求数(keep-alive 上限)
#[inline]
pub fn set_http1_max_requests_per_conn(&self, n: u32) {
self.config
.http1_max_requests_per_conn
.store(n as u64, Ordering::Relaxed);
}
/// 设置 HTTP/1.1 空闲超时(毫秒)
#[inline]
pub fn set_http1_idle_timeout_ms(&self, ms: u64) {
self.config
.http1_idle_timeout_ms
.store(ms, Ordering::Relaxed);
}
/// 设置最大请求体大小(字节)
#[inline]
pub fn set_max_body_size(&self, bytes: usize) {
self.config.max_body_size.store(bytes as u64, Ordering::Relaxed);
}
/// 设置读缓冲区大小(字节)
#[inline]
pub fn set_read_buffer_size(&self, bytes: usize) {
self.config
.read_buffer_size
.store(bytes as u64, Ordering::Relaxed);
}
/// 设置写缓冲区初始容量(字节)
#[inline]
pub fn set_write_buffer_size(&self, bytes: usize) {
self.config
.write_buffer_size
.store(bytes as u64, Ordering::Relaxed);
}
/// 设置 HTTP/2 最大帧大小(RFC 7540 范围 16384..=16777215,热更新钳制)
#[inline]
pub fn set_http2_max_frame_size(&self, size: u32) {
self.config
.http2_max_frame_size
.store((size.clamp(16_384, 16_777_215)) as u64, Ordering::Relaxed);
}
/// 设置 HTTP/2 单连接并发流上限
#[inline]
pub fn set_http2_max_concurrent_streams(&self, n: u32) {
self.config
.http2_max_concurrent_streams
.store(n as u64, Ordering::Relaxed);
}
/// 设置 HTTP/3 头部字段段最大字节数(QPACK 解码上限)
#[inline]
pub fn set_http3_max_field_section_size(&self, size: u64) {
self.config
.http3_max_field_section_size
.store(size, Ordering::Relaxed);
}
/// 设置 /metrics 端点认证令牌(None = 端点不可访问,返回 404)
#[inline]
pub fn set_metrics_auth_token(&self, token: Option<String>) {
*write_recover(&self.config.metrics_auth_token) = token;
}
/// 设置监听地址(启用/禁用/更改 :authority/Host 端口一致性检查 → 421)。
///
/// 实际 socket 监听由调用方持有;本值仅驱动内置端口一致性检查与逻辑标识,
/// 热更新后对**新连接**生效(每连接读取一次)。
#[inline]
pub fn set_bind_addr(&self, addr: Option<SocketAddr>) {
*write_recover(&self.config.bind_addr) = addr;
self.config.bind_enabled.store(addr.is_some(), Ordering::Relaxed);
}
}
impl Clone for SecurityPipeline {
fn clone(&self) -> Self {
Self {
waf: self.waf.clone(),
cache: self.cache.clone(),
metrics: self.metrics.clone(),
permissions: self.permissions,
#[cfg(feature = "runtime")]
supervisor: self.supervisor.clone(),
#[cfg(feature = "runtime")]
changeset: self.changeset.clone(),
#[cfg(feature = "runtime")]
task_channel: self.task_channel.clone(),
#[cfg(feature = "runtime")]
offload_worker: self.offload_worker.clone(),
#[cfg(feature = "runtime")]
offload_submit_lock: self.offload_submit_lock.clone(),
#[cfg(feature = "runtime")]
offload_next_task_id: self.offload_next_task_id.clone(),
forward_engine: self.forward_engine.clone(),
audit_log: self.audit_log.clone(),
fingerprints: self.fingerprints.clone(),
fingerprint_blocklist: self.fingerprint_blocklist.clone(),
fingerprint_rate_limits: self.fingerprint_rate_limits.clone(),
proxy_routes: self.proxy_routes.clone(),
consecutive_5xx: self.consecutive_5xx.clone(),
runtime: Arc::clone(&self.runtime),
proxy: self.proxy.clone(),
}
}
}
impl std::fmt::Debug for SecurityPipeline {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SecurityPipeline").finish_non_exhaustive()
}
}
impl SecurityPipeline {
fn new(config: &ServerConfig) -> Self {
let mut permissions = PermissionSet::new();
permissions.add(Capability::NetworkAccess);
permissions.add(Capability::NetworkBind);
let waf = Arc::new(std::sync::RwLock::new(WafEngine::new().with_default_detectors()));
#[cfg(feature = "runtime")]
let task_channel = Arc::new(TaskOffloadChannel::new(1));
// 真实消费线程:drain 通道执行大 body WAF 检查(drop 时优雅退出)
#[cfg(feature = "runtime")]
let offload_worker = Arc::new(OffloadWorker::spawn(task_channel.clone(), waf.clone()));
// Supervisor 真实接入:web 域注册到 Node(5xx 反馈降级,成功反馈恢复)
#[cfg(feature = "runtime")]
let mut node = NodeSupervisor::new(1);
#[cfg(feature = "runtime")]
if let Err(e) = node.spawn_domain(WEB_DOMAIN_ID) {
// 全新节点注册唯一域不会失败;失败仅记录(fail-visible),门控按 Running 放行
tracing::error!("supervisor spawn_domain failed: {e}");
}
Self {
waf,
cache: Arc::new(std::sync::Mutex::new(CacheEngine::new(
config.cache_max_entries,
config.cache_max_size_bytes,
))),
metrics: Arc::new(std::sync::Mutex::new(MetricsCollector::new())),
permissions,
#[cfg(feature = "runtime")]
supervisor: Arc::new(std::sync::Mutex::new(node)),
#[cfg(feature = "runtime")]
changeset: Arc::new(std::sync::Mutex::new(ChangeSet::new(0, 1))),
#[cfg(feature = "runtime")]
task_channel,
#[cfg(feature = "runtime")]
offload_worker,
#[cfg(feature = "runtime")]
offload_submit_lock: Arc::new(std::sync::Mutex::new(())),
#[cfg(feature = "runtime")]
offload_next_task_id: Arc::new(std::sync::atomic::AtomicU64::new(1)),
forward_engine: Arc::new(std::sync::Mutex::new(ForwardEngine::with_config(
config.forward,
))),
audit_log: Arc::new(std::sync::Mutex::new(AuditLogger::new())),
fingerprints: Arc::new(std::sync::Mutex::new(Vec::new())),
fingerprint_blocklist: Arc::new(std::sync::Mutex::new(Vec::new())),
fingerprint_rate_limits: Arc::new(std::array::from_fn(|_| {
std::sync::Mutex::new(FxHashMap::default())
})),
proxy_routes: Arc::new(std::sync::Mutex::new(Vec::new())),
consecutive_5xx: Arc::new(std::sync::atomic::AtomicU64::new(0)),
// 运行时热更新配置:原子化存储,默认关闭(严格按需)
runtime: Arc::new(RuntimeConfig::from_server_config(config)),
proxy: Arc::new(std::sync::RwLock::new(config.proxy.clone())),
}
}
/// 读取运行时配置快照(观测用;热路径不使用)
#[inline]
pub fn runtime_snapshot(&self) -> RuntimeSnapshot {
self.runtime.snapshot()
}
/// 读取监听地址(运行时热更新;默认关闭时零锁快速路径)。
///
/// 仅一次 `AtomicBool::load` 即跳过(`bind_addr` 未配置时),启用时才取读锁。
#[inline]
pub fn runtime_bind_addr(&self) -> Option<SocketAddr> {
if self.runtime.bind_enabled.load(Ordering::Relaxed) {
*read_recover(&self.runtime.bind_addr)
} else {
None
}
}
/// 运行时热更新内置缓存容量(全局条目数 / 字节数)。
///
/// 无锁原子 `store`(写频率极低),热路径 `put` 每写入一次原子加载;
/// 已存在条目不会立即淘汰,新淘汰从下次写入压力生效。无需重建引擎/服务器。
#[inline]
pub fn set_cache_capacity(&self, max_entries: usize, max_size_bytes: usize) {
lock_recover(&self.cache).set_capacity(max_entries, max_size_bytes);
}
/// 运行时热更新 L4 转发引擎参数(并发会话上限 / 单会话带宽)。
///
/// 引擎经锁持有,此写为低频 `set_config`;热路径 `create_session`/`reset_bandwidth`
/// 在锁内读取当前配置,热更新后对后续会话/配额立即生效,无需重建引擎/服务器。
#[inline]
pub fn set_forward_config(&self, config: zenith_forward::ForwardConfig) {
lock_recover(&self.forward_engine).set_config(config);
}
/// 读取当前 L4 转发引擎参数(观测)。
#[inline]
pub fn forward_config(&self) -> zenith_forward::ForwardConfig {
lock_recover(&self.forward_engine).config()
}
/// 运行时热更新反向代理运行参数(连接池/超时/健康阈值)。
///
/// `f` 收到 `&mut ProxyConfig`,可对任意字段独立赋值。写低频(RwLock 写锁);
/// 请求路径的转发超时(connect/read/H3/auto-TLS)每请求读取当前值,对既有路由
/// 立即生效;连接池/健康阈值对后续 `add_proxy_route` 注册的路由生效。无需重建引擎。
#[inline]
pub fn update_proxy_config(&self, f: impl FnOnce(&mut ProxyConfig)) {
f(&mut write_recover(&self.proxy));
}
/// 整体替换反向代理运行参数(热更新)。
#[inline]
pub fn set_proxy_config(&self, config: ProxyConfig) {
*write_recover(&self.proxy) = config;
}
/// 读取当前反向代理运行参数(观测)。
#[inline]
pub fn proxy_config(&self) -> ProxyConfig {
read_recover(&self.proxy).clone()
}
/// 运行时热更新配置(无锁标量 + host 名单写锁)。
///
/// `f` 收到 [`RuntimeConfigRef`] 描述符,可对每个旋钮独立赋值/追加/移除。
/// 所有修改经原子 `store`(标量)或写锁(host 名单)施加,对 `SecurityPipeline`
/// 的所有共享副本立即生效,**无需重建服务器**。写频率极低,不影响读热路径。
///
/// # 示例
/// ```rust,ignore
/// server.update_runtime(|r| {
/// r.set_waf_enabled(true);
/// r.enable_waf_for_host("api.example.com");
/// r.set_fingerprint_rate_limit(200, 30_000);
/// });
/// ```
#[inline]
pub fn update_runtime(&self, f: impl FnOnce(&RuntimeConfigRef<'_>)) {
f(&RuntimeConfigRef { config: &self.runtime });
}
/// 判断给定 host 是否应启用 WAF(全局开关 + 按 host 黑白名单合成)。
///
/// 判定规则:`(waf_enabled || host ∈ waf_enabled_hosts) && host ∉ waf_disabled_hosts`。
/// host 传入前已由调用方小写化;此处做大小写不敏感比较兜底。
///
/// ## 性能
/// 默认(WAF 关闭且名单为空)时仅一次 `AtomicBool::load` 即返回,**零锁**;
/// 仅当 WAF 启用或名单非空时才触碰 host 名单的 `RwLock` 读锁。
pub fn waf_enabled_for_host(&self, host: &str) -> bool {
let rt = &self.runtime;
let enable = rt.waf_enabled.load(Ordering::Acquire)
|| read_recover(&rt.waf_enabled_hosts)
.iter()
.any(|h| h.eq_ignore_ascii_case(host));
if !enable {
return false;
}
!read_recover(&rt.waf_disabled_hosts)
.iter()
.any(|h| h.eq_ignore_ascii_case(host))
}
/// 注册反向代理路由(路径前缀 → 上游集合 + 负载均衡策略)
///
/// 前缀匹配规则:`path == prefix` 或 `path` 以 `prefix + "/"` 开头
/// (防止 `/api` 误匹配 `/apix`)。命中前缀的请求在 Cache 查询之后、
/// App 处理之前被转发到上游;转发路径为原始 path+query(v1 语义,不做前缀剥离)。
pub fn add_proxy_route(
&self,
prefix: &str,
upstreams: Vec<(String, u32)>,
strategy: LoadBalanceStrategy,
) {
// 引擎与转发配置均取自当前 ProxyConfig(连接池/超时/健康全可配置,支持热更新)
let cfg = read_recover(&self.proxy);
let mut engine = ProxyEngine::with_config(strategy, &cfg);
engine.set_upstreams(upstreams);
let fwd = ForwardConfig::new()
.with_connect_timeout_ms(cfg.forward_connect_timeout_ms)
.with_read_timeout_ms(cfg.forward_read_timeout_ms)
.with_max_response_bytes(cfg.forward_max_response_bytes)
.with_h3_request_timeout_ms(cfg.h3_request_timeout_ms)
.with_auto_tls_handshake_timeout_ms(cfg.auto_tls_handshake_timeout_ms);
drop(cfg);
let mut routes = lock_recover(&self.proxy_routes);
routes.push((prefix.to_string(), Arc::new(std::sync::Mutex::new(engine)), fwd));
}
/// 统一健康反馈(三条请求路径共用):5xx 计数 + 超阈值触发 Failed 熔断
///
/// - 正常响应(< 500):重置计数器,Supervisor 恢复 Running
/// - 5xx 响应:计数器 +1,Supervisor 置 Degraded;
/// 连续 5xx 超 `supervisor_max_consecutive_5xx` 时调用 `restart_domain`
/// 触发 Failed 熔断(后续请求直接 503,直到手动恢复)
fn report_health(&self, healthy: bool) {
// runtime 特性关闭时无 Supervisor 可反馈:仅保留计数器语义(零成本 no-op 门控)
#[cfg(not(feature = "runtime"))]
let _ = healthy;
#[cfg(feature = "runtime")]
{
use std::sync::atomic::Ordering;
if healthy {
self.consecutive_5xx.store(0, Ordering::Relaxed);
} else {
let count = self.consecutive_5xx.fetch_add(1, Ordering::Relaxed) + 1;
if count >= self.runtime.supervisor_max_consecutive_5xx.load(Ordering::Relaxed) {
// 连续 5xx 超阈值:触发 Failed 熔断(restart_domain 内部置 Failed)
let mut sup = lock_recover(&self.supervisor);
match sup.restart_domain(WEB_DOMAIN_ID, zenith_runtime::ExitReason::Abnormal) {
Ok(backoff) => {
tracing::error!(
"supervisor: 连续 {} 次 5xx,触发 Failed 熔断(backoff {:?})",
count, backoff
);
self.audit(
"SUPERVISOR_FAILED",
&format!("consecutive_5xx={count} backoff={backoff:?}"),
);
}
Err(e) => {
tracing::error!("supervisor restart_domain failed: {e}");
}
}
// 重置计数器(熔断后重新计数,避免重复触发)
self.consecutive_5xx.store(0, Ordering::Relaxed);
return;
}
}
// 常规反馈:healthy → Running,5xx → Degraded
let mut sup = lock_recover(&self.supervisor);
if let Err(e) = sup.mark_domain_healthy(WEB_DOMAIN_ID, healthy) {
tracing::error!("supervisor mark_domain_healthy failed: {e}");
}
}
}
/// 反向代理转发(请求路径在 Cache 查询之后、App 处理之前调用)
///
/// 命中前缀路由时:
/// 1. `select_upstream` 负载均衡选上游(无健康上游 → 502)
/// 2. `forward_request` 真实 TCP 转发(Host 头透传原始值,
/// 附加 `x-forwarded-for` = 客户端 IP 与 `x-forwarded-proto` = 原始协议)
/// 3. 成功返回上游响应(记录 `proxy_upstream_success` 指标);
/// 失败返回 502 JSON(记录 `proxy_upstream_error` 指标 + PROXY_ERROR 审计)
///
/// 未命中任何路由返回 None,请求继续流向 Supervisor 检查与 App。
///
/// # 锁域(禁锁跨 I/O)
/// 1. 路由表锁:仅前缀匹配(克隆引擎 Arc + 配置后立即释放)
/// 2. 引擎锁短临界区 A:`begin_forward` 选上游 + 借出连接(纯记账)
/// 3. **无锁** `forward_lease_io`:connect + 请求/响应往返(上游慢响应只影响本请求)
/// 4. 引擎锁短临界区 B:`finish_forward` 归还/丢弃池条目 + 熔断记账
#[allow(clippy::too_many_arguments)]
fn try_proxy(
&self,
method: &str,
path: &str,
query: &str,
host: &str,
headers: &FxHashMap<&str, &str>,
body: &[u8],
client_ip: &str,
proto: &str,
) -> Option<CanonicalResponse> {
// 阶段 0:前缀匹配(path == prefix 或 path 以 prefix + "/" 开头)
let (prefix, engine_arc) = {
let routes = lock_recover(&self.proxy_routes);
routes
.iter()
.find(|(p, _, _)| {
path == p
|| (path.len() > p.len()
&& path.starts_with(p.as_str())
&& path.as_bytes()[p.len()] == b'/')
})
.map(|(p, e, _)| (p.clone(), Arc::clone(e)))?
};
// 热更新:每请求转发超时取当前 ProxyConfig(而非路由登记时的冻结值),
// 使 connect/read/H3/auto-TLS 超时对既有路由即时生效,无需重建引擎。
let config = {
let cfg = read_recover(&self.proxy);
ForwardConfig::new()
.with_connect_timeout_ms(cfg.forward_connect_timeout_ms)
.with_read_timeout_ms(cfg.forward_read_timeout_ms)
.with_max_response_bytes(cfg.forward_max_response_bytes)
.with_h3_request_timeout_ms(cfg.h3_request_timeout_ms)
.with_auto_tls_handshake_timeout_ms(cfg.auto_tls_handshake_timeout_ms)
};
// 阶段 1(引擎锁短临界区):选上游 + 提取地址 + 借出连接(纯记账,零 I/O)
let (mut lease, addr, auto_health) = {
let mut engine = lock_recover(&engine_arc);
// 1. 负载均衡选上游(无健康上游 → 502,fail-closed)
//
// LB 键 = client_ip(与策略语义对齐):
// - IpHash / Rendezvous / 一致性哈希类策略:客户端粘性(同一
// 客户端稳定落到同一上游)—— 修复前用 path 做键 = 路径粘性,
// 与 IpHash 语义相反(同一客户端不同路径会落到不同上游);
// - RoundRobin / P2C / LeastConn:对键不敏感(行为等价不变)。
let Some(upstream_id) = engine.select_upstream(client_ip.as_bytes()) else {
drop(engine);
self.record_counter("proxy_upstream_error", 1);
self.audit(
"PROXY_ERROR",
&format!("prefix={prefix} path={path} reason=no_healthy_upstream"),
);
return Some(Self::bad_gateway_response());
};
let Some(addr) = engine.get_upstream(upstream_id).map(|u| u.address.clone()) else {
// select 与 get 之间拓扑不会变化(同一把锁);防御性 fail-closed
drop(engine);
self.record_counter("proxy_upstream_error", 1);
self.audit(
"PROXY_ERROR",
&format!("prefix={prefix} path={path} reason=upstream_vanished"),
);
return Some(Self::bad_gateway_response());
};
match engine.begin_forward(upstream_id) {
Ok(l) => {
// Auto 上游:引擎锁内克隆共享健康状态 Arc(无锁 AtomicU64 位域),
// 锁外安全传给无锁 forward_lease_io(AutoPathHealth 生命周期随 Arc)。
let auto_health =
if matches!(l.scheme(), zenith_proxy::scheme::UpstreamScheme::Auto) {
engine.auto_path_health(upstream_id)
} else {
None
};
(l, addr, auto_health)
}
Err(e) => {
drop(engine);
self.record_counter("proxy_upstream_error", 1);
self.audit(
"PROXY_ERROR",
&format!("prefix={prefix} path={path} error={e}"),
);
return Some(Self::bad_gateway_response());
}
}
};
// 2. 构造转发请求:透传头剔除 host / 逐跳头 / content-length
// (由客户端编码器重建),剔除入站 XFF/XFP(防伪造)。
// X-Forwarded-For 由 forward_inner_generic 根据 client_ip 参数自动添加,
// X-Forwarded-Proto 在此处附加(forward 层不感知原始协议)。
// owned 仅发生于代理分支(非每请求路径)
let mut fwd_headers: Vec<(String, String)> = headers
.iter()
.filter(|(n, _)| {
!n.eq_ignore_ascii_case("host")
&& !n.eq_ignore_ascii_case("content-length")
&& !n.eq_ignore_ascii_case("x-forwarded-for")
&& !n.eq_ignore_ascii_case("x-forwarded-proto")
&& !is_hop_by_hop(n)
})
.map(|(n, v)| ((*n).to_string(), (*v).to_string()))
.collect();
// 剥离入站 XFF/XFP 后附加可信值(防客户端伪造)
fwd_headers.push(("x-forwarded-proto".to_string(), proto.to_string()));
// v1 语义:转发原始 path+query,不做前缀剥离
let path_with_query = if query.is_empty() {
path.to_string()
} else {
format!("{path}?{query}")
};
// 阶段 2(无锁网络 I/O):连接 + 转发往返,不持有任何路由/引擎锁
let outcome = ProxyEngine::forward_lease_io(
&mut lease,
&addr,
method,
&path_with_query,
host,
&fwd_headers,
body,
&config,
auto_health.as_deref(),
Some(client_ip),
);
// 阶段 3 前快照协议归属(lease 随后被 finish_forward 消费)
let protocol_used = lease.protocol_used;
let scheme = lease.scheme();
// 阶段 3(引擎锁短临界区):归还/丢弃池条目 + 熔断记账
let result = {
let mut engine = lock_recover(&engine_arc);
engine.finish_forward(lease, outcome)
};
match result {
Ok(resp) => {
self.record_counter("proxy_upstream_success", 1);
// 协议级闭环观测:按实际使用协议细分成功计数
self.record_counter(proxy_success_metric(protocol_used), 1);
// 自动最优路径闭环观测:Auto 上游最终以 h1 路径成功
// (ALPN 协商 http/1.1 或 H2 降级),审计可观测该路径选择
if scheme == zenith_proxy::scheme::UpstreamScheme::Auto
&& protocol_used == Some("http/1.1")
{
self.audit(
"PROXY_AUTO_HTTP11",
&format!("prefix={prefix} path={path}"),
);
}
Some(resp)
}
Err(e) => {
self.record_counter("proxy_upstream_error", 1);
self.record_counter(proxy_error_metric(protocol_used), 1);
self.audit(
"PROXY_ERROR",
&format!("prefix={prefix} path={path} error={e}"),
);
Some(Self::bad_gateway_response())
}
}
}
/// 构造 502 Bad Gateway JSON 响应(上游不可用 / 转发失败统一出口)
fn bad_gateway_response() -> CanonicalResponse {
let mut resp = CanonicalResponse::new(502);
resp.set_body(b"{\"error\":\"bad_gateway\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
resp
}
/// 记录 TLS 指纹(JA3/JA4)
pub fn record_fingerprint(&self, fp: Ja3Fingerprint) {
let mut fps = lock_recover(&self.fingerprints);
if fps.len() < 10000 {
fps.push(fp);
}
}
/// 获取所有 TLS 指纹快照
pub fn fingerprint_snapshot(&self) -> Vec<Ja3Fingerprint> {
let fps = lock_recover(&self.fingerprints);
fps.clone()
}
/// 获取指纹数量
pub fn fingerprint_count(&self) -> usize {
lock_recover(&self.fingerprints).len()
}
/// 将 JA3 哈希前缀添加到拒绝列表
///
/// # 参数
/// - `ja3_prefix`: JA3 哈希前缀(支持前缀匹配,如 "abc123" 会拒绝所有以 "abc123" 开头的 JA3 哈希)
pub fn add_fingerprint_to_blocklist(&self, ja3_prefix: String) {
let mut blocklist = lock_recover(&self.fingerprint_blocklist);
if !blocklist.contains(&ja3_prefix) {
blocklist.push(ja3_prefix);
}
}
/// 清空指纹拒绝列表
pub fn clear_fingerprint_blocklist(&self) {
let mut blocklist = lock_recover(&self.fingerprint_blocklist);
blocklist.clear();
}
/// 获取指纹拒绝列表快照
pub fn fingerprint_blocklist_snapshot(&self) -> Vec<String> {
lock_recover(&self.fingerprint_blocklist).clone()
}
/// 从指纹拒绝列表移除单个 JA3 前缀(运行时热更新指纹阻断规则)
pub fn remove_fingerprint_from_blocklist(&self, ja3_prefix: &str) {
let mut blocklist = lock_recover(&self.fingerprint_blocklist);
blocklist.retain(|p| p != ja3_prefix);
}
// ── 防火墙(WAF)规则运行时热更新 ───────────────────────────
// WAF 引擎内部分片/规则本就经 RwLock 读多写少;以下方法经写锁热增删规则,
// 读热路径(check_waf 读锁并发)不受影响。
/// 运行时新增 WAF 规则(写锁施加,立即生效)
pub fn add_waf_rule(&self, rule: zenith_waf::CompiledRule) {
write_recover(&self.waf).add_rule(rule);
}
/// 运行时批量新增 WAF 规则(写锁施加,立即生效)
pub fn add_waf_rules<I>(&self, rules: I)
where
I: IntoIterator<Item = zenith_waf::CompiledRule>,
{
write_recover(&self.waf).add_rules(rules);
}
/// 运行时移除 WAF 规则(按规则 ID)
pub fn remove_waf_rule(&self, rule_id: &str) {
write_recover(&self.waf).remove_rule(rule_id);
}
/// 运行时启用/禁用 WAF 规则(按规则 ID)
pub fn set_waf_rule_enabled(&self, rule_id: &str, enabled: bool) {
write_recover(&self.waf).set_rule_enabled(rule_id, enabled);
}
/// 运行时清空全部 WAF 规则(写锁施加,立即生效)
pub fn clear_waf_rules(&self) {
write_recover(&self.waf).clear_rules();
}
/// 运行时清空全部 WAF 检测器(写锁施加,立即生效)
pub fn clear_waf_detectors(&self) {
write_recover(&self.waf).clear_detectors();
}
/// 运行时新增 WAF 检测器(写锁施加,立即生效)
pub fn add_waf_detector(&self, detector: Box<dyn zenith_waf::Detector>) {
write_recover(&self.waf).add_detector(detector);
}
/// 当前 WAF 规则数量(观测)
pub fn waf_rule_count(&self) -> usize {
read_recover(&self.waf).rule_count()
}
/// 检查 TLS 指纹是否在拒绝列表中
///
/// # 参数
/// - `fingerprint`: 当前连接的 JA3 指纹
///
/// # 返回
/// - `Some(reason)`: 被拒绝,返回拒绝原因
/// - `None`: 未被拒绝
pub fn check_fingerprint_blocklist(&self, fingerprint: Option<&Ja3Fingerprint>) -> Option<String> {
let fp = fingerprint?;
// 读取运行期可热更新的匹配策略(读锁,低频加载)
let mode = *read_recover(&self.runtime.fingerprint_match);
let blocklist = lock_recover(&self.fingerprint_blocklist);
for prefix in blocklist.iter() {
// 按用户选择的策略匹配(JA3 / JA4 / 任一 / 都要)。
// 说明:JA3 对 ClientHello 扩展/套件的**原始顺序**敏感,同一客户端
// (如 curl 8.20.0)每次连接会因扩展顺序随机化而得到不同 JA3 哈希,
// 但字段集合不变、JA4 稳定——故提供多种策略供按需选择。
let hit_ja3 = fp.ja3_hash.starts_with(prefix.as_str());
let hit_ja4 = fp.ja4_hash.starts_with(prefix.as_str());
let matched = match mode {
FingerprintMatch::Ja3 => hit_ja3,
FingerprintMatch::Ja4 => hit_ja4,
FingerprintMatch::Ja3OrJa4 => hit_ja3 || hit_ja4,
FingerprintMatch::Ja3AndJa4 => hit_ja3 && hit_ja4,
};
if matched {
return Some(format!(
"TLS fingerprint blocked: ja3={} ja4={} matches prefix {} (mode={mode:?})",
fp.ja3_hash, fp.ja4_hash, prefix
));
}
}
None
}
/// 检查 TLS 指纹是否超过速率限制
///
/// # 参数
/// - `fingerprint`: 当前连接的 JA3 指纹
/// - `max_requests_per_window`: 每个时间窗口内的最大请求数
/// - `window_ms`: 时间窗口大小(毫秒)
///
/// # 返回
/// - `true`: 超过速率限制(应拒绝)
/// - `false`: 未超过速率限制
pub fn check_fingerprint_rate_limit(
&self,
fingerprint: Option<&Ja3Fingerprint>,
max_requests_per_window: u32,
window_ms: u64,
) -> bool {
let fp = match fingerprint {
Some(fp) => fp,
None => return false,
};
let now = current_time_ms();
let shard_idx = fp_rate_limit_shard_index(&fp.ja3_hash);
let mut rate_limits = lock_recover(&self.fingerprint_rate_limits[shard_idx]);
let entry = rate_limits.entry(fp.ja3_hash.clone())
.or_insert((now, 0));
// 检查是否超过窗口
if now - entry.0 > window_ms {
// 新窗口
entry.0 = now;
entry.1 = 1;
false
} else {
entry.1 += 1;
entry.1 > max_requests_per_window
}
}
/// 获取指纹速率限制状态快照
pub fn fingerprint_rate_limit_snapshot(&self) -> FxHashMap<String, (u64, u32)> {
let mut merged = FxHashMap::default();
for shard in self.fingerprint_rate_limits.iter() {
let guard = lock_recover(shard);
merged.extend(guard.iter().map(|(k, v)| (k.clone(), *v)));
}
merged
}
/// 检查指纹决策结果,转换为 HTTP 响应
///
/// `Allow` → `None`(继续处理);`Block`/`RateLimit` → `Some(CanonicalResponse)`
pub fn check_fingerprint_decision(
&self,
action: &FingerprintDecision,
) -> Option<CanonicalResponse> {
match action {
FingerprintDecision::Allow => None,
FingerprintDecision::Block(reason) => {
let mut resp = CanonicalResponse::new(403);
let _ = resp.add_header(b"content-type", b"application/json");
resp.set_body(
format!(r#"{{"error":"blocked","reason":"{reason}"}}"#).into_bytes(),
);
Some(resp)
}
FingerprintDecision::RateLimit(retry_ms) => {
let mut resp = CanonicalResponse::new(429);
let _ = resp.add_header(b"retry-after", retry_ms.to_string().as_bytes());
Some(resp)
}
}
}
/// 能力权限校验
fn check_capability(&self, required: Capability) -> bool {
self.permissions.has(required)
}
/// 挂载审计文件落盘槽(JSON Lines 追加写)
///
/// 打开失败时返回 Err 且管道保持仅内存模式,
/// 由构造方决定 fail-closed(向上传播)或降级继续。
fn mount_audit_sink(&mut self, path: &str) -> Result<(), String> {
let logger = AuditLogger::new()
.with_file_sink(path)
.map_err(|e| format!("audit log open failed ({path}): {e}"))?;
let mut slot = lock_recover(&self.audit_log);
*slot = logger;
Ok(())
}
/// 记录审计日志(统一经 zenith-observability AuditLogger,环形缓冲 + 可选落盘)
fn audit(&self, event: &str, details: &str) {
// 安全事件(拦截/拒绝/不一致/故障/限流)提升为 Warning,其余 Info
let severity = if event.contains("BLOCKED")
|| event.contains("DENIED")
|| event.contains("MISMATCH")
|| event.contains("FAILED")
|| event.contains("RATE_LIMITED")
{
Severity::Warning
} else {
Severity::Info
};
let entry = AuditEvent::new(
current_time_ms(),
severity,
"web",
"server",
event,
details,
"",
);
let mut log = lock_recover(&self.audit_log);
let _ = log.log(entry);
}
/// 获取审计日志快照(格式化为 `[ts] EVENT: details` 行,保持兼容)
pub fn audit_snapshot(&self) -> Vec<String> {
let log = lock_recover(&self.audit_log);
log.events()
.iter()
.map(|e| format!("[{}] {}: {}", e.timestamp, e.action_str(), e.target_str()))
.collect()
}
/// 身份一致性三步校验公共方法(AGENT §4.5)
///
/// H1/H2(`process_request_with_security`)与 H3(`build_app_handler`)共用,
/// 确保三条路径执行完全相同的身份校验逻辑。
///
/// 0. SNI↔Host 一致性(都存在时必须一致,否则 421)
/// 0b. 端口一致性(`bind_addr` 配置时,Host 显式端口须与监听端口一致)
/// 0c. 虚拟主机白名单(`identity` 配置时,Host 须命中白名单)
///
/// 返回 `None` = 全部通过,`Some(resp)` = 某步失败(421 Misdirected Request)。
fn check_identity_consistency(
&self,
req: &CanonicalRequest,
host: &str,
sni: Option<&str>,
bind_addr: Option<SocketAddr>,
identity: Option<&IdentityMiddleware>,
) -> Option<CanonicalResponse> {
// 0. 四元一致性(AGENT §4.5):TLS SNI 与 Host/:authority 必须一致(都存在时)
// 不一致 = 跨站点请求走私/缓存投毒前兆 → 421 Misdirected Request
if let Some(sni_host) = sni
&& !host.is_empty()
{
// SNI 小写化写入独立栈缓冲(零堆分配)
let mut sni_buf = [0u8; 256];
let sni_l = lower_ascii_into(sni_host, &mut sni_buf);
// 剥离显式端口统一委托 zenith-api split_host_port(单一实现源),
// 修复前 split(':').next() 对 `[::1]:port` IPv6 authority 截断为 "[",
// 导致 SNI/Host 一致性检查在 IPv6 场景误判 421。
// IPv6 字面量另需剥括号(SNI 侧 RFC 6066 不携带方括号,
// host=`[::1]` 与 sni=`::1` 属同一身份 → 比较前同形化)
let (host_no_port_raw, _) = zenith_api::normalize::split_host_port(host);
let host_no_port = zenith_api::normalize::unbracket_ipv6(host_no_port_raw);
if sni_l != host && sni_l != host_no_port {
self.audit("SNI_HOST_MISMATCH", &format!("sni={sni_l} host={host}"));
let mut resp = CanonicalResponse::new(421);
resp.set_body(b"{\"error\":\"misdirected request\",\"reason\":\"sni_host_mismatch\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
return Some(resp);
}
}
// 0b. 四元一致性(AGENT §4.5):传输层目的地址项——配置了监听地址时,
// Host/:authority 的显式端口必须与本地监听端口一致,不一致 = 跨端口
// 请求走私 → 421。authority 无显式端口时跳过端口检查(宽松默认语义)。
if let Some(bind_addr) = bind_addr
&& let Some(port) = host_explicit_port(host)
&& port != bind_addr.port()
{
self.audit(
"HOST_PORT_MISMATCH",
&format!("bind_port={} host={host}", bind_addr.port()),
);
let mut resp = CanonicalResponse::new(421);
resp.set_body(b"{\"error\":\"misdirected request\",\"reason\":\"host_port_mismatch\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
return Some(resp);
}
// 0c. 四元一致性(AGENT §4.5):虚拟主机白名单(默认装配 IdentityMiddleware)。
// allowed_hosts 非空时:authority/Host 必须命中白名单(ct 比较),否则 421;
// 未配置时 None → pass-through 零开销(无配置部署行为完全不变)。
if let Some(identity) = identity
&& let Err(reason) = identity.verify(req)
{
self.audit("IDENTITY_VIOLATION", &format!("host={host} reason={reason}"));
let mut resp = CanonicalResponse::new(421);
let _ = resp.add_header(b"content-type", b"text/plain");
resp.set_body(reason.as_bytes().to_vec());
return Some(resp);
}
None
}
/// `/metrics` 端点(Prometheus 0.0.4 文本导出)
///
/// 非 `GET|HEAD /metrics` 返回 None;命中时导出全部计数器/仪表/直方图。
/// 该端点豁免 WAF body 检查与缓存(观测数据必须实时),由调用方计入 requests_total。
/// 若配置了 `metrics_auth_token`,则校验 `Authorization: Bearer {token}` 头,
/// 未配置时端点不可访问(返回 None → 404)。
fn try_metrics_endpoint(
&self,
method: &str,
path: &str,
auth_header: Option<&str>,
) -> Option<CanonicalResponse> {
if method != "GET" && method != "HEAD" {
return None;
}
if path != "/metrics" {
return None;
}
// 认证校验:未配置 token 时端点不可访问(fail-closed → None → 404)
let token_guard = read_recover(&self.runtime.metrics_auth_token);
let expected_token = match token_guard.as_deref() {
None => return None,
Some(t) => t.as_bytes(),
};
// 校验 Bearer Token(恒定时间比较防时序侧信道)
let provided = match auth_header {
Some(h) if h.starts_with("Bearer ") => &h[7..],
_ => {
let mut resp = CanonicalResponse::new(401);
let _ = resp.add_header(b"www-authenticate", b"Bearer");
return Some(resp);
}
};
if !zenith_foundation::constant_time_eq(provided.as_bytes(), expected_token) {
let mut resp = CanonicalResponse::new(401);
let _ = resp.add_header(b"www-authenticate", b"Bearer");
return Some(resp);
}
let text = {
let metrics = lock_recover(&self.metrics);
metrics.export_prometheus()
};
let mut resp = CanonicalResponse::new(200);
resp.set_body(text.into_bytes());
let _ = resp.add_header(
b"content-type",
b"text/plain; version=0.0.4; charset=utf-8",
);
Some(resp)
}
/// 执行 WAF 检查。返回 None 表示安全,返回 Some(response) 表示被拦截
///
/// 大 body(> 64 KiB)经 TaskOffloadChannel 卸载到消费线程执行;
/// 卸载不可用/超时/失败一律回退内联执行(检查绝不丢弃,fail-closed)。
/// WAF 检查(类型化贯穿入口:直接基于规范化 `CanonicalRequest`,AGENT §4.8)。
///
/// 三协议(H1/H2/H3)normalize 后调用本入口,WAF 引擎对同一语义请求
/// 做出一致阻断决策;大 body(> 64 KiB)经 TaskOffloadChannel 卸载执行,
/// 卸载不可用/超时/失败一律回退内联(检查绝不丢弃,fail-closed)。
fn check_waf(&self, req: &CanonicalRequest) -> Option<CanonicalResponse> {
#[cfg(feature = "runtime")]
if req.body().len() > self.runtime.waf_offload_body_threshold.load(Ordering::Relaxed) as usize {
// 卸载通道载荷为 owned(跨线程必须);借用头图仅在本冷路径构造
let header_map: FxHashMap<&str, &str> = req
.headers_iter()
.iter()
.map(|h| (h.name_str(), h.value_str()))
.collect();
if let Some(verdict) = self.check_waf_offloaded(
req.method.as_str(),
req.path_str(),
req.query_str(),
&header_map,
req.body(),
) {
return verdict;
}
}
// 卸载不可用(阈值内或卸载失败)→ 内联执行(读锁并发:多连接并行检查)
let result: WafResult = {
let waf = read_recover(&self.waf);
waf.check_canonical(req)
};
if result.has_threat {
let mut metrics = lock_recover(&self.metrics);
let _ = metrics.counter_inc("waf_blocked", &[]);
Some(Self::waf_block_response(
result.severity.as_str(),
&result.triggered_rules,
))
} else {
None
}
}
/// 构造 WAF 拦截响应(403 JSON)
///
/// 参数经 `escape_json_string` 转义,防止规则名/严重度中的
/// `"`/`\`/控制字符破坏 JSON 结构(JSON 注入防护)。
fn waf_block_response(severity: &str, triggered_rules: &[String]) -> CanonicalResponse {
let mut resp = CanonicalResponse::new(403);
let escaped_severity = escape_json_string(severity);
let escaped_rules = escape_json_string(&triggered_rules.join(","));
resp.set_body(
format!(
r#"{{"error":"blocked","reason":"{escaped_severity}","rule":"{escaped_rules}"}}"#
)
.into_bytes(),
);
let _ = resp.add_header(b"content-type", b"application/json");
resp
}
/// 经 TaskOffloadChannel 卸载的 WAF 检查
///
/// 三态返回:`Some(verdict)` = 卸载成功(verdict 为 None 放行 / Some 拦截);
/// `None` = 卸载不可用(序列化失败/通道满/超时/结果异常),调用方必须回退内联。
/// 单提交者语义:`offload_submit_lock` 保证结果队列中至多一条在途任务。
#[cfg(feature = "runtime")]
fn check_waf_offloaded(
&self,
method: &str,
path: &str,
query: &str,
headers: &FxHashMap<&str, &str>,
body: &[u8],
) -> Option<Option<CanonicalResponse>> {
// 借用头图 → owned 仅发生于大 body 卸载冷路径(序列化需要 owned 载荷)
let req_payload = WafOffloadRequest {
method: method.to_string(),
path: path.to_string(),
query: query.to_string(),
headers: headers
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect(),
body: body.to_vec(),
};
let data = serde_json::to_vec(&req_payload).ok()?;
// 单次加载卸载期限(Relaxed),供 build_request 与等待循环共用同一值
let deadline_ms = self.runtime.waf_offload_deadline_ms.load(Ordering::Relaxed);
let task_id = self
.offload_next_task_id
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let request = TaskOffloadChannel::<1024>::build_request(
1,
task_id,
0,
TaskPayload::Custom {
kind: WAF_OFFLOAD_TASK_KIND,
data,
},
deadline_ms,
);
// 单提交者临界区:submit → 等待结果 全程序列化
let _submit_guard = lock_recover(&self.offload_submit_lock);
self.task_channel.submit(request).ok()?;
let start = Instant::now();
let deadline = start + std::time::Duration::from_millis(deadline_ms);
// 无睡眠等待策略:前 4096 次自旋(消费线程 WAF 检查典型延迟 << 100µs,
// 自旋可在微秒级收割结果;消除原 0~1ms 固定睡眠尾延迟);仍未完成则
// yield_now 让出时间片(避免长时间占核),全程零 sleep、零系统调用。
let mut spins: u32 = 0;
loop {
if let Some(result) = self.task_channel.poll_result() {
if result.task_id != task_id {
// 单提交者语义下不可能发生;发生即通道异常,回退内联
return None;
}
return match result.result {
Ok(output) => match serde_json::from_slice::<WafOffloadResponse>(&output.data) {
Ok(r) => {
if r.has_threat {
let mut metrics = lock_recover(&self.metrics);
let _ = metrics.counter_inc("waf_blocked", &[]);
Some(Some(Self::waf_block_response(&r.severity, &r.triggered_rules)))
} else {
Some(None)
}
}
// 结果解码失败 → 回退内联
Err(_) => None,
},
// 执行失败/超时 → 回退内联
Err(_) => None,
};
}
if Instant::now() >= deadline {
return None;
}
if spins < 4096 {
std::hint::spin_loop();
spins += 1;
} else {
std::thread::yield_now();
}
}
}
/// 执行 Cache 查询(类型化贯穿入口:由 CanonicalRequest 派生缓存键)。
/// 返回 Some(response) 表示命中,None 表示未命中。
/// host 必须参与 key(防跨站点缓存投毒)
fn check_cache(
&self,
req: &CanonicalRequest,
host: &str,
) -> Option<CanonicalResponse> {
let method = req.method.as_str();
if method != "GET" && method != "HEAD" {
return None;
}
let key = CacheKeyBuilder::from_canonical(req)
.with_query(req.query_str())
.host(host)
.build();
let cache = lock_recover(&self.cache);
match cache.get(&key, 0, current_time_ms()) {
CacheHit::Fresh(entry) | CacheHit::Stale(entry) => {
let mut metrics = lock_recover(&self.metrics);
let _ = metrics.counter_inc("cache_hits", &[]);
let mut resp = CanonicalResponse::new(entry.status_code);
resp.set_body(entry.value.to_vec());
let _ = resp.add_header(b"x-cache", b"HIT");
Some(resp)
}
_ => {
let mut metrics = lock_recover(&self.metrics);
let _ = metrics.counter_inc("cache_misses", &[]);
None
}
}
}
/// 将响应存入缓存(Cache-Control 感知 + host 参与 key)
///
/// 缓存安全规则(RFC 9111):
/// - 响应含 no-store / private / no-cache → 不缓存
/// - 请求含 Authorization 头且响应未显式 public → 不缓存(防越权内容入共享缓存)
/// - max-age 取响应 Cache-Control 的 max-age(无则默认 3600s)
fn store_cache(
&self,
method: &str,
path: &str,
query: &str,
host: &str,
req_has_auth: bool,
resp: &CanonicalResponse,
) {
if method != "GET" && method != "HEAD" {
return;
}
if resp.status_code != 200 {
return;
}
// 解析响应 Cache-Control
let mut cc = String::new();
for h in resp.headers_iter() {
if h.name_str().eq_ignore_ascii_case("cache-control") {
cc = h.value_str().to_string();
break;
}
}
let cc_l = cc.to_ascii_lowercase();
if cc_l.contains("no-store") || cc_l.contains("private") || cc_l.contains("no-cache") {
return;
}
let is_public = cc_l.contains("public");
if req_has_auth && !is_public {
return;
}
let max_age: u64 = cc_l
.split(',')
.find_map(|d| {
let d = d.trim();
d.strip_prefix("max-age=")
.and_then(|v| v.trim_matches(|c: char| !c.is_ascii_digit()).parse().ok())
})
.unwrap_or(3600);
// RFC 9111 §5.2.1.9:`s-maxage` 覆盖 `max-age`(共享缓存语义)。
// 解析后挂到 policy,引擎入库时按共享属性应用覆盖。
let s_maxage: Option<u64> = cc_l
.split(',')
.find_map(|d| {
let d = d.trim();
d.strip_prefix("s-maxage=")
.and_then(|v| v.trim_matches(|c: char| !c.is_ascii_digit()).parse().ok())
});
let key = CacheKeyBuilder::new(method, path)
.with_query(query)
.host(host)
.build();
// 锁外完成昂贵工作(策略构建 + body 克隆),锁内仅 put(零昂贵操作)
let mut policy_builder =
zenith_cache::CachePolicyBuilder::new(zenith_cache::Cacheability::Public)
.max_age(max_age);
if let Some(s) = s_maxage {
policy_builder = policy_builder.s_maxage(s);
}
let policy = policy_builder.build();
let entry = zenith_cache::CacheEntry::new(
key,
resp.body().to_vec(),
resp.status_code,
"application/octet-stream".to_string(),
policy,
0,
current_time_ms(),
);
let cache = lock_recover(&self.cache);
cache.put(entry);
}
fn record_counter(&self, name: &str, delta: u64) {
let mut metrics = lock_recover(&self.metrics);
let _ = metrics.counter_add(name, delta, &[]);
}
/// 请求完成指标批量记录:单锁内完成 histogram + 计数器组,
/// 将热路径 metrics 锁获取次数从每请求 2~4 次收敛为 1 次。
fn record_req_done_metrics(&self, elapsed_us: u64, extra_counters: &[&str]) {
let mut metrics = lock_recover(&self.metrics);
let _ = metrics.histogram_record("request_duration_us", elapsed_us, &[]);
for name in extra_counters {
let _ = metrics.counter_inc(name, &[]);
}
}
/// 零堆分配审计:格式化直接写入固定栈缓冲(512B,足够 method/path/status 载荷),
/// 热路径消除 per-request `format!` 堆分配;超长 fail-closed 截断。
fn auditf(&self, event: &str, args: std::fmt::Arguments<'_>) {
const CAP: usize = 512;
let mut buf = [0u8; CAP];
let mut cursor: &mut [u8] = &mut buf;
// &mut [u8] 实现 io::Write:写满即截断(fail-closed,绝不 panic)
use std::io::Write as _;
let _ = write!(cursor, "{args}");
let used = CAP - cursor.len();
// 写入源全部为 ASCII 格式占位,from_utf8 恒 Ok;失败时保守返回静态串
let details = std::str::from_utf8(&buf[..used]).unwrap_or("<fmt>");
self.audit(event, details);
}
#[cfg(feature = "runtime")]
fn record_gauge(&self, name: &str, value: u64) {
let mut metrics = lock_recover(&self.metrics);
// u64 → i64 收窄:生成号远大于 i64::MAX 需 2^63 次热更新(不现实),
// 仍用 try_from fail-closed(禁 as 截断)
let Ok(v) = i64::try_from(value) else {
tracing::warn!("gauge value {} exceeds i64::MAX, skipped (name={})", value, name);
return;
};
let _ = metrics.gauge_set(name, v, &[]);
}
}
/// 协议服务器主结构体
pub struct ProtocolServer {
config: ServerConfig,
app: Arc<App>,
security: SecurityPipeline,
/// QUIC 传输服务器(HTTP/3)
quic_server: Option<QuicTransportServer>,
/// 身份一致性中间件(AGENT §4.5)默认装配:
/// `ServerConfig::allowed_hosts` 非空时启用(ct 比较白名单 → 421),
/// 空列表 = None(pass-through 零开销,默认行为对无配置部署完全不变)。
identity: Option<IdentityMiddleware>,
}
/// 从配置构建身份一致性中间件(空白名单 → None,零开销穿透)
fn build_identity_middleware(config: &ServerConfig) -> Option<IdentityMiddleware> {
if config.allowed_hosts.is_empty() {
None
} else {
// 小写规范化白名单(与 extract_host 的小写化对齐)
let hosts = config
.allowed_hosts
.iter()
.map(|h| h.to_ascii_lowercase())
.collect();
Some(IdentityMiddleware::new(hosts))
}
}
impl Clone for ProtocolServer {
fn clone(&self) -> Self {
Self {
config: self.config.clone(),
app: Arc::clone(&self.app),
// 复用 SecurityPipeline 的 Clone(共享 Arc 内部状态 + 复制 metrics_auth_token),
// 避免原先 SecurityPipeline::new() 丢失认证令牌及 WAF/缓存等共享状态
security: self.security.clone(),
quic_server: None,
identity: self.identity.clone(),
}
}
}
impl fmt::Debug for ProtocolServer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProtocolServer")
.field("config", &self.config)
.field("app", &self.app)
.finish()
}
}
impl ProtocolServer {
/// 使用默认配置创建服务器
#[inline]
pub fn new(app: App) -> Self {
let config = ServerConfig::new();
let identity = build_identity_middleware(&config);
let security = SecurityPipeline::new(&config);
Self {
config,
app: Arc::new(app),
security,
quic_server: None,
identity,
}
}
/// 使用自定义配置创建服务器
///
/// 审计落盘打开失败时降级为仅内存模式(错误经 tracing 暴露,fail-visible);
/// 需要 fail-closed 语义的调用方请使用 [`Self::try_with_config`]。
#[inline]
pub fn with_config(app: App, config: ServerConfig) -> Self {
let mut security = SecurityPipeline::new(&config);
if let Some(path) = &config.audit_log_path
&& let Err(e) = security.mount_audit_sink(path)
{
tracing::error!("audit sink open failed, fallback to memory-only: {e}");
}
let identity = build_identity_middleware(&config);
Self {
config,
app: Arc::new(app),
security,
quic_server: None,
identity,
}
}
/// 使用自定义配置创建服务器(fail-closed:审计落盘打开失败直接返回错误)
#[inline]
pub fn try_with_config(app: App, config: ServerConfig) -> Result<Self, ServerError> {
let mut security = SecurityPipeline::new(&config);
if let Some(path) = &config.audit_log_path {
security
.mount_audit_sink(path)
.map_err(ServerError::Internal)?;
}
let identity = build_identity_middleware(&config);
Ok(Self {
config,
app: Arc::new(app),
security,
quic_server: None,
identity,
})
}
/// 获取配置引用
#[inline]
pub fn config(&self) -> &ServerConfig {
&self.config
}
/// 获取 App 引用
#[inline]
pub fn app(&self) -> &App {
&self.app
}
/// 获取安全管道引用(WAF + Cache + Metrics + Capability + Supervisor + ChangeSet + Forward + Proxy)
#[inline]
pub fn security(&self) -> &SecurityPipeline {
&self.security
}
/// 读取当前运行时配置快照(观测用;热路径不调用)
#[inline]
pub fn runtime_snapshot(&self) -> RuntimeSnapshot {
self.security.runtime_snapshot()
}
/// 运行时热更新(无需重建服务器,对所有共享副本立即生效)。
///
/// `f` 收到 [`RuntimeConfigRef`] 描述符,可对每个旋钮独立赋值/追加/移除。
/// 所有标量修改经 `AtomicU64`/`AtomicBool` 无锁 `store`(Relaxed),
/// host 名单经 `RwLock` 写锁施加——**不触碰读热路径**。
///
/// # 示例
/// ```rust,ignore
/// server.update_runtime(|r| {
/// r.set_waf_enabled(true);
/// r.enable_waf_for_host("api.example.com");
/// r.bypass_waf_for_host("static.example.com");
/// r.set_fingerprint_rate_limit(200, 30_000);
/// r.set_udp_max_sessions(8192);
/// });
/// ```
///
/// # 说明
/// [`Self::config`] 返回的是**构建期**配置快照,不受运行时更新影响;
/// 运行时值请用 [`Self::runtime_snapshot`] 读取。
#[inline]
pub fn update_runtime(&self, f: impl FnOnce(&RuntimeConfigRef<'_>)) {
self.security.update_runtime(f);
}
/// 运行时热更新内置缓存容量(全局条目数 / 字节数)。
///
/// 无锁原子 `store`,热路径 `put` 每写入一次原子加载;无需重建引擎/服务器。
#[inline]
pub fn set_cache_capacity(&self, max_entries: usize, max_size_bytes: usize) {
self.security.set_cache_capacity(max_entries, max_size_bytes);
}
/// 运行时热更新 L4 转发引擎参数(并发会话上限 / 单会话带宽)。
///
/// 写低频 `set_config`,热更新后对后续会话/配额立即生效,无需重建引擎/服务器。
#[inline]
pub fn set_forward_config(&self, config: zenith_forward::ForwardConfig) {
self.security.set_forward_config(config);
}
/// 读取当前 L4 转发引擎参数(观测)。
#[inline]
pub fn forward_config(&self) -> zenith_forward::ForwardConfig {
self.security.forward_config()
}
/// 运行时热更新反向代理运行参数(连接池/超时/健康阈值)。
#[inline]
pub fn update_proxy_config(&self, f: impl FnOnce(&mut ProxyConfig)) {
self.security.update_proxy_config(f);
}
/// 整体替换反向代理运行参数(热更新)。
#[inline]
pub fn set_proxy_config(&self, config: ProxyConfig) {
self.security.set_proxy_config(config);
}
/// 读取当前反向代理运行参数(观测)。
#[inline]
pub fn proxy_config(&self) -> ProxyConfig {
self.security.proxy_config()
}
/// 启动 Supervisor 节点(验证健康状态并确保运行中)
#[cfg(feature = "runtime")]
pub fn start_supervisor(&self) {
let mut supervisor = lock_recover(&self.security.supervisor);
let _ = supervisor.health_check();
}
/// 停止 Supervisor 节点(优雅关闭)
#[cfg(feature = "runtime")]
pub fn stop_supervisor(&self) {
let mut supervisor = lock_recover(&self.security.supervisor);
supervisor.shutdown();
}
/// 获取 Supervisor 当前状态
#[cfg(feature = "runtime")]
pub fn supervisor_state(&self) -> SupervisorState {
let supervisor = lock_recover(&self.security.supervisor);
supervisor.state()
}
/// 导出 Prometheus 0.0.4 文本格式指标(公开 API,供外部观测系统拉取)
///
/// 与 `/metrics` 端点使用同一导出引擎,格式完全一致。
pub fn export_metrics(&self) -> String {
let metrics = lock_recover(&self.security.metrics);
metrics.export_prometheus()
}
/// 触发 ChangeSet 热更新(完整八态机驱动)
///
/// 合法序列:prepare → validate → resource_proof → shadow → activate →
/// stop_old_admission → drain → commit(迁移表见 zenith-runtime changeset.rs)。
/// web 场景各阶段无额外校验,以最小真实回调推进;每次触发以
/// `active+1` 为目标生成号构造新实例,提交后换入,保证生成号连续递增。
///
/// # Returns
/// * `Ok(u64)` - 已提交的生成号
/// * `Err(String)` - 失败阶段与原因(原实例不受影响)
#[cfg(feature = "runtime")]
pub fn trigger_changeset(&self) -> Result<u64, String> {
let mut guard = lock_recover(&self.security.changeset);
let active = guard.active_generation();
let mut cs = ChangeSet::new(active, active.saturating_add(1));
cs.prepare().map_err(|e| format!("changeset prepare failed: {e}"))?;
cs.validate().map_err(|e| format!("changeset validate failed: {e}"))?;
cs.resource_proof(|| Ok(()))
.map_err(|e| format!("changeset resource_proof failed: {e}"))?;
cs.shadow(|| Ok(()))
.map_err(|e| format!("changeset shadow failed: {e}"))?;
cs.activate(active)
.map_err(|e| format!("changeset activate failed: {e}"))?;
cs.stop_old_admission()
.map_err(|e| format!("changeset stop_old_admission failed: {e}"))?;
cs.drain(|| Ok(None))
.map_err(|e| format!("changeset drain failed: {e}"))?;
match cs.commit() {
Ok(ChangeSetOutcome::Committed { generation }) => {
// 换入已提交实例:下次触发从新生成号继续
*guard = cs;
Ok(generation)
}
// commit 成功只会返回 Committed;其余结果视为内部异常
Ok(ChangeSetOutcome::RolledBack { generation }) => Err(format!(
"changeset commit unexpectedly rolled back to generation {generation}"
)),
Err(e) => Err(format!("changeset commit failed: {e}")),
}
}
/// 获取 ChangeSet 当前状态
#[cfg(feature = "runtime")]
pub fn changeset_state(&self) -> ChangeSetState {
let changeset = lock_recover(&self.security.changeset);
changeset.state()
}
/// 获取审计日志快照
pub fn audit_log(&self) -> Vec<String> {
self.security.audit_snapshot()
}
/// 获取任务通道统计
#[cfg(feature = "runtime")]
pub fn task_channel_stats(&self) -> (u64, u64) {
(
self.security.task_channel.pending_count(),
self.security.task_channel.completed_count(),
)
}
/// 添加 TCP 转发会话(L4 forwarding)
pub fn create_forward_session(
&self,
client_addr: SocketAddr,
upstream_addr: SocketAddr,
) -> Option<u64> {
let mut engine = lock_recover(&self.security.forward_engine);
engine.create_session(
zenith_forward::ForwardProtocol::Tcp,
client_addr,
upstream_addr,
)
}
/// 执行一次 TCP L4 转发闭环(仅 Linux:splice(2) 内核零拷贝双线程中继)
///
/// # 流程(fail-closed,每阶段审计 + 指标)
/// 1. 能力闸门:`NetworkAccess`(与 L7 安全管道一致)
/// 2. 会话登记:白名单校验 + 并发配额(拒绝 → 审计 + Err)
/// 3. 连接上游(`TcpStream::connect`,失败 → 会话拒绝登记 + Err)
/// 4. `session.activate()` → `TcpSpliceRelay::relay` 全双工零拷贝中继
/// (阻塞至双方 EOF;调用方应在专用工作线程/连接线程上下文中调用,
/// 禁止与单线程事件循环同线程使用)
/// 5. 分方向字节记账(rx=c2u / tx=u2c)→ close → cleanup(顺带周期清理)
///
/// # 平台
/// 仅 `target_os = "linux"` 编译此 API(splice(2) 约束,与 zenith-forward 一致);
/// 非 Linux 目标编译期不包含本方法(非运行时降级)。
///
/// # 返回
/// `Ok((c2u_bytes, u2c_bytes))` 分方向传输字节数
///
/// 需 `afxdp` 特性(zenith-forward 的 splice 中继依赖 zenith-linux)
#[cfg(all(feature = "afxdp", target_os = "linux"))]
pub fn forward_tcp_conn(
&self,
client: TcpStream,
client_addr: SocketAddr,
upstream_addr: SocketAddr,
) -> Result<(u64, u64), ServerError> {
// 1. 能力闸门
if !self.security.check_capability(Capability::NetworkAccess) {
self.security.audit(
"CAPABILITY_DENIED",
&format!("l4 forward {client_addr} -> {upstream_addr}"),
);
return Err(ServerError::Protocol(
"capability denied: network_access".into(),
));
}
// 2. 会话登记(白名单 + 并发配额,fail-closed)
let session_id = {
let mut engine = lock_recover(&self.security.forward_engine);
match engine.create_session(
zenith_forward::ForwardProtocol::Tcp,
client_addr,
upstream_addr,
) {
Some(id) => id,
None => {
drop(engine);
self.security.audit(
"FORWARD_DENIED",
&format!(
"client={client_addr} upstream={upstream_addr} reason=whitelist_or_quota"
),
);
return Err(ServerError::Protocol(
"forward denied (whitelist or session quota)".into(),
));
}
}
};
self.security.record_counter("forward_sessions_total", 1);
// 内部收尾:记账(可选字节)+ close + cleanup(全部分支唯一出口,杜绝泄漏)
let finish = |bytes: Option<(u64, u64)>| {
let mut engine = lock_recover(&self.security.forward_engine);
if let Some((rx, tx)) = bytes
&& let Some(s) = engine.get_session_mut(session_id)
{
s.record_rx(rx);
s.record_tx(tx);
}
engine.close_session(session_id);
engine.cleanup_closed(self.security.runtime.forward_session_timeout_ms.load(Ordering::Relaxed));
};
// 3. 连接上游
let upstream = match TcpStream::connect(upstream_addr) {
Ok(s) => s,
Err(e) => {
finish(None);
self.security.record_counter("forward_upstream_error", 1);
self.security.audit(
"FORWARD_ERROR",
&format!("session={session_id} upstream={upstream_addr} connect failed: {e}"),
);
return Err(ServerError::Io(e));
}
};
// 4. activate + 零拷贝中继
{
let mut engine = lock_recover(&self.security.forward_engine);
if let Some(s) = engine.get_session_mut(session_id) {
s.activate();
}
}
let relay_result = zenith_forward::TcpSpliceRelay::default().relay(&client, &upstream);
// 5. 记账 + close + cleanup
match relay_result {
Ok((c2u, u2c)) => {
// usize → u64:目标平台 usize ≤ u64 恒成立,但禁 as 截断,
// try_from fail-closed(溢出饱和为 MAX,宁可夸大不得归零)
let rx = u64::try_from(c2u).unwrap_or(u64::MAX);
let tx = u64::try_from(u2c).unwrap_or(u64::MAX);
finish(Some((rx, tx)));
self.security.record_counter("forward_sessions_ok", 1);
Ok((rx, tx))
}
Err(e) => {
finish(None);
self.security.record_counter("forward_relay_error", 1);
self.security.audit(
"FORWARD_ERROR",
&format!("session={session_id} relay failed: {e}"),
);
Err(ServerError::Protocol(format!("splice relay failed: {e}")))
}
}
}
/// 获取代理统计(按路由前缀分组的真实引擎池统计)
///
/// 每条路由的 `ProxyEngine` 持有独立连接池与上游 ID 空间,
/// 因此统计按前缀粒度返回(不做跨引擎合并,避免不同上游被错误归并)。
pub fn proxy_stats(&self) -> Vec<(String, zenith_proxy::PoolStats)> {
let routes = lock_recover(&self.security.proxy_routes);
routes
.iter()
.map(|(prefix, engine, _)| {
let stats = lock_recover(engine).pool().stats();
(prefix.clone(), stats)
})
.collect()
}
/// 注册反向代理路由(路径前缀 → 上游集合 + 负载均衡策略)
///
/// 命中前缀的请求在 Cache 查询之后、App 处理之前被真实转发到上游:
/// - 前缀匹配:`path == prefix` 或 `path` 以 `prefix + "/"` 开头
/// - 转发路径为原始 path+query(v1 语义,不做前缀剥离)
/// - Host 头透传原始值,附加 `x-forwarded-for` / `x-forwarded-proto`
/// - 上游不可用 / 转发失败 → 502 JSON `{"error":"bad_gateway"}`
///
/// # 参数
/// - `prefix`:路径前缀(如 `/api`)
/// - `upstreams`:上游集合 `(地址, 权重)`(地址为 `ip:port` 或可解析主机名)
/// - `strategy`:负载均衡策略
pub fn add_proxy_route(
&self,
prefix: &str,
upstreams: Vec<(String, u32)>,
strategy: LoadBalanceStrategy,
) {
self.security.add_proxy_route(prefix, upstreams, strategy);
}
// ─────────────────────────────────────────────────────────────────────
// 4.4 L4 转发(TCP/UDP 透明转发,跨平台)
// ─────────────────────────────────────────────────────────────────────
/// 启动一个 L4 TCP 转发监听器(跨平台:Linux 用 splice(2),其他用 io::copy)
///
/// 在 `listen_addr` 监听 TCP 连接,每条连接经白名单/配额校验后转发到
/// `upstream_addr`。使用 [`zenith_forward::TcpRelay`] 自动选择最优策略:
/// - Linux + `linux` feature:`splice(2)` 内核零拷贝
/// - 非 Linux 或无 `linux` feature:`std::io::copy` 用户态拷贝
///
/// # 流程(fail-closed)
/// 1. `TcpListener::bind` 绑定监听地址
/// 2. 每条连接 spawn 独立线程:会话登记(白名单 + 并发配额)→
/// `TcpStream::connect` 上游 → `TcpRelay::relay` 双向中继 → 记账
///
/// # 参数
/// - `listen_addr`:监听地址(如 `0.0.0.0:3306`)
/// - `upstream_addr`:上游地址(如 `10.0.0.1:3306`)
///
/// # 返回
/// - `Ok(JoinHandle)`:后台线程句柄(调用方可 join 或忽略)
/// - `Err(ServerError)`:bind 失败
pub fn add_l4_tcp_forward(
&self,
listen_addr: SocketAddr,
upstream_addr: SocketAddr,
) -> Result<std::thread::JoinHandle<()>, ServerError> {
let listener = std::net::TcpListener::bind(listen_addr).map_err(ServerError::Io)?;
let security = self.security.clone();
let handle = std::thread::Builder::new()
.name(format!("zenith-l4-tcp-{}", listen_addr.port()))
.spawn(move || {
let relay = zenith_forward::TcpRelay::default();
for stream in listener.incoming() {
let Ok(client_stream) = stream else { continue };
let client_addr = match client_stream.peer_addr() {
Ok(a) => a,
Err(_) => continue,
};
let sec = security.clone();
// TcpRelay 为 Clone(非 Copy):每个连接克隆一份供 move 闭包使用
let relay = relay.clone();
let _ = std::thread::Builder::new()
.name(format!("l4-tcp-{}", client_addr.port()))
.spawn(move || {
// 会话登记(白名单 + 并发配额,fail-closed)
let session_id = {
let mut engine = lock_recover(&sec.forward_engine);
match engine.create_session(
zenith_forward::ForwardProtocol::Tcp,
client_addr,
upstream_addr,
) {
Some(id) => id,
None => {
sec.audit(
"FORWARD_DENIED",
&format!(
"client={client_addr} upstream={upstream_addr} reason=whitelist_or_quota"
),
);
return;
}
}
};
sec.record_counter("forward_sessions_total", 1);
// 连接上游
let upstream_stream = match std::net::TcpStream::connect(upstream_addr) {
Ok(s) => s,
Err(e) => {
let mut engine = lock_recover(&sec.forward_engine);
engine.close_session(session_id);
engine.cleanup_closed(sec.runtime.forward_session_timeout_ms.load(Ordering::Relaxed));
sec.record_counter("forward_upstream_error", 1);
sec.audit(
"FORWARD_ERROR",
&format!(
"session={session_id} upstream={upstream_addr} connect failed: {e}"
),
);
return;
}
};
// activate + 双向中继
{
let mut engine = lock_recover(&sec.forward_engine);
if let Some(s) = engine.get_session_mut(session_id) {
s.activate();
}
}
let relay_result = relay.relay(&client_stream, &upstream_stream);
// 记账 + close + cleanup
let mut engine = lock_recover(&sec.forward_engine);
match relay_result {
Ok((c2u, u2c)) => {
if let Some(s) = engine.get_session_mut(session_id) {
s.record_rx(u64::try_from(c2u).unwrap_or(u64::MAX));
s.record_tx(u64::try_from(u2c).unwrap_or(u64::MAX));
}
sec.record_counter("forward_sessions_ok", 1);
}
Err(e) => {
sec.record_counter("forward_relay_error", 1);
sec.audit(
"FORWARD_ERROR",
&format!("session={session_id} relay failed: {e}"),
);
}
}
engine.close_session(session_id);
engine.cleanup_closed(sec.runtime.forward_session_timeout_ms.load(Ordering::Relaxed));
let _ = client_stream.shutdown(std::net::Shutdown::Both);
});
}
})
.map_err(|e| ServerError::Internal(format!("spawn l4 tcp thread: {e}")))?;
Ok(handle)
}
/// 启动一个 L4 UDP 转发监听器(跨平台:双线程 + per-client 会话映射表)
///
/// 在 `listen_addr` 监听 UDP 数据报,每条数据报转发到 `upstream_addr`。
/// 为每个客户端源地址维护**专属上游 socket**(临时端口绑定),回包逆向送达
/// —— 修复旧实现 `last_client` 单客户端缺陷:多客户端并发回包按源正确分拣。
///
/// # 并发模型(每监听器固定 2 线程,不随客户端数增长)
/// - 线程 A(c2u):`listener` **阻塞**收包 → 逐客户端会话(白名单/配额)→
/// 经客户端专属 socket `send_to` 上游
/// - 线程 B(u2c):轮询各客户端专属 socket **非阻塞**收包 → `send_to` 回发
/// 原客户端;顺带空闲超时回收 + 线程退出统一清账
///
/// # 安全(fail-closed)
/// - 每包经 `ForwardEngine::create_session` 白名单 + 配额校验
/// - 并发上限(`udp_max_sessions`)(防映射表无限增长 → 资源耗尽)
/// - 空闲超时(`udp_session_idle_timeout_ms`)自动回收
/// - 回包仅发往已登记客户端(防 UDP 反射放大)
/// - 临时错误(Windows ICMP unreachable = ConnectionReset)不终止转发
///
/// # 参数
/// - `listen_addr`:监听地址(如 `0.0.0.0:53`)
/// - `upstream_addr`:上游地址(如 `10.0.0.1:53`)
///
/// # 返回
/// - `Ok(JoinHandle)`:c2u 后台线程句柄(u2c 线程随 stop 标志自动收尾退出)
/// - `Err(ServerError)`:bind 失败
pub fn add_l4_udp_forward(
&self,
listen_addr: SocketAddr,
upstream_addr: SocketAddr,
) -> Result<std::thread::JoinHandle<()>, ServerError> {
use std::net::UdpSocket;
let listener = UdpSocket::bind(listen_addr).map_err(ServerError::Io)?;
let security = self.security.clone();
// 共享 per-client 会话映射表 + 停止标志(c2u 致命错误置位 → u2c 清账退出)
let sessions: Arc<std::sync::Mutex<FxHashMap<SocketAddr, UdpClientSession>>> =
Arc::new(std::sync::Mutex::new(FxHashMap::default()));
let stop = Arc::new(AtomicBool::new(false));
// u2c 回发句柄:listener 克隆(send_to 专用),需在 move 进 c2u 闭包前复制
let write_sock = listener
.try_clone()
.map_err(|e| ServerError::Io(e))?;
// ── 线程 A(c2u):listener 阻塞收包 → 逐客户端会话 + 专属 socket 上行 ──
let c2u_sessions = Arc::clone(&sessions);
let c2u_stop = Arc::clone(&stop);
let c2u_security = security.clone();
let c2u_upstream = upstream_addr;
let c2u_handle = std::thread::Builder::new()
.name(format!("zenith-l4-udp-c2u-{}", listen_addr.port()))
.spawn(move || {
let buf_size = zenith_forward::DEFAULT_BUFFER_SIZE;
let mut buf = vec![0u8; buf_size];
loop {
match listener.recv_from(&mut buf) {
Ok((n, client_addr)) => {
// 单锁短临界区:查找/创建会话 + send_to 上游(每包一次锁获取)
let mut guard = lock_recover(&c2u_sessions);
if !guard.contains_key(&client_addr)
&& !create_udp_session(
&mut guard,
&c2u_security,
client_addr,
c2u_upstream,
)
{
continue; // 已计数 + 审计(白名单/配额/上限/bind 失败)
}
let Some(session) = guard.get_mut(&client_addr) else {
continue;
};
session.last_active = Instant::now();
session.rx = session.rx.saturating_add(n as u64);
if let Err(e) = session.upstream_sock.send_to(&buf[..n], c2u_upstream) {
c2u_security.record_counter("forward_relay_error", 1);
c2u_security.audit(
"FORWARD_ERROR",
&format!("udp c2u send client={client_addr}: {e}"),
);
}
}
Err(ref e) if is_transient_udp_error(e.kind()) => {}
Err(e) => {
// 致命错误(socket 失效):停止转发,通知 u2c 清账退出
c2u_security.record_counter("forward_relay_error", 1);
c2u_security.audit(
"FORWARD_ERROR",
&format!("udp c2u recv fatal: {e}"),
);
c2u_stop.store(true, std::sync::atomic::Ordering::Release);
break;
}
}
}
})
.map_err(|e| ServerError::Internal(format!("spawn l4 udp c2u thread: {e}")))?;
// ── 线程 B(u2c):轮询各客户端专属 socket → 回发 + 空闲回收 ──
let u2c_sessions = Arc::clone(&sessions);
let u2c_stop = Arc::clone(&stop);
let u2c_security = security.clone();
let _u2c_handle = std::thread::Builder::new()
.name(format!("zenith-l4-udp-u2c-{}", listen_addr.port()))
.spawn(move || {
let buf_size = zenith_forward::DEFAULT_BUFFER_SIZE;
let mut buf = vec![0u8; buf_size];
loop {
// c2u 已退出 → 清空残留会话并退出(唯一退出路径)
if u2c_stop.load(std::sync::atomic::Ordering::Acquire) {
drain_udp_sessions(&u2c_security, &u2c_sessions);
break;
}
let mut progress = false;
let mut expired: Vec<SocketAddr> = Vec::new();
{
let mut guard = lock_recover(&u2c_sessions);
let now = Instant::now();
for (client, session) in guard.iter_mut() {
// 空闲超时 → 标记回收(锁外记账,避免持 sessions 锁嵌套 engine 锁)
if now.duration_since(session.last_active).as_millis() as u64
> u2c_security.runtime.udp_session_idle_timeout_ms.load(Ordering::Relaxed)
{
expired.push(*client);
continue;
}
match session.upstream_sock.recv_from(&mut buf) {
Ok((n, _peer)) => {
session.tx = session.tx.saturating_add(n as u64);
if let Err(e) = write_sock.send_to(&buf[..n], *client) {
u2c_security.record_counter("forward_relay_error", 1);
u2c_security.audit(
"FORWARD_ERROR",
&format!("udp u2c send client={client}: {e}"),
);
} else {
progress = true;
}
}
Err(ref e) if is_transient_udp_error(e.kind()) => {}
Err(_) => {} // 单个会话错误不影响整体轮询
}
}
}
for client in expired {
reap_udp_session(&u2c_security, &u2c_sessions, client, "idle_timeout");
}
// 无数据且未停止 → 短 sleep 避免 100% CPU(c2u 方向不受影响:阻塞收包)
if !progress {
std::thread::sleep(Duration::from_millis(1));
}
}
})
.map_err(|e| ServerError::Internal(format!("spawn l4 udp u2c thread: {e}")))?;
Ok(c2u_handle)
}
// ─────────────────────────────────────────────────────────────────────
// 4.5 QUIC / HTTP/3 传输层集成
// ─────────────────────────────────────────────────────────────────────
/// 绑定 QUIC/HTTP3 传输层
///
/// # 参数
/// - `config`: QUIC 服务器配置(含绑定地址)
/// - `cert_gen`: 证书代际(用于 QUIC 握手)
///
/// # 返回
/// - `Ok(())`: 绑定成功
/// - `Err(String)`: 绑定失败
pub fn bind_quic(
&mut self,
config: QuicServerConfig,
cert_gen: &CertGeneration,
) -> Result<(), String> {
let mut quic = QuicTransportServer::new(config);
quic.bind_cert(cert_gen)
.map_err(|e| format!("QUIC cert bind: {e}"))?;
quic.bind()
.map_err(|e| format!("QUIC bind: {e}"))?;
self.quic_server = Some(quic);
Ok(())
}
/// 绑定 QUIC(无内核 socket 模式:AF_XDP 数据面专用)
///
/// 仅初始化 QUIC 传输层(证书 / 连接表 / H3 状态机),**不创建内核 UDP socket**——
/// 数据报由 AF_XDP 桥(`afxdp_bridge`)从 XDP 主数据面直接喂入
/// [`Self::serve_udp_quic_datagram`],回包经 Worker TX Ring 注入网卡。
///
/// 铁则 1 合规:主数据面全程零内核 socket 旁路。
/// 与 [`Self::bind_quic`] 互斥:重复调用会覆盖既有 QUIC 服务器实例。
///
/// # 参数
/// - `config`: QUIC 服务器配置(bind_addr 仅作逻辑标识,不触发 socket 绑定)
/// - `cert_gen`: 证书代际(用于 QUIC 握手)
pub fn bind_quic_socketless(
&mut self,
config: QuicServerConfig,
cert_gen: &CertGeneration,
) -> Result<(), String> {
let mut quic = QuicTransportServer::new(config);
quic.bind_cert(cert_gen)
.map_err(|e| format!("QUIC cert bind: {e}"))?;
self.quic_server = Some(quic);
Ok(())
}
/// 处理一个 UDP/QUIC 数据包(HTTP/3 入口)
///
/// 从 UDP socket 读取数据包并喂入 QUIC 传输层,解密后得到 HTTP/3 请求,
/// 经安全管道处理后返回响应数据包。
///
/// # 流程
/// 1. UDP 接收 → QUIC 包解析 → QUIC 解密 → HTTP/3 帧解析
/// 2. HTTP/3 请求 → SecurityPipeline → App → HTTP/3 响应编码
/// 3. 响应 → QUIC 加密 → UDP 发送
pub fn serve_udp_quic_datagram(
&mut self,
data: &[u8],
from: SocketAddr,
) -> Result<Vec<(Vec<u8>, SocketAddr)>, ServerError> {
// 提前拆出 app/security,避免闭包内捕获 `self` 导致的借用冲突
// (self.quic_server 需要 mut 借用,self.process_request_with_security 需要 &self)
let app = self.app.clone();
let security = self.security.clone();
let bind_addr = self.security.runtime_bind_addr();
let identity = self.identity.clone();
let quic = self
.quic_server
.as_mut()
.ok_or_else(|| ServerError::Protocol("QUIC server not bound".into()))?;
let app_handler = move |req: CanonicalRequest, fp: Option<&Ja3Fingerprint>| -> zenith_api::CanonicalResponse {
// 内联 process_request_with_security 的最小必需子集(安全管道 + App)
// 借用管线(L7 热路径零堆分配):与主安全管道同款语义
let start = Instant::now();
let method = req.method.as_str();
let path = req.path_str();
let query = req.query_str();
// body 借用(零拷贝):WAF/try_proxy 仅读取,req 在 app.handle 才被消费
let body = req.body();
let mut header_map: FxHashMap<&str, &str> = FxHashMap::default();
for h in req.headers_iter() {
header_map.insert(h.name_str(), h.value_str());
}
let mut host_buf = [0u8; 256];
let host = req_host(&header_map, &mut host_buf);
let req_has_auth = header_map.contains_key("authorization");
// path/query 预拷贝入定长栈缓冲:脱离 req 生命周期(供 handle 后 store_cache 复用)
let mut path_buf = [0u8; MAX_PATH_LEN];
let mut query_buf = [0u8; MAX_QUERY_LEN];
let path = copy_str_into(path, &mut path_buf);
let query = copy_str_into(query, &mut query_buf);
// 0. 身份一致性三步校验(AGENT §4.5)
if let Some(resp) = security.check_identity_consistency(
&req, host, None, bind_addr, identity.as_ref(),
) {
return resp;
}
// 0a. /metrics 端点(身份校验之后,豁免 WAF/缓存,计入 requests_total)
if let Some(metrics_resp) = security.try_metrics_endpoint(method, path, header_map.get("authorization").copied()) {
security.record_counter("requests_total", 1);
return metrics_resp;
}
// 1. 能力权限校验
if !security.check_capability(Capability::NetworkAccess) {
security.audit("CAPABILITY_DENIED", &format!("method={method} path={path}"));
let mut resp = CanonicalResponse::new(403);
resp.set_body(b"{\"error\":\"capability denied\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
return resp;
}
// 2. TLS 指纹安全控制(黑名单 + 速率限制;严格按需,默认关闭)
if security.runtime.fingerprint_security_enabled.load(Ordering::Relaxed) {
// 2a. 指纹黑名单检查
if let Some(reason) = security.check_fingerprint_blocklist(fp) {
security.audit("FINGERPRINT_BLOCKED", &reason);
let mut resp = CanonicalResponse::new(403);
resp.set_body(format!(
r#"{{"error":"blocked","reason":"{}","rule":"tls_fingerprint"}}"#,
reason
).into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
security.record_counter("fingerprint_blocked", 1);
return resp;
}
// 2b. TLS 指纹速率限制
if security.check_fingerprint_rate_limit(
fp,
security.runtime.fingerprint_rate_limit_requests.load(Ordering::Relaxed) as u32,
security.runtime.fingerprint_rate_limit_window_ms.load(Ordering::Relaxed),
) {
security.audit("FINGERPRINT_RATE_LIMITED", &format!("method={method} path={path}"));
let mut resp = CanonicalResponse::new(429);
resp.set_body(b"{\"error\":\"rate_limit\",\"reason\":\"tls_fingerprint_rate\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
security.record_counter("fingerprint_rate_limited", 1);
return resp;
}
}
// 4. WAF 检查(仅当该 host 按需启用 WAF;默认关闭)
if security.waf_enabled_for_host(host)
&& let Some(blocked) = security.check_waf(&req)
{
let elapsed_us = start.elapsed().as_micros() as u64;
security.record_req_done_metrics(elapsed_us, &["waf_blocked"]);
security.auditf("WAF_BLOCKED", format_args!("method={method} path={path}"));
return blocked;
}
// 5. Cache 查询
if let Some(cached) = security.check_cache(&req, host) {
security.auditf("CACHE_HIT", format_args!("method={method} path={path}"));
return cached;
}
// 5a. 反向代理转发(Cache 之后、App 之前;QUIC 必然加密 → proto=https)
// client_ip 格式化写入栈缓冲(IPv6 最长 45B,零堆分配)
let mut ip_buf = [0u8; 46];
let client_ip = {
use std::io::Write as _;
let mut cur: &mut [u8] = &mut ip_buf;
let _ = write!(cur, "{}", from.ip());
let used = 46 - cur.len();
std::str::from_utf8(&ip_buf[..used]).unwrap_or("0.0.0.0")
};
if let Some(proxied) =
security.try_proxy(method, path, query, host, &header_map, body, client_ip, "https")
{
let elapsed_us = start.elapsed().as_micros() as u64;
security.record_req_done_metrics(elapsed_us, &["requests_total"]);
return proxied;
}
// 6. Supervisor 状态检查
#[cfg(feature = "runtime")]
{
let supervisor = lock_recover(&security.supervisor);
let state = supervisor.state();
if state == SupervisorState::Failed {
let mut resp = CanonicalResponse::new(503);
resp.set_body(b"{\"error\":\"service unavailable\",\"reason\":\"supervisor failed\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
security.audit("SUPERVISOR_FAILED", &format!("state={:?}", state));
return resp;
}
}
security.auditf("REQUEST", format_args!("method={method} path={path}"));
let resp = app.handle(req);
// Supervisor 健康反馈:5xx 计数 + 超阈值 Failed 熔断(统一闭环)
security.report_health(resp.status_code < 500);
security.store_cache(method, path, query, host, req_has_auth, &resp);
let elapsed_us = start.elapsed().as_micros() as u64;
security.record_req_done_metrics(elapsed_us, &["requests_total"]);
security.auditf(
"RESPONSE",
format_args!("method={method} status={}", resp.status_code),
);
resp
};
quic.handle_packet(data, from, &app_handler)
.map_err(|e| ServerError::Protocol(format!("QUIC packet error: {e}")))
}
/// 获取 QUIC 服务器本地地址
pub fn quic_local_addr(&self) -> Option<SocketAddr> {
self.quic_server.as_ref().and_then(|q| q.local_addr())
}
/// QUIC 服务器是否已初始化(bind_quic 或 bind_quic_socketless 任一完成)
#[inline]
pub fn is_quic_bound(&self) -> bool {
self.quic_server.is_some()
}
/// QUIC 服务器是否为无内核 socket 模式(socketless:AF_XDP 数据面专用)
///
/// 仅 `bind_quic_socketless` 初始化的实例返回 `true`;
/// `bind_quic`(内核 UDP socket)或未绑定时返回 `false`。
#[inline]
pub fn is_quic_socketless(&self) -> bool {
self.quic_server.as_ref().map(|q| q.is_socketless()).unwrap_or(false)
}
/// 获取 QUIC 活动连接数
pub fn quic_active_connections(&self) -> usize {
self.quic_server.as_ref().map(|q| q.active_connections()).unwrap_or(0)
}
/// QUIC/HTTP3 服务器主循环(内核 UDP socket 旁路)
///
/// 从绑定的 UDP socket 接收数据包,喂入 QUIC 传输层处理,
/// 解密得到 HTTP/3 请求后经安全管道处理,加密响应并回发。
///
/// # 平台合规警告
/// **本路径走内核 UDP socket(recv_from/send_to),属于铁则 1 的旁路。**
/// Linux 生产部署必须使用 AF_XDP 主数据面(`afxdp_bridge::AfxdpH3Bridge`),
/// 本方法仅用于非 Linux 平台(Windows/macOS)的开发演示与功能验证。
///
/// # 流程
/// 1. UDP recv_from → QUIC 包解析/解密 → HTTP/3 帧解析
/// 2. HTTP/3 请求 → SecurityPipeline → App → HTTP/3 响应编码
/// 3. 响应 → QUIC 加密 → UDP send_to
///
/// # 参数
/// - `max_packet_size`: UDP 接收缓冲区大小(建议 1500 以支持以太网 MTU)
///
/// # 返回
/// - `Ok(())`: 正常退出(如 socket 关闭)
/// - `Err(ServerError)`: 致命错误
///
/// 构建 UDP 服务循环的应用层请求处理器(serve_udp_loop / io_uring 路径共享)
///
/// app_handler 签名:接收请求 + 可选 TLS 指纹(由 QUIC 传输层从 ClientHello 解密提取并传递)
/// 指纹绝不通过共享状态传递,而是作为参数显式传入,杜绝多连接竞争
fn build_app_handler(
app: Arc<App>,
security: SecurityPipeline,
from: SocketAddr,
bind_addr: Option<SocketAddr>,
identity: Option<IdentityMiddleware>,
) -> impl Fn(CanonicalRequest, Option<&Ja3Fingerprint>) -> zenith_api::CanonicalResponse {
let app_for_handler = app;
let sec_for_handler = security;
move |req: CanonicalRequest, fp: Option<&Ja3Fingerprint>| -> zenith_api::CanonicalResponse {
// 借用管线(L7 热路径零堆分配):与主安全管道同款语义
let start = Instant::now();
let method = req.method.as_str();
let path = req.path_str();
let query = req.query_str();
// body 借用(零拷贝):WAF/try_proxy 仅读取,req 在 app.handle 才被消费
let body = req.body();
let mut header_map: FxHashMap<&str, &str> = FxHashMap::default();
for h in req.headers_iter() {
header_map.insert(h.name_str(), h.value_str());
}
let mut host_buf = [0u8; 256];
let host = req_host(&header_map, &mut host_buf);
let req_has_auth = header_map.contains_key("authorization");
// path/query 预拷贝入定长栈缓冲:脱离 req 生命周期(供 handle 后 store_cache 复用)
let mut path_buf = [0u8; MAX_PATH_LEN];
let mut query_buf = [0u8; MAX_QUERY_LEN];
let path = copy_str_into(path, &mut path_buf);
let query = copy_str_into(query, &mut query_buf);
// 0. 身份一致性三步校验(AGENT §4.5):SNI↔Host、端口一致、虚拟主机白名单。
// H3 路径与 H1/H2 共用 check_identity_consistency,确保完全相同的验证逻辑。
// SNI 在 H3 闭包中不可用(QUIC 连接级 SNI 未传入请求处理器),传 None
// → SNI↔Host 检查跳过(与 H1/H2 中 SNI=None 时行为一致),端口与白名单仍执行。
// /metrics 不再豁免身份校验——防止绕过虚拟主机白名单(ISSUE H3 修复)。
if let Some(resp) = sec_for_handler.check_identity_consistency(
&req, host, None, bind_addr, identity.as_ref(),
) {
return resp;
}
// 0a. /metrics 端点(身份校验之后,豁免 WAF/缓存,计入 requests_total)
if let Some(metrics_resp) = sec_for_handler.try_metrics_endpoint(method, path, header_map.get("authorization").copied()) {
sec_for_handler.record_counter("requests_total", 1);
return metrics_resp;
}
// 1. 能力权限校验(Capability-based security)
if !sec_for_handler.check_capability(Capability::NetworkAccess) {
sec_for_handler.audit("CAPABILITY_DENIED", &format!("method={method} path={path}"));
let mut resp = CanonicalResponse::new(403);
resp.set_body(b"{\"error\":\"capability denied\",\"required\":\"network_access\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
return resp;
}
// 2. TLS 指纹安全控制(QUIC 连接级,黑名单 + 速率限制;严格按需,默认关闭)
if sec_for_handler.runtime.fingerprint_security_enabled.load(Ordering::Relaxed) {
// 2a. 指纹黑名单检查
if let Some(reason) = sec_for_handler.check_fingerprint_blocklist(fp) {
sec_for_handler.audit("FINGERPRINT_BLOCKED", &reason);
let mut resp = CanonicalResponse::new(403);
resp.set_body(format!(
r#"{{"error":"blocked","reason":"{}","rule":"tls_fingerprint"}}"#,
reason
).into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
sec_for_handler.record_counter("fingerprint_blocked", 1);
return resp;
}
// 2b. TLS 指纹速率限制(每 JA3 hash 独立计数,窗口/次数可配置)
let rate_requests = sec_for_handler.runtime.fingerprint_rate_limit_requests.load(Ordering::Relaxed);
let rate_window = sec_for_handler.runtime.fingerprint_rate_limit_window_ms.load(Ordering::Relaxed);
if sec_for_handler.check_fingerprint_rate_limit(fp, rate_requests as u32, rate_window) {
sec_for_handler.audit("FINGERPRINT_RATE_LIMITED", &format!("method={method} path={path}"));
let mut resp = CanonicalResponse::new(429);
resp.set_body(format!(
r#"{{"error":"rate_limit","reason":"tls_fingerprint_rate","limit":{},"window_ms":{}}}"#,
rate_requests,
rate_window
).into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
sec_for_handler.record_counter("fingerprint_rate_limited", 1);
return resp;
}
}
// 4. WAF 检查(SQL 注入 / XSS / SSRF 等攻击特征检测;仅当该 host 按需启用)
if sec_for_handler.waf_enabled_for_host(host)
&& let Some(blocked) = sec_for_handler.check_waf(&req)
{
let elapsed_us = start.elapsed().as_micros() as u64;
sec_for_handler.record_req_done_metrics(elapsed_us, &["waf_blocked"]);
sec_for_handler.auditf("WAF_BLOCKED", format_args!("method={method} path={path}"));
return blocked;
}
// 5. Cache 查询(规范化 method+path+query 作为 key)
if let Some(cached) = sec_for_handler.check_cache(&req, host) {
sec_for_handler.auditf("CACHE_HIT", format_args!("method={method} path={path}"));
return cached;
}
// 5a. 反向代理转发(Cache 之后、App 之前;QUIC 必然加密 → proto=https)
// client_ip 格式化写入栈缓冲(IPv6 最长 45B,零堆分配)
let mut ip_buf = [0u8; 46];
let client_ip = {
use std::io::Write as _;
let mut cur: &mut [u8] = &mut ip_buf;
let _ = write!(cur, "{}", from.ip());
let used = 46 - cur.len();
std::str::from_utf8(&ip_buf[..used]).unwrap_or("0.0.0.0")
};
if let Some(proxied) =
sec_for_handler.try_proxy(method, path, query, host, &header_map, body, client_ip, "https")
{
let elapsed_us = start.elapsed().as_micros() as u64;
sec_for_handler.record_req_done_metrics(elapsed_us, &["requests_total"]);
return proxied;
}
// 6. Supervisor 状态检查(Node 级故障熔断)
#[cfg(feature = "runtime")]
{
let supervisor = lock_recover(&sec_for_handler.supervisor);
let state = supervisor.state();
if state == SupervisorState::Failed {
let mut resp = CanonicalResponse::new(503);
resp.set_body(b"{\"error\":\"service unavailable\",\"reason\":\"supervisor failed\",\"node\":\"quic\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
sec_for_handler.audit("SUPERVISOR_FAILED", &format!("state={:?}", state));
return resp;
}
}
// 7. 正常请求处理
sec_for_handler.auditf("REQUEST", format_args!("method={method} path={path}"));
let resp = app_for_handler.handle(req);
// Supervisor 健康反馈:5xx 计数 + 超阈值 Failed 熔断(统一闭环)
sec_for_handler.report_health(resp.status_code < 500);
sec_for_handler.store_cache(method, path, query, host, req_has_auth, &resp);
let elapsed_us = start.elapsed().as_micros() as u64;
sec_for_handler.record_req_done_metrics(elapsed_us, &["requests_total"]);
sec_for_handler.auditf(
"RESPONSE",
format_args!("method={method} status={}", resp.status_code),
);
resp
}
}
/// io_uring 批量收发 UDP 服务循环(Linux 5.1+ 高性能路径)
///
/// 与 serve_udp_loop 行为完全一致(相同安全管线),
/// 将每包 2 次 syscall(recv_from + send_to)合并为 ≤2 次 io_uring_enter:
/// - 接收:32 个 recv slot 预武装 → submit_and_wait(1) → 批量收割
/// - 发送:响应包批量 push_sendmsg → 单次 submit_and_wait 全部完成
///
/// # 返回
/// - `Ok(false)`:io_uring 不可用(内核不支持/资源不足),调用方回落内核 socket 路径
/// - `Err(_)`:运行期致命错误(io_uring_enter 失败)
/// - 正常情况永不返回(同 serve_udp_loop)
#[cfg(all(feature = "afxdp", target_os = "linux"))]
fn serve_udp_loop_io_uring(&mut self, max_packet_size: usize) -> Result<bool, ServerError> {
use std::os::unix::io::AsRawFd;
let quic = self
.quic_server
.as_mut()
.ok_or_else(|| ServerError::Protocol("QUIC server not bound — call bind_quic() first".into()))?;
let app = self.app.clone();
let security = self.security.clone();
let bind_addr = self.security.runtime_bind_addr();
let identity = self.identity.clone();
let socket = quic
.socket()
.ok_or_else(|| ServerError::Protocol("QUIC socket not available".into()))?
.try_clone()
.map_err(ServerError::Io)?;
let fd = socket.as_raw_fd();
let mut io = match zenith_linux::UdpBatchIo::new(fd, 32, 64, max_packet_size) {
Ok(io) => io,
Err(e) => {
tracing::warn!(error = %e, "io_uring 不可用,回落内核 socket 旁路");
return Ok(false);
}
};
tracing::info!("serve_udp_loop 使用 io_uring 批量收发(recv=32 send=64 slots)");
loop {
io.arm_recv()
.map_err(|e| ServerError::Protocol(format!("io_uring arm_recv: {e}")))?;
// early_recv 暂存非空(flush_send 期间提前到达的包)时跳过阻塞等待,
// 立即收割处理,避免无新包到达时死等
if io.early_recv_empty() {
io.submit_and_wait(1)
.map_err(|e| ServerError::Protocol(format!("io_uring submit_and_wait: {e}")))?;
}
let recv_packets = io.collect_recv();
for (data, from) in recv_packets {
let app_handler = Self::build_app_handler(app.clone(), security.clone(), from, bind_addr, identity.clone());
match quic.handle_packet(&data, from, &app_handler) {
Ok(packets) => {
if let Some(fp) = quic.take_last_fingerprint() {
tracing::debug!(
ja3 = %fp.ja3_hash,
from = %from,
"QUIC fingerprint captured"
);
security.record_fingerprint(fp);
}
for (packet, addr) in packets {
tracing::debug!("[SENDDBG] {}B to {} first={:02x?}", packet.len(), addr, &packet[..packet.len().min(40)]);
tracing::debug!("[SENDFULL] {:02x?}", packet);
match io.push_send(&packet, &addr) {
Ok(true) => {}
Ok(false) => {
// send slot 满:先 flush 再重试
io.flush_send().map_err(|e| {
ServerError::Protocol(format!("io_uring flush_send: {e}"))
})?;
if let Err(e) = io.push_send(&packet, &addr) {
tracing::warn!(error = %e, "io_uring push_send retry failed");
}
}
Err(e) => {
tracing::warn!(error = %e, to = %addr, "io_uring push_send failed");
}
}
}
}
Err(e) => {
tracing::warn!(error = %e, from = %from, "QUIC packet handling error");
}
}
// 关键修复:HANDSHAKE_DONE 即时送达。
// 当握手(Handshake 完成) 与 1-RTT 请求在同一 UDP 数据报(coalesced)时,
// handle_packet 已把 1-RTT 子包推迟到 pending_1rtt;这里先 flush 使
// HANDSHAKE_DONE 独立成包发出,客户端在写请求体(DATA) 前即可收到,
// 消除 `ngtcp2_conn_writev_stream returned error: ERR_CLOSING` 的竞态
// (HTTP/3 POST 稳定失败)。先于 pending_1rtt 重处理 flush 是关键——
// 否则 HANDSHAKE_DONE 与 1-RTT 响应仍会在同一批次发出。
io.flush_send()
.map_err(|e| ServerError::Protocol(format!("io_uring flush_send: {e}")))?;
// 重处理握手期间缓存的 1-RTT 包(与原循环一致的安全管线)
if !quic.pending_1rtt.is_empty() {
let pending = std::mem::take(&mut quic.pending_1rtt);
for (pkt_data, pkt_from) in pending {
match quic.handle_packet(&pkt_data, pkt_from, &app_handler) {
Ok(packets) => {
for (packet, addr) in packets {
match io.push_send(&packet, &addr) {
Ok(true) => {}
Ok(false) => {
io.flush_send().map_err(|e| {
ServerError::Protocol(format!(
"io_uring flush_send: {e}"
))
})?;
let _ = io.push_send(&packet, &addr);
}
Err(e) => {
tracing::warn!(error = %e, "io_uring push_send failed");
}
}
}
}
Err(e) => {
tracing::warn!(error = %e, "pending 1-RTT reprocess error");
}
}
}
// 重处理产生的 1-RTT 响应一并 flush
io.flush_send()
.map_err(|e| ServerError::Protocol(format!("io_uring flush_send: {e}")))?;
}
}
io.flush_send()
.map_err(|e| ServerError::Protocol(format!("io_uring flush_send: {e}")))?;
}
}
/// UDP/QUIC 服务循环(内核 socket 路径,非 AF_XDP 主路径)
///
/// Linux 下优先 io_uring 批量收发(syscall 从 2/包 降到 ≤2/批),
/// 内核不支持时回落 `UdpSocket` 旁路。生产主路径应使用
/// `afxdp_bridge::AfxdpH3Bridge`(铁则 1),本方法用于开发/调试与
/// 非 Linux 平台降级。
///
/// `max_packet_size` 为单包接收缓冲上限(字节),超限数据报截断处理。
pub fn serve_udp_loop(&mut self, max_packet_size: usize) -> Result<(), ServerError> {
// Linux + afxdp:优先 io_uring 批量收发路径(syscall 从 2/包 降到 ≤2/批);
// 内核不支持时 Ok(false) 回落内核 socket 旁路
#[cfg(all(feature = "afxdp", target_os = "linux"))]
{
match self.serve_udp_loop_io_uring(max_packet_size) {
Ok(false) => {
tracing::warn!("io_uring 路径不可用,使用内核 socket 旁路");
}
Ok(true) => {
// io_uring 服务循环正常退出(连接关闭/超时),非错误
return Ok(());
}
Err(e) => return Err(e),
}
}
// Linux 平台警告:生产环境应使用 AF_XDP 桥而非内核 socket 旁路
#[cfg(target_os = "linux")]
tracing::warn!(
"serve_udp_loop 走内核 UDP socket 旁路(铁则 1 例外)。\
Linux 生产部署请使用 afxdp_bridge::AfxdpH3Bridge(AF_XDP 主数据面)。"
);
// 提前拆出需要的所有权,避免闭包捕获 self 导致的借用冲突
let quic = self
.quic_server
.as_mut()
.ok_or_else(|| ServerError::Protocol("QUIC server not bound — call bind_quic() first".into()))?;
let app = self.app.clone();
let security = self.security.clone();
let bind_addr = self.security.runtime_bind_addr();
let identity = self.identity.clone();
let socket = quic.socket()
.ok_or_else(|| ServerError::Protocol("QUIC socket not available".into()))?
.try_clone()
.map_err(ServerError::Io)?;
let mut buf = vec![0u8; max_packet_size];
loop {
match socket.recv_from(&mut buf) {
Ok((n, from)) => {
let data = &buf[..n];
// app_handler 签名:接收请求 + 可选 TLS 指纹(由 QUIC 传输层从 ClientHello 解密提取并传递)
// 指纹绝不通过共享状态传递,而是作为参数显式传入,杜绝多连接竞争
let app_handler =
Self::build_app_handler(app.clone(), security.clone(), from, bind_addr, identity.clone());
match quic.handle_packet(data, from, &app_handler) {
Ok(packets) => {
// 记录 QUIC 连接的 TLS 指纹到审计日志
if let Some(fp) = quic.take_last_fingerprint() {
tracing::debug!(
ja3 = %fp.ja3_hash,
from = %from,
"QUIC fingerprint captured"
);
security.record_fingerprint(fp);
}
for (packet, addr) in packets {
if let Err(e) = socket.send_to(&packet, addr) {
tracing::warn!(error = %e, to = %addr, "QUIC send failed");
}
}
}
Err(e) => {
tracing::warn!(
error = %e,
from = %from,
"QUIC packet handling error"
);
}
}
// 重处理握手期间缓存的 1-RTT 包(握手完成后状态已切换为 Established)
// 用 if 而非 while:避免 Handshaking 状态下无限重新缓存
if !quic.pending_1rtt.is_empty() {
let pending = std::mem::take(&mut quic.pending_1rtt);
for (pkt_data, pkt_from) in pending {
// 安全铁律:重处理必须走与正常包完全相同的安全管线
// (capability/指纹/WAF/Cache/审计),禁止裸调 app.handle 绕过
match quic.handle_packet(&pkt_data, pkt_from, &app_handler) {
Ok(packets) => {
for (packet, addr) in packets {
let _ = socket.send_to(&packet, addr);
}
}
Err(e) => {
tracing::warn!(error = %e, "pending 1-RTT reprocess error");
}
}
}
}
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
continue;
}
Err(ref e) if e.kind() == std::io::ErrorKind::ConnectionReset => {
continue;
}
Err(e) => {
tracing::error!(error = %e, "QUIC UDP recv error");
return Err(ServerError::Io(e));
}
}
}
}
/// 获取 TLS 指纹快照
pub fn tls_fingerprints(&self) -> Vec<Ja3Fingerprint> {
self.security.fingerprint_snapshot()
}
/// 获取 TLS 指纹数量
pub fn tls_fingerprint_count(&self) -> usize {
self.security.fingerprint_count()
}
// ─────────────────────────────────────────────────────────────────────
// 5. HTTP/2 Preface 检测
// ─────────────────────────────────────────────────────────────────────
/// 检测缓冲区首字节是否为 HTTP/2 连接前言
///
/// 判断是否为 HTTP/2 客户端前言
///
/// RFC 7540 §3.5:精确匹配 24B PREFACE → H2 路径。
///
/// 宽松兜底:长度 ≥ 24B 且以 `"PRI "`(4B)开头的非精确匹配字节
/// 也判为 H2 → 路由到 `handle_http2_connection`,由其做精确校验后
/// 发 GOAWAY(PROTOCOL_ERROR) + 断连(RFC 7540 §3.5 "MUST" 语义)。
/// 修复前精确匹配将这些 invalid preface 误判为 H1 → 400 响应,
/// h2spec 3.5 #2 期望 GOAWAY 而非 400。
///
/// # 安全
/// `"PRI "` 不是合法 HTTP/1.1 方法(GET/POST/PUT/DELETE/...),不存在
/// 合法 H1 请求以 `"PRI "` 开头的场景——宽松匹配不会误吞 H1 流量。
#[inline]
pub fn is_http2_preface(buf: &[u8]) -> bool {
if buf.len() >= PREFACE_LEN && &buf[..PREFACE_LEN] == PREFACE {
return true;
}
// 宽松兜底:长度 >= 24B 且不是合法 HTTP/1.1 请求行开头
// → 判为 H2 路径(h2spec 3.5 #2 发 "INVALID CONNECTION PREFACE\r\n\r\n",
// 不是已知 H1 方法 → 判 H2 → handle_http2_connection 内精确校验后 GOAWAY)
if buf.len() >= PREFACE_LEN {
let first_space = buf.iter().position(|&b| b == b' ').unwrap_or(buf.len());
let method = &buf[..first_space.min(16)];
// RFC 9110 §9:已知 HTTP/1.1 方法白名单(大写 + '-')
const KNOWN_H1_METHODS: &[&[u8]] = &[
b"GET", b"POST", b"PUT", b"PATCH", b"DELETE", b"HEAD",
b"OPTIONS", b"CONNECT", b"TRACE",
];
let is_h1_method = !method.is_empty()
&& KNOWN_H1_METHODS.contains(&method)
&& first_space < buf.len()
&& buf[first_space] == b' ';
if !is_h1_method {
return true;
}
}
false
}
// ─────────────────────────────────────────────────────────────────────
// 6. 协议自动检测
// ─────────────────────────────────────────────────────────────────────
/// 根据 TLS ALPN 协商结果与 post-handshake 首字节自动检测协议
///
/// 优先级(从高到低):
/// 1. ALPN 已协商且已知 → 使用 ALPN(rustls 在握手时完成协商,结果真实可靠)
/// 2. post_handshake_data 长度 ≥ 24 且匹配 HTTP/2 preface → Http2
/// (这是 TLS 握手完成后客户端发送的实际 HTTP 数据,不是 ClientHello)
/// 3. 其他情况 → 默认 Http1
///
/// # 重要
/// - `peeked` 参数必须是 TLS 握手**之后**客户端发送的数据(initial_buf),
/// 绝不能传入 ClientHello 原始字节——ClientHello 以 0x16 开头,
/// 不可能匹配 HTTP/2 preface,会导致 fallback 永远失效。
/// - ALPN 结果来自 rustls 的真实 TLS 握手(`TlsStream::alpn_protocol()`),
/// 只有当客户端在 ClientHello 中声明了 ALPN 且服务器支持时才会有值。
/// 若客户端未声明 ALPN,rustls 返回 None,此时必须依赖 post-handshake 数据检测。
#[inline]
pub fn detect_protocol_from_post_tls(
post_handshake_data: &[u8],
alpn: Option<&[u8]>,
) -> Protocol {
// 第一优先级:ALPN 协商结果
if let Some(alpn_bytes) = alpn
&& let Some(p) = alpn_to_protocol(alpn_bytes) {
return p;
}
// 第二优先级:post-handshake 数据检测(此时 TLS 已完成,
// 客户端要么发 H2 preface 要么发 H1 请求)
if Self::is_http2_preface(post_handshake_data) {
Protocol::Http2
} else {
Protocol::Http1
}
}
/// 根据 peeked 首字节与 ALPN 协商结果自动检测协议(明文 TCP 路径专用)
///
/// 用于明文 TCP 分支:直接 peek 原始 TCP 数据(此时数据就是 HTTP 请求,
/// 不是 ClientHello),所以 fallback 检查 HTTP/2 preface 是正确的。
#[inline]
pub fn detect_protocol_from_peek(peeked: &[u8], alpn: Option<&[u8]>) -> Protocol {
if let Some(alpn_bytes) = alpn
&& let Some(p) = alpn_to_protocol(alpn_bytes) {
return p;
}
if Self::is_http2_preface(peeked) {
Protocol::Http2
} else {
Protocol::Http1
}
}
// ─────────────────────────────────────────────────────────────────────
// 4. HTTP/1.1 连接处理器
// ─────────────────────────────────────────────────────────────────────
/// 处理一条 HTTP/1.1 连接(含初始缓冲数据,用于 TLS 握手后直接处理请求)
///
/// 关键修复:正确处理 initial 数据中可能包含的完整 HTTP 请求。
/// `parser.feed(initial)` 返回 `Ok((Some(req), consumed))` 时,
/// 必须立即处理该请求,不能忽略。否则请求已被 parser 消耗,
/// 后续 `parser.feed(&[])` 无法再获取,导致阻塞等待下一个请求。
///
/// TLS 指纹通过参数传递(而非共享状态),确保连接级隔离。
#[inline]
fn handle_http1_connection_with_initial<IO: Read + Write>(
&self,
io: &mut IO,
transport: Transport,
initial: &[u8],
tls_fingerprint: Option<Ja3Fingerprint>,
sni: Option<&str>,
client_ip: &str,
) -> Result<(), ServerError> {
// 运行时热更新值:每连接一次原子加载(单指令),本连接内复用
let rt = &self.security.runtime;
let http1_max_requests = rt.http1_max_requests_per_conn.load(Ordering::Relaxed) as u32;
let max_body_size = rt.max_body_size.load(Ordering::Relaxed) as usize;
let http1_idle = rt.http1_idle_timeout_ms.load(Ordering::Relaxed);
let read_buffer_size = rt.read_buffer_size.load(Ordering::Relaxed) as usize;
let write_buffer_size = rt.write_buffer_size.load(Ordering::Relaxed) as usize;
let http1_max_buf = read_buffer_size
.checked_mul(2)
.ok_or_else(|| ServerError::Internal("read_buffer_size * 2 overflow".into()))?;
let http1_config = Http1Config::new()
.with_max_body_size(max_body_size)
.with_idle_timeout_ms(http1_idle)
.with_max_buffer_size(http1_max_buf);
let mut parser = Http1Parser::new(http1_config);
let mut read_buf: Vec<u8> = vec![0u8; read_buffer_size];
let mut write_buf: Vec<u8> = Vec::with_capacity(write_buffer_size);
let mut request_count: u32 = 0;
let mut any_bytes_read: bool = !initial.is_empty();
// 先喂入初始数据,捕获可能包含的完整请求
if !initial.is_empty() {
match parser.feed(initial) {
Ok((Some(req), _consumed)) => {
// initial 包含完整请求,立即处理
request_count = request_count
.checked_add(1)
.ok_or_else(|| ServerError::Internal("request_count overflow".into()))?;
let should_close = !req.keep_alive
|| req.line.version.as_ref() == "HTTP/1.0"
// 达到 keep-alive 上限:本响应为最后一个,须通知客户端关闭
|| request_count >= http1_max_requests;
// fail-closed 且通信反馈义务(§4.4 + RFC 7231):规范化层拒绝
// 必须明确回写 400,禁止静默关闭(对端不得感知 EOF-instead-of-4xx)
let canonical_req = match normalize_http1_request(&req, transport) {
Ok(r) => r,
Err(e) => {
let mut resp = CanonicalResponse::new(400);
resp.set_body(b"{\"error\":\"bad request\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::from(e));
}
};
let canonical_resp = self.process_request_with_security(canonical_req, tls_fingerprint.as_ref(), sni, client_ip);
// 若本响应后即将关闭,写入 `Connection: close`(RFC 7230 §6.1),
// 避免客户端连接池竞态复用导致 read error。
let mut resp = canonical_resp;
if should_close {
let already_has_connection = resp
.headers_iter()
.iter()
.any(|h| h.name[..h.name_len as usize].eq_ignore_ascii_case(b"connection"));
if !already_has_connection {
let _ = resp.add_header(b"connection", b"close");
}
}
encode_response_http1(&resp, &mut write_buf)?;
io.write_all(&write_buf)?;
io.flush()?;
write_buf.clear();
if should_close || request_count > http1_max_requests {
return Ok(());
}
}
Ok((None, _)) => {
// initial 数据不足一个完整请求,继续从 IO 读取
}
Err(Http1Error::NeedMoreData) => {
// 需要更多数据
}
Err(e) => {
// 解析层拒绝(未知方法/语法错误):尽力回写 4xx 再关闭(fail-closed 但不裸断)
let (code, msg) = match &e {
Http1Error::UnsupportedMethod(_) => (405, "method not allowed"),
Http1Error::IdleTimeout => (408, "request timeout"),
_ => (400, "bad request"),
};
let mut resp = CanonicalResponse::new(code);
resp.set_body(format!("{{\"error\":\"{msg}\"}}").into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::Http1(e));
}
}
}
loop {
request_count = request_count
.checked_add(1)
.ok_or_else(|| ServerError::Internal("request_count overflow".into()))?;
if request_count > http1_max_requests {
break;
}
let http_req: Http1Request = loop {
match parser.feed(&[]) {
Ok((Some(req), _consumed)) => break req,
Ok((None, _)) => {}
Err(Http1Error::NeedMoreData) => {}
Err(e) => {
// 解析层拒绝(未知方法/语法错误):尽力回写 4xx 再关闭(fail-closed 但不裸断)
let (code, msg) = match &e {
Http1Error::UnsupportedMethod(_) => (405, "method not allowed"),
Http1Error::IdleTimeout => (408, "request timeout"),
_ => (400, "bad request"),
};
let mut resp = CanonicalResponse::new(code);
resp.set_body(format!("{{\"error\":\"{msg}\"}}").into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::Http1(e));
}
}
let n = match io.read(&mut read_buf) {
Ok(0) => {
if !any_bytes_read {
return Ok(());
}
return Err(ServerError::ConnectionClosed);
}
Ok(n) => n,
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
// socket 级读超时(serve_std_tcp_conn 已按
// http1_idle_timeout_ms 设置)触发:驱动 parser 双时间戳
// Slowloris 判决(first_byte/last_activity)。
// 修复前两处层保护均未接线:socket 无超时 = read 永不返回,
// parser 时间戳无人记录 = 判决永不执行。
// IdleTimeout → 408 Request Timeout(RFC 9110 §15.5.11),
// 尽力回写后断开(fail-closed 且不裸断)。
if let Err(he) =
parser.check_idle_timeout(current_time_ms())
{
let mut resp = CanonicalResponse::new(408);
resp.set_body(b"{\"error\":\"request timeout\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::Http1(he));
}
continue;
}
Err(e) => return Err(ServerError::Io(e)),
};
any_bytes_read = true;
// 每次真实收到字节都刷新 parser 活跃时间戳(Slowloris 判决的计时基准,
// 连接层按 note_activity 契约驱动;此前无人调用,判决永不触发)
parser.note_activity(current_time_ms());
match parser.feed(&read_buf[..n]) {
Ok((Some(req), _consumed)) => break req,
Ok((None, _)) => continue,
Err(Http1Error::NeedMoreData) => continue,
Err(e) => {
// 解析层拒绝(未知方法/语法错误):尽力回写 4xx 再关闭(fail-closed 但不裸断)
let (code, msg) = match &e {
Http1Error::UnsupportedMethod(_) => (405, "method not allowed"),
Http1Error::IdleTimeout => (408, "request timeout"),
_ => (400, "bad request"),
};
let mut resp = CanonicalResponse::new(code);
resp.set_body(format!("{{\"error\":\"{msg}\"}}").into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::Http1(e));
}
}
};
let should_close: bool = !http_req.keep_alive || http_req.line.version.as_ref() == "HTTP/1.0";
// 规范化层拒绝 → 明确 400(见 serve_tcp 同款 fail-closed 注释)
let canonical_req: CanonicalRequest = match normalize_http1_request(&http_req, transport) {
Ok(r) => r,
Err(e) => {
let mut resp = CanonicalResponse::new(400);
resp.set_body(b"{\"error\":\"bad request\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::from(e));
}
};
let canonical_resp = self.process_request_with_security(canonical_req, tls_fingerprint.as_ref(), sni, client_ip);
encode_response_http1(&canonical_resp, &mut write_buf)?;
io.write_all(&write_buf)?;
io.flush()?;
write_buf.clear();
if should_close {
break;
}
}
Ok(())
}
/// 处理一条 HTTP/1.1 连接(含 keep-alive 循环)
///
/// 使用同一个同时实现 `Read + Write` 的 IO 对象(TcpStream 或 TlsStream),
/// 避免 TlsStream 无法 try_clone 的问题,并减少 TCP 路径上额外的 fd 复制开销。
/// HTTP/1.1 本身是串行半双工(请求→响应→下一个请求→…),单 IO 对象足够。
///
/// # 算法
/// 1. 初始化增量解析器与读写缓冲区
/// 2. keep-alive 循环,每次迭代:
/// - 检查请求计数是否超出上限
/// - 从 io 读入数据并 feed 给解析器,直到得到完整请求或错误
/// - 请求规范化 → App::handle → 响应编码 → 同一个 io 写出并 flush
/// - 根据 Connection: close / HTTP/1.0 决定是否终止循环
///
/// # 错误处理
/// - `ConnectionClosed`:对端在完整请求前 EOF,且无字节可读
/// - 其他错误向上传播,由调用方关闭连接
pub fn handle_http1_connection<IO: Read + Write>(
&self,
io: &mut IO,
transport: Transport,
client_ip: &str,
) -> Result<(), ServerError> {
// 运行时热更新值:每连接一次原子加载(单指令),本连接内复用
let rt = &self.security.runtime;
let http1_max_requests = rt.http1_max_requests_per_conn.load(Ordering::Relaxed) as u32;
let max_body_size = rt.max_body_size.load(Ordering::Relaxed) as usize;
let http1_idle = rt.http1_idle_timeout_ms.load(Ordering::Relaxed);
let read_buffer_size = rt.read_buffer_size.load(Ordering::Relaxed) as usize;
let write_buffer_size = rt.write_buffer_size.load(Ordering::Relaxed) as usize;
let http1_max_buf = read_buffer_size
.checked_mul(2)
.ok_or_else(|| ServerError::Internal("read_buffer_size * 2 overflow".into()))?;
let http1_config = Http1Config::new()
.with_max_body_size(max_body_size)
.with_idle_timeout_ms(http1_idle)
.with_max_buffer_size(http1_max_buf);
let mut parser = Http1Parser::new(http1_config);
let mut read_buf: Vec<u8> = vec![0u8; read_buffer_size];
let mut write_buf: Vec<u8> = Vec::with_capacity(write_buffer_size);
let mut request_count: u32 = 0;
let mut any_bytes_read: bool = false;
loop {
request_count = request_count
.checked_add(1)
.ok_or_else(|| ServerError::Internal("request_count overflow".to_string()))?;
if request_count > http1_max_requests {
break;
}
let http_req: Http1Request = loop {
match parser.feed(&[]) {
Ok((Some(req), _consumed)) => break req,
Ok((None, _)) => {}
Err(Http1Error::NeedMoreData) => {}
Err(e) => {
// 解析层拒绝(未知方法/语法错误):尽力回写 4xx 再关闭(fail-closed 但不裸断)
let (code, msg) = match &e {
Http1Error::UnsupportedMethod(_) => (405, "method not allowed"),
Http1Error::IdleTimeout => (408, "request timeout"),
_ => (400, "bad request"),
};
let mut resp = CanonicalResponse::new(code);
resp.set_body(format!("{{\"error\":\"{msg}\"}}").into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::Http1(e));
}
}
let n = match io.read(&mut read_buf) {
Ok(0) => {
if !any_bytes_read {
return Ok(());
}
return Err(ServerError::ConnectionClosed);
}
Ok(n) => n,
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
// socket 级读超时(serve_std_tcp_conn 已按
// http1_idle_timeout_ms 设置)触发:驱动 parser 双时间戳
// Slowloris 判决(first_byte/last_activity)。
// 修复前两处层保护均未接线:socket 无超时 = read 永不返回,
// parser 时间戳无人记录 = 判决永不执行。
// IdleTimeout → 408 Request Timeout(RFC 9110 §15.5.11),
// 尽力回写后断开(fail-closed 且不裸断)。
if let Err(he) =
parser.check_idle_timeout(current_time_ms())
{
let mut resp = CanonicalResponse::new(408);
resp.set_body(b"{\"error\":\"request timeout\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::Http1(he));
}
continue;
}
Err(e) => return Err(ServerError::Io(e)),
};
any_bytes_read = true;
// 每次真实收到字节都刷新 parser 活跃时间戳(Slowloris 判决的计时基准,
// 连接层按 note_activity 契约驱动;此前无人调用,判决永不触发)
parser.note_activity(current_time_ms());
match parser.feed(&read_buf[..n]) {
Ok((Some(req), _consumed)) => break req,
Ok((None, _)) => continue,
Err(Http1Error::NeedMoreData) => continue,
Err(e) => {
// 解析层拒绝(未知方法/语法错误):尽力回写 4xx 再关闭(fail-closed 但不裸断)
let (code, msg) = match &e {
Http1Error::UnsupportedMethod(_) => (405, "method not allowed"),
Http1Error::IdleTimeout => (408, "request timeout"),
_ => (400, "bad request"),
};
let mut resp = CanonicalResponse::new(code);
resp.set_body(format!("{{\"error\":\"{msg}\"}}").into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::Http1(e));
}
}
};
let should_close: bool = !http_req.keep_alive
|| http_req.line.version.as_ref() == "HTTP/1.0"
// 达到 keep-alive 上限:本响应为最后一个,必须通知客户端关闭
|| request_count >= http1_max_requests;
// 规范化层拒绝 → 明确 400 写回(fail-closed 且不裸断,§4.4);
// 禁止静默关闭(对端不得感知 EOF-instead-of-4xx)
let canonical_req: CanonicalRequest = match normalize_http1_request(&http_req, transport) {
Ok(r) => r,
Err(e) => {
let mut resp = CanonicalResponse::new(400);
resp.set_body(b"{\"error\":\"bad request\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
let mut wb = Vec::new();
if encode_response_http1(&resp, &mut wb).is_ok() {
let _ = io.write_all(&wb);
let _ = io.flush();
}
return Err(ServerError::from(e));
}
};
let canonical_resp = self.process_request_with_security(canonical_req, None, None, client_ip);
// 若本响应后即将关闭连接(Connection: close / HTTP/1.0 / keep-alive 上限),
// 必须写入 `Connection: close` 头(RFC 7230 §6.1),通知客户端勿复用该连接,
// 避免客户端连接池在关闭瞬间竞态复用导致 read error。
let mut resp = canonical_resp;
if should_close {
let already_has_connection = resp
.headers_iter()
.iter()
.any(|h| h.name[..h.name_len as usize].eq_ignore_ascii_case(b"connection"));
if !already_has_connection {
let _ = resp.add_header(b"connection", b"close");
}
}
encode_response_http1(&resp, &mut write_buf)?;
io.write_all(&write_buf)?;
io.flush()?;
write_buf.clear();
if should_close {
break;
}
// parser 已在 build_request 中重置状态(WaitingRequest)并保留
// 缓冲区中属于下一个请求的剩余字节(pipelining / keep-alive)。
// 不调用 parser.reset()——那会清空缓冲区,丢失下一个请求的字节。
}
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// 7. serve_std_tcp_conn:带自动检测 + TLS 的连接服务
// ─────────────────────────────────────────────────────────────────────
/// 服务一条标准 TCP 连接,可选择升级 TLS 并自动检测协议
///
/// # 流程(严格真实链路,fail-closed)
///
/// - **TLS 分支(真实加密,零明文旁路)**:
/// 1. `stream.peek` 最多 16KB ClientHello(不移动游标,保证 StreamOwned 后续完整握手)
/// 2. 解析 SNI/客户端 ALPN 列表
/// 3. 通过 `TlsAcceptor::resolve_server_config` 按 SNI 获取已预加载的证书 →
/// **无证书时严格 fail-closed 返回 ServerError::Tls(绝不回退明文)**
/// 4. 构造 `TlsStream::new(stream, config)` → `rustls::StreamOwned` 做完整 TLS 1.3
/// 真实加解密握手,后续所有 HTTP 读写均走加密链路
/// 5. 按 ALPN 协商结果或 H2 preface 检测协议
/// - **明文分支**:
/// 1. `stream.peek` 首 24 字节检测 H2 preface
/// 2. 协议自动检测,无 ALPN 时默认 Http1
/// - **协议分发(严格 fail-closed,绝不再回退 H1)**:
/// - Http1 → handle_http1_connection 完整 keep-alive 循环
/// - Http2 / Http3 → 当前状态机/流复用器未接入,**返回明确 Protocol 错误**,
/// 绝不再用 H1 响应冒充 H2/H3 标识
/// - 原始 L4 (Tcp/Udp/Quic) → 要求专用 dispatcher
///
/// # 性能设计
/// - TCP_NODELAY 强制开启(禁用 Nagle,减少小包延迟)
/// - 整个 HTTP/1.1 处理使用同一个 IO 对象(TcpStream 或 TlsStream),
/// 避免了 TcpStream try_clone() 的额外 fd 复制 + 文件描述符表膨胀
/// - TlsStream 内部是 rustls StreamOwned(堆对象 + 单一所有权),零额外引用计数
/// - peek/initial 缓冲区使用栈上数组,零堆分配热路径(规范 §6.1.2)
/// - 日志走 tracing span,不再 eprintln! 锁 stderr(规范 §6.3)
pub fn serve_std_tcp_conn(
&self,
stream: TcpStream,
client_addr: SocketAddr,
tls_acceptor: Option<&mut TlsAcceptor>,
) -> Result<(), ServerError> {
stream.set_nodelay(true).map_err(ServerError::Io)?;
// 运行时热更新空闲超时:每连接一次原子加载(单指令)
let http1_idle = self
.security
.runtime
.http1_idle_timeout_ms
.load(Ordering::Relaxed);
// Slowloris 防线接线(修复读路径零超时缺陷):
// 1) socket 级读/写超时覆盖 TLS 分支 peek(握手前)+ TLS 握手 + 明文/H2 全链路
// read 阻塞期间 —— 此前仅 H1 parser 内部有时间戳检查,但 `io.read` 阻塞时
// 永不返回、检查永不触发,攻击者连上不发一字节即可永久占住处理线程;
// 2) 超时返回 WouldBlock:H1 分支循环 `feed(&[])` 驱动 parser 双时间戳
// Slowloris 检查作出细粒度判决;H2 分支 `Err(WouldBlock) => break` 直接断开;
// fd 级属性随 try_clone/TlsStream 包装传播,无需逐层重复设置。
stream
.set_read_timeout(Some(Duration::from_millis(
http1_idle,
)))
.map_err(ServerError::Io)?;
stream
.set_write_timeout(Some(Duration::from_millis(
http1_idle,
)))
.map_err(ServerError::Io)?;
// ── 分支 1:TLS(真实加解密,零明文旁路) ──────────────────────────
if let Some(tls_acc) = tls_acceptor {
// 极致性能:栈上 peek 缓冲区,零堆分配
// 16KB 栈数组在 server 处理线程的栈空间内(默认 8MB,16384 字节仅占 0.2%)
let mut peek_buf: [u8; 16_384] = [0u8; 16_384];
let peek_n: usize = match stream.peek(&mut peek_buf) {
Ok(0) => return Err(ServerError::ConnectionClosed),
Ok(n) => n,
Err(e) => return Err(ServerError::Io(e)),
};
let peeked: &[u8] = &peek_buf[..peek_n];
// SNI 解析(用于选择证书)
let sni = TlsAcceptor::peek_sni(peeked);
// 严格 fail-closed:无证书绝不回退明文
let server_config = tls_acc
.resolve_server_config(sni)
.ok_or_else(|| {
TlsAcceptError::CertRotate(CertRotateError::NoCertificateConfigured {
domain: sni.unwrap_or("<default>").to_string(),
})
})?;
// 连接表清扫闭环(修复 gc 零调用方缺陷):
// 本 accept 登记新条目前,先统一回收前人遗留的 Closed/空闲/
// 握手超时条目 —— 否则从 accept() 创建的引擎连接条目将随
// 成功握手永久驻留连接表(上限 MAX_TLS_SESSIONS=1024),
// 灌满后所有新 TLS 连接被 ConnectionTableFull 拒绝。
// 空闲阈值与读超时量级对齐(保活连接在 idle_timeout 内活跃
// 判定:last_active 由 process_tls_data 驱动刷新,
// Closed 标记路径由下方出口处 close_conn 即时驱动)。
//
// 修复 ConnectionTableFull 持久死锁:必须在本 accept() 之前执行。
// 一旦连接表灌满,accept() 会立即在 `?` 处返回
// ConnectionTableFull,导致 gc_engine() 永远无法执行,
// 形成"表满 → accept 失败 → 无法 gc → 表永远满"的自锁,
// 所有新 TLS 连接被永久拒绝(持久 DoS)。
// 先 gc 再 accept:表满时先回收 Closed/空闲/握手超时条目,
// 为新连接腾出槽位,表可自愈。
tls_acc.gc_engine(Duration::from_millis(http1_idle));
// 同时完成 conn_id/metadata/identity 登记(用于审计/监控/连接表)
let accepted: AcceptedTlsConn<TcpStream> = tls_acc.accept(
stream.try_clone().map_err(ServerError::Io)?,
client_addr.ip(),
client_addr.port(),
peeked,
)?;
// 真实构造 TLS 加密流
let mut tls_stream: TlsStream = TlsStream::new(stream, server_config)?;
// 读取初始数据:触发 TLS 握手并获取客户端发送的前几个字节
// StreamOwned 首次 read 自动完成 TLS 握手(ServerHello + Certificate + Finished)
// 极致性能:栈上 8KB 缓冲区,零堆分配
let mut initial_buf: [u8; 8192] = [0u8; 8192];
let initial_n = match tls_stream.read(&mut initial_buf) {
Ok(0) => return Err(ServerError::ConnectionClosed),
Ok(n) => n,
Err(e) => return Err(ServerError::Io(e)),
};
let initial_slice: &[u8] = &initial_buf[..initial_n];
// 从实际 TLS 握手中获取协商的 ALPN(RFC 7301)
let alpn_protocol = tls_stream.alpn_protocol();
let alpn_opt: Option<&[u8]> = alpn_protocol.as_deref();
// ALPN 协商结果日志(真实链路,非摆设)—— tracing 替代 eprintln!
if let Some(proto) = alpn_opt {
let proto_str = String::from_utf8_lossy(proto);
tracing::debug!(
alpn = %proto_str,
client = %client_addr,
"TLS ALPN negotiated"
);
} else {
tracing::debug!(
client = %client_addr,
"TLS ALPN not negotiated by client, falling back to post-handshake detection"
);
}
// TLS 指纹识别(JA3/JA4)——从 ClientHello 字节提取
let tls_fingerprint = if let Some(fp) = Ja3Fingerprint::from_client_hello(peeked) {
tracing::debug!(
ja3 = %fp.ja3_hash,
ja4 = %fp.ja4_hash,
client = %client_addr,
"TLS fingerprint captured"
);
// 记录指纹到历史库(用于审计分析)
self.security.record_fingerprint(fp.clone());
// 指纹通过参数传递给后续处理管道(不再使用共享状态)
Some(fp)
} else {
None
};
let transport = Transport::Tls13;
// 使用 initial_slice(TLS 握手后的真实 HTTP 数据)做 fallback 检测
// 绝不能用 peeked(ClientHello 字节)——那会导致 fallback 永远失效
let protocol = Self::detect_protocol_from_post_tls(initial_slice, alpn_opt);
// 协议分发:严格 fail-closed,绝不静默降级
let outcome: Result<(), ServerError> = match protocol {
Protocol::Http1 => {
tracing::debug!(
client = %client_addr,
"Dispatch: HTTP/1.1 over TLS (h1 over TLS is fully supported)"
);
self.handle_http1_connection_with_initial(
&mut tls_stream,
transport,
initial_slice,
tls_fingerprint,
sni,
&client_addr.ip().to_string(),
)
}
Protocol::Http2 => {
tracing::debug!(
client = %client_addr,
"Dispatch: HTTP/2 over TLS"
);
self.handle_http2_connection_with_initial(
&mut tls_stream,
transport,
initial_slice,
tls_fingerprint,
sni,
&client_addr.ip().to_string(),
)
}
Protocol::Http3 => {
// HTTP/3 不能在 TCP/TLS 上运行,必须走 QUIC/UDP
Err(ServerError::Protocol(
"HTTP/3 (h3) requires QUIC transport, not TLS/TCP. \
Use bind_quic() + serve_udp_quic_datagram() for HTTP/3."
.to_string(),
))
}
other => Err(ServerError::Protocol(format!(
"unsupported protocol on TLS transport: {other:?}. \
Expected h2 or http/1.1 ALPN negotiation."
))),
};
// 连接处理完成(正常/错误任一出口):即时标记引擎侧连接为 Closed,
// 槽位由后续 accept 的 gc_engine 统一回收 —— 与 accepted 保留
// 构成健康路径即时回收闭环(修复连接表永不回收缺陷)。
tls_acc.close_conn(accepted.engine_conn_id());
drop(tls_stream);
return outcome;
}
// ── 分支 2:明文 TCP ───────────────────────────────────────────────
let mut plain_stream = stream;
{
let mut peek_buf: [u8; PREFACE_LEN] = [0u8; PREFACE_LEN];
let peeked: &[u8] = match plain_stream.peek(&mut peek_buf) {
Ok(0) => return Err(ServerError::ConnectionClosed),
Ok(n) => &peek_buf[..n],
Err(e) => return Err(ServerError::Io(e)),
};
let transport = Transport::Plaintext;
let protocol = Self::detect_protocol_from_peek(peeked, None);
let result = self.dispatch_protocol(protocol, transport, &mut plain_stream, client_addr);
// H2 优雅关闭:dispatch 返回后 TcpStream drop 会 close,若 recv buffer
// 非空(对端 GOAWAY 后可能仍有残留帧),Linux TCP 发 RST 而非 FIN。
// h2spec 3.8 #1 期望 "Connection closed"(FIN)而非 RST。
// 仅对 H2 连接执行(H1 已由 handle_http1_connection 内部管理关闭语义),
// 开销:最多 100ms drain read + 1 次 shutdown 系统调用(仅连接关闭时)。
if matches!(protocol, Protocol::Http2) {
let _ = plain_stream.set_read_timeout(Some(Duration::from_millis(100)));
let mut drain = [0u8; 8192];
loop {
match plain_stream.read(&mut drain) {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
}
let _ = plain_stream.shutdown(std::net::Shutdown::Both);
}
result
}
}
/// 协议分发(严格 fail-closed)
///
/// 统一 place 以保证 TLS/明文两条链路的协议选择完全一致:
/// - Http1 走 handle_http1_connection 完整 keep-alive
/// - Http2 走 handle_http2_connection 完整帧状态机(HPACK + mux + flow control)
/// - Http3 仍需 QUIC 传输层(AF_XDP DGRAM),std-TCP 不支持 → 明确报错
/// - 其他原始 L4 → 要求专用 dispatcher
#[inline(always)]
fn dispatch_protocol<IO: Read + Write>(
&self,
protocol: Protocol,
transport: Transport,
io: &mut IO,
client_addr: SocketAddr,
) -> Result<(), ServerError> {
// 客户端 IP 字符串沿 handler 透传至安全管道(try_proxy 路由匹配/审计)
let client_ip = client_addr.ip().to_string();
match protocol {
Protocol::Http1 => {
self.handle_http1_connection(io, transport, &client_ip)?;
}
Protocol::Http2 => {
self.handle_http2_connection(io, transport, &client_ip)?;
}
Protocol::Http3 => {
return Err(ServerError::Protocol(
"HTTP/3 requires QUIC transport (AF_XDP DGRAM + QUIC packet \
number space + loss recovery + QPACK). It cannot run on std-TCP; \
use zenith-http3 APIs directly if low-level QUIC frames are required."
.to_string(),
));
}
Protocol::Tcp | Protocol::Udp | Protocol::Quic => {
return Err(ServerError::Protocol(format!(
"raw L4 protocol {protocol:?} requires dedicated transport dispatcher"
)));
}
}
Ok(())
}
// ─────────────────────────────────────────────────────────────────────────────
// 5. HTTP/2 连接处理器(真实帧状态机:HPACK + mux + flow control)
// ─────────────────────────────────────────────────────────────────────────────
/// 处理一条 HTTP/2 连接(完整 RFC 7540 帧状态机)
///
/// # 链路
/// 1. 读取并验证 client preface(24 字节 magic `PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n`)
/// 2. 发送 server SETTINGS(MAX_CONCURRENT_STREAMS / INITIAL_WINDOW_SIZE / MAX_FRAME_SIZE / HEADER_TABLE_SIZE)
/// 3. 帧循环:从 IO 读取 → `Frame::parse_header` → `Http2Connection::on_frame` → `FrameAction`
/// 4. 对完整请求(HEADERS END_STREAM 或 HEADERS+DATA END_STREAM):
/// - 提取 `:method` / `:path` / `:scheme` / `:authority` 伪首部 + 常规头部
/// - 构造 `CanonicalRequest` → `App::handle` → `Http2ResponseEncoder::encode` → 写回 IO
/// 5. 对 SETTINGS(非 ACK)→ 回送 SETTINGS ACK;对 PING → 回送 PING ACK(携带原始 8 字节 payload)
/// 6. GOAWAY / RST_STREAM / 连接 EOF → 终止循环
///
/// # 安全
/// - preface 严格匹配,不匹配直接 fail-closed
/// - HPACK 解码、伪首部校验、流状态机均由 `Http2Connection` 内部严格处理
/// - 不 panic,所有错误映射到 [`ServerError`]
pub fn handle_http2_connection<IO: Read + Write>(
&self,
io: &mut IO,
transport: Transport,
client_ip: &str,
) -> Result<(), ServerError> {
// ── 1. client preface ──────────────────────────────────────────────
let mut preface_buf = [0u8; PREFACE_LEN];
io.read_exact(&mut preface_buf).map_err(|e| {
if e.kind() == std::io::ErrorKind::UnexpectedEof {
ServerError::ConnectionClosed
} else {
ServerError::Io(e)
}
})?;
if preface_buf != *PREFACE {
// RFC 7540 §3.5:无效前言 → GOAWAY(PROTOCOL_ERROR) + 断连
// (h2spec 3.5 #2:期望 GOAWAY 或 Connection closed,而非裸 EOF)
// 返回 Ok 而非 Err:让 serve_std_tcp_conn 的 H2 drain + shutdown(Both)
// 优雅关闭路径执行(GOAWAY 已 flush 到 OS send buffer,drain 清空 recv
// buffer 后 shutdown 发 FIN,h2spec 收到 GOAWAY + FIN)。
let _ = io.write_all(&GOAWAY_PROTOCOL_ERROR);
let _ = io.flush();
return Ok(());
}
// ── 2. 创建 H2 连接 + 发送 server SETTINGS ───────────────────────
let h2_config = ConnectionConfig::default();
let mut conn = Http2Connection::new(h2_config);
conn.on_client_preface(true)?;
let settings = vec![
Setting { id: SettingId::MaxConcurrentStreams, value: 100 },
Setting { id: SettingId::InitialWindowSize, value: 65535 },
Setting { id: SettingId::MaxFrameSize, value: 16384 },
Setting { id: SettingId::HeaderTableSize, value: 4096 },
];
let settings_frame = conn.send_settings(settings)?;
io.write_all(&settings_frame).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
// 流控感知响应挂起队列 + 最近接受的流 ID(GOAWAY last_stream_id 用)
let mut pend_resp: FxHashMap<u32, PendingH2Response> = FxHashMap::default();
let mut last_stream_id: u32 = 0;
// 是否已因收到对端 GOAWAY 回发过本端 GOAWAY(EOF 时避免重复发送)
let mut goaway_sent = false;
// ── 3. 帧处理循环 ──────────────────────────────────────────────────
let mut resp_encoder = Http2ResponseEncoder::new(4096);
let mut read_buf: Vec<u8> = Vec::with_capacity(65536);
// pending streams: stream_id → 累积的请求状态(HEADERS 已到但 body 未完)
let mut pending: FxHashMap<u32, PendingH2Stream> = FxHashMap::default();
loop {
// 从 IO 读取更多字节
let mut tmp = [0u8; 8192];
let n = match io.read(&mut tmp) {
Ok(0) => break, // 对端 EOF
Ok(n) => n,
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(ref e)
if e.kind() == std::io::ErrorKind::ConnectionReset
|| e.kind() == std::io::ErrorKind::BrokenPipe =>
{
break
}
Err(e) => return Err(ServerError::Io(e)),
};
read_buf.extend_from_slice(&tmp[..n]);
// 尽可能多地解析帧
loop {
match Frame::parse_header(&read_buf) {
// RFC 7540 §5.5:未知扩展帧已按 length 跳过,丢弃跳过字节继续
Ok((consumed, None)) => {
// RFC 7540 §6.2/§5.5:header block 进行中收到非 CONTINUATION 帧
// (已被跳过为 unknown)→ 连接错误 PROTOCOL_ERROR(h2spec 5.5 #2)
if conn.is_continuation_pending() {
read_buf.drain(..consumed);
let goaway = conn.close(last_stream_id, Http2ErrorCode::ProtocolError);
let _ = io.write_all(&goaway);
let _ = io.flush();
return Err(ServerError::Http2(Http2Error::ProtocolError(
"unknown frame during header block".into(),
)));
}
read_buf.drain(..consumed);
continue;
}
Ok((consumed, Some(frame))) => {
// 在 on_frame 消费 frame 前保存元数据;
// payload 克隆仅对 PING 有必要(回送原始 8 字节内容,RFC 7540 §6.7),
// 修复前每帧无条件 to_vec() = hot path 每帧一次堆分配。
let ft = frame.frame_type;
let fflags = frame.flags;
let fpayload = if ft == FrameType::Ping {
frame.payload.to_vec()
} else {
Vec::new()
};
let action = match conn.on_frame(frame) {
Ok(a) => a,
Err(e) => {
// 协议错误:GOAWAY/RST_STREAM 后断连(h2spec 各错误场景)
h2_write_error_and_close(io, &mut conn, last_stream_id, &e)?;
return Err(ServerError::Http2(e));
}
};
match action {
FrameAction::HeadersReceived {
stream_id,
headers,
end_stream,
} => {
last_stream_id = last_stream_id.max(stream_id);
let (method, path, scheme, authority) =
extract_h2_pseudo(&headers);
let regular: Vec<(String, String)> = headers
.iter()
.filter(|h| !h.name.starts_with(':'))
.map(|h| {
(h.name.as_str().to_string(), h.value.as_str().to_string())
})
.collect();
if end_stream {
// 无 body 请求 → HEADERS-only 响应 + 流控感知 DATA
match self.process_h2_request(
&method, &path, &scheme, &authority, ®ular, &[],
transport, None, None, client_ip,
) {
Ok(resp) => {
let headers_bytes = resp_encoder
.encode_headers_only(&resp, stream_id)
?;
io.write_all(&headers_bytes).map_err(ServerError::Io)?;
if !resp.body().is_empty() {
pend_resp.insert(stream_id, PendingH2Response {
body: resp.body().to_vec(),
offset: 0,
});
} else {
io.flush().map_err(ServerError::Io)?;
}
}
Err(()) => {
// RFC 7540 §8.1.2:malformed → RST_STREAM(PROTOCOL_ERROR)
let rst = build_rst_stream_frame(
stream_id,
Http2ErrorCode::ProtocolError as u32,
);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
}
}
} else {
// 有 body 请求 → 存入 pending 等待 DATA 帧
pending.insert(stream_id, PendingH2Stream {
method,
path,
scheme,
authority,
headers: regular,
body: Vec::new(),
});
}
}
FrameAction::DataReceived {
stream_id,
data,
end_stream,
} => {
if let Some(ps) = pending.get_mut(&stream_id) {
// fail-closed:H2 请求体聚合上限与 H1 对齐(config.max_body_size),
// 超限即拒绝该流(413 + RST_STREAM),防止单连接多流内存 DoS。
if ps.body.len().saturating_add(data.len())
> self.security.runtime.max_body_size.load(Ordering::Relaxed) as usize
{
pending.remove(&stream_id);
let mut resp = CanonicalResponse::new(413);
resp.set_body(
b"{\"error\":\"payload too large\"}".to_vec(),
);
let _ = resp
.add_header(b"content-type", b"application/json");
let resp_bytes = resp_encoder
.encode(&resp, stream_id)
?;
io.write_all(&resp_bytes).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
let rst = build_rst_stream_frame(
stream_id,
Http2ErrorCode::Cancel as u32,
);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
} else {
ps.body.extend_from_slice(&data);
if end_stream {
let Some(ps) = pending.remove(&stream_id) else {
// get_mut 守卫后 remove 失败(理论不可达,fail-closed)
continue;
};
// RFC 7540 §8.1.2.6:content-length 与 DATA 总长
// RFC 7540 §8.1.2.6:content-length ≠ body → RST
if let Some(cl_str) = ps.headers.iter()
.find(|(n, _)| n.eq_ignore_ascii_case("content-length"))
.map(|(_, v)| v.as_str())
&& let Ok(cl) = cl_str.parse::<usize>()
&& cl != ps.body.len()
{
let rst = build_rst_stream_frame(
stream_id,
Http2ErrorCode::ProtocolError as u32,
);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
read_buf.drain(..consumed);
continue;
}
let resp = match self.process_h2_request(
&ps.method,
&ps.path,
&ps.scheme,
&ps.authority,
&ps.headers,
&ps.body,
transport, None, None, client_ip,
) {
Ok(r) => r,
Err(()) => {
// RFC 7540 §8.1.2:malformed → RST
let rst = build_rst_stream_frame(
stream_id,
Http2ErrorCode::ProtocolError as u32,
);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
read_buf.drain(..consumed);
continue;
}
};
let headers_bytes = resp_encoder
.encode_headers_only(&resp, stream_id)
?;
io.write_all(&headers_bytes).map_err(ServerError::Io)?;
if !resp.body().is_empty() {
pend_resp.insert(stream_id, PendingH2Response {
body: resp.body().to_vec(),
offset: 0,
});
} else {
io.flush().map_err(ServerError::Io)?;
}
}
}
}
// stream_id 不在 pending 中(已关闭/重置)→ 丢弃 DATA
}
FrameAction::SettingsAck => {
// 只对客户端的 SETTINGS(非 ACK)回送 ACK
if ft == FrameType::Settings && (fflags & 0x01) == 0 {
io.write_all(&SETTINGS_ACK_FRAME)
.map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
}
}
FrameAction::PingResponse => {
// 回送 PING ACK(flags=0x01, stream=0, 原始 8 字节 payload)
let mut ping_ack = Vec::with_capacity(17);
ping_ack.extend_from_slice(&8u32.to_be_bytes()[1..]); // length=8
ping_ack.push(FrameType::Ping as u8);
ping_ack.push(0x01); // ACK flag
ping_ack.extend_from_slice(&0u32.to_be_bytes()); // stream 0
ping_ack.extend_from_slice(&fpayload);
io.write_all(&ping_ack).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
}
FrameAction::GoAwayReceived(_) => {
// RFC 7540 §6.8:收到对端 GOAWAY → 回发 GOAWAY(NoError)。
// 不能立即断连:对端在 GOAWAY 后可能仍发送帧(h2spec 7.#1 的
// GOAWAY 未知错误码测试会随后发送 PING),立即 return 会因
// recv 缓冲残留未读数据 → Linux 发 RST(connection reset)。
// 正确做法:回发 GOAWAY 但不置 Closed,继续处理后续帧
// (应答 PING),待对端 EOF 后再优雅关闭(发 FIN)。
let goaway =
conn.build_goaway(last_stream_id, Http2ErrorCode::NoError);
io.write_all(&goaway).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
goaway_sent = true;
}
FrameAction::ResetSent { stream_id, .. } => {
pending.remove(&stream_id);
pend_resp.remove(&stream_id);
}
FrameAction::WindowUpdate | FrameAction::PriorityAck => {
// 窗口更新 / 优先级 → 内部已由 on_frame 处理
}
FrameAction::ContinuationPending { .. } => {
// HEADERS 跨 CONTINUATION 帧重组中 → 内部已由 on_frame 处理
}
FrameAction::WindowUpdateNeeded(wu) => {
// 接收窗口续期:回写 WINDOW_UPDATE 帧(RFC 7540 §6.9)
if let Some(bytes) = wu.to_bytes() {
io.write_all(&bytes).map_err(ServerError::Io)?;
}
}
}
// 帧处理完成后推进挂起响应(WINDOW_UPDATE 后恢复发送)
h2_flush_pending_responses(io, &mut conn, &resp_encoder, &mut pend_resp)?;
read_buf.drain(..consumed);
}
Err(Http2Error::FrameTooShort) => break, // 需要更多数据
Err(e) => {
// 连接级帧格式错误 → GOAWAY 后断
h2_write_error_and_close(io, &mut conn, last_stream_id, &e)?;
return Err(ServerError::Http2(e));
}
}
}
}
// 连接 EOF:发 GOAWAY(NoError) 优雅关闭(h2spec 3.8 #1)。
// 若已因收到对端 GOAWAY 回发过本端 GOAWAY,则不再重复发送。
if !goaway_sent {
let goaway = conn.close(last_stream_id, Http2ErrorCode::NoError);
let _ = io.write_all(&goaway);
}
io.flush().map_err(ServerError::Io)?;
Ok(())
}
/// 处理 HTTP/2 连接(含初始缓冲数据,用于 TLS 握手后直接处理)
pub fn handle_http2_connection_with_initial<IO: Read + Write>(
&self,
io: &mut IO,
transport: Transport,
initial: &[u8],
tls_fingerprint: Option<Ja3Fingerprint>,
sni: Option<&str>,
client_ip: &str,
) -> Result<(), ServerError> {
let h2_config = ConnectionConfig::default();
let mut conn = Http2Connection::new(h2_config);
// 检查初始数据中是否包含 client preface
let preface_consumed: usize;
if initial.len() >= PREFACE_LEN && &initial[..PREFACE_LEN] == PREFACE {
conn.on_client_preface(true)?;
preface_consumed = PREFACE_LEN;
} else if !initial.is_empty() {
// 初始数据不以 preface 开头,尝试读取完整 preface
let remaining = if initial.len() < PREFACE_LEN {
let mut preface_buf = [0u8; PREFACE_LEN];
preface_buf[..initial.len()].copy_from_slice(initial);
let _need = PREFACE_LEN - initial.len();
io.read_exact(&mut preface_buf[initial.len()..])
.map_err(|e| match e.kind() {
std::io::ErrorKind::UnexpectedEof => ServerError::ConnectionClosed,
_ => ServerError::Io(e),
})?;
if preface_buf != *PREFACE {
let _ = io.write_all(&GOAWAY_PROTOCOL_ERROR);
let _ = io.flush();
return Ok(());
}
conn.on_client_preface(true)?;
preface_buf.len()
} else {
let _ = io.write_all(&GOAWAY_PROTOCOL_ERROR);
let _ = io.flush();
return Ok(());
};
preface_consumed = remaining;
} else {
// 无初始数据,读取 preface
let mut preface_buf = [0u8; PREFACE_LEN];
io.read_exact(&mut preface_buf).map_err(|e| {
if e.kind() == std::io::ErrorKind::UnexpectedEof {
ServerError::ConnectionClosed
} else {
ServerError::Io(e)
}
})?;
if preface_buf != *PREFACE {
let _ = io.write_all(&GOAWAY_PROTOCOL_ERROR);
let _ = io.flush();
return Ok(());
}
conn.on_client_preface(true)?;
preface_consumed = PREFACE_LEN;
}
// 发送 server SETTINGS
let settings = vec![
Setting { id: SettingId::MaxConcurrentStreams, value: 100 },
Setting { id: SettingId::InitialWindowSize, value: 65535 },
Setting { id: SettingId::MaxFrameSize, value: 16384 },
Setting { id: SettingId::HeaderTableSize, value: 4096 },
];
let settings_frame = conn.send_settings(settings)?;
io.write_all(&settings_frame).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
// 初始数据中 preface 之后的剩余数据
let remaining_initial = if preface_consumed < initial.len() {
&initial[preface_consumed..]
} else {
&[]
};
let mut resp_encoder = Http2ResponseEncoder::new(4096);
let mut read_buf: Vec<u8> = Vec::with_capacity(65536);
read_buf.extend_from_slice(remaining_initial);
let mut pending: FxHashMap<u32, PendingH2Stream> = FxHashMap::default();
let mut pend_resp: FxHashMap<u32, PendingH2Response> = FxHashMap::default();
let mut last_stream_id: u32 = 0;
// 是否已因收到对端 GOAWAY 回发过本端 GOAWAY(EOF 时避免重复发送)
let mut goaway_sent = false;
loop {
let mut tmp = [0u8; 8192];
let n = match io.read(&mut tmp) {
Ok(0) => break,
Ok(n) => n,
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(ref e)
if e.kind() == std::io::ErrorKind::ConnectionReset
|| e.kind() == std::io::ErrorKind::BrokenPipe =>
{
break
}
Err(e) => return Err(ServerError::Io(e)),
};
read_buf.extend_from_slice(&tmp[..n]);
loop {
match Frame::parse_header(&read_buf) {
Ok((consumed, None)) => {
if conn.is_continuation_pending() {
read_buf.drain(..consumed);
let goaway = conn.close(last_stream_id, Http2ErrorCode::ProtocolError);
let _ = io.write_all(&goaway);
let _ = io.flush();
return Err(ServerError::Http2(Http2Error::ProtocolError(
"unknown frame during header block".into(),
)));
}
read_buf.drain(..consumed);
continue;
}
Ok((consumed, Some(frame))) => {
let ft = frame.frame_type;
let fflags = frame.flags;
let fpayload = if ft == FrameType::Ping {
frame.payload.to_vec()
} else {
Vec::new()
};
let action = match conn.on_frame(frame) {
Ok(a) => a,
Err(e) => {
h2_write_error_and_close(io, &mut conn, last_stream_id, &e)?;
return Err(ServerError::Http2(e));
}
};
match action {
FrameAction::HeadersReceived {
stream_id,
headers,
end_stream,
} => {
last_stream_id = last_stream_id.max(stream_id);
let (method, path, scheme, authority) =
extract_h2_pseudo(&headers);
let regular: Vec<(String, String)> = headers
.iter()
.filter(|h| !h.name.starts_with(':'))
.map(|h| {
(h.name.as_str().to_string(), h.value.as_str().to_string())
})
.collect();
if end_stream {
match self.process_h2_request(
&method, &path, &scheme, &authority, ®ular, &[],
transport, tls_fingerprint.as_ref(), sni, client_ip,
) {
Ok(resp) => {
let headers_bytes = resp_encoder
.encode_headers_only(&resp, stream_id)
?;
io.write_all(&headers_bytes).map_err(ServerError::Io)?;
if !resp.body().is_empty() {
pend_resp.insert(stream_id, PendingH2Response {
body: resp.body().to_vec(),
offset: 0,
});
} else {
io.flush().map_err(ServerError::Io)?;
}
}
Err(()) => {
let rst = build_rst_stream_frame(
stream_id,
Http2ErrorCode::ProtocolError as u32,
);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
}
}
} else {
pending.insert(stream_id, PendingH2Stream {
method,
path,
scheme,
authority,
headers: regular,
body: Vec::new(),
});
}
}
FrameAction::DataReceived {
stream_id,
data,
end_stream,
} => {
if let Some(ps) = pending.get_mut(&stream_id) {
if ps.body.len().saturating_add(data.len())
> self.security.runtime.max_body_size.load(Ordering::Relaxed) as usize
{
pending.remove(&stream_id);
let mut resp = CanonicalResponse::new(413);
resp.set_body(
b"{\"error\":\"payload too large\"}".to_vec(),
);
let _ = resp
.add_header(b"content-type", b"application/json");
let resp_bytes = resp_encoder
.encode(&resp, stream_id)
?;
io.write_all(&resp_bytes).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
let rst = build_rst_stream_frame(
stream_id,
Http2ErrorCode::Cancel as u32,
);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
} else {
ps.body.extend_from_slice(&data);
if end_stream {
let Some(ps) = pending.remove(&stream_id) else {
continue;
};
// RFC 7540 §8.1.2.6:content-length ≠ body → RST
if let Some(cl_str) = ps.headers.iter()
.find(|(n, _)| n.eq_ignore_ascii_case("content-length"))
.map(|(_, v)| v.as_str())
&& let Ok(cl) = cl_str.parse::<usize>()
&& cl != ps.body.len()
{
let rst = build_rst_stream_frame(
stream_id,
Http2ErrorCode::ProtocolError as u32,
);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
read_buf.drain(..consumed);
continue;
}
let resp = match self.process_h2_request(
&ps.method,
&ps.path,
&ps.scheme,
&ps.authority,
&ps.headers,
&ps.body,
transport, tls_fingerprint.as_ref(), sni, client_ip,
) {
Ok(r) => r,
Err(()) => {
let rst = build_rst_stream_frame(
stream_id,
Http2ErrorCode::ProtocolError as u32,
);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
read_buf.drain(..consumed);
continue;
}
};
let headers_bytes = resp_encoder
.encode_headers_only(&resp, stream_id)
?;
io.write_all(&headers_bytes).map_err(ServerError::Io)?;
if !resp.body().is_empty() {
pend_resp.insert(stream_id, PendingH2Response {
body: resp.body().to_vec(),
offset: 0,
});
} else {
io.flush().map_err(ServerError::Io)?;
}
}
}
}
}
FrameAction::SettingsAck => {
if ft == FrameType::Settings && (fflags & 0x01) == 0 {
io.write_all(&SETTINGS_ACK_FRAME)
.map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
}
}
FrameAction::PingResponse => {
let mut ping_ack = Vec::with_capacity(17);
ping_ack.extend_from_slice(&8u32.to_be_bytes()[1..]);
ping_ack.push(FrameType::Ping as u8);
ping_ack.push(0x01);
ping_ack.extend_from_slice(&0u32.to_be_bytes());
ping_ack.extend_from_slice(&fpayload);
io.write_all(&ping_ack).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
}
FrameAction::GoAwayReceived(_) => {
// RFC 7540 §6.8:收到对端 GOAWAY → 回发 GOAWAY(NoError)。
// 不能立即断连:对端在 GOAWAY 后可能仍发送帧(h2spec 7.#1 的
// GOAWAY 未知错误码测试会随后发送 PING),立即 return 会因
// recv 缓冲残留未读数据 → Linux 发 RST(connection reset)。
// 正确做法:回发 GOAWAY 但不置 Closed,继续处理后续帧
// (应答 PING),待对端 EOF 后再优雅关闭(发 FIN)。
let goaway =
conn.build_goaway(last_stream_id, Http2ErrorCode::NoError);
io.write_all(&goaway).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
goaway_sent = true;
}
FrameAction::ResetSent { stream_id, .. } => {
pending.remove(&stream_id);
pend_resp.remove(&stream_id);
}
FrameAction::WindowUpdate | FrameAction::PriorityAck => {}
FrameAction::ContinuationPending { .. } => {}
FrameAction::WindowUpdateNeeded(wu) => {
if let Some(bytes) = wu.to_bytes() {
io.write_all(&bytes).map_err(ServerError::Io)?;
}
}
}
h2_flush_pending_responses(io, &mut conn, &resp_encoder, &mut pend_resp)?;
read_buf.drain(..consumed);
}
Err(Http2Error::FrameTooShort) => break,
Err(e) => {
h2_write_error_and_close(io, &mut conn, last_stream_id, &e)?;
return Err(ServerError::Http2(e));
}
}
}
}
if !goaway_sent {
let goaway = conn.close(last_stream_id, Http2ErrorCode::NoError);
let _ = io.write_all(&goaway);
}
io.flush().map_err(ServerError::Io)?;
Ok(())
}
/// 全链路安全管道:WAF → Cache → App → Cache Store
///
/// 在请求到达业务 App 之前执行 WAF 恶意检测,之后查询缓存,
/// App 处理完成后将响应存入缓存并记录指标。
///
/// # 执行顺序(严格 fail-closed)
/// 1. Capability 权限校验
/// 2. TLS 指纹检查(JA3/JA4 blocklist + rate limit)
/// 3. WAF 检测:SQL 注入 / XSS / SSRF / 命令注入 / 路径穿越
/// → 命中则直接返回 403 JSON 响应,绝不触及 App
/// 4. Cache 查询:GET/HEAD 请求命中缓存则直接返回,跳过 App
/// 5. Supervisor 状态检查
/// 6. App 业务处理
/// 7. Cache 存储
/// 8. 指标记录 + 审计日志
#[inline]
fn process_request_with_security(
&self,
req: CanonicalRequest,
tls_fingerprint: Option<&Ja3Fingerprint>,
sni: Option<&str>,
client_ip: &str,
) -> CanonicalResponse {
let start = Instant::now();
// 借用管线(L7 热路径零堆分配):method/path/query 借用自
// CanonicalRequest 的固定容量存储;头部仅引用拷贝,不经 String
let method = req.method.as_str();
let path = req.path_str();
let query = req.query_str();
// body 借用(零拷贝):WAF/try_proxy 仅读取,req 在 app.handle 才被消费
let body = req.body();
// 提取头部到借用 FxHashMap 供 WAF/proxy 使用(零堆分配)
let mut header_map: FxHashMap<&str, &str> = FxHashMap::default();
for h in req.headers_iter() {
header_map.insert(h.name_str(), h.value_str());
}
// host:小写化写入栈缓冲(DNS 主机名契约 ASCII ≤253B)
let mut host_buf = [0u8; 256];
let host = req_host(&header_map, &mut host_buf);
let req_has_auth = header_map.contains_key("authorization");
// path/query 预拷贝入定长栈缓冲:脱离 req 生命周期,
// 供 app.handle(req) 消费 req 之后的 store_cache 阶段复用(零堆分配)
let mut path_buf = [0u8; MAX_PATH_LEN];
let mut query_buf = [0u8; MAX_QUERY_LEN];
let path = copy_str_into(path, &mut path_buf);
let query = copy_str_into(query, &mut query_buf);
// 0. 身份一致性三步校验(AGENT §4.5):SNI↔Host、端口一致、虚拟主机白名单。
// H1/H2/H3 三条路径共用 check_identity_consistency,确保完全相同的验证逻辑。
// /metrics 不再豁免身份校验——防止绕过虚拟主机白名单(ISSUE H3 修复)。
if let Some(resp) = self.security.check_identity_consistency(
&req, host, sni, self.security.runtime_bind_addr(), self.identity.as_ref(),
) {
return resp;
}
// 0a. /metrics 端点(身份校验之后,豁免 WAF/缓存,计入 requests_total)
if let Some(metrics_resp) = self.security.try_metrics_endpoint(method, path, header_map.get("authorization").copied()) {
self.security.record_counter("requests_total", 1);
return metrics_resp;
}
// 1. 能力权限校验(Capability-based security)
if !self.security.check_capability(Capability::NetworkAccess) {
self.security.audit("CAPABILITY_DENIED", &format!("method={method} path={path}"));
let mut resp = CanonicalResponse::new(403);
resp.set_body(b"{\"error\":\"capability denied\",\"required\":\"network_access\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
return resp;
}
// 2. TLS 指纹安全控制(JA3/JA4 blocklist + rate limit;严格按需,默认关闭)
if self.security.runtime.fingerprint_security_enabled.load(Ordering::Relaxed) {
if let Some(reason) = self.security.check_fingerprint_blocklist(tls_fingerprint) {
self.security.audit("FINGERPRINT_BLOCKED", &reason);
let mut resp = CanonicalResponse::new(403);
resp.set_body(format!(
r#"{{"error":"blocked","reason":"{}","rule":"tls_fingerprint"}}"#,
reason
).into_bytes());
let _ = resp.add_header(b"content-type", b"application/json");
self.security.record_counter("fingerprint_blocked", 1);
return resp;
}
if self.security.check_fingerprint_rate_limit(
tls_fingerprint,
self.security.runtime.fingerprint_rate_limit_requests.load(Ordering::Relaxed) as u32,
self.security.runtime.fingerprint_rate_limit_window_ms.load(Ordering::Relaxed),
) {
self.security.audit("FINGERPRINT_RATE_LIMITED", &format!("method={method} path={path}"));
let mut resp = CanonicalResponse::new(429);
resp.set_body(b"{\"error\":\"rate_limit\",\"reason\":\"tls_fingerprint_rate\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
self.security.record_counter("fingerprint_rate_limited", 1);
return resp;
}
}
// TODO: Full fingerprint vector decision will be integrated here
// when zenith-fingerprint integration is wired up via feature gate
// 1. WAF 检查(类型化贯穿:CanonicalRequest 直传,AGENT §4.8;仅当该 host 按需启用)
if self.security.waf_enabled_for_host(host)
&& let Some(blocked) = self.security.check_waf(&req)
{
let elapsed_us = start.elapsed().as_micros() as u64;
self.security.record_req_done_metrics(elapsed_us, &["waf_blocked"]);
self.security.auditf("WAF_BLOCKED", format_args!("method={method} path={path}"));
return blocked;
}
// 2. Cache 查询(仅 GET/HEAD)
if let Some(cached) = self.security.check_cache(&req, host) {
let elapsed_us = start.elapsed().as_micros() as u64;
self.security.record_req_done_metrics(elapsed_us, &["cache_hits"]);
self.security.auditf("CACHE_HIT", format_args!("method={method} path={path}"));
return cached;
}
// 2a. 反向代理转发(Cache 之后、App 之前;未命中路由返回 None 继续走 App)
// client_ip:由连接层传入的真实对端 IP(TCP: SocketAddr::ip(),QUIC: from.ip())
// proto:由请求传输层推导(TLS 1.3 → https,明文 → http)
let proto = if matches!(req.transport, Transport::Tls13) { "https" } else { "http" };
if let Some(proxied) =
self.security
.try_proxy(method, path, query, host, &header_map, body, client_ip, proto)
{
let elapsed_us = start.elapsed().as_micros() as u64;
self.security.record_req_done_metrics(elapsed_us, &["requests_total"]);
return proxied;
}
// 3. Supervisor 状态检查
#[cfg(feature = "runtime")]
{
let supervisor = lock_recover(&self.security.supervisor);
let state = supervisor.state();
if state == SupervisorState::Failed {
let mut resp = CanonicalResponse::new(503);
resp.set_body(b"{\"error\":\"service unavailable\",\"reason\":\"supervisor failed\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
self.security.audit("SUPERVISOR_FAILED", &format!("state={:?}", state));
return resp;
}
}
// 3a. ChangeSet 准入闸门 + 生成号上报(热更新闭环)
// StopOldAdmission(切断旧流量)/ Drain(排空旧数据)期间拒绝新请求准入,
// 使排空得以确定性完成;Prepare(待机)/ Commit(已提交)放行。
// 活跃生成号以 gauge 上报(可观测性闭环)。
#[cfg(feature = "runtime")]
{
let changeset = lock_recover(&self.security.changeset);
let state = changeset.state();
if matches!(state, ChangeSetState::StopOldAdmission | ChangeSetState::Drain) {
self.security.audit(
"CHANGESET_ADMISSION_STOPPED",
&format!("state={state:?} method={method} path={path}"),
);
let mut resp = CanonicalResponse::new(503);
resp.set_body(b"{\"error\":\"service unavailable\",\"reason\":\"changeset draining\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
return resp;
}
self.security.record_gauge("changeset_active_generation", changeset.active_generation());
}
// 4. 审计请求到达(零堆分配格式化)
self.security.auditf("REQUEST", format_args!("method={method} path={path}"));
// 5. App 处理
let resp = self.app.handle(req);
// 5a. Supervisor 健康反馈:5xx 计数 + 超阈值 Failed 熔断(统一闭环)
self.security.report_health(resp.status_code < 500);
// 6. Cache 存储
self.security.store_cache(method, path, query, host, req_has_auth, &resp);
// 7. 指标记录(单锁批量)
let elapsed_us = start.elapsed().as_micros() as u64;
self.security.record_req_done_metrics(elapsed_us, &["requests_total"]);
self.security.auditf(
"RESPONSE",
format_args!("method={method} status={}", resp.status_code),
);
resp
}
/// 从 H2 伪首部 + 常规头部 + body 构造 CanonicalRequest 并交给安全管道处理
#[inline]
// H2 请求各字段需独立传入以保持与 HTTP/1 解码路径一致的清晰签名,重组为结构体会降低可读性
#[allow(clippy::too_many_arguments)]
fn process_h2_request(
&self,
method: &str,
path: &str,
scheme: &str,
authority: &str,
headers: &[(String, String)],
body: &[u8],
transport: Transport,
tls_fingerprint: Option<&Ja3Fingerprint>,
sni: Option<&str>,
client_ip: &str,
) -> Result<CanonicalResponse, ()> {
// 重组 HeaderField 列表(伪首部在前),走严格 normalize——
// 与 H1/H3 生产路径同一严格等级(伪首部顺序/禁连头/scheme 一致性/
// CRLF/计数上限),禁止宽松手工构建(旧实现静默吞掉 add_header 错误)。
let mut hfields: Vec<HeaderField> = Vec::with_capacity(headers.len() + 4);
hfields.push(HeaderField::new(":method", method));
hfields.push(HeaderField::new(":path", path));
hfields.push(HeaderField::new(":scheme", scheme));
if !authority.is_empty() {
hfields.push(HeaderField::new(":authority", authority));
}
for (name, value) in headers {
hfields.push(HeaderField::new(name.as_str(), value.as_str()));
}
let mut req = match normalize_http2_request(&hfields, transport) {
Ok(r) => r,
Err(ProtocolNormalizeError::UnsupportedMethod(_)) => {
// 未知方法 fail-closed 拒绝:降级为 GET 会让 WAF 按 GET 检查、
// 缓存按 GET 命中,构成安全语义绕过
let mut resp = CanonicalResponse::new(405);
resp.set_body(b"{\"error\":\"method not allowed\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
return Ok(resp);
}
Err(ProtocolNormalizeError::ProtocolViolation(ref msg))
if msg.contains("duplicate pseudo-header")
|| msg.contains("uppercase header name")
|| msg.contains("te header")
|| msg.contains("empty :path")
|| msg.contains("forbidden connection-specific")
|| msg.contains("unknown pseudo-header")
|| msg.contains("pseudo-header after regular")
|| msg.contains("transport/scheme mismatch")
|| msg.contains("missing :method")
|| msg.contains("missing :scheme")
|| msg.contains("missing :authority") =>
{
// RFC 7540 §8.1.2:malformed request → stream error PROTOCOL_ERROR
// (h2spec 8.1.2.3 #1 等)。返回 Err(()) 让调用方发 RST_STREAM
// 而非 400 HTTP 响应(后者会通过 DATA 帧回传,h2spec 期望 RST/GOAWAY)。
tracing::warn!("[H2 NORM] protocol violation -> RST: {msg}");
return Err(());
}
Err(e) => {
tracing::warn!("[H2 NORM] normalize rejected: {e}");
let mut resp = CanonicalResponse::new(400);
resp.set_body(b"{\"error\":\"bad request\",\"reason\":\"normalize_failed\"}".to_vec());
let _ = resp.add_header(b"content-type", b"application/json");
return Ok(resp);
}
};
// :authority 必须进入请求(RFC 9113 §8.3.1 等效 Host),
// 参与四元一致性校验与缓存 key;常规头部已含 host 时不重复设置
let has_host = headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("host"));
if !authority.is_empty() && !has_host {
let _ = req.add_header(b"host", authority.as_bytes());
}
if !body.is_empty() {
req.set_body(body.to_vec());
}
Ok(self.process_request_with_security(
req,
tls_fingerprint,
sni,
client_ip,
))
}
}
// ─────────────────────────────────────────────────────────────────────────────
// HTTP/2 辅助类型与函数
// ─────────────────────────────────────────────────────────────────────────────
/// 待完成的 H2 请求(HEADERS 已到达但 body 未完成)
#[derive(Debug)]
struct PendingH2Stream {
method: String,
path: String,
scheme: String,
authority: String,
headers: Vec<(String, String)>,
body: Vec<u8>,
}
/// 待发送的 H2 响应 body(流控感知分片挂起队列)
///
/// 当响应 body 超过当前可用发送窗口时,剩余字节暂存于此;
/// 每次帧循环尾部(或收到 WINDOW_UPDATE 后)由 `h2_flush_pending_responses`
/// 推进发送。END_STREAM 仅在该流最后一帧 DATA 置位。
#[derive(Debug)]
struct PendingH2Response {
body: Vec<u8>,
offset: usize,
}
/// 推进挂起响应队列:按连接级/流级发送窗口分片写出 DATA 帧
///
/// 在每次帧处理循环尾部调用(WindowUpdate 处理后推进挂起响应)。
/// 满足 h2spec 6.5.3/6.9.1/6.9.2 流控一致性:DATA 帧长度不得超出发送窗口。
fn h2_flush_pending_responses<IO: Read + Write>(
io: &mut IO,
conn: &mut Http2Connection,
encoder: &Http2ResponseEncoder,
pend_resp: &mut FxHashMap<u32, PendingH2Response>,
) -> Result<(), ServerError> {
if pend_resp.is_empty() {
return Ok(());
}
let mfs = encoder.max_frame_size().max(1) as u64;
let sids: Vec<u32> = pend_resp.keys().copied().collect();
for sid in sids {
let mut made_progress = true;
while made_progress {
made_progress = false;
let Some(pr) = pend_resp.get_mut(&sid) else { continue; };
let remaining = pr.body.len() - pr.offset;
if remaining == 0 {
pend_resp.remove(&sid);
continue;
}
let s_win = match conn.stream_send_window(sid) {
Some(w) => w,
None => {
// 流已关闭/不存在 → 丢弃挂起 body
pend_resp.remove(&sid);
break;
}
};
if s_win <= 0 {
break; // 窗口耗尽,等待 WINDOW_UPDATE
}
let c_win = conn.connection_send_window();
if c_win == 0 {
break; // 连接级窗口耗尽
}
let avail = (s_win as u64).min(c_win).min(mfs).min(remaining as u64);
if avail == 0 {
break;
}
let n = avail as usize;
let is_last = pr.offset + n == pr.body.len();
let chunk = &pr.body[pr.offset..pr.offset + n];
let mut frame_bytes = Vec::with_capacity(9 + n);
Http2ResponseEncoder::encode_data_frame_to(&mut frame_bytes, sid, chunk, is_last)?;
io.write_all(&frame_bytes).map_err(ServerError::Io)?;
conn.record_data_sent(sid, n as u32);
pr.offset += n;
made_progress = true;
}
}
io.flush().map_err(ServerError::Io)?;
Ok(())
}
/// 连接级帧格式错误 → 发送合适错误帧(GOAWAY / RST_STREAM)后断连
fn h2_write_error_and_close<IO: Read + Write>(
io: &mut IO,
conn: &mut Http2Connection,
last_stream_id: u32,
e: &Http2Error,
) -> Result<(), ServerError> {
use zenith_http2::error::Http2Error as E;
match e {
E::StreamError(sid, info) => {
let rst = build_rst_stream_frame(*sid, info.code as u32);
io.write_all(&rst).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
Ok(())
}
E::ConnectionError(code) => {
let goaway = conn.close(last_stream_id, *code);
io.write_all(&goaway).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
Ok(())
}
E::RapidReset(_) => {
let goaway = conn.close(last_stream_id, Http2ErrorCode::Cancel);
io.write_all(&goaway).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
Ok(())
}
_ => {
let goaway = conn.close(last_stream_id, Http2ErrorCode::InternalError);
io.write_all(&goaway).map_err(ServerError::Io)?;
io.flush().map_err(ServerError::Io)?;
Ok(())
}
}
}
/// 静态 GOAWAY 帧字节(preface 不匹配时立即写出,conn 尚未建立)
///
/// 帧格式(RFC 7540 §6.8):len(3)=8 | type=0x07 | flags=0 | R(1)+streamID(3)=0 |
/// last_stream_id(4)=0 | error_code(4)=0x00000002(PROTOCOL_ERROR, 大端)
static GOAWAY_PROTOCOL_ERROR: [u8; 17] = {
let mut f = [0u8; 17];
f[2] = 8; // length = 8
f[3] = 0x07; // GOAWAY
// f[4]=0 flags, f[5..9]=0 stream_id, f[9..13]=0 last_stream_id
f[16] = 0x01; // error_code = PROTOCOL_ERROR(RFC 7540 §7:0x01, 大端 u32 最低字节)
f
};
/// SETTINGS ACK 空帧(length=0, type=0x4, flags=0x01, stream=0)
static SETTINGS_ACK_FRAME: [u8; 9] = [
0x00, 0x00, 0x00, // length = 0
0x04, // type = SETTINGS
0x01, // flags = ACK
0x00, 0x00, 0x00, 0x00, // stream_id = 0
];
/// 构造 RST_STREAM 帧(RFC 7540 §6.4,13 字节:len(3)=4 | type=0x03 | flags=0 | sid | errno)
///
/// 栈上返回定长数组,热路径零堆分配。
/// `error_code` 仅接受 RFC 标准码(0x0-0xD);`Http2ErrorCode` 的 `#[repr(u32)]`
/// 判别值即线格式值层(0x0E/0x0F 内部扩展不得传入——调用方硬编码标准码)。
#[inline]
fn build_rst_stream_frame(stream_id: u32, error_code: u32) -> [u8; 13] {
let mut f = [0u8; 13];
// length = 4(24-bit 大端;4 < 0x100,高两字节为 0)
f[2] = 4;
f[3] = 0x03; // RST_STREAM
f[4] = 0x00; // flags
f[5..9].copy_from_slice(&stream_id.to_be_bytes());
f[5] &= 0x7F; // 保留位清零(RFC 7540 §4.1)
f[9..13].copy_from_slice(&error_code.to_be_bytes());
f
}
/// 从 HPACK 解码后的头部列表提取伪首部 (:method, :path, :scheme, :authority)
#[inline]
fn extract_h2_pseudo(headers: &[HeaderField]) -> (String, String, String, String) {
let mut method = String::new();
let mut path = String::new();
let mut scheme = String::new();
let mut authority = String::new();
for h in headers {
match h.name.as_str() {
":method" => method = h.value.as_str().to_string(),
":path" => path = h.value.as_str().to_string(),
":scheme" => scheme = h.value.as_str().to_string(),
":authority" => authority = h.value.as_str().to_string(),
_ => {}
}
}
(method, path, scheme, authority)
}
// 8. 单元测试
// ─────────────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::time::Duration;
use zenith_api::Protocol;
/// 测试用内存 IO:从固定 input 读,写到内部 output buffer
/// 同时实现 Read + Write,满足 handle_http1_connection 的 IO 约束
struct MockIo {
input: std::io::Cursor<Vec<u8>>,
output: Vec<u8>,
}
impl MockIo {
fn new(input: &[u8]) -> Self {
Self {
input: std::io::Cursor::new(input.to_vec()),
output: Vec::new(),
}
}
}
impl Read for MockIo {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.input.read(buf)
}
}
impl Write for MockIo {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.output.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// 构造 H2 帧(24-bit 长度、type、flags、stream_id、payload)
fn build_h2_frame(frame_type: u8, flags: u8, stream_id: u32, payload: &[u8]) -> Vec<u8> {
let mut v = Vec::with_capacity(9 + payload.len());
let len = payload.len() as u32;
v.extend_from_slice(&len.to_be_bytes()[1..]); // 24-bit length
v.push(frame_type);
v.push(flags);
v.extend_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes()); // 保留位清零
v.extend_from_slice(payload);
v
}
/// 回归(曾 H2 body 无上限聚合 → 单连接多流内存 DoS):
/// 请求体聚合超过 `max_body_size` 必须立即拒绝该流(413 HPACK :status
/// 字面编码出现于响应 + RESET_STREAM 帧出现),连接后续帧仍被处理(fail-closed)。
#[test]
fn h2_body_aggregation_over_limit_rejected_413_and_rst() {
let config = ServerConfig::new().with_max_body_size(16);
let srv = ProtocolServer::with_config(App::new(), config);
// ── 客户端字节流:preface + SETTINGS + HEADERS + DATA×2(32B > 16 上限)──
let mut input = Vec::new();
input.extend_from_slice(PREFACE);
// 客户端空 SETTINGS
input.extend_from_slice(&build_h2_frame(0x04, 0x00, 0, &[]));
// HEADERS(HPACK::method POST / :path / :scheme http / :authority a.com / content-length 64)
let mut hh = Vec::new();
hh.extend_from_slice(&[0x83, 0x84, 0x86]); // 静态表索引:POST / http
hh.push(0x41); // :authority 字面(增量索引,名索引 1)
hh.push(5);
hh.extend_from_slice(b"a.com");
hh.push(0x00); // 字面无索引头:名长前缀
hh.push(14); // name len = 14
hh.extend_from_slice(b"content-length");
hh.push(2); // value len = 2
hh.extend_from_slice(b"64");
input.extend_from_slice(&build_h2_frame(0x01, 0x04, 1, &hh)); // HEADERS|END_HEADERS
// DATA 16B(未超 16 上限)+ DATA 16B(累计 32 > 16 → 触发拒绝)
input.extend_from_slice(&build_h2_frame(0x00, 0x00, 1, &[b'x'; 16]));
input.extend_from_slice(&build_h2_frame(0x00, 0x01, 1, &[b'y'; 16])); // END_STREAM
let mut mock = MockIo::new(&input);
let result = srv.handle_http2_connection(&mut mock, Transport::Plaintext, "127.0.0.1");
assert!(result.is_ok(), "connection must close cleanly: {:?}", result.err());
let out = &mock.output;
// 断言 1:RESET_STREAM 帧(len=4, type=0x03)
let mut rst_found = false;
let mut i = 0usize;
while i + 9 <= out.len() {
let flen = ((out[i] as usize) << 16) | ((out[i + 1] as usize) << 8) | (out[i + 2] as usize);
let ftype = out[i + 3];
if ftype == 0x03 {
assert_eq!(flen, 4, "RST_STREAM payload must be 4 bytes (RFC 7540 §6.4)");
rst_found = true;
}
if i + 9 + flen > out.len() {
break;
}
i += 9 + flen;
}
assert!(rst_found, "RST_STREAM frame must be emitted for over-limit stream");
// 断言 2:响应 :status 413 字面编码出现(HPACK 字面值)
assert!(
out.windows(3).any(|w| w == b"413"),
"413 status must be encoded in response"
);
}
/// 回归:body 恰在上限边界(=max_body_size)必须通过(fail-open 边界放行),
/// 上限+1 必须拒绝(fail-closed 精确边界)。
#[test]
fn h2_body_aggregation_boundary_exact_and_over() {
fn run_case(body_len: usize) -> Vec<u8> {
let config = ServerConfig::new().with_max_body_size(64);
let srv = ProtocolServer::with_config(App::new(), config);
let mut input = Vec::new();
input.extend_from_slice(PREFACE);
input.extend_from_slice(&build_h2_frame(0x04, 0x00, 0, &[]));
// :scheme=http 与 Transport::Plaintext 一致(normalize scheme/transport 校验)
let mut hh = Vec::new();
hh.extend_from_slice(&[0x83, 0x84, 0x86, 0x41, 5]); // :method POST, :path /, :scheme http, :authority
hh.extend_from_slice(b"a.com");
let cl = body_len.to_string();
hh.push(0x00);
hh.push(14);
hh.extend_from_slice(b"content-length");
assert!(cl.len() < 16, "content-length value overflow test frame");
hh.push(cl.len() as u8);
hh.extend_from_slice(cl.as_bytes());
input.extend_from_slice(&build_h2_frame(0x01, 0x04, 1, &hh));
input.extend_from_slice(&build_h2_frame(0x00, 0x01, 1, &vec![b'z'; body_len]));
let mut mock = MockIo::new(&input);
let _ = srv.handle_http2_connection(&mut mock, Transport::Plaintext, "127.0.0.1");
mock.output
}
// 恰等于上限(64 B)→ 不拒绝(413 不出现、无 RST_STREAM)
let out_eq = run_case(64);
assert!(
!out_eq.windows(3).any(|w| w == b"413"),
"exact-limit body must NOT be rejected"
);
// 无 RST_STREAM:逐帧扫描
let mut i = 0usize;
let mut rst = false;
while i + 9 <= out_eq.len() {
let flen = ((out_eq[i] as usize) << 16) | ((out_eq[i + 1] as usize) << 8) | (out_eq[i + 2] as usize);
if out_eq[i + 3] == 0x03 { rst = true; }
if i + 9 + flen > out_eq.len() { break; }
i += 9 + flen;
}
assert!(!rst, "exact-limit body must NOT emit RST_STREAM");
// 上限+1(65 B)→ 413 + RST_STREAM
let out_over = run_case(65);
assert!(out_over.windows(3).any(|w| w == b"413"), "over-limit must reject 413");
let mut i = 0usize;
let mut rst = false;
while i + 9 <= out_over.len() {
let flen = ((out_over[i] as usize) << 16) | ((out_over[i + 1] as usize) << 8) | (out_over[i + 2] as usize);
if out_over[i + 3] == 0x03 { rst = true; }
if i + 9 + flen > out_over.len() { break; }
i += 9 + flen;
}
assert!(rst, "over-limit must emit RST_STREAM");
}
// ───────── ServerConfig 测试 ─────────
#[test]
fn server_config_defaults() {
let c = ServerConfig::new();
assert_eq!(c.http1_max_requests_per_conn, 100);
assert_eq!(c.http1_idle_timeout_ms, 30_000);
assert_eq!(c.http2_max_frame_size, 16_384);
assert_eq!(c.http2_max_concurrent_streams, 100);
assert_eq!(c.http3_max_field_section_size, 1_048_576);
assert_eq!(c.read_buffer_size, 65_536);
assert_eq!(c.write_buffer_size, 65_536);
assert_eq!(c.max_body_size, 16_777_216);
}
#[test]
fn server_config_builder_setters() {
let c = ServerConfig::new()
.with_http1_max_requests_per_conn(50)
.with_http1_idle_timeout_ms(10_000)
.with_http2_max_frame_size(32_768)
.with_http2_max_concurrent_streams(200)
.with_http3_max_field_section_size(2_000_000)
.with_read_buffer_size(4096)
.with_write_buffer_size(8192)
.with_max_body_size(1024);
assert_eq!(c.http1_max_requests_per_conn, 50);
assert_eq!(c.http1_idle_timeout_ms, 10_000);
assert_eq!(c.http2_max_frame_size, 32_768);
assert_eq!(c.http2_max_concurrent_streams, 200);
assert_eq!(c.http3_max_field_section_size, 2_000_000);
assert_eq!(c.read_buffer_size, 4096);
assert_eq!(c.write_buffer_size, 8192);
assert_eq!(c.max_body_size, 1024);
}
#[test]
fn server_config_default_trait() {
let a = ServerConfig::new();
let b = ServerConfig::default();
assert_eq!(a, b);
}
#[test]
fn server_config_clone_eq() {
let a = ServerConfig::new().with_http1_max_requests_per_conn(42);
let b = a.clone();
assert_eq!(a, b);
}
// ───────── 四元一致性(§4.5):端口校验与 IdentityMiddleware 默认装配 ─────────
fn direct_get_with_host(host: &str) -> CanonicalRequest {
let mut req = CanonicalRequest::empty();
req.method = zenith_api::Method::Get;
let _ = req.set_path("/status");
req.add_header(b"host", host.as_bytes()).expect("add host header");
req
}
#[test]
fn host_explicit_port_parsing() {
assert_eq!(host_explicit_port("example.com:8443"), Some(8443));
assert_eq!(host_explicit_port("example.com"), None);
assert_eq!(host_explicit_port("[::1]:8443"), Some(8443));
assert_eq!(host_explicit_port("[::1]"), None);
// 未括号化 IPv6:无权威端口语义
assert_eq!(host_explicit_port("::1"), None);
assert_eq!(host_explicit_port("example.com:abc"), None);
assert_eq!(host_explicit_port("example.com:"), None);
}
#[test]
fn bind_addr_port_mismatch_rejected_421() {
let config = ServerConfig::new()
.with_bind_addr("127.0.0.1:8443".parse().expect("addr"));
let srv = ProtocolServer::with_config(App::new(), config);
let resp = srv.process_request_with_security(
direct_get_with_host("example.com:8080"),
None,
None,
"127.0.0.1",
);
assert_eq!(resp.status_code, 421);
}
#[test]
fn bind_addr_port_match_and_absent_port_passed() {
let config = ServerConfig::new()
.with_bind_addr("127.0.0.1:8443".parse().expect("addr"));
let srv = ProtocolServer::with_config(App::new(), config);
// 显式端口一致 → 放行(404:空路由表;关键非 421)
let resp = srv.process_request_with_security(
direct_get_with_host("example.com:8443"),
None,
None,
"127.0.0.1",
);
assert_ne!(resp.status_code, 421);
// 无显式端口 → 跳过端口检查(宽松默认)
let resp = srv.process_request_with_security(
direct_get_with_host("example.com"),
None,
None,
"127.0.0.1",
);
assert_ne!(resp.status_code, 421);
}
/// 回归(曾 split(':') 截断为 "["):IPv6 authority 与 SNI 同形化比较。
/// host="[::1]" / "[::1]:443"、sni="::1" 属同一身份 → 不得误判 421;
/// sni="evil" 与 host="[::1]" 必须 421。
#[test]
fn sni_host_consistency_ipv6_bracketed() {
let srv = ProtocolServer::new(App::new());
// bracketed IPv6 host 与 SNI ipv6 字面量 → 同形化后一致,放行(非 421)
let resp = srv.process_request_with_security(
direct_get_with_host("[::1]"),
None,
Some("::1"),
"127.0.0.1",
);
assert_ne!(resp.status_code, 421, "bracketed ipv6 must match bare sni");
// 带显式端口的 IPv6 host → 剥离端口后与 SNI 一致
let resp = srv.process_request_with_security(
direct_get_with_host("[::1]:8443"),
None,
Some("::1"),
"127.0.0.1",
);
assert_ne!(resp.status_code, 421);
// SNI 与 host 显式不一致 → 421(fail-closed 身份校验)
let resp = srv.process_request_with_security(
direct_get_with_host("[::1]"),
None,
Some("::2"),
"127.0.0.1",
);
assert_eq!(resp.status_code, 421);
// 域名基线:sni 与 host 常量字符串一致 → 放行
let resp = srv.process_request_with_security(
direct_get_with_host("example.com:8443"),
None,
Some("example.com"),
"127.0.0.1",
);
assert_ne!(resp.status_code, 421);
let resp = srv.process_request_with_security(
direct_get_with_host("example.com:8443"),
None,
Some("other.com"),
"127.0.0.1",
);
assert_eq!(resp.status_code, 421);
}
#[test]
fn bind_addr_unset_no_port_check() {
// 未配置 bind_addr:显式端口差异不触发 421(默认行为完全不变)
let srv = ProtocolServer::new(App::new());
let resp = srv.process_request_with_security(
direct_get_with_host("example.com:9999"),
None,
None,
"127.0.0.1",
);
assert_ne!(resp.status_code, 421);
}
#[test]
fn identity_whitelist_rejects_unknown_host_421() {
let config = ServerConfig::new().with_allowed_hosts(["example.com"]);
let srv = ProtocolServer::with_config(App::new(), config);
let resp = srv.process_request_with_security(
direct_get_with_host("evil.com"),
None,
None,
"127.0.0.1",
);
assert_eq!(resp.status_code, 421);
// 白名单命中(大小写不敏感)→ 放行
let resp = srv.process_request_with_security(
direct_get_with_host("EXAMPLE.com"),
None,
None,
"127.0.0.1",
);
assert_ne!(resp.status_code, 421);
}
#[test]
fn identity_unset_pass_through() {
// 未配置 allowed_hosts:任何 host 不触发身份 421(默认行为完全不变)
let srv = ProtocolServer::new(App::new());
let resp = srv.process_request_with_security(
direct_get_with_host("anything.example"),
None,
None,
"127.0.0.1",
);
assert_ne!(resp.status_code, 421);
}
// ───────── is_http2_preface 测试 ─────────
#[test]
fn is_http2_preface_correct_bytes() {
assert!(ProtocolServer::is_http2_preface(PREFACE));
}
#[test]
fn is_http2_preface_with_trailing_bytes() {
let mut buf = PREFACE.to_vec();
buf.extend_from_slice(b"extra data here");
assert!(ProtocolServer::is_http2_preface(&buf));
}
#[test]
fn is_http2_preface_wrong_bytes() {
assert!(!ProtocolServer::is_http2_preface(b"GET / HTTP/1.1\r\nHos"));
assert!(!ProtocolServer::is_http2_preface(b""));
assert!(!ProtocolServer::is_http2_preface(b"short"));
}
#[test]
fn is_http2_preface_exactly_24_bytes_boundary() {
let short: Vec<u8> = PREFACE[..23].to_vec();
assert!(!ProtocolServer::is_http2_preface(&short));
let exact: Vec<u8> = PREFACE[..24].to_vec();
assert!(ProtocolServer::is_http2_preface(&exact));
}
// ───────── detect_protocol_from_peek 测试 ─────────
#[test]
fn detect_alpn_h2_takes_priority_over_preface() {
let peeked = b"GET / HTTP/1.1\r\nHost: x\r\n\r\n";
let p = ProtocolServer::detect_protocol_from_peek(peeked, Some(b"h2"));
assert_eq!(p, Protocol::Http2);
}
#[test]
fn detect_alpn_http11() {
let p = ProtocolServer::detect_protocol_from_peek(&[], Some(b"http/1.1"));
assert_eq!(p, Protocol::Http1);
}
#[test]
fn detect_alpn_h3() {
let p = ProtocolServer::detect_protocol_from_peek(&[], Some(b"h3"));
assert_eq!(p, Protocol::Http3);
}
#[test]
fn detect_unknown_alpn_falls_back_to_preface() {
let p = ProtocolServer::detect_protocol_from_peek(PREFACE, Some(b"unknown-proto"));
assert_eq!(p, Protocol::Http2);
}
#[test]
fn detect_preface_only_no_alpn() {
let p = ProtocolServer::detect_protocol_from_peek(PREFACE, None);
assert_eq!(p, Protocol::Http2);
}
#[test]
fn detect_no_info_defaults_http1() {
let p = ProtocolServer::detect_protocol_from_peek(&[], None);
assert_eq!(p, Protocol::Http1);
let p2 = ProtocolServer::detect_protocol_from_peek(b"GET /", None);
assert_eq!(p2, Protocol::Http1);
}
// ───────── ServerError Display + From 测试 ─────────
#[test]
fn server_error_display_all_variants() {
let cases: Vec<(ServerError, &str)> = vec![
(
ServerError::Normalize(ProtocolNormalizeError::TooManyHeaders),
"normalize error",
),
(
ServerError::Http1(Http1Error::MissingHost),
"http1 error",
),
(
ServerError::Accept(AcceptError::AddrInUse),
"accept error",
),
(
ServerError::Tls(TlsAcceptError::ConnectionTableFull),
"tls error",
),
(
ServerError::Io(std::io::Error::from(std::io::ErrorKind::BrokenPipe)),
"io error",
),
(
ServerError::Protocol("bad state".into()),
"protocol error: bad state",
),
(ServerError::ConnectionClosed, "connection closed"),
(ServerError::Timeout, "operation timed out"),
(
ServerError::Internal("oops".into()),
"internal server error: oops",
),
];
for (err, substr) in cases {
let s = format!("{}", err);
assert!(
s.contains(substr),
"error '{}' should contain '{}'",
s,
substr
);
}
}
#[test]
fn server_error_from_normalize() {
let ne = ProtocolNormalizeError::RequestTargetTooLong;
let se: ServerError = ne.into();
assert!(matches!(se, ServerError::Normalize(_)));
}
#[test]
fn server_error_from_io() {
let ioe = std::io::Error::from(std::io::ErrorKind::ConnectionReset);
let se: ServerError = ioe.into();
assert!(matches!(se, ServerError::Io(_)));
}
#[test]
fn server_error_from_http1() {
let he = Http1Error::BufferOverflow;
let se: ServerError = he.into();
assert!(matches!(se, ServerError::Http1(_)));
}
#[test]
fn server_error_from_accept() {
let ae = AcceptError::ListenTableFull;
let se: ServerError = ae.into();
assert!(matches!(se, ServerError::Accept(_)));
}
#[test]
fn server_error_from_tls() {
let te = TlsAcceptError::ConnectionTableFull;
let se: ServerError = te.into();
assert!(matches!(se, ServerError::Tls(_)));
}
#[test]
fn server_error_debug_impl() {
let err = ServerError::Timeout;
let dbg = format!("{:?}", err);
assert!(!dbg.is_empty());
}
// ───────── ProtocolServer 构造与访问器测试 ─────────
#[test]
fn protocol_server_new_default_config() {
let app = App::new();
let srv = ProtocolServer::new(app);
assert_eq!(srv.config().http1_max_requests_per_conn, 100);
assert_eq!(srv.app().route_count(), 0);
}
#[test]
fn protocol_server_with_config_custom() {
let app = App::new();
let cfg = ServerConfig::new().with_http1_max_requests_per_conn(7);
let srv = ProtocolServer::with_config(app, cfg);
assert_eq!(srv.config().http1_max_requests_per_conn, 7);
}
#[test]
fn protocol_server_clone() {
let mut app = App::new();
app.get("/", |_r, _p| Ok(CanonicalResponse::new(200)));
let srv = ProtocolServer::new(app);
let srv2 = srv.clone();
assert_eq!(
srv.config().http1_max_requests_per_conn,
srv2.config().http1_max_requests_per_conn
);
assert_eq!(srv.app().route_count(), srv2.app().route_count());
}
#[test]
fn protocol_server_debug_format() {
let srv = ProtocolServer::new(App::new());
let dbg = format!("{:?}", srv);
assert!(dbg.contains("ProtocolServer"));
}
// ───────── 运行时热更新(RuntimeConfig)测试 ─────────
#[test]
fn runtime_config_defaults_off() {
let srv = ProtocolServer::new(App::new());
let snap = srv.runtime_snapshot();
assert!(!snap.waf_enabled);
assert!(!snap.fingerprint_security_enabled);
assert!(snap.waf_enabled_hosts.is_empty());
}
#[test]
fn runtime_config_hot_update_waf() {
let srv = ProtocolServer::new(App::new());
// 默认关闭
assert!(!srv.security().waf_enabled_for_host("api.example.com"));
// 热更新:全局启用 + 按 host 白名单 + 黑名单
srv.update_runtime(|r| {
r.set_waf_enabled(true);
r.enable_waf_for_host("api.example.com");
r.bypass_waf_for_host("static.example.com");
});
assert!(srv.security().waf_enabled_for_host("api.example.com"));
assert!(!srv.security().waf_enabled_for_host("static.example.com"));
assert!(srv.security().waf_enabled_for_host("other.example.com"));
let snap = srv.runtime_snapshot();
assert!(snap.waf_enabled);
assert!(snap.waf_enabled_hosts.contains(&"api.example.com".to_string()));
assert!(snap.waf_disabled_hosts.contains(&"static.example.com".to_string()));
}
#[test]
fn runtime_config_hot_update_host_specific() {
// WAF 全局关闭,但 api host 白名单强制启用
let srv = ProtocolServer::new(App::new());
srv.update_runtime(|r| r.enable_waf_for_host("api.example.com"));
assert!(srv.security().waf_enabled_for_host("api.example.com"));
assert!(!srv.security().waf_enabled_for_host("other.example.com"));
// 移除白名单 → 恢复关闭
srv.update_runtime(|r| r.disable_waf_for_host("api.example.com"));
assert!(!srv.security().waf_enabled_for_host("api.example.com"));
}
#[test]
fn runtime_config_hot_update_fingerprint_and_scalars() {
let srv = ProtocolServer::new(App::new());
srv.update_runtime(|r| {
r.set_fingerprint_security(true);
r.set_fingerprint_rate_limit(500, 10_000);
r.set_udp_max_sessions(8192);
r.set_forward_session_timeout_ms(120_000);
r.set_supervisor_max_consecutive_5xx(3);
r.set_waf_offload(128_000, 8_000);
});
let snap = srv.runtime_snapshot();
assert!(snap.fingerprint_security_enabled);
assert_eq!(snap.fingerprint_rate_limit_requests, 500);
assert_eq!(snap.fingerprint_rate_limit_window_ms, 10_000);
assert_eq!(snap.udp_max_sessions, 8192);
assert_eq!(snap.forward_session_timeout_ms, 120_000);
assert_eq!(snap.supervisor_max_consecutive_5xx, 3);
assert_eq!(snap.waf_offload_body_threshold, 128_000);
assert_eq!(snap.waf_offload_deadline_ms, 8_000);
}
#[test]
fn runtime_config_hot_update_shared_across_clones() {
let srv = ProtocolServer::new(App::new());
let srv2 = srv.clone();
srv.update_runtime(|r| r.set_waf_enabled(true));
// clone 共享同一 `Arc<RuntimeConfig>`,更新立即可见
assert!(srv2.security().waf_enabled_for_host("any.example.com"));
assert!(srv2.runtime_snapshot().waf_enabled);
}
#[test]
fn runtime_config_initialized_from_server_config() {
let cfg = ServerConfig::new().with_waf(true).with_fingerprint_security(true);
let srv = ProtocolServer::with_config(App::new(), cfg);
let snap = srv.runtime_snapshot();
assert!(snap.waf_enabled);
assert!(snap.fingerprint_security_enabled);
}
#[test]
fn forward_config_initialized_from_server_config() {
// 构建期注入 L4 转发参数(with_forward_config)
let cfg = ServerConfig::new().with_forward_config(
zenith_forward::ForwardConfig::default()
.with_max_concurrent_sessions(128)
.with_max_bandwidth_per_session(1_000_000),
);
let srv = ProtocolServer::with_config(App::new(), cfg);
let fc = srv.forward_config();
assert_eq!(fc.max_concurrent_sessions, 128);
assert_eq!(fc.max_bandwidth_per_session, 1_000_000);
}
#[test]
fn forward_config_hot_update() {
// 运行时热更新 L4 转发参数(set_forward_config)即时生效,共享引擎
let srv = ProtocolServer::new(App::new());
let srv2 = srv.clone();
srv.set_forward_config(
zenith_forward::ForwardConfig::default().with_max_concurrent_sessions(256),
);
// clone 共享同一 forward_engine,更新立即可见
assert_eq!(srv2.forward_config().max_concurrent_sessions, 256);
}
#[test]
fn proxy_config_hot_update() {
// 运行时热更新反向代理参数(set_proxy_config / update_proxy_config),clone 立即可见
let srv = ProtocolServer::new(App::new());
let srv2 = srv.clone();
srv.set_proxy_config(
ProxyConfig::default().with_forward_connect_timeout_ms(5_000),
);
assert_eq!(srv2.proxy_config().forward_connect_timeout_ms, 5_000);
// update_proxy_config:对既有路由的每请求转发超时即时生效
srv.update_proxy_config(|p| {
p.forward_read_timeout_ms = 30_000;
p.health_failure_threshold = 3;
});
let pc = srv2.proxy_config();
assert_eq!(pc.forward_read_timeout_ms, 30_000);
assert_eq!(pc.health_failure_threshold, 3);
}
#[test]
fn runtime_config_hot_update_protocol_and_metrics() {
let srv = ProtocolServer::new(App::new());
srv.update_runtime(|r| {
r.set_http1_max_requests_per_conn(5);
r.set_http1_idle_timeout_ms(15_000);
r.set_max_body_size(8 * 1024 * 1024);
r.set_read_buffer_size(32_768);
r.set_write_buffer_size(16_384);
r.set_metrics_auth_token(Some("secret-token".to_string()));
});
let snap = srv.runtime_snapshot();
assert_eq!(snap.http1_max_requests_per_conn, 5);
assert_eq!(snap.http1_idle_timeout_ms, 15_000);
assert_eq!(snap.max_body_size, 8 * 1024 * 1024);
assert_eq!(snap.read_buffer_size, 32_768);
assert_eq!(snap.write_buffer_size, 16_384);
assert_eq!(snap.metrics_auth_token.as_deref(), Some("secret-token"));
// 关闭 /metrics 端点(None → 不可访问)
srv.update_runtime(|r| r.set_metrics_auth_token(None));
assert!(srv.runtime_snapshot().metrics_auth_token.is_none());
}
#[test]
fn runtime_config_hot_update_cache_capacity() {
let srv = ProtocolServer::new(App::new());
// 不 panic 即生效;容量经原子 store 立即更新(stats 分片均摊)
srv.set_cache_capacity(1024, 2 * 1024 * 1024);
srv.set_cache_capacity(65536, 16 * 1024 * 1024);
}
#[test]
fn runtime_config_hot_update_bind_addr() {
let srv = ProtocolServer::new(App::new());
// 默认未配置:runtime_bind_addr 为 None,零锁快速路径
assert!(srv.security().runtime_bind_addr().is_none());
// 热启用监听地址(启用端口一致性检查)
let addr: SocketAddr = "127.0.0.1:8443".parse().expect("addr");
srv.update_runtime(|r| r.set_bind_addr(Some(addr)));
assert_eq!(srv.security().runtime_bind_addr(), Some(addr));
assert_eq!(srv.runtime_snapshot().bind_addr, Some(addr));
// 热关闭
srv.update_runtime(|r| r.set_bind_addr(None));
assert!(srv.security().runtime_bind_addr().is_none());
}
#[test]
fn runtime_config_hot_update_firewall_rules() {
use zenith_waf::RuleBuilder;
let srv = ProtocolServer::new(App::new());
let rule = RuleBuilder::new("block-admin").path("/admin").build();
srv.security().add_waf_rule(rule);
assert_eq!(srv.security().waf_rule_count(), 1);
// 运行时移除
srv.security().remove_waf_rule("block-admin");
assert_eq!(srv.security().waf_rule_count(), 0);
// 运行时清空
srv.security().add_waf_rules([
RuleBuilder::new("a").path("/a").build(),
RuleBuilder::new("b").path("/b").build(),
]);
assert_eq!(srv.security().waf_rule_count(), 2);
srv.security().clear_waf_rules();
assert_eq!(srv.security().waf_rule_count(), 0);
}
#[test]
fn runtime_config_hot_update_fingerprint_blocklist() {
let srv = ProtocolServer::new(App::new());
srv.security().add_fingerprint_to_blocklist("abc123".to_string());
assert!(srv
.security()
.fingerprint_blocklist_snapshot()
.contains(&"abc123".to_string()));
// 运行时移除单个前缀
srv.security().remove_fingerprint_from_blocklist("abc123");
assert!(srv.security().fingerprint_blocklist_snapshot().is_empty());
}
// ───────── handle_http1_connection 集成测试 (std::net) ─────────
fn build_test_app() -> App {
let mut app = App::new();
app.get("/", |_req, _params| {
let mut resp = CanonicalResponse::new(200);
let _ = resp.add_header(b"content-type", b"text/plain");
resp.set_body(b"OK".to_vec());
Ok(resp)
});
app.get("/health", |_req, _params| {
Ok(CanonicalResponse::new(204))
});
app
}
#[test]
fn handle_http1_connection_simple_get_via_tcp() {
let app = build_test_app();
let srv = ProtocolServer::new(app);
let srv = std::sync::Arc::new(srv);
let listener = TcpListener::bind("127.0.0.1:0").expect("bind ok");
let port: u16 = listener.local_addr().expect("local addr").port();
let server_handle = {
let srv = std::sync::Arc::clone(&srv);
thread::spawn(move || {
let (mut stream, remote) = listener.accept().expect("accept ok");
// TcpStream 同时实现 Read + Write,直接作为单一 IO 传入
srv.handle_http1_connection(&mut stream, Transport::Plaintext, &remote.ip().to_string())
})
};
thread::sleep(Duration::from_millis(20));
let mut client =
TcpStream::connect(("127.0.0.1", port)).expect("client connect ok");
client
.set_read_timeout(Some(Duration::from_millis(500)))
.expect("set timeout");
let req = b"GET / HTTP/1.1\r\nHost: test.example\r\nConnection: close\r\n\r\n";
client.write_all(req).expect("write request");
client.flush().expect("flush");
let mut resp_buf: Vec<u8> = Vec::new();
let mut tmp = [0u8; 4096];
loop {
match client.read(&mut tmp) {
Ok(0) => break,
Ok(n) => resp_buf.extend_from_slice(&tmp[..n]),
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(ref e)
if e.kind() == std::io::ErrorKind::ConnectionReset
|| e.kind() == std::io::ErrorKind::BrokenPipe =>
{
break
}
Err(e) => panic!("client read error: {}", e),
}
}
let resp_str = String::from_utf8_lossy(&resp_buf);
assert!(
resp_str.starts_with("HTTP/1.1 200 OK\r\n"),
"unexpected response start: {:?}",
resp_str.lines().next()
);
assert!(resp_str.contains("OK"));
assert!(resp_str.contains("content-type: text/plain"));
let server_result = server_handle.join().expect("server thread ok");
assert!(
server_result.is_ok()
|| matches!(server_result, Err(ServerError::ConnectionClosed))
|| matches!(server_result, Err(ServerError::Io(_)))
);
}
#[test]
fn handle_http1_connection_empty_request_returns_ok() {
let srv = ProtocolServer::new(App::new());
let mut io = MockIo::new(b"");
let result = srv.handle_http1_connection(&mut io, Transport::Plaintext, "127.0.0.1");
assert!(result.is_ok());
assert!(io.output.is_empty());
}
#[test]
fn handle_http1_connection_request_count_limit() {
let app = build_test_app();
let cfg = ServerConfig::new().with_http1_max_requests_per_conn(2);
let srv = ProtocolServer::with_config(app, cfg);
let req = b"GET /health HTTP/1.1\r\nHost: x\r\n\r\nGET /health HTTP/1.1\r\nHost: x\r\n\r\nGET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n";
let mut io = MockIo::new(req);
let result =
srv.handle_http1_connection(&mut io, Transport::Plaintext, "127.0.0.1");
assert!(result.is_ok() || matches!(result, Err(ServerError::ConnectionClosed)));
let out_str = String::from_utf8_lossy(&io.output);
let count_204 = out_str.matches("HTTP/1.1 204 No Content").count();
assert!(count_204 <= 2, "expected at most 2 responses, got {}", count_204);
}
#[test]
fn handle_http1_connection_bad_request_returns_error() {
let srv = ProtocolServer::new(App::new());
let mut io = MockIo::new(b"NOT_A_METHOD / HTTP/1.1\r\nHost: x\r\n\r\n");
let result = srv.handle_http1_connection(&mut io, Transport::Tls13, "127.0.0.1");
assert!(result.is_err());
}
#[test]
fn handle_http1_connection_chunked_body_via_mockio() {
// 验证 chunked 请求体通过完整 parse→normalize→app→encode 链路
let mut app = App::new();
app.post("/echo", |req, _params| {
let mut resp = CanonicalResponse::new(200);
let _ = resp.add_header(b"content-type", b"text/plain");
// 回显请求体
resp.set_body(req.body().to_vec());
Ok(resp)
});
let srv = ProtocolServer::new(app);
let req = b"POST /echo HTTP/1.1\r\nHost: test.example\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n5\r\nHello\r\n6\r\n World\r\n0\r\n\r\n";
let mut io = MockIo::new(req);
let result = srv.handle_http1_connection(&mut io, Transport::Plaintext, "127.0.0.1");
assert!(result.is_ok(), "chunked request should succeed: {:?}", result);
let out_str = String::from_utf8_lossy(&io.output);
assert!(out_str.starts_with("HTTP/1.1 200 OK\r\n"), "response: {}", out_str);
assert!(out_str.contains("Hello World"), "body should contain echoed chunked body: {}", out_str);
}
// ───────── serve_std_tcp_conn 明文路径测试 ─────────
#[test]
fn serve_std_tcp_conn_plaintext_integration() {
let app = build_test_app();
let srv = ProtocolServer::new(app);
let srv = std::sync::Arc::new(srv);
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let port: u16 = listener.local_addr().expect("local addr").port();
let srv_clone = std::sync::Arc::clone(&srv);
let server_handle = thread::spawn(move || {
let (stream, remote) = listener.accept().expect("accept");
srv_clone.serve_std_tcp_conn(stream, remote, None)
});
thread::sleep(Duration::from_millis(20));
let mut client = TcpStream::connect(("127.0.0.1", port)).expect("connect");
client
.set_read_timeout(Some(Duration::from_millis(500)))
.expect("set timeout");
client
.write_all(b"GET / HTTP/1.1\r\nHost: plain.example\r\nConnection: close\r\n\r\n")
.expect("write");
client.flush().expect("flush");
let mut resp_buf: Vec<u8> = Vec::new();
let mut tmp = [0u8; 4096];
loop {
match client.read(&mut tmp) {
Ok(0) => break,
Ok(n) => resp_buf.extend_from_slice(&tmp[..n]),
Err(_) => break,
}
}
let resp = String::from_utf8_lossy(&resp_buf);
assert!(
resp.starts_with("HTTP/1.1 200 OK"),
"expected 200, got: {:?}",
resp.lines().next()
);
let r = server_handle.join().expect("join");
let _ = r;
}
// ───────── 反向代理转发闭环集成测试 ─────────
/// 启动 loopback 上游:接受一个连接,读取请求(经 channel 回传),写回固定响应后关闭
fn spawn_fixed_upstream(response: &'static [u8]) -> (String, std::sync::mpsc::Receiver<Vec<u8>>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind upstream");
let addr = listener.local_addr().expect("local addr").to_string();
let (tx, rx) = std::sync::mpsc::channel();
thread::spawn(move || {
if let Ok((mut stream, _)) = listener.accept() {
let _ = stream.set_read_timeout(Some(Duration::from_millis(2_000)));
let mut req = Vec::new();
let mut tmp = [0u8; 4096];
loop {
match stream.read(&mut tmp) {
Ok(0) => break,
Ok(n) => {
req.extend_from_slice(&tmp[..n]);
// 请求头区到达即停止(测试请求均无 body)
if req.windows(4).any(|w| w == b"\r\n\r\n") {
break;
}
}
Err(_) => break,
}
}
let _ = tx.send(req);
let _ = stream.write_all(response);
let _ = stream.flush();
}
});
(addr, rx)
}
/// 经 MockIo 走完整 H1 链路(parse → 安全管道 → 代理转发 → encode)
fn h1_round_trip(srv: &ProtocolServer, request: &[u8]) -> String {
let mut io = MockIo::new(request);
let result = srv.handle_http1_connection(&mut io, Transport::Plaintext, "127.0.0.1");
assert!(
result.is_ok() || matches!(result, Err(ServerError::ConnectionClosed)),
"h1 connection should succeed: {result:?}"
);
String::from_utf8_lossy(&io.output).to_string()
}
#[test]
fn proxy_forward_200_end_to_end() {
let (addr, rx) = spawn_fixed_upstream(
b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nfrom-upstream",
);
let srv = ProtocolServer::new(App::new());
srv.add_proxy_route("/api", vec![(addr, 1)], LoadBalanceStrategy::RoundRobin);
let out = h1_round_trip(
&srv,
b"GET /api/x?q=1 HTTP/1.1\r\nHost: web.example\r\nConnection: close\r\n\r\n",
);
// 响应体来自上游(而非 App 404)
assert!(out.starts_with("HTTP/1.1 200 OK\r\n"), "response: {out}");
assert!(out.contains("from-upstream"), "body must come from upstream: {out}");
assert!(out.to_ascii_lowercase().contains("content-type: text/plain\r\n"), "upstream header passthrough: {out}");
// 上游真实收到的请求:原始 path+query(v1 不剥离前缀)、Host 透传、X-Forwarded-* 注入
let upstream_req = rx.recv_timeout(Duration::from_secs(2)).expect("upstream received request");
let s = String::from_utf8_lossy(&upstream_req);
assert!(s.starts_with("GET /api/x?q=1 HTTP/1.1\r\n"), "forwarded request line: {s}");
assert!(s.contains("Host: web.example\r\n"), "host passthrough: {s}");
assert!(s.contains("X-Forwarded-For: 127.0.0.1\r\n"), "x-forwarded-for must reach upstream: {s}");
assert!(s.contains("x-forwarded-proto: http\r\n"), "x-forwarded-proto: {s}");
// 连接池复用后,转发请求改写为 keep-alive(连接复用前提),
// 不再是旧行为的 Connection: close
assert!(s.contains("Connection: keep-alive\r\n"), "proxy sets keep-alive for pool reuse: {s}");
}
#[test]
fn proxy_forward_chunked_upstream_end_to_end() {
let (addr, _rx) = spawn_fixed_upstream(
b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nchunk-\r\n3\r\nres\r\n0\r\n\r\n",
);
let srv = ProtocolServer::new(App::new());
srv.add_proxy_route("/api", vec![(addr, 1)], LoadBalanceStrategy::RoundRobin);
let out = h1_round_trip(
&srv,
b"GET /api/c HTTP/1.1\r\nHost: web.example\r\nConnection: close\r\n\r\n",
);
assert!(out.starts_with("HTTP/1.1 200 OK\r\n"), "response: {out}");
assert!(out.contains("chunk-res"), "chunked body decoded: {out}");
// 下游响应必须是合法 CL 分帧(transfer-encoding 逐跳头不得透传)
assert!(!out.to_ascii_lowercase().contains("transfer-encoding"), "hop-by-hop stripped: {out}");
assert!(out.to_ascii_lowercase().contains("content-length: 9\r\n"), "cl rebuilt: {out}");
}
#[test]
fn proxy_upstream_down_returns_502() {
// 127.0.0.1:1 端口必然拒绝连接(上游宕机语义)
let srv = ProtocolServer::new(App::new());
srv.add_proxy_route("/api", vec![("127.0.0.1:1".to_string(), 1)], LoadBalanceStrategy::RoundRobin);
let out = h1_round_trip(
&srv,
b"GET /api/x HTTP/1.1\r\nHost: web.example\r\nConnection: close\r\n\r\n",
);
assert!(out.starts_with("HTTP/1.1 502 Bad Gateway\r\n"), "response: {out}");
assert!(out.contains("{\"error\":\"bad_gateway\"}"), "502 json body: {out}");
// PROXY_ERROR 审计真实落库
let audit = srv.audit_log();
assert!(
audit.iter().any(|line| line.contains("PROXY_ERROR")),
"audit must contain PROXY_ERROR: {audit:?}"
);
}
#[test]
fn proxy_prefix_match_boundary() {
let (addr, _rx) = spawn_fixed_upstream(
b"HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nfrom-upstream",
);
let mut app = App::new();
app.get("/apix", |_req, _params| {
let mut resp = CanonicalResponse::new(200);
resp.set_body(b"from-app".to_vec());
Ok(resp)
});
let srv = ProtocolServer::new(app);
srv.add_proxy_route("/api", vec![(addr, 1)], LoadBalanceStrategy::RoundRobin);
// /apix 不得命中 /api 前缀(防误配),应流向 App
let out = h1_round_trip(
&srv,
b"GET /apix HTTP/1.1\r\nHost: web.example\r\nConnection: close\r\n\r\n",
);
assert!(out.contains("from-app"), "non-matching prefix must reach app: {out}");
assert!(!out.contains("from-upstream"), "must not be proxied: {out}");
// 未注册任何路由的路径也不命中代理 → App 404
let out2 = h1_round_trip(
&srv,
b"GET /other/y HTTP/1.1\r\nHost: web.example\r\nConnection: close\r\n\r\n",
);
assert!(out2.starts_with("HTTP/1.1 404"), "unmatched path falls to app 404: {out2}");
}
#[test]
fn proxy_exact_prefix_path_matches() {
let (addr, _rx) = spawn_fixed_upstream(
b"HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nfrom-upstream",
);
let srv = ProtocolServer::new(App::new());
srv.add_proxy_route("/api", vec![(addr, 1)], LoadBalanceStrategy::RoundRobin);
// path == prefix 精确匹配同样命中代理
let out = h1_round_trip(
&srv,
b"GET /api HTTP/1.1\r\nHost: web.example\r\nConnection: close\r\n\r\n",
);
assert!(out.contains("from-upstream"), "exact prefix must be proxied: {out}");
}
}