summaryrefslogtreecommitdiff
path: root/pod/nginx/development_guide.pod
blob: 6a7383b38f243a4e103515f05449e6c3e073912c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
=encoding utf-8


=head1 Name


development_guide - Development guide


=head1 Introduction


=head2 Code layout


=over



=item *

C<auto> — Build scripts



=item *

C<src>


=over




=item *

C<core> — Basic types and functions — string, array, log,
pool, etc.



=item *

C<event> — Event core


=over




=item *

C<modules> — Event notification modules:
C<epoll>, C<kqueue>, C<select>
etc.



=back






=item *

C<http> — Core HTTP module and common code


=over




=item *

C<modules> — Other HTTP modules



=item *

C<v2> — HTTPE<sol>2



=back






=item *

C<mail> — Mail modules



=item *

C<os> — Platform-specific code


=over




=item *

 C<unix>



=item *

 C<win32>



=back






=item *

C<stream> — Stream modules



=back






=back




=head2 Include files



The following two C<#include> statements must appear at the
beginning of every nginx file:




    
    #include <ngx_config.h>
    #include <ngx_core.h>





In addition to that, HTTP code should include





    
    #include <ngx_http.h>





Mail code should include





    
    #include <ngx_mail.h>





Stream code should include





    
    #include <ngx_stream.h>




=head2 Integers



For general purposes, nginx code uses two integer types,
C<ngx_int_t> and C<ngx_uint_t>, which are
typedefs for C<intptr_t> and C<uintptr_t>
respectively.




=head2 Common return codes



Most functions in nginx return the following codes:




=over




=item *

C<NGX_OK> — Operation succeeded.



=item *

C<NGX_ERROR> — Operation failed.



=item *

C<NGX_AGAIN> — Operation incomplete; call the function again.



=item *

C<NGX_DECLINED> — Operation rejected, for example, because it is
disabled in the configuration. This is never an error.



=item *

C<NGX_BUSY> — Resource is not available.



=item *

C<NGX_DONE> — Operation complete or continued elsewhere.
Also used as an alternative success code.



=item *

C<NGX_ABORT> — Function was aborted.
Also used as an alternative error code.



=back




=head2 Error handling



The C<ngx_errno> macro returns the last system error code.
It's mapped to C<errno> on POSIX platforms and to
C<GetLastError()> call in Windows.
The C<ngx_socket_errno> macro returns the last socket error
number.
Like the C<ngx_errno> macro, it's mapped to
C<errno> on POSIX platforms.
It's mapped to the C<WSAGetLastError()> call on Windows.
Accessing the values of C<ngx_errno> or
C<ngx_socket_errno> more than once in a row can cause
performance issues.
If the error value might be used multiple times, store it in a local variable
of type C<ngx_err_t>.
To set errors, use the C<ngx_set_errno(errno)> and
C<ngx_set_socket_errno(errno)> macros.





The values of C<ngx_errno> and
C<ngx_socket_errno> can be passed to the logging functions
C<ngx_log_error()> and C<ngx_log_debugX()>, in
which case system error text is added to the log message.





Example using C<ngx_errno>:





    
    ngx_int_t
    ngx_my_kill(ngx_pid_t pid, ngx_log_t *log, int signo)
    {
        ngx_err_t  err;
    
        if (kill(pid, signo) == -1) {
            err = ngx_errno;
    
            ngx_log_error(NGX_LOG_ALERT, log, err, "kill(%P, %d) failed", pid, signo);
    
            if (err == NGX_ESRCH) {
                return 2;
            }
    
            return 1;
        }
    
        return 0;
    }




=head1 Strings


=head2 Overview



For C strings, nginx uses the unsigned character type pointer
C<u_char *>.





The nginx string type C<ngx_str_t> is defined as follows:





    
    typedef struct {
        size_t      len;
        u_char     *data;
    } ngx_str_t;





The C<len> field holds the string length and
C<data> holds the string data.
The string, held in C<ngx_str_t>, may or may not be
null-terminated after the C<len> bytes.
In most cases it’s not.
However, in certain parts of the code (for example, when parsing configuration),
C<ngx_str_t> objects are known to be null-terminated, which
simplifies string comparison and makes it easier to pass the strings to
syscalls.





The string operations in nginx are declared in
F<srcE<sol>coreE<sol>ngx_string.h>
Some of them are wrappers around standard C functions:






=over




=item *

C<ngx_strcmp()>



=item *

C<ngx_strncmp()>



=item *

C<ngx_strstr()>



=item *

C<ngx_strlen()>



=item *

C<ngx_strchr()>



=item *

C<ngx_memcmp()>



=item *

C<ngx_memset()>



=item *

C<ngx_memcpy()>



=item *

C<ngx_memmove()>



=back








Other string functions are nginx-specific






=over




=item *

C<ngx_memzero()> — Fills memory with zeroes.



=item *

C<ngx_explicit_memzero()> — Does the same as
C<ngx_memzero()>, but this call is never removed by the
compiler's dead store elimination optimization.
This function can be used to clear sensitive data such as passwords and keys.



=item *

C<ngx_cpymem()> — Does the same as
C<ngx_memcpy()>, but returns the final destination address
This one is handy for appending multiple strings in a row.



=item *

C<ngx_movemem()> — Does the same as
C<ngx_memmove()>, but returns the final destination address.



=item *

C<ngx_strlchr()> — Searches for a character in a string,
delimited by two pointers.


=back







The following functions perform case conversion and comparison:






=over




=item *

C<ngx_tolower()>



=item *

C<ngx_toupper()>



=item *

C<ngx_strlow()>



=item *

C<ngx_strcasecmp()>



=item *

C<ngx_strncasecmp()>



=back







The following macros simplify string initialization:




=over




=item *

C<ngx_string(text)> — static initializer for the
C<ngx_str_t> type from the C string literal
C<text>



=item *

C<ngx_null_string> — static empty string initializer for the
C<ngx_str_t> type



=item *

C<ngx_str_set(str, text)> — initializes string
C<str> of C<ngx_str_t *> type with the C string
literal C<text>



=item *

C<ngx_str_null(str)> — initializes string C<str>
of C<ngx_str_t *> type with the empty string



=back




=head2 Formatting



The following formatting functions support nginx-specific types:







=over




=item *

C<ngx_sprintf(buf, fmt, ...)>



=item *

C<ngx_snprintf(buf, max, fmt, ...)>



=item *

C<ngx_slprintf(buf, last, fmt, ...)>



=item *

C<ngx_vslprintf(buf, last, fmt, args)>



=item *

C<ngx_vsnprintf(buf, max, fmt, args)>



=back







The full list of formatting options, supported by these functions is
in F<srcE<sol>coreE<sol>ngx_string.c>. Some of them are:





=over




=item *

C<%O> — C<off_t>



=item *

C<%T> — C<time_t>



=item *

C<%z> — C<ssize_t>



=item *

C<%i> — C<ngx_int_t>



=item *

C<%p> — C<void *>



=item *

C<%V> — C<ngx_str_t *>



=item *

C<%s> — C<u_char *> (null-terminated)



=item *

C<%*s> — C<size_t + u_char *>



=back






You can prepend C<u> on most types to make them unsigned.
To convert output to hex, use C<X> or C<x>.





For example:


    
    u_char      buf[NGX_INT_T_LEN];
    size_t      len;
    ngx_uint_t  n;
    
    /* set n here */
    
    len = ngx_sprintf(buf, "%ui", n) — buf;







=head2 Numeric conversion



Several functions for numeric conversion are implemented in nginx.
The first four each convert a string of given length to a positive integer of
the indicated type.
They return C<NGX_ERROR> on error.


=over




=item *

C<ngx_atoi(line, n)> — C<ngx_int_t>



=item *

C<ngx_atosz(line, n)> — C<ssize_t>



=item *

C<ngx_atoof(line, n)> — C<off_t>



=item *

C<ngx_atotm(line, n)> — C<time_t>



=back







There are two additional numeric conversion functions.
Like the first four, they return C<NGX_ERROR> on error.


=over




=item *

C<ngx_atofp(line, n, point)> — Converts a fixed point floating
number of given length to a positive integer of type
C<ngx_int_t>.
The result is shifted left by C<point> decimal
positions.
The string representation of the number is expected to have no more
than C<points> fractional digits.
For example, C<ngx_atofp("10.5", 4, 2)> returns
C<1050>.



=item *

C<ngx_hextoi(line, n)> — Converts a hexadecimal representation
of a positive integer to C<ngx_int_t>.



=back






=head2 Regular expressions



The regular expressions interface in nginx is a wrapper around
the L<PCRE|http://www.pcre.org>
library.
The corresponding header file is F<srcE<sol>coreE<sol>ngx_regex.h>.





To use a regular expression for string matching, it first needs to be
compiled, which is usually done at the configuration phase.
Note that since PCRE support is optional, all code using the interface must
be protected by the surrounding C<NGX_PCRE> macro:


    
    #if (NGX_PCRE)
    ngx_regex_t          *re;
    ngx_regex_compile_t   rc;
    
    u_char                errstr[NGX_MAX_CONF_ERRSTR];
    
    ngx_str_t  value = ngx_string("message (\\d\\d\\d).*Codeword is '(?<cw>\\w+)'");
    
    ngx_memzero(&rc, sizeof(ngx_regex_compile_t));
    
    rc.pattern = value;
    rc.pool = cf->pool;
    rc.err.len = NGX_MAX_CONF_ERRSTR;
    rc.err.data = errstr;
    /* rc.options can be set to NGX_REGEX_CASELESS */
    
    if (ngx_regex_compile(&rc) != NGX_OK) {
        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V", &rc.err);
        return NGX_CONF_ERROR;
    }
    
    re = rc.regex;
    #endif


After successful compilation, the C<captures> and
C<named_captures> fields in the
C<ngx_regex_compile_t> structure contain the count of all
captures and named captures, respectively, found in the regular expression.





The compiled regular expression can then be used for matching against strings:

    
    ngx_int_t  n;
    int        captures[(1 + rc.captures) * 3];
    
    ngx_str_t input = ngx_string("This is message 123. Codeword is 'foobar'.");
    
    n = ngx_regex_exec(re, &input, captures, (1 + rc.captures) * 3);
    if (n >= 0) {
        /* string matches expression */
    
    } else if (n == NGX_REGEX_NO_MATCHED) {
        /* no match was found */
    
    } else {
        /* some error */
        ngx_log_error(NGX_LOG_ALERT, log, 0, ngx_regex_exec_n " failed: %i", n);
    }


The arguments to C<ngx_regex_exec()> are the compiled regular
expression C<re>, the string to match C<input>,
an optional array of integers to hold any C<captures> that are
found, and the array's C<size>.
The size of the C<captures> array must be a multiple of three,
as required by the
L<PCRE API|http://www.pcre.org/original/doc/html/pcreapi.html>.
In the example, the size is calculated from the total number of captures plus
one for the matched string itself.





If there are matches, captures can be accessed as follows:

    
    u_char     *p;
    size_t      size;
    ngx_str_t   name, value;
    
    /* all captures */
    for (i = 0; i < n * 2; i += 2) {
        value.data = input.data + captures[i];
        value.len = captures[i + 1] — captures[i];
    }
    
    /* accessing named captures */
    
    size = rc.name_size;
    p = rc.names;
    
    for (i = 0; i < rc.named_captures; i++, p += size) {
    
        /* capture name */
        name.data = &p[2];
        name.len = ngx_strlen(name.data);
    
        n = 2 * ((p[0] << 8) + p[1]);
    
        /* captured value */
        value.data = &input.data[captures[n]];
        value.len = captures[n + 1] — captures[n];
    }







The C<ngx_regex_exec_array()> function accepts the array of
C<ngx_regex_elt_t> elements (which are just compiled regular
expressions with associated names), a string to match, and a log.
The function applies expressions from the array to the string until
either a match is found or no more expressions are left.
The return value is C<NGX_OK> when there is a match and
C<NGX_DECLINED> otherwise, or C<NGX_ERROR>
in case of error.




=head1 Time



The C<ngx_time_t> structure represents time with three separate
types for seconds, milliseconds, and the GMT offset:

    
    typedef struct {
        time_t      sec;
        ngx_uint_t  msec;
        ngx_int_t   gmtoff;
    } ngx_time_t;


The C<ngx_tm_t> structure is an alias for
C<struct tm> on UNIX platforms and C<SYSTEMTIME>
on Windows.





To obtain the current time, it is usually sufficient to access one of the
available global variables, representing the cached time value in the desired
format.





The available string representations are:


=over




=item *

C<ngx_cached_err_log_time> — Used in error log entries:
C<"1970E<sol>09E<sol>28 12:00:00">



=item *

C<ngx_cached_http_log_time> — Used in HTTP access log entries:
C<"28E<sol>SepE<sol>1970:12:00:00 +0600">



=item *

C<ngx_cached_syslog_time> — Used in syslog entries:
C<"Sep 28 12:00:00">



=item *

C<ngx_cached_http_time> — Used in HTTP headers:
C<"Mon, 28 Sep 1970 06:00:00 GMT">



=item *

C<ngx_cached_http_log_iso8601> — The ISO 8601
standard format:
C<"1970-09-28T12:00:00+06:00">



=back







The C<ngx_time()> and C<ngx_timeofday()> macros
return the current time value in seconds and are the preferred way to access
the cached time value.





To obtain the time explicitly, use C<ngx_gettimeofday()>,
which updates its argument (pointer to
C<struct timeval>).
The time is always updated when nginx returns to the event loop from system
calls.
To update the time immediately, call C<ngx_time_update()>,
or C<ngx_time_sigsafe_update()> if updating the time in the
signal handler context.





The following functions convert C<time_t> into the indicated
broken-down time representation.
The first function in each pair converts C<time_t> to
C<ngx_tm_t> and the second (with the C<_libc_>
infix) to C<struct tm>:


=over




=item *

C<ngx_gmtime(), ngx_libc_gmtime()> — Time expressed as UTC



=item *

C<ngx_localtime(), ngx_libc_localtime()> — Time expressed
relative to the local time zone



=back



The C<ngx_http_time(buf, time)> function returns a string
representation suitable for use in HTTP headers (for example,
C<"Mon, 28 Sep 1970 06:00:00 GMT">).
The C<ngx_http_cookie_time(buf, time)> returns a string
representation function returns a string representation suitable
for HTTP cookies (C<"Thu, 31-Dec-37 23:55:55 GMT">).




=head1 Containers


=head2 Array



The nginx array type C<ngx_array_t> is defined as follows





    
    typedef struct {
        void        *elts;
        ngx_uint_t   nelts;
        size_t       size;
        ngx_uint_t   nalloc;
        ngx_pool_t  *pool;
    } ngx_array_t;





The elements of the array are available in the C<elts> field.
The C<nelts> field holds the number of elements.
The C<size> field holds the size of a single element and is set
when the array is initialized.





Use the C<ngx_array_create(pool, n, size)> call to create an
array in a pool, and the C<ngx_array_init(array, pool, n, size)>
call to initialize an array object that has already been allocated.





    
    ngx_array_t  *a, b;
    
    /* create an array of strings with preallocated memory for 10 elements */
    a = ngx_array_create(pool, 10, sizeof(ngx_str_t));
    
    /* initialize string array for 10 elements */
    ngx_array_init(&b, pool, 10, sizeof(ngx_str_t));





Use the following functions to add elements to an array:






=over




=item *

C<ngx_array_push(a)> adds one tail element and returns pointer
to it



=item *

C<ngx_array_push_n(a, n)> adds C<n> tail elements
and returns pointer to the first one



=back







If the currently allocated amount of memory is not large enough to accommodate
the new elements, a new block of memory is allocated and the existing elements
are copied to it.
The new memory block is normally twice as large as the existing one.





    
    s = ngx_array_push(a);
    ss = ngx_array_push_n(&b, 3);




=head2 List



In nginx a list is a sequence of arrays, optimized for inserting a potentially
large number of items.
The C<ngx_list_t> list type is defined as follows:





    
    typedef struct {
        ngx_list_part_t  *last;
        ngx_list_part_t   part;
        size_t            size;
        ngx_uint_t        nalloc;
        ngx_pool_t       *pool;
    } ngx_list_t;





The actual items are stored in list parts, which are defined as follows:





    
    typedef struct ngx_list_part_s  ngx_list_part_t;
    
    struct ngx_list_part_s {
        void             *elts;
        ngx_uint_t        nelts;
        ngx_list_part_t  *next;
    };





Before use, a list must be initialized by calling
C<ngx_list_init(list, pool, n, size)> or created by calling
C<ngx_list_create(pool, n, size)>.
Both functions take as arguments the size of a single item and a number of
items per list part.
To add an item to a list, use the C<ngx_list_push(list)>
function.
To iterate over the items, directly access the list fields as shown in the
example:





    
    ngx_str_t        *v;
    ngx_uint_t        i;
    ngx_list_t       *list;
    ngx_list_part_t  *part;
    
    list = ngx_list_create(pool, 100, sizeof(ngx_str_t));
    if (list == NULL) { /* error */ }
    
    /* add items to the list */
    
    v = ngx_list_push(list);
    if (v == NULL) { /* error */ }
    ngx_str_set(v, "foo");
    
    v = ngx_list_push(list);
    if (v == NULL) { /* error */ }
    ngx_str_set(v, "bar");
    
    /* iterate over the list */
    
    part = &list->part;
    v = part->elts;
    
    for (i = 0; /* void */; i++) {
    
        if (i >= part->nelts) {
            if (part->next == NULL) {
                break;
            }
    
            part = part->next;
            v = part->elts;
            i = 0;
        }
    
        ngx_do_smth(&v[i]);
    }





Lists are primarily used for HTTP input and output headers.





Lists do not support item removal.
However, when needed, items can internally be marked as missing without actually
being removed from the list.
For example, to mark HTTP output headers (which are stored as
C<ngx_table_elt_t> objects) as missing, set the
C<hash> field in C<ngx_table_elt_t> to
zero.
Items marked in this way are explicitly skipped when the headers are iterated
over.




=head2 Queue



In nginx a queue is an intrusive doubly linked list, with each node defined as
follows:





    
    typedef struct ngx_queue_s  ngx_queue_t;
    
    struct ngx_queue_s {
        ngx_queue_t  *prev;
        ngx_queue_t  *next;
    };





The head queue node is not linked with any data.
Use the C<ngx_queue_init(q)> call to initialize the list head
before use.
Queues support the following operations:






=over




=item *

C<ngx_queue_insert_head(h, x)>,
C<ngx_queue_insert_tail(h, x)> — Insert a new node



=item *

C<ngx_queue_remove(x)> — Remove a queue node



=item *

C<ngx_queue_split(h, q, n)> — Split a queue at a node,
returning the queue tail in a separate queue



=item *

C<ngx_queue_add(h, n)> — Add a second queue to the first queue



=item *

C<ngx_queue_head(h)>,
C<ngx_queue_last(h)> — Get first or last queue node



=item *

C<ngx_queue_sentinel(h)> - Get a queue sentinel object to end
iteration at



=item *

C<ngx_queue_data(q, type, link)> — Get a reference to the
beginning of a queue node data structure, considering the queue field offset in
it



=back







An example:





    
    typedef struct {
        ngx_str_t    value;
        ngx_queue_t  queue;
    } ngx_foo_t;
    
    ngx_foo_t    *f;
    ngx_queue_t   values, *q;
    
    ngx_queue_init(&values);
    
    f = ngx_palloc(pool, sizeof(ngx_foo_t));
    if (f == NULL) { /* error */ }
    ngx_str_set(&f->value, "foo");
    
    ngx_queue_insert_tail(&values, &f->queue);
    
    /* insert more nodes here */
    
    for (q = ngx_queue_head(&values);
         q != ngx_queue_sentinel(&values);
         q = ngx_queue_next(q))
    {
        f = ngx_queue_data(q, ngx_foo_t, queue);
    
        ngx_do_smth(&f->value);
    }




=head2 Red-Black tree



The F<srcE<sol>coreE<sol>ngx_rbtree.h> header file provides access to the
effective implementation of red-black trees.





    
    typedef struct {
        ngx_rbtree_t       rbtree;
        ngx_rbtree_node_t  sentinel;
    
        /* custom per-tree data here */
    } my_tree_t;
    
    typedef struct {
        ngx_rbtree_node_t  rbnode;
    
        /* custom per-node data */
        foo_t              val;
    } my_node_t;





To deal with a tree as a whole, you need two nodes: root and sentinel.
Typically, they are added to a custom structure, allowing you to
organize your data into a tree in which the leaves contain a link to or embed
your data.





To initialize a tree:





    
    my_tree_t  root;
    
    ngx_rbtree_init(&root.rbtree, &root.sentinel, insert_value_function);





To traverse a tree and insert new values, use the
"C<insert_value>" functions.
For example, the C<ngx_str_rbtree_insert_value> function deals
with the C<ngx_str_t> type.
Its arguments are pointers to a root node of an insertion, the newly created
node to be added, and a tree sentinel.





    
    void ngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp,
                                     ngx_rbtree_node_t *node,
                                     ngx_rbtree_node_t *sentinel)






The traversal is pretty straightforward and can be demonstrated with the
following lookup function pattern:





    
    my_node_t *
    my_rbtree_lookup(ngx_rbtree_t *rbtree, foo_t *val, uint32_t hash)
    {
        ngx_int_t           rc;
        my_node_t          *n;
        ngx_rbtree_node_t  *node, *sentinel;
    
        node = rbtree->root;
        sentinel = rbtree->sentinel;
    
        while (node != sentinel) {
    
            n = (my_node_t *) node;
    
            if (hash != node->key) {
                node = (hash < node->key) ? node->left : node->right;
                continue;
            }
    
            rc = compare(val, node->val);
    
            if (rc < 0) {
                node = node->left;
                continue;
            }
    
            if (rc > 0) {
                node = node->right;
                continue;
            }
    
            return n;
        }
    
        return NULL;
    }





The C<compare()> function is a classic comparator function that
returns a value less than, equal to, or greater than zero.
To speed up lookups and avoid comparing user objects that can be big, an integer
hash field is used.





To add a node to a tree, allocate a new node, initialize it and call
C<ngx_rbtree_insert()>:





    
        my_node_t          *my_node;
        ngx_rbtree_node_t  *node;
    
        my_node = ngx_palloc(...);
        init_custom_data(&my_node->val);
    
        node = &my_node->rbnode;
        node->key = create_key(my_node->val);
    
        ngx_rbtree_insert(&root->rbtree, node);





To remove a node, call the C<ngx_rbtree_delete()> function:





    
    ngx_rbtree_delete(&root->rbtree, node);




=head2 Hash



Hash table functions are declared in F<srcE<sol>coreE<sol>ngx_hash.h>.
Both exact and wildcard matching are supported.
The latter requires extra setup and is described in a separate section below.





Before initializing a hash, you need to know the number of elements it will
hold so that nginx can build it optimally.
Two parameters that need to be configured are C<max_size>
and C<bucket_size>, as detailed in a separate
L<document|hash>.
They are usually configurable by the user.
Hash initialization settings are stored with the
C<ngx_hash_init_t> type, and the hash itself is
C<ngx_hash_t>:

    
    ngx_hash_t       foo_hash;
    ngx_hash_init_t  hash;
    
    hash.hash = &foo_hash;
    hash.key = ngx_hash_key;
    hash.max_size = 512;
    hash.bucket_size = ngx_align(64, ngx_cacheline_size);
    hash.name = "foo_hash";
    hash.pool = cf->pool;
    hash.temp_pool = cf->temp_pool;


The C<key> is a pointer to a function that creates the hash
integer key from a string.
There are two generic key-creation functions:
C<ngx_hash_key(data, len)> and
C<ngx_hash_key_lc(data, len)>.
The latter converts a string to all lowercase characters, so the passed string
must be writable.
If that is not true, pass the C<NGX_HASH_READONLY_KEY> flag
to the function, initializing the key array (see below).





The hash keys are stored in C<ngx_hash_keys_arrays_t> and
are initialized with C<ngx_hash_keys_array_init(arr, type)>:
The second parameter (C<type>) controls the amount of resources
preallocated for the hash and can be either C<NGX_HASH_SMALL> or
C<NGX_HASH_LARGE>.
The latter is appropriate if you expect the hash to contain thousands of
elements.


    
    ngx_hash_keys_arrays_t  foo_keys;
    
    foo_keys.pool = cf->pool;
    foo_keys.temp_pool = cf->temp_pool;
    
    ngx_hash_keys_array_init(&foo_keys, NGX_HASH_SMALL);







To insert keys into a hash keys array, use the
C<ngx_hash_add_key(keys_array, key, value, flags)> function:

    
    ngx_str_t k1 = ngx_string("key1");
    ngx_str_t k2 = ngx_string("key2");
    
    ngx_hash_add_key(&foo_keys, &k1, &my_data_ptr_1, NGX_HASH_READONLY_KEY);
    ngx_hash_add_key(&foo_keys, &k2, &my_data_ptr_2, NGX_HASH_READONLY_KEY);







To build the hash table, call the
C<ngx_hash_init(hinit, key_names, nelts)> function:


    
    ngx_hash_init(&hash, foo_keys.keys.elts, foo_keys.keys.nelts);



The function fails if C<max_size> or
C<bucket_size> parameters are not big enough.





When the hash is built, use the
C<ngx_hash_find(hash, key, name, len)> function to look up
elements:

    
    my_data_t   *data;
    ngx_uint_t   key;
    
    key = ngx_hash_key(k1.data, k1.len);
    
    data = ngx_hash_find(&foo_hash, key, k1.data, k1.len);
    if (data == NULL) {
        /* key not found */
    }







=head3 Wildcard matching



To create a hash that works with wildcards, use the
C<ngx_hash_combined_t> type.
It includes the hash type described above and has two additional keys arrays:
C<dns_wc_head> and C<dns_wc_tail>.
The initialization of basic properties is similar to a regular hash:

    
    ngx_hash_init_t      hash
    ngx_hash_combined_t  foo_hash;
    
    hash.hash = &foo_hash.hash;
    hash.key = ...;







It is possible to add wildcard keys using the
C<NGX_HASH_WILDCARD_KEY> flag:

    
    /* k1 = ".example.org"; */
    /* k2 = "foo.*";        */
    ngx_hash_add_key(&foo_keys, &k1, &data1, NGX_HASH_WILDCARD_KEY);
    ngx_hash_add_key(&foo_keys, &k2, &data2, NGX_HASH_WILDCARD_KEY);


The function recognizes wildcards and adds keys into the corresponding arrays.
Please refer to the
L<ngx_http_map_module> module
documentation for the description of the wildcard syntax and the
matching algorithm.





Depending on the contents of added keys, you may need to initialize up to three
key arrays: one for exact matching (described above), and two more to enable
matching starting from the head or tail of a string:

    
    if (foo_keys.dns_wc_head.nelts) {
    
        ngx_qsort(foo_keys.dns_wc_head.elts,
                  (size_t) foo_keys.dns_wc_head.nelts,
                  sizeof(ngx_hash_key_t),
                  cmp_dns_wildcards);
    
        hash.hash = NULL;
        hash.temp_pool = pool;
    
        if (ngx_hash_wildcard_init(&hash, foo_keys.dns_wc_head.elts,
                                   foo_keys.dns_wc_head.nelts)
            != NGX_OK)
        {
            return NGX_ERROR;
        }
    
        foo_hash.wc_head = (ngx_hash_wildcard_t *) hash.hash;
    }


The keys array needs to be sorted, and initialization results must be added
to the combined hash.
The initialization of C<dns_wc_tail> array is done similarly.





The lookup in a combined hash is handled by the
C<ngx_hash_find_combined(chash, key, name, len)>:

    
    /* key = "bar.example.org"; — will match ".example.org" */
    /* key = "foo.example.com"; — will match "foo.*"        */
    
    hkey = ngx_hash_key(key.data, key.len);
    res = ngx_hash_find_combined(&foo_hash, hkey, key.data, key.len);






=head1 Memory management


=head2 Heap



To allocate memory from system heap, use the following functions:






=over




=item *

C<ngx_alloc(size, log)> — Allocate memory from system heap.
This is a wrapper around C<malloc()> with logging support.
Allocation error and debugging information is logged to C<log>.



=item *

C<ngx_calloc(size, log)> — Allocate memory from system heap
like C<ngx_alloc()>, but fill memory with zeros after
allocation.



=item *

C<ngx_memalign(alignment, size, log)> — Allocate aligned memory
from system heap.
This is a wrapper around C<posix_memalign()>
on those platforms that provide that function.
Otherwise implementation falls back to C<ngx_alloc()> which
provides maximum alignment.



=item *

C<ngx_free(p)> — Free allocated memory.
This is a wrapper around C<free()>



=back






=head2 Pool



Most nginx allocations are done in pools.
Memory allocated in an nginx pool is freed automatically when the pool is
destroyed.
This provides good allocation performance and makes memory control easy.





A pool internally allocates objects in continuous blocks of memory.
Once a block is full, a new one is allocated and added to the pool memory
block list.
When the requested allocation is too large to fit into a block, the request
is forwarded to the system allocator and the
returned pointer is stored in the pool for further deallocation.





The type for nginx pools is C<ngx_pool_t>.
The following operations are supported:






=over




=item *

C<ngx_create_pool(size, log)> — Create a pool with specified
block size.
The pool object returned is allocated in the pool as well.
The C<size>
should be at least C<NGX_MIN_POOL_SIZE>
and a multiple of C<NGX_POOL_ALIGNMENT>.



=item *

C<ngx_destroy_pool(pool)> — Free all pool memory, including
the pool object itself.



=item *

C<ngx_palloc(pool, size)> — Allocate aligned memory from the
specified pool.



=item *

C<ngx_pcalloc(pool, size)> — Allocate aligned memory
from the specified pool and fill it with zeroes.



=item *

C<ngx_pnalloc(pool, size)> — Allocate unaligned memory from the
specified pool.
Mostly used for allocating strings.



=item *

C<ngx_pfree(pool, p)> — Free memory that was previously
allocated in the specified pool.
Only allocations that result from requests forwarded to the system allocator
can be freed.



=back






    
    u_char      *p;
    ngx_str_t   *s;
    ngx_pool_t  *pool;
    
    pool = ngx_create_pool(1024, log);
    if (pool == NULL) { /* error */ }
    
    s = ngx_palloc(pool, sizeof(ngx_str_t));
    if (s == NULL) { /* error */ }
    ngx_str_set(s, "foo");
    
    p = ngx_pnalloc(pool, 3);
    if (p == NULL) { /* error */ }
    ngx_memcpy(p, "foo", 3);





Chain links (C<ngx_chain_t>) are actively used in nginx,
so the nginx pool implementation provides a way to reuse them.
The C<chain> field of C<ngx_pool_t> keeps a
list of previously allocated links ready for reuse.
For efficient allocation of a chain link in a pool, use the
C<ngx_alloc_chain_link(pool)> function.
This function looks up a free chain link in the pool list and allocates a new
chain link if the pool list is empty.
To free a link, call the C<ngx_free_chain(pool, cl)> function.





Cleanup handlers can be registered in a pool.
A cleanup handler is a callback with an argument which is called when pool is
destroyed.
A pool is usually tied to a specific nginx object (like an HTTP request) and is
destroyed when the object reaches the end of its lifetime.
Registering a pool cleanup is a convenient way to release resources, close
file descriptors or make final adjustments to the shared data associated with
the main object.





To register a pool cleanup, call
C<ngx_pool_cleanup_add(pool, size)>, which returns a
C<ngx_pool_cleanup_t> pointer to
be filled in by the caller.
Use the C<size> argument to allocate context for the cleanup
handler.





    
    ngx_pool_cleanup_t  *cln;
    
    cln = ngx_pool_cleanup_add(pool, 0);
    if (cln == NULL) { /* error */ }
    
    cln->handler = ngx_my_cleanup;
    cln->data = "foo";
    
    ...
    
    static void
    ngx_my_cleanup(void *data)
    {
        u_char  *msg = data;
    
        ngx_do_smth(msg);
    }




=head2 Shared memory



Shared memory is used by nginx to share common data between processes.
The C<ngx_shared_memory_add(cf, name, size, tag)> function adds
a new shared memory entry C<ngx_shm_zone_t> to a cycle.
The function receives the C<name> and C<size>
of the zone.
Each shared zone must have a unique name.
If a shared zone entry with the provided C<name> and
C<tag> already exists, the existing zone entry is reused.
The function fails with an error if an existing entry with the same name has a
different tag.
Usually, the address of the module structure is passed as
C<tag>, making it possible to reuse shared zones by name within
one nginx module.





The shared memory entry structure C<ngx_shm_zone_t> has the
following fields:






=over




=item *

C<init> — Initialization callback, called after the shared zone
is mapped to actual memory



=item *

C<data> — Data context, used to pass arbitrary data to the
C<init> callback



=item *

C<noreuse> — Flag that disables reuse of a shared zone from the
old cycle



=item *

C<tag> — Shared zone tag



=item *

C<shm> — Platform-specific object of type
C<ngx_shm_t>, having at least the following fields:

=over




=item *

C<addr> — Mapped shared memory address, initially NULL



=item *

C<size> — Shared memory size



=item *

C<name> — Shared memory name



=item *

C<log> — Shared memory log



=item *

C<exists> — Flag that indicates shared memory was inherited
from the master process (Windows-specific)



=back





=back







Shared zone entries are mapped to actual memory in
C<ngx_init_cycle()> after the configuration is parsed.
On POSIX systems, the C<mmap()> syscall is used to create the
shared anonymous mapping.
On Windows, the C<CreateFileMapping()>E<sol>
C<MapViewOfFileEx()> pair is used.





For allocating in shared memory, nginx provides the slab pool
C<ngx_slab_pool_t> type.
A slab pool for allocating memory is automatically created in each nginx shared
zone.
The pool is located in the beginning of the shared zone and can be accessed by
the expression C<(ngx_slab_pool_t *) shm_zone-E<gt>shm.addr>.
To allocate memory in a shared zone, call either
C<ngx_slab_alloc(pool, size)> or
C<ngx_slab_calloc(pool, size)>.
To free memory, call C<ngx_slab_free(pool, p)>.





Slab pool divides all shared zone into pages.
Each page is used for allocating objects of the same size.
The specified size must be a power of 2, and greater than the minimum size of
8 bytes.
Nonconforming values are rounded up.
A bitmask for each page tracks which blocks are in use and which are free for
allocation.
For sizes greater than a half page (which is usually 2048 bytes), allocation is
done an entire page at a time





To protect data in shared memory from concurrent access, use the mutex
available in the C<mutex> field of
C<ngx_slab_pool_t>.
A mutex is most commonly used by the slab pool while allocating and freeing
memory, but it can be used to protect any other user data structures allocated
in the shared zone.
To lock or unlock a mutex, call
C<ngx_shmtx_lock(E<amp>shpool-E<gt>mutex)> or
C<ngx_shmtx_unlock(E<amp>shpool-E<gt>mutex)> respectively.





    
    ngx_str_t        name;
    ngx_foo_ctx_t   *ctx;
    ngx_shm_zone_t  *shm_zone;
    
    ngx_str_set(&name, "foo");
    
    /* allocate shared zone context */
    ctx = ngx_pcalloc(cf->pool, sizeof(ngx_foo_ctx_t));
    if (ctx == NULL) {
        /* error */
    }
    
    /* add an entry for 64k shared zone */
    shm_zone = ngx_shared_memory_add(cf, &name, 65536, &ngx_foo_module);
    if (shm_zone == NULL) {
        /* error */
    }
    
    /* register init callback and context */
    shm_zone->init = ngx_foo_init_zone;
    shm_zone->data = ctx;
    
    
    ...
    
    
    static ngx_int_t
    ngx_foo_init_zone(ngx_shm_zone_t *shm_zone, void *data)
    {
        ngx_foo_ctx_t  *octx = data;
    
        size_t            len;
        ngx_foo_ctx_t    *ctx;
        ngx_slab_pool_t  *shpool;
    
        value = shm_zone->data;
    
        if (octx) {
            /* reusing a shared zone from old cycle */
            ctx->value = octx->value;
            return NGX_OK;
        }
    
        shpool = (ngx_slab_pool_t *) shm_zone->shm.addr;
    
        if (shm_zone->shm.exists) {
            /* initialize shared zone context in Windows nginx worker */
            ctx->value = shpool->data;
            return NGX_OK;
        }
    
        /* initialize shared zone */
    
        ctx->value = ngx_slab_alloc(shpool, sizeof(ngx_uint_t));
        if (ctx->value == NULL) {
            return NGX_ERROR;
        }
    
        shpool->data = ctx->value;
    
        return NGX_OK;
    }




=head1 Logging



For logging nginx uses C<ngx_log_t> objects.
The nginx logger supports several types of output:


=over




=item *

stderr — Logging to standard error (stderr)



=item *

file — Logging to a file



=item *

syslog — Logging to syslog



=item *

memory — Logging to internal memory storage for development purposes; the memory
can be accessed later with a debugger



=back







A logger instance can be a chain of loggers, linked to each other with
the C<next> field.
In this case, each message is written to all loggers in the chain.





For each logger, a severity level controls which messages are written to the
log (only events assigned that level or higher are logged).
The following severity levels are supported:






=over




=item *

 C<NGX_LOG_EMERG>



=item *

 C<NGX_LOG_ALERT>



=item *

 C<NGX_LOG_CRIT>



=item *

 C<NGX_LOG_ERR>



=item *

 C<NGX_LOG_WARN>



=item *

 C<NGX_LOG_NOTICE>



=item *

 C<NGX_LOG_INFO>



=item *

 C<NGX_LOG_DEBUG>



=back







For debug logging, the debug mask is checked as well.
The debug masks are:






=over




=item *

 C<NGX_LOG_DEBUG_CORE>



=item *

 C<NGX_LOG_DEBUG_ALLOC>



=item *

 C<NGX_LOG_DEBUG_MUTEX>



=item *

 C<NGX_LOG_DEBUG_EVENT>



=item *

 C<NGX_LOG_DEBUG_HTTP>



=item *

 C<NGX_LOG_DEBUG_MAIL>



=item *

 C<NGX_LOG_DEBUG_STREAM>



=back







Normally, loggers are created by existing nginx code from
C<error_log> directives and are available at nearly every stage
of processing in cycle, configuration, client connection and other objects.





Nginx provides the following logging macros:






=over




=item *

C<ngx_log_error(level, log, err, fmt, ...)> — Error logging



=item *

C<ngx_log_debug0(level, log, err, fmt)>,
C<ngx_log_debug1(level, log, err, fmt, arg1)> etc — Debug
logging with up to eight supported formatting arguments



=back







A log message is formatted in a buffer of size
C<NGX_MAX_ERROR_STR> (currently, 2048 bytes) on stack.
The message is prepended with the severity level, process ID (PID), connection
ID (stored in C<log-E<gt>connection>), and the system error text.
For non-debug messages C<log-E<gt>handler> is called as well to
prepend more specific information to the log message.
HTTP module sets C<ngx_http_log_error()> function as log
handler to log client and server addresses, current action (stored in
C<log-E<gt>action>), client request line, server name etc.




    
    /* specify what is currently done */
    log->action = "sending mp4 to client";
    
    /* error and debug log */
    ngx_log_error(NGX_LOG_INFO, c->log, 0, "client prematurely
                  closed connection");
    
    ngx_log_debug2(NGX_LOG_DEBUG_HTTP, mp4->file.log, 0,
                   "mp4 start:%ui, length:%ui", mp4->start, mp4->length);





The example above results in log entries like these:





    
    2016/09/16 22:08:52 [info] 17445#0: *1 client prematurely closed connection while
    sending mp4 to client, client: 127.0.0.1, server: , request: "GET /file.mp4 HTTP/1.1"
    2016/09/16 23:28:33 [debug] 22140#0: *1 mp4 start:0, length:10000




=head1 Cycle



A cycle object stores the nginx runtime context created from a specific
configuration.
Its type is C<ngx_cycle_t>.
The current cycle is referenced by the C<ngx_cycle> global
variable and inherited by nginx workers as they start.
Each time the nginx configuration is reloaded, a new cycle is created from the
new nginx configuration; the old cycle is usually deleted after the new one is
successfully created.





A cycle is created by the C<ngx_init_cycle()> function, which
takes the previous cycle as its argument.
The function locates the previous cycle's configuration file and inherits as
many resources as possible from the previous cycle.
A placeholder cycle called "init cycle" is created as nginx start, then is
replaced by an actual cycle built from configuration.





Members of the cycle include:






=over




=item *

C<pool> — Cycle pool.
Created for each new cycle.



=item *

C<log> — Cycle log.
Initially inherited from the old cycle, it is set to point to
C<new_log> after the configuration is read.



=item *

C<new_log> — Cycle log, created by the configuration.
It's affected by the root-scope C<error_log> directive.



=item *

C<connections>, C<connection_n> —
Array of connections of type C<ngx_connection_t>, created by
the event module while initializing each nginx worker.
The C<worker_connections> directive in the nginx configuration
sets the number of connections C<connection_n>.



=item *

C<free_connections>,
C<free_connection_n> — List and number of currently available
connections.
If no connections are available, an nginx worker refuses to accept new clients
or connect to upstream servers.



=item *

C<files>, C<files_n> — Array for mapping file
descriptors to nginx connections.
This mapping is used by the event modules, having the
C<NGX_USE_FD_EVENT> flag (currently, it's
C<poll> and C<devpoll>).



=item *

C<conf_ctx> — Array of core module configurations.
The configurations are created and filled during reading of nginx configuration
files.



=item *

C<modules>, C<modules_n> — Array of modules
of type C<ngx_module_t>, both static and dynamic, loaded by
the current configuration.



=item *

C<listening> — Array of listening objects of type
C<ngx_listening_t>.
Listening objects are normally added by the C<listen>
directive of different modules which call the
C<ngx_create_listening()> function.
Listen sockets are created based on the listening objects.



=item *

C<paths> — Array of paths of type C<ngx_path_t>.
Paths are added by calling the function C<ngx_add_path()> from
modules which are going to operate on certain directories.
These directories are created by nginx after reading configuration, if missing.
Moreover, two handlers can be added for each path:


=over




=item *

path loader — Executes only once in 60 seconds after starting or reloading
nginx.
Normally, the loader reads the directory and stores data in nginx shared
memory.
The handler is called from the dedicated nginx process “nginx cache loader”.



=item *

path manager — Executes periodically.
Normally, the manager removes old files from the directory and updates nginx
memory to reflect the changes.
The handler is called from the dedicated “nginx cache manager” process.



=back





=item *

C<open_files> — List of open file objects of type
C<ngx_open_file_t>, which are created by calling the function
C<ngx_conf_open_file()>.
Currently, nginx uses this kind of open files for logging.
After reading the configuration, nginx opens all files in the
C<open_files> list and stores each file descriptor in the
object's C<fd> field.
The files are opened in append mode and are created if missing.
The files in the list are reopened by nginx workers upon receiving the
reopen signal (most often C<USR1>).
In this case the descriptor in the C<fd> field is changed to a
new value.



=item *

C<shared_memory> — List of shared memory zones, each added by
calling the C<ngx_shared_memory_add()> function.
Shared zones are mapped to the same address range in all nginx processes and
are used to share common data, for example the HTTP cache in-memory tree.



=back






=head1 Buffer



For inputE<sol>output operations, nginx provides the buffer type
C<ngx_buf_t>.
Normally, it's used to hold data to be written to a destination or read from a
source.
A buffer can reference data in memory or in a file and it's technically
possible for a buffer to reference both at the same time.
Memory for the buffer is allocated separately and is not related to the buffer
structure C<ngx_buf_t>.





The C<ngx_buf_t> structure has the following fields:






=over




=item *

C<start>, C<end> — The boundaries of the memory
block allocated for the buffer.



=item *

C<pos>, C<last> — The boundaries of the memory
buffer; normally a subrange of C<start> ..
C<end>.



=item *

C<file_pos>, C<file_last> — The boundaries of a
file buffer, expressed as offsets from the beginning of the file.



=item *

C<tag> — Unique value used to distinguish buffers; created by
different nginx modules, usually for the purpose of buffer reuse.



=item *

C<file> — File object.



=item *

C<temporary> — Flag indicating that the buffer references
writable memory.



=item *

C<memory> — Flag indicating that the buffer references read-only
memory.



=item *

C<in_file> — Flag indicating that the buffer references data
in a file.



=item *

C<flush> — Flag indicating that all data prior to the buffer
need to be flushed.



=item *

C<recycled> — Flag indicating that the buffer can be reused and
needs to be consumed as soon as possible.



=item *

C<sync> — Flag indicating that the buffer carries no data or
special signal like C<flush> or C<last_buf>.
By default nginx considers such buffers an error condition, but this flag tells
nginx to skip the error check.



=item *

C<last_buf> — Flag indicating that the buffer is the last in
output.



=item *

C<last_in_chain> — Flag indicating that there are no more data
buffers in a request or subrequest.



=item *

C<shadow> — Reference to another ("shadow") buffer related to
the current buffer, usually in the sense that the buffer uses data from the
shadow.
When the buffer is consumed, the shadow buffer is normally also marked as
consumed.



=item *

C<last_shadow> — Flag indicating that the buffer is the last
one that references a particular shadow buffer.



=item *

C<temp_file> — Flag indicating that the buffer is in a temporary
file.



=back







For input and output operations buffers are linked in chains.
A chain is a sequence of chain links of type C<ngx_chain_t>,
defined as follows:





    
    typedef struct ngx_chain_s  ngx_chain_t;
    
    struct ngx_chain_s {
        ngx_buf_t    *buf;
        ngx_chain_t  *next;
    };





Each chain link keeps a reference to its buffer and a reference to the next
chain link.





An example of using buffers and chains:





    
    ngx_chain_t *
    ngx_get_my_chain(ngx_pool_t *pool)
    {
        ngx_buf_t    *b;
        ngx_chain_t  *out, *cl, **ll;
    
        /* first buf */
        cl = ngx_alloc_chain_link(pool);
        if (cl == NULL) { /* error */ }
    
        b = ngx_calloc_buf(pool);
        if (b == NULL) { /* error */ }
    
        b->start = (u_char *) "foo";
        b->pos = b->start;
        b->end = b->start + 3;
        b->last = b->end;
        b->memory = 1; /* read-only memory */
    
        cl->buf = b;
        out = cl;
        ll = &cl->next;
    
        /* second buf */
        cl = ngx_alloc_chain_link(pool);
        if (cl == NULL) { /* error */ }
    
        b = ngx_create_temp_buf(pool, 3);
        if (b == NULL) { /* error */ }
    
        b->last = ngx_cpymem(b->last, "foo", 3);
    
        cl->buf = b;
        cl->next = NULL;
        *ll = cl;
    
        return out;
    }




=head1 Networking


=head2 Connection



The connection type C<ngx_connection_t> is a wrapper around a
socket descriptor.
It includes the following fields:






=over




=item *

C<fd> — Socket descriptor



=item *

C<data> — Arbitrary connection context.
Normally, it is a pointer to a higher-level object built on top of the
connection, such as an HTTP request or a Stream session.



=item *

C<read>, C<write> — Read and write events for
the connection.



=item *

C<recv>, C<send>,
C<recv_chain>, C<send_chain> — IE<sol>O operations
for the connection.



=item *

C<pool> — Connection pool.



=item *

C<log> — Connection log.



=item *

C<sockaddr>, C<socklen>,
C<addr_text> — Remote socket address in binary and text forms.



=item *

C<local_sockaddr>, C<local_socklen> — Local
socket address in binary form.
Initially, these fields are empty.
Use the C<ngx_connection_local_sockaddr()> function to get the
local socket address.



=item *

C<proxy_protocol_addr>, C<proxy_protocol_port>
- PROXY protocol client address and port, if the PROXY protocol is enabled for
the connection.



=item *

C<ssl> — SSL context for the connection.



=item *

C<reusable> — Flag indicating the connection is in a state that
makes it eligible for reuse.



=item *

C<close> — Flag indicating that the connection is being reused
and needs to be closed.



=back







An nginx connection can transparently encapsulate the SSL layer.
In this case the connection's C<ssl> field holds a pointer to an
C<ngx_ssl_connection_t> structure, keeping all SSL-related data
for the connection, including C<SSL_CTX> and
C<SSL>.
The C<recv>, C<send>,
C<recv_chain>, and C<send_chain> handlers are
set to SSL-enabled functions as well.





The C<worker_connections> directive in the nginx configuration
limits the number of connections per nginx worker.
All connection structures are precreated when a worker starts and stored in
the C<connections> field of the cycle object.
To retrieve a connection structure, use the
C<ngx_get_connection(s, log)> function.
It takes as its C<s> argument a socket descriptor, which needs
to be wrapped in a connection structure.





Because the number of connections per worker is limited, nginx provides a
way to grab connections that are currently in use.
To enable or disable reuse of a connection, call the
C<ngx_reusable_connection(c, reusable)> function.
Calling C<ngx_reusable_connection(c, 1)> sets the
C<reuse> flag in the connection structure and inserts the
connection into the C<reusable_connections_queue> of the cycle.
Whenever C<ngx_get_connection()> finds out there are no
available connections in the cycle's C<free_connections> list,
it calls C<ngx_drain_connections()> to release a
specific number of reusable connections.
For each such connection, the C<close> flag is set and its read
handler is called which is supposed to free the connection by calling
C<ngx_close_connection(c)> and make it available for reuse.
To exit the state when a connection can be reused
C<ngx_reusable_connection(c, 0)> is called.
HTTP client connections are an example of reusable connections in nginx; they
are marked as reusable until the first request byte is received from the client.




=head1 Events


=head2 Event



Event object C<ngx_event_t> in nginx provides a mechanism
for notification that a specific event has occurred.





Fields in C<ngx_event_t> include:






=over




=item *

C<data> — Arbitrary event context used in event handlers,
usually as pointer to a connection related to the event.



=item *

C<handler> — Callback function to be invoked when the event
happens.



=item *

C<write> — Flag indicating a write event.
Absence of the flag indicates a read event.



=item *

C<active> — Flag indicating that the event is registered for
receiving IE<sol>O notifications, normally from notification mechanisms like
C<epoll>, C<kqueue>, C<poll>.



=item *

C<ready> — Flag indicating that the event has received an
IE<sol>O notification.



=item *

C<delayed> — Flag indicating that IE<sol>O is delayed due to rate
limiting.



=item *

C<timer> — Red-black tree node for inserting the event into
the timer tree.



=item *

C<timer_set> — Flag indicating that the event timer is set and
not yet expired.



=item *

C<timedout> — Flag indicating that the event timer has expired.



=item *

C<eof> — Flag indicating that EOF occurred while reading data.



=item *

C<pending_eof> — Flag indicating that EOF is pending on the
socket, even though there may be some data available before it.
The flag is delivered via the C<EPOLLRDHUP>
C<epoll> event or
C<EV_EOF> C<kqueue> flag.



=item *

C<error> — Flag indicating that an error occurred during
reading (for a read event) or writing (for a write event).



=item *

C<cancelable> — Timer event flag indicating that the event
should be ignored while shutting down the worker.
Graceful worker shutdown is delayed until there are no non-cancelable timer
events scheduled.



=item *

C<posted> — Flag indicating that the event is posted to a queue.



=item *

C<queue> — Queue node for posting the event to a queue.



=back






=head2 I/O events



Each connection obtained by calling the C<ngx_get_connection()>
function has two attached events, C<c-E<gt>read> and
C<c-E<gt>write>, which are used for receiving notification that the
socket is ready for reading or writing.
All such events operate in Edge-Triggered mode, meaning that they only trigger
notifications when the state of the socket changes.
For example, doing a partial read on a socket does not make nginx deliver a
repeated read notification until more data arrives on the socket.
Even when the underlying IE<sol>O notification mechanism is essentially
Level-Triggered (C<poll>, C<select> etc), nginx
converts the notifications to Edge-Triggered.
To make nginx event notifications consistent across all notifications systems
on different platforms, the functions
C<ngx_handle_read_event(rev, flags)> and
C<ngx_handle_write_event(wev, lowat)> must be called after
handling an IE<sol>O socket notification or calling any IE<sol>O functions on that socket.
Normally, the functions are called once at the end of each read or write
event handler.




=head2 Timer events



An event can be set to send a notification when a timeout expires.
The timer used by events counts milliseconds since some unspecified point
in the past truncated to C<ngx_msec_t> type.
Its current value can be obtained from the C<ngx_current_msec>
variable.





The function C<ngx_add_timer(ev, timer)> sets a timeout for an
event, C<ngx_del_timer(ev)> deletes a previously set timeout.
The global timeout red-black tree C<ngx_event_timer_rbtree>
stores all timeouts currently set.
The key in the tree is of type C<ngx_msec_t> and is the time
when the event occurs.
The tree structure enables fast insertion and deletion operations, as well as
access to the nearest timeouts, which nginx uses to find out how long to wait
for IE<sol>O events and for expiring timeout events.




=head2 Posted events



An event can be posted which means that its handler will be called at some
point later within the current event loop iteration.
Posting events is a good practice for simplifying code and escaping stack
overflows.
Posted events are held in a post queue.
The C<ngx_post_event(ev, q)> macro posts the event
C<ev> to the post queue C<q>.
The C<ngx_delete_posted_event(ev)> macro deletes the event
C<ev> from the queue it's currently posted in.
Normally, events are posted to the C<ngx_posted_events> queue,
which is processed late in the event loop — after all IE<sol>O and timer
events are already handled.
The function C<ngx_event_process_posted()> is called to process
an event queue.
It calls event handlers until the queue is not empty.
This means that a posted event handler can post more events to be processed
within the current event loop iteration.





An example:





    
    void
    ngx_my_connection_read(ngx_connection_t *c)
    {
        ngx_event_t  *rev;
    
        rev = c->read;
    
        ngx_add_timer(rev, 1000);
    
        rev->handler = ngx_my_read_handler;
    
        ngx_my_read(rev);
    }
    
    
    void
    ngx_my_read_handler(ngx_event_t *rev)
    {
        ssize_t            n;
        ngx_connection_t  *c;
        u_char             buf[256];
    
        if (rev->timedout) { /* timeout expired */ }
    
        c = rev->data;
    
        while (rev->ready) {
            n = c->recv(c, buf, sizeof(buf));
    
            if (n == NGX_AGAIN) {
                break;
            }
    
            if (n == NGX_ERROR) { /* error */ }
    
            /* process buf */
        }
    
        if (ngx_handle_read_event(rev, 0) != NGX_OK) { /* error */ }
    }




=head2 Event loop



Except for the nginx master process, all nginx processes do IE<sol>O and so have an
event loop.
(The nginx master process instead spends most of its time in the
 C<sigsuspend()> call waiting for signals to arrive.)
The nginx event loop is implemented in the
C<ngx_process_events_and_timers()> function, which is called
repeatedly until the process exits.





The event loop has the following stages:


=over




=item *

Find the timeout that is closest to expiring, by calling
C<ngx_event_find_timer()>.
This function finds the leftmost node in the timer tree and returns the
number of milliseconds until the node expires.



=item *

Process IE<sol>O events by calling a handler, specific to the event notification
mechanism, chosen by nginx configuration.
This handler waits for at least one IE<sol>O event to happen, but only until the next
timeout expires.
When a read or write event occurs, the C<ready>
flag is set and the event's handler is called.
For Linux, the C<ngx_epoll_process_events()> handler
is normally used, which calls C<epoll_wait()> to wait for IE<sol>O
events.



=item *

Expire timers by calling C<ngx_event_expire_timers()>.
The timer tree is iterated from the leftmost element to the right until an
unexpired timeout is found.
For each expired node the C<timedout> event flag is set,
the C<timer_set> flag is reset, and the event handler is called



=item *

Process posted events by calling C<ngx_event_process_posted()>.
The function repeatedly removes the first element from the posted events
queue and calls the element's handler, until the queue is empty.



=back







All nginx processes handle signals as well.
Signal handlers only set global variables which are checked after the
C<ngx_process_events_and_timers()> call.




=head1 Processes



There are several types of processes in nginx.
The type of a process is kept in the C<ngx_process>
global variable, and is one of the following:




=over




=item *




C<NGX_PROCESS_MASTER> — The master process, which reads the
NGINX configuration, creates cycles, and starts and controls child processes.
It does not perform any IE<sol>O and responds only to signals.
Its cycle function is C<ngx_master_process_cycle()>.







=item *




C<NGX_PROCESS_WORKER> — The worker process, which handles client
connections.
It is started by the master process and responds to its signals and channel
commands as well.
Its cycle function is C<ngx_worker_process_cycle()>.
There can be multiple worker processes, as configured by the
C<worker_processes> directive.






=item *




C<NGX_PROCESS_SINGLE> — The single process, which exists only in
C<master_process off> mode, and is the only process running in
that mode.
It creates cycles (like the master process does) and handles client connections
(like the worker process does).
Its cycle function is C<ngx_single_process_cycle()>.






=item *




C<NGX_PROCESS_HELPER> — The helper process, of which currently
there are two types: cache manager and cache loader.
The cycle function for both is
C<ngx_cache_manager_process_cycle()>.






=back





The nginx processes handle the following signals:




=over




=item *




C<NGX_SHUTDOWN_SIGNAL> (C<SIGQUIT> on most
systems) — Gracefully shutdown.
Upon receiving this signal, the master process sends a shutdown signal to all
child processes.
When no child processes are left, the master destroys the cycle pool and exits.
When a worker process receives this signal, it closes all listening sockets and
waits until there are no non-cancelable events scheduled, then destroys the
cycle pool and exits.
When the cache manager or the cache loader process receives this signal, it
exits immediately.
The C<ngx_quit> variable is set to C<1> when a
process receives this signal, and is immediately reset after being processed.
The C<ngx_exiting> variable is set to C<1> while
a worker process is in the shutdown state.






=item *




C<NGX_TERMINATE_SIGNAL> (C<SIGTERM> on most
systems) — Terminate.
Upon receiving this signal, the master process sends a terminate signal to all
child processes.
If a child process does not exit within 1 second, the master process sends the
C<SIGKILL> signal to kill it.
When no child processes are left, the master process destroys the cycle pool and
exits.
When a worker process, the cache manager process or the cache loader process
receives this signal, it destroys the cycle pool and exits.
The variable C<ngx_terminate> is set to C<1>
when this signal is received.






=item *




C<NGX_NOACCEPT_SIGNAL> (C<SIGWINCH> on most
systems) - Shut down all worker and helper processes.
Upon receiving this signal, the master process shuts down its child processes.
If a previously started new nginx binary exits, the child processes of the old
master are started again.
When a worker process receives this signal, it shuts down in debug mode
set by the C<debug_points> directive.







=item *




C<NGX_RECONFIGURE_SIGNAL> (C<SIGHUP> on most
systems) - Reconfigure.
Upon receiving this signal, the master process re-reads the configuration and
creates a new cycle based on it.
If the new cycle is created successfully, the old cycle is deleted and new
child processes are started.
Meanwhile, the old child processes receive the
C<NGX_SHUTDOWN_SIGNAL> signal.
In single-process mode, nginx creates a new cycle, but keeps the old one until
there are no longer clients with active connections tied to it.
The worker and helper processes ignore this signal.






=item *




C<NGX_REOPEN_SIGNAL> (C<SIGUSR1> on most
systems) — Reopen files.
The master process sends this signal to workers, which reopen all
C<open_files> related to the cycle.






=item *




C<NGX_CHANGEBIN_SIGNAL> (C<SIGUSR2> on most
systems) — Change the nginx binary.
The master process starts a new nginx binary and passes in a list of all listen
sockets.
The text-format list, passed in the C<“NGINX”> environment
variable, consists of descriptor numbers separated with semicolons.
The new nginx binary reads the C<“NGINX”> variable and adds the
sockets to its init cycle.
Other processes ignore this signal.






=back





While all nginx worker processes are able to receive and properly handle POSIX
signals, the master process does not use the standard C<kill()>
syscall to pass signals to workers and helpers.
Instead, nginx uses inter-process socket pairs which allow sending messages
between all nginx processes.
Currently, however, messages are only sent from the master to its children.
The messages carry the standard signals.




=head1 Threads



It is possible to offload into a separate thread tasks that would otherwise
block the nginx worker process.
For example, nginx can be configured to use threads to perform
L<file IE<sol>O|ngx_http_core_module>.
Another use case is a library that doesn't have asynchronous interface
and thus cannot be normally used with nginx.
Keep in mind that the threads interface is a helper for the existing
asynchronous approach to processing client connections, and by no means
intended as a replacement.





To deal with synchronization, the following wrappers over
C<pthreads> primitives are available:


=over




=item *

C<typedef pthread_mutex_t  ngx_thread_mutex_t;>


=over




=item *

C<ngx_int_t
ngx_thread_mutex_create(ngx_thread_mutex_t *mtx, ngx_log_t *log);>



=item *

C<ngx_int_t
ngx_thread_mutex_destroy(ngx_thread_mutex_t *mtx, ngx_log_t *log);>



=item *

C<ngx_int_t
ngx_thread_mutex_lock(ngx_thread_mutex_t *mtx, ngx_log_t *log);>



=item *

C<ngx_int_t
ngx_thread_mutex_unlock(ngx_thread_mutex_t *mtx, ngx_log_t *log);>



=back






=item *

C<typedef pthread_cond_t  ngx_thread_cond_t;>


=over




=item *

C<ngx_int_t
ngx_thread_cond_create(ngx_thread_cond_t *cond, ngx_log_t *log);>



=item *

C<ngx_int_t
ngx_thread_cond_destroy(ngx_thread_cond_t *cond, ngx_log_t *log);>



=item *

C<ngx_int_t
ngx_thread_cond_signal(ngx_thread_cond_t *cond, ngx_log_t *log);>



=item *

C<ngx_int_t
ngx_thread_cond_wait(ngx_thread_cond_t *cond, ngx_thread_mutex_t *mtx,
ngx_log_t *log);>



=back






=back








Instead of creating a new thread for each task, nginx implements
a L<ngx_core_module> strategy.
Multiple thread pools may be configured for different purposes
(for example, performing IE<sol>O on different sets of disks).
Each thread pool is created at startup and contains a limited number of threads
that process a queue of tasks.
When a task is completed, a predefined completion handler is called.





The C<srcE<sol>coreE<sol>ngx_thread_pool.h> header file contains
relevant definitions:

    
    struct ngx_thread_task_s {
        ngx_thread_task_t   *next;
        ngx_uint_t           id;
        void                *ctx;
        void               (*handler)(void *data, ngx_log_t *log);
        ngx_event_t          event;
    };
    
    typedef struct ngx_thread_pool_s  ngx_thread_pool_t;
    
    ngx_thread_pool_t *ngx_thread_pool_add(ngx_conf_t *cf, ngx_str_t *name);
    ngx_thread_pool_t *ngx_thread_pool_get(ngx_cycle_t *cycle, ngx_str_t *name);
    
    ngx_thread_task_t *ngx_thread_task_alloc(ngx_pool_t *pool, size_t size);
    ngx_int_t ngx_thread_task_post(ngx_thread_pool_t *tp, ngx_thread_task_t *task);
    


At configuration time, a module willing to use threads has to obtain a
reference to a thread pool by calling
C<ngx_thread_pool_add(cf, name)>, which either creates a
new thread pool with the given C<name> or returns a reference
to the pool with that name if it already exists.





To add a C<task> into a queue of a specified thread pool
C<tp> at runtime, use the
C<ngx_thread_task_post(tp, task)> function.

To execute a function in a thread, pass parameters and setup a completion
handler using the C<ngx_thread_task_t> structure:

    
    typedef struct {
        int    foo;
    } my_thread_ctx_t;
    
    
    static void
    my_thread_func(void *data, ngx_log_t *log)
    {
        my_thread_ctx_t *ctx = data;
    
        /* this function is executed in a separate thread */
    }
    
    
    static void
    my_thread_completion(ngx_event_t *ev)
    {
        my_thread_ctx_t *ctx = ev->data;
    
        /* executed in nginx event loop */
    }
    
    
    ngx_int_t
    my_task_offload(my_conf_t *conf)
    {
        my_thread_ctx_t    *ctx;
        ngx_thread_task_t  *task;
    
        task = ngx_thread_task_alloc(conf->pool, sizeof(my_thread_ctx_t));
        if (task == NULL) {
            return NGX_ERROR;
        }
    
        ctx = task->ctx;
    
        ctx->foo = 42;
    
        task->handler = my_thread_func;
        task->event.handler = my_thread_completion;
        task->event.data = ctx;
    
        if (ngx_thread_task_post(conf->thread_pool, task) != NGX_OK) {
            return NGX_ERROR;
        }
    
        return NGX_OK;
    }







=head1 Modules


=head2 Adding new modules



Each standalone nginx module resides in a separate directory that contains
at least two files:
C<config> and a file with the module source code.
The C<config> file contains all information needed for nginx to
integrate the module, for example:

    
    ngx_module_type=CORE
    ngx_module_name=ngx_foo_module
    ngx_module_srcs="$ngx_addon_dir/ngx_foo_module.c"
    
    . auto/module
    
    ngx_addon_name=$ngx_module_name


The C<config> file is a POSIX shell script that can set
and access the following variables:

=over




=item *

C<ngx_module_type> — Type of module to build.
Possible values are C<CORE>, C<HTTP>,
C<HTTP_FILTER>, C<HTTP_INIT_FILTER>,
C<HTTP_AUX_FILTER>, C<MAIL>,
C<STREAM>, or C<MISC>.



=item *

C<ngx_module_name> — Module names.
To build multiple modules from a set of source files, specify a
whitespace-separated list of names.
The first name indicates the name of the output binary for the dynamic module.
The names in the list must match the names used in the source code.



=item *

C<ngx_addon_name> — Name of the module as it appears in output
on the console from the configure script.



=item *

C<ngx_module_srcs> — Whitespace-separated list of source
files used to compile the module.
The C<$ngx_addon_dir> variable can be used to represent the path
to the module directory.



=item *

C<ngx_module_incs> — Include paths required to build the module



=item *

C<ngx_module_deps> — Whitespace-separated list of the module's
dependencies.
Usually, it is the list of header files.



=item *

C<ngx_module_libs> — Whitespace-separated list of libraries to
link with the module.
For example, use C<ngx_module_libs=-lpthread> to link
C<libpthread> library.
The following macros can be used to link against the same libraries as
nginx:
C<LIBXSLT>, C<LIBGD>, C<GEOIP>,
C<PCRE>, C<OPENSSL>, C<MD5>,
C<SHA1>, C<ZLIB>, and C<PERL>.



=item *

C<ngx_module_link> — Variable set by the build system to
C<DYNAMIC> for a dynamic module or C<ADDON>
for a static module and used to determine different actions to perform
depending on linking type.



=item *

C<ngx_module_order> — Load order for the module;
useful for the C<HTTP_FILTER> and
C<HTTP_AUX_FILTER> module types.
The format for this option is a whitespace-separated list of modules.
All modules in the list following the current module's name end up after it in
the global list of modules, which sets up the order for modules initialization.
For filter modules later initialization means earlier execution.



The following modules are typically used as references.
The C<ngx_http_copy_filter_module> reads the data for other
filter modules and is placed near the bottom of the list so that it is one of
the first to be executed.
The C<ngx_http_write_filter_module> writes the data to the
client socket and is placed near the top of the list, and is the last to be
executed.





By default, filter modules are placed before the
C<ngx_http_copy_filter> in the module list so that the filter
handler is executed after the copy filter handler.
For other module types the default is the empty string.






=back



To compile a module into nginx statically, use the
C<--add-module=E<sol>pathE<sol>toE<sol>module> argument to the configure
script.
To compile a module for later dynamic loading into nginx, use the
C<--add-dynamic-module=E<sol>pathE<sol>toE<sol>module> argument.




=head2 Core Modules



Modules are the building blocks of nginx, and most of its functionality is
implemented as modules.
The module source file must contain a global variable of type
C<ngx_module_t>, which is defined as follows:

    
    struct ngx_module_s {
    
        /* private part is omitted */
    
        void                 *ctx;
        ngx_command_t        *commands;
        ngx_uint_t            type;
    
        ngx_int_t           (*init_master)(ngx_log_t *log);
    
        ngx_int_t           (*init_module)(ngx_cycle_t *cycle);
    
        ngx_int_t           (*init_process)(ngx_cycle_t *cycle);
        ngx_int_t           (*init_thread)(ngx_cycle_t *cycle);
        void                (*exit_thread)(ngx_cycle_t *cycle);
        void                (*exit_process)(ngx_cycle_t *cycle);
    
        void                (*exit_master)(ngx_cycle_t *cycle);
    
        /* stubs for future extensions are omitted */
    };


The omitted private part includes the module version and a signature and is
filled using the predefined macro C<NGX_MODULE_V1>.





Each module keeps its private data in the C<ctx> field,
recognizes the configuration directives, specified in the
C<commands> array, and can be invoked at certain stages of
nginx lifecycle.
The module lifecycle consists of the following events:


=over




=item *

Configuration directive handlers are called as they appear
in configuration files in the context of the master process.



=item *

After the configuration is parsed successfully, C<init_module>
handler is called in the context of the master process.
The C<init_module> handler is called in the master process each
time a configuration is loaded.



=item *

The master process creates one or more worker processes and the
C<init_process> handler is called in each of them.



=item *

When a worker process receives the shutdown or terminate command from the
master, it invokes the C<exit_process> handler.



=item *

The master process calls the C<exit_master> handler before
exiting.



=back



Because threads are used in nginx only as a supplementary IE<sol>O facility with its
own API, C<init_thread> and C<exit_thread>
handlers are not currently called.
There is also no C<init_master> handler, because it would be
unnecessary overhead.





The module C<type> defines exactly what is stored in the
C<ctx> field.
Its value is one of the following types:

=over



=item *
C<NGX_CORE_MODULE>

=item *
C<NGX_EVENT_MODULE>

=item *
C<NGX_HTTP_MODULE>

=item *
C<NGX_MAIL_MODULE>

=item *
C<NGX_STREAM_MODULE>

=back


The C<NGX_CORE_MODULE> is the most basic and thus the most
generic and most low-level type of module.
The other module types are implemented on top of it and provide a more
convenient way to deal with corresponding domains, like handling events or HTTP
requests.





The set of core modules includes C<ngx_core_module>,
C<ngx_errlog_module>, C<ngx_regex_module>,
C<ngx_thread_pool_module> and
C<ngx_openssl_module> modules.
The HTTP module, the stream module, the mail module and event modules are core
modules too.
The context of a core module is defined as:

    
    typedef struct {
        ngx_str_t             name;
        void               *(*create_conf)(ngx_cycle_t *cycle);
        char               *(*init_conf)(ngx_cycle_t *cycle, void *conf);
    } ngx_core_module_t;


where the C<name> is a module name string,
C<create_conf> and C<init_conf>
are pointers to functions that create and initialize module configuration
respectively.
For core modules, nginx calls C<create_conf> before parsing
a new configuration and C<init_conf> after all configuration
is parsed successfully.
The typical C<create_conf> function allocates memory for the
configuration and sets default values.





For example, a simplistic module called C<ngx_foo_module> might
look like this:

    
    /*
     * Copyright (C) Author.
     */
    
    
    #include <ngx_config.h>
    #include <ngx_core.h>
    
    
    typedef struct {
        ngx_flag_t  enable;
    } ngx_foo_conf_t;
    
    
    static void *ngx_foo_create_conf(ngx_cycle_t *cycle);
    static char *ngx_foo_init_conf(ngx_cycle_t *cycle, void *conf);
    
    static char *ngx_foo_enable(ngx_conf_t *cf, void *post, void *data);
    static ngx_conf_post_t  ngx_foo_enable_post = { ngx_foo_enable };
    
    
    static ngx_command_t  ngx_foo_commands[] = {
    
        { ngx_string("foo_enabled"),
          NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_FLAG,
          ngx_conf_set_flag_slot,
          0,
          offsetof(ngx_foo_conf_t, enable),
          &ngx_foo_enable_post },
    
          ngx_null_command
    };
    
    
    static ngx_core_module_t  ngx_foo_module_ctx = {
        ngx_string("foo"),
        ngx_foo_create_conf,
        ngx_foo_init_conf
    };
    
    
    ngx_module_t  ngx_foo_module = {
        NGX_MODULE_V1,
        &ngx_foo_module_ctx,                   /* module context */
        ngx_foo_commands,                      /* module directives */
        NGX_CORE_MODULE,                       /* module type */
        NULL,                                  /* init master */
        NULL,                                  /* init module */
        NULL,                                  /* init process */
        NULL,                                  /* init thread */
        NULL,                                  /* exit thread */
        NULL,                                  /* exit process */
        NULL,                                  /* exit master */
        NGX_MODULE_V1_PADDING
    };
    
    
    static void *
    ngx_foo_create_conf(ngx_cycle_t *cycle)
    {
        ngx_foo_conf_t  *fcf;
    
        fcf = ngx_pcalloc(cycle->pool, sizeof(ngx_foo_conf_t));
        if (fcf == NULL) {
            return NULL;
        }
    
        fcf->enable = NGX_CONF_UNSET;
    
        return fcf;
    }
    
    
    static char *
    ngx_foo_init_conf(ngx_cycle_t *cycle, void *conf)
    {
        ngx_foo_conf_t *fcf = conf;
    
        ngx_conf_init_value(fcf->enable, 0);
    
        return NGX_CONF_OK;
    }
    
    
    static char *
    ngx_foo_enable(ngx_conf_t *cf, void *post, void *data)
    {
        ngx_flag_t  *fp = data;
    
        if (*fp == 0) {
            return NGX_CONF_OK;
        }
    
        ngx_log_error(NGX_LOG_NOTICE, cf->log, 0, "Foo Module is enabled");
    
        return NGX_CONF_OK;
    }






=head2 Configuration Directives



The C<ngx_command_t> type defines a single configuration
directive.
Each module that supports configuration provides an array of such structures
that describe how to process arguments and what handlers to call:

    
    typedef struct ngx_command_s  ngx_command_t;
    
    struct ngx_command_s {
        ngx_str_t             name;
        ngx_uint_t            type;
        char               *(*set)(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
        ngx_uint_t            conf;
        ngx_uint_t            offset;
        void                 *post;
    };


Terminate the array with the special value C<ngx_null_command>.
The C<name> is the name of a directive as it appears
in the configuration file, for example "worker_processes" or "listen".
The C<type> is a bit-field of flags that specify the number of
arguments the directive takes, its type, and the context in which it appears.
The flags are:


=over




=item *

C<NGX_CONF_NOARGS> — Directive takes no arguments.



=item *

C<NGX_CONF_1MORE> — Directive takes one or more arguments.



=item *

C<NGX_CONF_2MORE> — Directive takes two or more arguments.



=item *

C<NGX_CONF_TAKE1>..C<NGX_CONF_TAKE7> —
Directive takes exactly the indicated number of arguments.



=item *

C<NGX_CONF_TAKE12>, C<NGX_CONF_TAKE13>,
C<NGX_CONF_TAKE23>, C<NGX_CONF_TAKE123>,
C<NGX_CONF_TAKE1234> — Directive may take different number of
arguments.
Options are limited to the given numbers.
For example, C<NGX_CONF_TAKE12> means it takes one or two
arguments.



=back



The flags for directive types are:


=over




=item *

C<NGX_CONF_BLOCK> — Directive is a block, that is, it can
contain other directives within its opening and closing braces, or even
implement its own parser to handle contents inside.



=item *

C<NGX_CONF_FLAG> — Directive takes a boolean value, either
C<on> or C<off>.



=back



A directive's context defines where it may appear in the configuration:


=over




=item *

C<NGX_MAIN_CONF> — In the top level context.



=item *

C<NGX_HTTP_MAIN_CONF> — In the C<http> block.



=item *

C<NGX_HTTP_SRV_CONF> — In a C<server> block
within the C<http> block.



=item *

C<NGX_HTTP_LOC_CONF> — In a C<location> block
within the C<http> block.



=item *

C<NGX_HTTP_UPS_CONF> — In an C<upstream> block
within the C<http> block.



=item *

C<NGX_HTTP_SIF_CONF> — In an C<if> block within
a C<server> block in the C<http> block.



=item *

C<NGX_HTTP_LIF_CONF> — In an C<if> block within
a C<location> block in the C<http> block.



=item *

C<NGX_HTTP_LMT_CONF> — In a C<limit_except>
block within the C<http> block.



=item *

C<NGX_STREAM_MAIN_CONF> — In the C<stream>
block.



=item *

C<NGX_STREAM_SRV_CONF> — In a C<server> block
within the C<stream> block.



=item *

C<NGX_STREAM_UPS_CONF> — In an C<upstream> block
within the C<stream> block.



=item *

C<NGX_MAIL_MAIN_CONF> — In the C<mail> block.



=item *

C<NGX_MAIL_SRV_CONF> — In a C<server> block
within the C<mail> block.



=item *

C<NGX_EVENT_CONF> — In the C<event> block.



=item *

C<NGX_DIRECT_CONF> — Used by modules that don't
create a hierarchy of contexts and only have one global configuration.
This configuration is passed to the handler as the C<conf>
argument.


=back



The configuration parser uses these flags to throw an error in case of
a misplaced directive and calls directive handlers supplied with a proper
configuration pointer, so that the same directives in different locations can
store their values in distinct places.





The C<set> field defines a handler that processes a directive
and stores parsed values into the corresponding configuration.
There's a number of functions that perform common conversions:


=over




=item *

C<ngx_conf_set_flag_slot> — Converts the literal strings
C<on> and C<off> into an
C<ngx_flag_t> value with values 1 or 0, respectively.



=item *

C<ngx_conf_set_str_slot> — Stores a string as a value of the
C<ngx_str_t> type.



=item *

C<ngx_conf_set_str_array_slot> — Appends a value to an array
C<ngx_array_t> of strings C<ngx_str_t>.
The array is created if does not already exist.



=item *

C<ngx_conf_set_keyval_slot> — Appends a key-value pair to an
array C<ngx_array_t> of key-value pairs
C<ngx_keyval_t>.
The first string becomes the key and the second the value.
The array is created if it does not already exist.



=item *

C<ngx_conf_set_num_slot> — Converts a directive's argument
to an C<ngx_int_t> value.



=item *

C<ngx_conf_set_size_slot> — Converts a
L<size|syntax> to a C<size_t> value
expressed in bytes.



=item *

C<ngx_conf_set_off_slot> — Converts an
L<offset|syntax> to an C<off_t> value
expressed in bytes.



=item *

C<ngx_conf_set_msec_slot> — Converts a
L<time|syntax> to an C<ngx_msec_t> value
expressed in milliseconds.



=item *

C<ngx_conf_set_sec_slot> — Converts a
L<time|syntax> to a C<time_t> value
expressed in in seconds.



=item *

C<ngx_conf_set_bufs_slot> — Converts the two supplied arguments
into an C<ngx_bufs_t> object that holds the number and
L<size|syntax> of buffers.



=item *

C<ngx_conf_set_enum_slot> — Converts the supplied argument
into an C<ngx_uint_t> value.
The null-terminated array of C<ngx_conf_enum_t> passed in the
C<post> field defines the acceptable strings and corresponding
integer values.



=item *

C<ngx_conf_set_bitmask_slot> — Converts the supplied arguments
into an C<ngx_uint_t> value.
The mask values for each argument are ORed producing the result.
The null-terminated array of C<ngx_conf_bitmask_t> passed in the
C<post> field defines the acceptable strings and corresponding
mask values.



=item *

C<set_path_slot> — Converts the supplied arguments to an
C<ngx_path_t> value and performs all required initializations.
For details, see the documentation for the
L<proxy_temp_path|ngx_http_proxy_module> directive.



=item *

C<set_access_slot> — Converts the supplied arguments to a file
permissions mask.
For details, see the documentation for the
L<proxy_store_access|ngx_http_proxy_module> directive.



=back








The C<conf> field defines which configuration structure is
passed to the directory handler.
Core modules only have the global configuration and set
C<NGX_DIRECT_CONF> flag to access it.
Modules like HTTP, Stream or Mail create hierarchies of configurations.
For example, a module's configuration is created for C<server>,
C<location> and C<if> scopes.


=over



=item *

C<NGX_HTTP_MAIN_CONF_OFFSET> — Configuration for the
C<http> block.



=item *

C<NGX_HTTP_SRV_CONF_OFFSET> — Configuration for a
C<server> block within the C<http> block.



=item *

C<NGX_HTTP_LOC_CONF_OFFSET> — Configuration for a
C<location> block within the C<http>.



=item *

C<NGX_STREAM_MAIN_CONF_OFFSET> — Configuration for the
C<stream> block.



=item *

C<NGX_STREAM_SRV_CONF_OFFSET> — Configuration for a
C<server> block within the C<stream> block.



=item *

C<NGX_MAIL_MAIN_CONF_OFFSET> — Configuration for the
C<mail> block.



=item *

C<NGX_MAIL_SRV_CONF_OFFSET> — Configuration for a
C<server> block within the C<mail> block.



=back








The C<offset> defines the offset of a field in a module
configuration structure that holds values for this particular directive.
The typical use is to employ the C<offsetof()> macro.





The C<post> field has two purposes: it may be used to define
a handler to be called after the main handler has completed, or to pass
additional data to the main handler.
In the first case, the C<ngx_conf_post_t> structure needs to
be initialized with a pointer to the handler, for example:

    
    static char *ngx_do_foo(ngx_conf_t *cf, void *post, void *data);
    static ngx_conf_post_t  ngx_foo_post = { ngx_do_foo };


The C<post> argument is the C<ngx_conf_post_t>
object itself, and the C<data> is a pointer to the value,
converted from arguments by the main handler with the appropriate type.




=head1 HTTP


=head2 Connection



Each HTTP client connection runs through the following stages:




=over




=item *

C<ngx_event_accept()> accepts a client TCP connection.
This handler is called in response to a read notification on a listen socket.
A new C<ngx_connection_t> object is created at this stage
to wrap the newly accepted client socket.
Each nginx listener provides a handler to pass the new connection object to.
For HTTP connections it's C<ngx_http_init_connection(c)>.



=item *

C<ngx_http_init_connection()> performs early initialization of
the HTTP connection.
At this stage an C<ngx_http_connection_t> object is created for
the connection and its reference is stored in the connection's
C<data> field.
Later it will be replaced by an HTTP request object.
A PROXY protocol parser and the SSL handshake are started at
this stage as well.



=item *

C<ngx_http_wait_request_handler()> read event handler
is called when data is available on the client socket.
At this stage an HTTP request object C<ngx_http_request_t> is
created and set to the connection's C<data> field.



=item *

C<ngx_http_process_request_line()> read event handler
reads client request line.
The handler is set by C<ngx_http_wait_request_handler()>.
The data is read into connection's C<buffer>.
The size of the buffer is initially set by the directive
L<ngx_http_core_module>.
The entire client header is supposed to fit in the buffer.
If the initial size is not sufficient, a bigger buffer is allocated,
with the capacity set by the C<large_client_header_buffers>
directive.



=item *

C<ngx_http_process_request_headers()> read event handler,
is set after C<ngx_http_process_request_line()> to read
the client request header.



=item *

C<ngx_http_core_run_phases()> is called when the request header
is completely read and parsed.
This function runs request phases from
C<NGX_HTTP_POST_READ_PHASE> to
C<NGX_HTTP_CONTENT_PHASE>.
The last phase is intended to generate a response and pass it along the filter
chain.
The response is not necessarily sent to the client at this phase.
It might remain buffered and be sent at the finalization stage.



=item *

C<ngx_http_finalize_request()> is usually called when the
request has generated all the output or produced an error.
In the latter case an appropriate error page is looked up and used as the
response.
If the response is not completely sent to the client by this point, an
HTTP writer C<ngx_http_writer()> is activated to finish
sending outstanding data.



=item *

C<ngx_http_finalize_connection()> is called when the complete
response has been sent to the client and the request can be destroyed.
If the client connection keepalive feature is enabled,
C<ngx_http_set_keepalive()> is called, which destroys the
current request and waits for the next request on the connection.
Otherwise, C<ngx_http_close_request()> destroys both the
request and the connection.



=back




=head2 Request



For each client HTTP request the C<ngx_http_request_t> object is
created.  Some of the fields of this object are:




=over




=item *




C<connection> — Pointer to a C<ngx_connection_t>
client connection object.
Several requests can reference the same connection object at the same time -
one main request and its subrequests.
After a request is deleted, a new request can be created on the same connection.





Note that for HTTP connections C<ngx_connection_t>'s
C<data> field points back to the request.
Such requests are called active, as opposed to the other requests tied to the
connection.
An active request is used to handle client connection events and is allowed to
output its response to the client.
Normally, each request becomes active at some point so that it can send its
output.






=item *




C<ctx> — Array of HTTP module contexts.
Each module of type C<NGX_HTTP_MODULE> can store any value
(normally, a pointer to a structure) in the request.
The value is stored in the C<ctx> array at the module's
C<ctx_index> position.
The following macros provide a convenient way to get and set request contexts:




=over




=item *

C<ngx_http_get_module_ctx(r, module)> — Returns
the C<module>'s context



=item *

C<ngx_http_set_ctx(r, c, module)> — Sets C<c>
as the C<module>'s context



=back






=item *

C<main_conf>, C<srv_conf>,
C<loc_conf> — Arrays of current request
configurations.
Configurations are stored at the module's C<ctx_index>
positions.



=item *

C<read_event_handler>, C<write_event_handler> -
Read and write event handlers for the request.
Normally, both the read and write event handlers for an HTTP connection
are set to C<ngx_http_request_handler()>.
This function calls the C<read_event_handler> and
C<write_event_handler> handlers for the currently
active request.



=item *

C<cache> — Request cache object for caching the
upstream response.



=item *

C<upstream> — Request upstream object for proxying.



=item *

C<pool> — Request pool.
The request object itself is allocated in this pool, which is destroyed when
the request is deleted.
For allocations that need to be available throughout the client connection's
lifetime, use C<ngx_connection_t>'s pool instead.



=item *

C<header_in> — Buffer into which the client HTTP request
header is read.



=item *

C<headers_in>, C<headers_out> — Input and
output HTTP headers objects.
Both objects contain the C<headers> field of type
C<ngx_list_t> for keeping the raw list of headers.
In addition to that, specific headers are available for getting and setting as
separate fields, for example C<content_length_n>,
C<status> etc.



=item *

C<request_body> — Client request body object.



=item *

C<start_sec>, C<start_msec> — Time point when
the request was created, used for tracking request duration.



=item *

C<method>, C<method_name> — Numeric and text
representation of the client HTTP request method.
Numeric values for methods are defined in
C<srcE<sol>httpE<sol>ngx_http_request.h> with the macros
C<NGX_HTTP_GET>, C<NGX_HTTP_HEAD>,
C<NGX_HTTP_POST>, etc.



=item *

C<http_protocol>  — Client HTTP protocol version in its
original text form (“HTTPE<sol>1.0”, “HTTPE<sol>1.1” etc).



=item *

C<http_version>  — Client HTTP protocol version in
numeric form  (C<NGX_HTTP_VERSION_10>,
C<NGX_HTTP_VERSION_11>, etc.).



=item *

C<http_major>, C<http_minor>  — Client HTTP
protocol version in numeric form split into major and minor parts.



=item *

C<request_line>, C<unparsed_uri> — Request line
and URI in the original client request.



=item *

C<uri>, C<args>, C<exten> —
URI, arguments and file extension for the current request.
The URI value here might differ from the original URI sent by the client due to
normalization.
Throughout request processing, these values can change as internal redirects
are performed.



=item *

C<main> — Pointer to a main request object.
This object is created to process a client HTTP request, as opposed to
subrequests, which are created to perform a specific subtask within the main
request.



=item *

C<parent> — Pointer to the parent request of a subrequest.



=item *

C<postponed> — List of output buffers and subrequests, in the
order in which they are sent and created.
The list is used by the postpone filter to provide consistent request output
when parts of it are created by subrequests.



=item *

C<post_subrequest> — Pointer to a handler with the context
to be called when a subrequest gets finalized.
Unused for main requests.



=item *




C<posted_requests> — List of requests to be started or
resumed, which is done by calling the request's
C<write_event_handler>.
Normally, this handler holds the request main function, which at first runs
request phases and then produces the output.





A request is usually posted by the
C<ngx_http_post_request(r, NULL)> call.
It is always posted to the main request C<posted_requests> list.
The function C<ngx_http_run_posted_requests(c)> runs all
requests that are posted in the main request of the passed
connection's active request.
All event handlers call C<ngx_http_run_posted_requests>,
which can lead to new posted requests.
Normally, it is called after invoking a request's read or write handler.






=item *

C<phase_handler> — Index of current request phase.



=item *

C<ncaptures>, C<captures>,
C<captures_data> — Regex captures produced
by the last regex match of the request.
A regex match can occur at a number of places during request processing:
map lookup, server lookup by SNI or HTTP Host, rewrite, proxy_redirect, etc.
Captures produced by a lookup are stored in the above mentioned fields.
The field C<ncaptures> holds the number of captures,
C<captures> holds captures boundaries and
C<captures_data> holds the string against which the regex was
matched and which is used to extract captures.
After each new regex match, request captures are reset to hold new values.



=item *

C<count> — Request reference counter.
The field only makes sense for the main request.
Increasing the counter is done by simple C<r-E<gt>main-E<gt>count++>.
To decrease the counter, call
C<ngx_http_finalize_request(r, rc)>.
Creating of a subrequest and running the request body read process both
increment the counter.



=item *

C<subrequests> — Current subrequest nesting level.
Each subrequest inherits its parent's nesting level, decreased by one.
An error is generated if the value reaches zero.
The value for the main request is defined by the
C<NGX_HTTP_MAX_SUBREQUESTS> constant.



=item *

C<uri_changes> — Number of URI changes remaining for
the request.
The total number of times a request can change its URI is limited by the
C<NGX_HTTP_MAX_URI_CHANGES> constant.
With each change the value is decremented until it reaches zero, at which time
an error is generated.
Rewrites and internal redirects to normal or named locations are considered URI
changes.



=item *

C<blocked> — Counter of blocks held on the request.
While this value is non-zero, the request cannot be terminated.
Currently, this value is increased by pending AIO operations (POSIX AIO and
thread operations) and active cache lock.



=item *

C<buffered> — Bitmask showing which modules have buffered the
output produced by the request.
A number of filters can buffer output; for example, sub_filter can buffer data
because of a partial string match, copy filter can buffer data because of the
lack of free output buffers etc.
As long as this value is non-zero, the request is not finalized
pending the flush.



=item *

C<header_only> — Flag indicating that the output does not
require a body.
For example, this flag is used by HTTP HEAD requests.



=item *



C<keepalive> — Flag indicating whether client connection
keepalive is supported.
The value is inferred from the HTTP version and the value of the
C<Connection> header.





=item *

C<header_sent> — Flag indicating that the output header
has already been sent by the request.



=item *

C<internal> — Flag indicating that the current request
is internal.
To enter the internal state, a request must pass through an internal
redirect or be a subrequest.
Internal requests are allowed to enter internal locations.



=item *

C<allow_ranges> — Flag indicating that a partial response
can be sent to the client, as requested by the HTTP Range header.



=item *

C<subrequest_ranges> — Flag indicating that a partial response
can be sent while a subrequest is being processed.



=item *

C<single_range> — Flag indicating that only a single continuous
range of output data can be sent to the client.
This flag is usually set when sending a stream of data, for example from a
proxied server, and the entire response is not available in one buffer.



=item *

C<main_filter_need_in_memory>,
C<filter_need_in_memory> — Flags
requesting that the output produced in memory buffers rather than files.
This is a signal to the copy filter to read data from file buffers even if
sendfile is enabled.
The difference between the two flags is the location of the filter modules that
set them.
Filters called before the postpone filter in the filter chain set
C<filter_need_in_memory>, requesting that only the current
request output come in memory buffers.
Filters called later in the filter chain set
C<main_filter_need_in_memory>, requesting that
both the main request and all subrequests read files in memory
while sending output.



=item *

C<filter_need_temporary> — Flag requesting that the request
output be produced in temporary buffers, but not in readonly memory buffers or
file buffers.
This is used by filters which may change output directly in the buffers where
it's sent.


=back




=head2 Configuration



Each HTTP module can have three types of configuration:




=over




=item *

Main configuration — Applies to the entire C<http> block.
Functions as global settings for a module.



=item *

Server configuration — Applies to a single C<server> block.
Functions as server-specific settings for a module.



=item *

Location configuration — Applies to a single C<location>,
C<if> or C<limit_except> block.
Functions as location-specific settings for a module.



=back





Configuration structures are created at the nginx configuration stage by
calling functions, which allocate the structures, initialize them
and merge them.
The following example shows how to create a simple location
configuration for a module.
The configuration has one setting, C<foo>, of type
unsigned integer.




    
    typedef struct {
        ngx_uint_t  foo;
    } ngx_http_foo_loc_conf_t;
    
    
    static ngx_http_module_t  ngx_http_foo_module_ctx = {
        NULL,                                  /* preconfiguration */
        NULL,                                  /* postconfiguration */
    
        NULL,                                  /* create main configuration */
        NULL,                                  /* init main configuration */
    
        NULL,                                  /* create server configuration */
        NULL,                                  /* merge server configuration */
    
        ngx_http_foo_create_loc_conf,          /* create location configuration */
        ngx_http_foo_merge_loc_conf            /* merge location configuration */
    };
    
    
    static void *
    ngx_http_foo_create_loc_conf(ngx_conf_t *cf)
    {
        ngx_http_foo_loc_conf_t  *conf;
    
        conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_foo_loc_conf_t));
        if (conf == NULL) {
            return NULL;
        }
    
        conf->foo = NGX_CONF_UNSET_UINT;
    
        return conf;
    }
    
    
    static char *
    ngx_http_foo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
    {
        ngx_http_foo_loc_conf_t *prev = parent;
        ngx_http_foo_loc_conf_t *conf = child;
    
        ngx_conf_merge_uint_value(conf->foo, prev->foo, 1);
    }





As seen in the example, the C<ngx_http_foo_create_loc_conf()>
function creates a new configuration structure, and
C<ngx_http_foo_merge_loc_conf()> merges a configuration with
configuration from a higher level.
In fact, server and location configuration do not exist only at the server and
location levels, but are also created for all levels above them.
Specifically, a server configuration is also created at the main level and
location configurations are created at the main, server, and location levels.
These configurations make it possible to specify server- and location-specific
settings at any level of an nginx configuration file.
Eventually configurations are merged down.
A number of macros like C<NGX_CONF_UNSET> and
C<NGX_CONF_UNSET_UINT> are provided
for indicating a missing setting and ignoring it while merging.
Standard nginx merge macros like C<ngx_conf_merge_value()> and
C<ngx_conf_merge_uint_value()> provide a convenient way to
merge a setting and set the default value if none of the configurations
provided an explicit value.
For complete list of macros for different types, see
C<srcE<sol>coreE<sol>ngx_conf_file.h>.





The following macros are available.
for accessing configuration for HTTP modules at configuration time.
They all take C<ngx_conf_t> reference as the first argument.




=over




=item *

C<ngx_http_conf_get_module_main_conf(cf, module)>



=item *

C<ngx_http_conf_get_module_srv_conf(cf, module)>



=item *

C<ngx_http_conf_get_module_loc_conf(cf, module)>



=back





The following example gets a pointer to a location configuration of
standard nginx core module
L<ngx_http_core_module|ngx_http_core_module>
and replaces the location content handler kept
in the C<handler> field of the structure.




    
    static ngx_int_t ngx_http_foo_handler(ngx_http_request_t *r);
    
    
    static ngx_command_t  ngx_http_foo_commands[] = {
    
        { ngx_string("foo"),
          NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
          ngx_http_foo,
          0,
          0,
          NULL },
    
          ngx_null_command
    };
    
    
    static char *
    ngx_http_foo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
    {
        ngx_http_core_loc_conf_t  *clcf;
    
        clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
        clcf->handler = ngx_http_bar_handler;
    
        return NGX_CONF_OK;
    }





The following macros are available for accessing configuration for HTTP
modules at runtime.




=over




=item *

C<ngx_http_get_module_main_conf(r, module)>



=item *

C<ngx_http_get_module_srv_conf(r, module)>



=item *

C<ngx_http_get_module_loc_conf(r, module)>



=back





These macros receive a reference to an HTTP request
C<ngx_http_request_t>.
The main configuration of a request never changes.
Server configuration can change from the default after
the virtual server for the request is chosen.
Location configuration selected for processing a request can change multiple
times as a result of a rewrite operation or internal redirect.
The following example shows how to access a module's HTTP configuration at
runtime.




    
    static ngx_int_t
    ngx_http_foo_handler(ngx_http_request_t *r)
    {
        ngx_http_foo_loc_conf_t  *flcf;
    
        flcf = ngx_http_get_module_loc_conf(r, ngx_http_foo_module);
    
        ...
    }




=head2 Phases



Each HTTP request passes through a sequence of phases.
In each phase a distinct type of processing is performed on the request.
Module-specific handlers can be registered in most phases,
and many standard nginx modules register their phase handlers as a way
to get called at a specific stage of request processing.
Phases are processed successively and the phase handlers are called
once the request reaches the phase.
Following is the list of nginx HTTP phases.




=over




=item *

C<NGX_HTTP_POST_READ_PHASE> — First phase.
The L<ngx_http_realip_module|ngx_http_realip_module>
registers its handler at this phase to enable
substitution of client addresses before any other module is invoked.



=item *

C<NGX_HTTP_SERVER_REWRITE_PHASE> — Phase where
rewrite directives defined in a C<server> block
(but outside a C<location> block) are processed.
The
L<ngx_http_rewrite_module|ngx_http_rewrite_module>
installs its handler at this phase.



=item *

C<NGX_HTTP_FIND_CONFIG_PHASE> — Special phase
where a location is chosen based on the request URI.
Before this phase, the default location for the relevant virtual server
is assigned to the request, and any module requesting a location configuration
receives the configuration for the default server location.
This phase assigns a new location to the request.
No additional handlers can be registered at this phase.



=item *

C<NGX_HTTP_REWRITE_PHASE> — Same as
C<NGX_HTTP_SERVER_REWRITE_PHASE>, but for
rewrite rules defined in the location, chosen in the previous phase.



=item *

C<NGX_HTTP_POST_REWRITE_PHASE> — Special phase
where the request is redirected to a new location if its URI changed
during a rewrite.
This is implemented by the request going through
the C<NGX_HTTP_FIND_CONFIG_PHASE> again.
No additional handlers can be registered at this phase.



=item *

C<NGX_HTTP_PREACCESS_PHASE> — A common phase for different
types of handlers, not associated with access control.
The standard nginx modules
L<ngx_http_limit_conn_module|ngx_http_limit_conn_module> and
L<ngx_http_limit_req_module|ngx_http_limit_req_module> register their handlers at this phase.



=item *

C<NGX_HTTP_ACCESS_PHASE> — Phase where it is verified
that the client is authorized to make the request.
Standard nginx modules such as
L<ngx_http_access_module|ngx_http_access_module> and
L<ngx_http_auth_basic_module|ngx_http_auth_basic_module> register their handlers at this phase.
By default the client must pass the authorization check of all handlers
registered at this phase for the request to continue to the next phase.
The L<ngx_http_core_module> directive,
can be used to permit processing to continue if any of the phase handlers
authorizes the client.



=item *

C<NGX_HTTP_POST_ACCESS_PHASE> — Special phase where the
L<satisfy any|ngx_http_core_module>
directive is processed.
If some access phase handlers denied access and none explicitly allowed it, the
request is finalized.
No additional handlers can be registered at this phase.



=item *

C<NGX_HTTP_PRECONTENT_PHASE> — Phase for handlers to be called
prior to generating content.
Standard modules such as
L<ngx_http_try_files_module|ngx_http_core_module> and
L<ngx_http_mirror_module|ngx_http_mirror_module>
register their handlers at this phase.



=item *

C<NGX_HTTP_CONTENT_PHASE> — Phase where the response
is normally generated.
Multiple nginx standard modules register their handlers at this phase,
including
L<ngx_http_index_module|ngx_http_index_module> or
C<ngx_http_static_module>.
They are called sequentially until one of them produces
the output.
It's also possible to set content handlers on a per-location basis.
If the
L<ngx_http_core_module|ngx_http_core_module>'s
location configuration has C<handler> set, it is
called as the content handler and the handlers installed at this phase
are ignored.



=item *

C<NGX_HTTP_LOG_PHASE> — Phase where request logging
is performed.
Currently, only the
L<ngx_http_log_module|ngx_http_log_module>
registers its handler
at this stage for access logging.
Log phase handlers are called at the very end of request processing, right
before freeing the request.



=back





Following is the example of a preaccess phase handler.




    
    static ngx_http_module_t  ngx_http_foo_module_ctx = {
        NULL,                                  /* preconfiguration */
        ngx_http_foo_init,                     /* postconfiguration */
    
        NULL,                                  /* create main configuration */
        NULL,                                  /* init main configuration */
    
        NULL,                                  /* create server configuration */
        NULL,                                  /* merge server configuration */
    
        NULL,                                  /* create location configuration */
        NULL                                   /* merge location configuration */
    };
    
    
    static ngx_int_t
    ngx_http_foo_handler(ngx_http_request_t *r)
    {
        ngx_table_elt_t  *ua;
    
        ua = r->headers_in.user_agent;
    
        if (ua == NULL) {
            return NGX_DECLINED;
        }
    
        /* reject requests with "User-Agent: foo" */
        if (ua->value.len == 3 && ngx_strncmp(ua->value.data, "foo", 3) == 0) {
            return NGX_HTTP_FORBIDDEN;
        }
    
        return NGX_DECLINED;
    }
    
    
    static ngx_int_t
    ngx_http_foo_init(ngx_conf_t *cf)
    {
        ngx_http_handler_pt        *h;
        ngx_http_core_main_conf_t  *cmcf;
    
        cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
    
        h = ngx_array_push(&cmcf->phases[NGX_HTTP_PREACCESS_PHASE].handlers);
        if (h == NULL) {
            return NGX_ERROR;
        }
    
        *h = ngx_http_foo_handler;
    
        return NGX_OK;
    }





Phase handlers are expected to return specific codes:




=over




=item *

C<NGX_OK> — Proceed to the next phase.



=item *

C<NGX_DECLINED> — Proceed to the next handler of the current
phase.
If the current handler is the last in the current phase,
move to the next phase.



=item *

C<NGX_AGAIN>, C<NGX_DONE> — Suspend
phase handling until some future event which can be
an asynchronous IE<sol>O operation or just a delay, for example.
It is assumed, that phase handling will be resumed later by calling
C<ngx_http_core_run_phases()>.



=item *

Any other value returned by the phase handler is treated as a request
finalization code, in particular, an HTTP response code.
The request is finalized with the code provided.



=back





For some phases, return codes are treated in a slightly different way.
At the content phase, any return code other that
C<NGX_DECLINED> is considered a finalization code.
Any return code from the location content handlers is considered a
finalization code.
At the access phase, in
L<satisfy any|ngx_http_core_module>
mode,
any return code other than C<NGX_OK>,
C<NGX_DECLINED>, C<NGX_AGAIN>,
C<NGX_DONE> is considered a denial.
If no subsequent access handlers allow or deny access with a different
code, the denial code will become the finalization code.




=head2 Variables


=head3 Accessing existing variables



Variables can be referenced by index (this is the most common method)
or name (see below).
The index is created at configuration stage, when a variable is added
to the configuration.
To obtain the variable index, use
C<ngx_http_get_variable_index()>:

    
    ngx_str_t  name;  /* ngx_string("foo") */
    ngx_int_t  index;
    
    index = ngx_http_get_variable_index(cf, &name);


Here, C<cf> is a pointer to nginx configuration and
C<name> points to a string containing the variable name.
The function returns C<NGX_ERROR> on error or a valid index
otherwise, which is typically stored somewhere in the module's
configuration for future use.





All HTTP variables are evaluated in the context of a given HTTP request,
and results are specific to and cached in that HTTP request.
All functions that evaluate variables return the
C<ngx_http_variable_value_t> type, representing
the variable value:

    
    typedef ngx_variable_value_t  ngx_http_variable_value_t;
    
    typedef struct {
        unsigned    len:28;
    
        unsigned    valid:1;
        unsigned    no_cacheable:1;
        unsigned    not_found:1;
        unsigned    escape:1;
    
        u_char     *data;
    } ngx_variable_value_t;


where:

=over




=item *

C<len> — The length of the value



=item *

C<data> — The value itself



=item *

C<valid> — The value is valid



=item *

C<not_found> — The variable was not found and thus
the C<data> and C<len> fields are irrelevant;
this can happen, for example, with variables like C<$arg_foo>
when a corresponding argument was not passed in a request



=item *

C<no_cacheable> — Do not cache result



=item *

C<escape> — Used internally by the logging module to mark
values that require escaping on output.



=back







The C<ngx_http_get_flushed_variable()>
and C<ngx_http_get_indexed_variable()> functions
are used to obtain the value of a variable.
They have the same interface - accepting an HTTP request C<r>
as a context for evaluating the variable and an C<index>
that identifies it.
An example of typical usage:

    
    ngx_http_variable_value_t  *v;
    
    v = ngx_http_get_flushed_variable(r, index);
    
    if (v == NULL || v->not_found) {
        /* we failed to get value or there is no such variable, handle it */
        return NGX_ERROR;
    }
    
    /* some meaningful value is found */


The difference between functions is that the
C<ngx_http_get_indexed_variable()> returns a cached value
and C<ngx_http_get_flushed_variable()> flushes the cache for
non-cacheable variables.





Some modules, such as SSI and Perl, need to deal with variables for which the
name is not known at configuration time.
An index therefore cannot be used to access them, but the
C<ngx_http_get_variable(r, name, key)> function
is available.
It searches for a variable with a given
C<name> and its hash C<key> derived
from the name.




=head3 Creating variables



To create a variable, use the C<ngx_http_add_variable()>
function.
It takes as arguments a configuration (where the variable is registered),
the variable name and flags that control the function's behaviour:


=over



=item *
C<NGX_HTTP_VAR_CHANGEABLE> — Enables redefinition of
the variable: there is no conflict if another module defines a variable with
the same name.
This allows the
L<ngx_http_rewrite_module> directive
to override variables.



=item *
C<NGX_HTTP_VAR_NOCACHEABLE> — Disables caching,
which is useful for variables such as C<$time_local>.



=item *
C<NGX_HTTP_VAR_NOHASH> — Indicates that
this variable is only accessible by index, not by name.
This is a small optimization for use when it is known that the
variable is not needed in modules like SSI or Perl.



=item *
C<NGX_HTTP_VAR_PREFIX> — The name of the
variable is a prefix.
In this case, a handler must implement additional logic to obtain the value
of a specific variable.
For example, all “C<arg_>” variables are processed by the
same handler, which performs lookup in request arguments and returns the value
of a specific argument.



=back



The function returns NULL in case of error or a pointer to
C<ngx_http_variable_t> otherwise:

    
    struct ngx_http_variable_s {
        ngx_str_t                     name;
        ngx_http_set_variable_pt      set_handler;
        ngx_http_get_variable_pt      get_handler;
        uintptr_t                     data;
        ngx_uint_t                    flags;
        ngx_uint_t                    index;
    };



The C<get> and C<set> handlers
are called to obtain or set the variable value,
C<data> is passed to variable handlers, and
C<index> holds assigned variable index used to reference
the variable.





Usually, a null-terminated static array of
C<ngx_http_variable_t> structures is created
by a module and processed at the preconfiguration stage to add variables
into the configuration, for example:

    
    static ngx_http_variable_t  ngx_http_foo_vars[] = {
    
        { ngx_string("foo_v1"), NULL, ngx_http_foo_v1_variable, 0, 0, 0 },
    
          ngx_http_null_variable
    };
    
    static ngx_int_t
    ngx_http_foo_add_variables(ngx_conf_t *cf)
    {
        ngx_http_variable_t  *var, *v;
    
        for (v = ngx_http_foo_vars; v->name.len; v++) {
            var = ngx_http_add_variable(cf, &v->name, v->flags);
            if (var == NULL) {
                return NGX_ERROR;
            }
    
            var->get_handler = v->get_handler;
            var->data = v->data;
        }
    
        return NGX_OK;
    }


This function in the example is used to initialize
the C<preconfiguration>
field of the HTTP module context and is called before the parsing of HTTP
configuration, so that the parser can refer to these variables.





The C<get> handler is responsible for evaluating a variable
in the context of a specific request, for example:

    
    static ngx_int_t
    ngx_http_variable_connection(ngx_http_request_t *r,
        ngx_http_variable_value_t *v, uintptr_t data)
    {
        u_char  *p;
    
        p = ngx_pnalloc(r->pool, NGX_ATOMIC_T_LEN);
        if (p == NULL) {
            return NGX_ERROR;
        }
    
        v->len = ngx_sprintf(p, "%uA", r->connection->number) - p;
        v->valid = 1;
        v->no_cacheable = 0;
        v->not_found = 0;
        v->data = p;
    
        return NGX_OK;
    }


It returns C<NGX_ERROR> in case of internal error
(for example, failed memory allocation) or C<NGX_OK> otherwise.
To learn the status of variable evaluation, inspect the flags
in C<ngx_http_variable_value_t> (see the description
above).





The C<set> handler allows setting the property
referenced by the variable.
For example, the set handler of the C<$limit_rate> variable
modifies the request's C<limit_rate> field:

    
    ...
    { ngx_string("limit_rate"), ngx_http_variable_request_set_size,
      ngx_http_variable_request_get_size,
      offsetof(ngx_http_request_t, limit_rate),
      NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 },
    ...
    
    static void
    ngx_http_variable_request_set_size(ngx_http_request_t *r,
        ngx_http_variable_value_t *v, uintptr_t data)
    {
        ssize_t    s, *sp;
        ngx_str_t  val;
    
        val.len = v->len;
        val.data = v->data;
    
        s = ngx_parse_size(&val);
    
        if (s == NGX_ERROR) {
            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                          "invalid size \"%V\"", &val);
            return;
        }
    
        sp = (ssize_t *) ((char *) r + data);
    
        *sp = s;
    
        return;
    }







=head2 Complex values



A complex value, despite its name, provides an easy way to evaluate
expressions which can contain text, variables, and their combination.





The complex value description in
C<ngx_http_compile_complex_value> is compiled at the
configuration stage into C<ngx_http_complex_value_t>
which is used at runtime to obtain results of expression evaluation.


    
    ngx_str_t                         *value;
    ngx_http_complex_value_t           cv;
    ngx_http_compile_complex_value_t   ccv;
    
    value = cf->args->elts; /* directive arguments */
    
    ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));
    
    ccv.cf = cf;
    ccv.value = &value[1];
    ccv.complex_value = &cv;
    ccv.zero = 1;
    ccv.conf_prefix = 1;
    
    if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {
        return NGX_CONF_ERROR;
    }



Here, C<ccv> holds all parameters that are required to
initialize the complex value C<cv>:


=over




=item *

C<cf> — Configuration pointer



=item *

C<value> — String to be parsed (input)



=item *

C<complex_value> — Compiled value (output)



=item *

C<zero> — Flag that enables zero-terminating value



=item *

C<conf_prefix> — Prefixes the result with the
configuration prefix (the directory where nginx is currently looking for
configuration)



=item *

C<root_prefix> — Prefixes the result with the root prefix
(the normal nginx installation prefix)



=back


The C<zero> flag is useful when results are to be passed to
libraries that require zero-terminated strings, and prefixes are handy when
dealing with filenames.





Upon successful compilation, C<cv.lengths>
contains information about the presence of variables
in the expression.
The NULL value means that the expression contained static text only,
and so can be stored in a simple string rather than as a complex value.





The C<ngx_http_set_complex_value_slot()> is a convenient
function used to initialize a complex value completely in the directive
declaration itself.





At runtime, a complex value can be calculated using the
C<ngx_http_complex_value()> function:

    
    ngx_str_t  res;
    
    if (ngx_http_complex_value(r, &cv, &res) != NGX_OK) {
        return NGX_ERROR;
    }


Given the request C<r> and previously compiled
value C<cv>, the function evaluates the
expression and writes the result to C<res>.




=head2 Request redirection



An HTTP request is always connected to a location via the
C<loc_conf> field of the C<ngx_http_request_t>
structure.
This means that at any point the location configuration of any module can be
retrieved from the request by calling
C<ngx_http_get_module_loc_conf(r, module)>.
Request location can change several times during the request's lifetime.
Initially, a default server location of the default server is assigned to a
request.
If the request switches to a different server (chosen by the HTTP
C<Host> header or SSL SNI extension), the request switches to the
default location of that server as well.
The next change of the location takes place at the
C<NGX_HTTP_FIND_CONFIG_PHASE> request phase.
At this phase a location is chosen by request URI among all non-named locations
configured for the server.
The
L<ngx_http_rewrite_module|ngx_http_rewrite_module>
can change the request URI at the
C<NGX_HTTP_REWRITE_PHASE> request phase as a result of
the L<rewrite|ngx_http_rewrite_module>
directive and send the request back
to the C<NGX_HTTP_FIND_CONFIG_PHASE> phase for selection of a
new location based on the new URI.





It is also possible to redirect a request to a new location at any point by
calling one of
C<ngx_http_internal_redirect(r, uri, args)> or
C<ngx_http_named_location(r, name)>.





The C<ngx_http_internal_redirect(r, uri, args)> function changes
the request URI and returns the request to the
C<NGX_HTTP_SERVER_REWRITE_PHASE> phase.
The request proceeds with a server default location.
Later at C<NGX_HTTP_FIND_CONFIG_PHASE> a new location is chosen
based on the new request URI.





The following example performs an internal redirect with the new request
arguments.




    
    ngx_int_t
    ngx_http_foo_redirect(ngx_http_request_t *r)
    {
        ngx_str_t  uri, args;
    
        ngx_str_set(&uri, "/foo");
        ngx_str_set(&args, "bar=1");
    
        return ngx_http_internal_redirect(r, &uri, &args);
    }





The function C<ngx_http_named_location(r, name)> redirects
a request to a named location.  The name of the location is passed as the
argument.
The location is looked up among all named locations of the current
server, after which the requests switches to the
C<NGX_HTTP_REWRITE_PHASE> phase.





The following example performs a redirect to a named location @foo.




    
    ngx_int_t
    ngx_http_foo_named_redirect(ngx_http_request_t *r)
    {
        ngx_str_t  name;
    
        ngx_str_set(&name, "foo");
    
        return ngx_http_named_location(r, &name);
    }





Both functions - C<ngx_http_internal_redirect(r, uri, args)>
and C<ngx_http_named_location(r, name)> can be called when
nginx modules have already stored some contexts in a request's
C<ctx> field.
It's possible for these contexts to become inconsistent with the new
location configuration.
To prevent inconsistency, all request contexts are
erased by both redirect functions.





Calling C<ngx_http_internal_redirect(r, uri, args)>
or C<ngx_http_named_location(r, name)> increases the request
C<count>.
For consistent request reference counting, call
C<ngx_http_finalize_request(r, NGX_DONE)> after redirecting the
request.
This will finalize current request code path and decrease the counter.





Redirected and rewritten requests become internal and can access the
L<internal|ngx_http_core_module>
locations.
Internal requests have the C<internal> flag set.




=head2 Subrequests



Subrequests are primarily used to insert output of one request into another,
possibly mixed with other data.
A subrequest looks like a normal request, but shares some data with its parent.
In particular, all fields related to client input are shared
because a subrequest does not receive any other input from the client.
The request field C<parent> for a subrequest contains a link
to its parent request and is NULL for the main request.
The field C<main> contains a link to the main request in
a group of requests.





A subrequest starts in the C<NGX_HTTP_SERVER_REWRITE_PHASE>
phase.
It passes through the same subsequent phases as a normal request and is
assigned a location based on its own URI.





The output header in a subrequest is always ignored.
The C<ngx_http_postpone_filter> places the subrequest's
output body in the right position relative to other data produced
by the parent request.





Subrequests are related to the concept of active requests.
A request C<r> is considered active if
C<c-E<gt>data == r>, where C<c> is the client
connection object.
At any given point, only the active request in a request group is allowed
to output its buffers to the client.
An inactive request can still send its output to the filter chain, but it
does not pass beyond the C<ngx_http_postpone_filter> and
remains buffered by that filter until the request becomes active.
Here are some rules of request activation:




=over




=item *

Initially, the main request is active.



=item *

The first subrequest of an active request becomes active right after creation.



=item *

The C<ngx_http_postpone_filter> activates the next request
in the active request's subrequest list, once all data prior to that request
are sent.



=item *

When a request is finalized, its parent is activated.



=back





Create a subrequest by calling the function
C<ngx_http_subrequest(r, uri, args, psr, ps, flags)>, where
C<r> is the parent request, C<uri> and
C<args> are the URI and arguments of the
subrequest, C<psr> is the output parameter, which receives the
newly created subrequest reference, C<ps> is a callback object
for notifying the parent request that the subrequest is being finalized, and
C<flags> is bitmask of flags.
The following flags are available:




=over




=item *

C<NGX_HTTP_SUBREQUEST_IN_MEMORY> - Output is not
sent to the client, but rather stored in memory.
The flag only affects subrequests which are processed by one of the proxying
modules.
After a subrequest is finalized its output is available in
C<r-E<gt>out> of type C<ngx_buf_t>.



=item *

C<NGX_HTTP_SUBREQUEST_WAITED> - The subrequest's
C<done> flag is set even if the subrequest is not active when
it is finalized.
This subrequest flag is used by the SSI filter.



=item *

C<NGX_HTTP_SUBREQUEST_CLONE> - The subrequest is created as a
clone of its parent.
It is started at the same location and proceeds from the same phase as the
parent request.



=back





The following example creates a subrequest with the URI
of C<E<sol>foo>.




    
    ngx_int_t            rc;
    ngx_str_t            uri;
    ngx_http_request_t  *sr;
    
    ...
    
    ngx_str_set(&uri, "/foo");
    
    rc = ngx_http_subrequest(r, &uri, NULL, &sr, NULL, 0);
    if (rc == NGX_ERROR) {
        /* error */
    }





This example clones the current request and sets a finalization callback for the
subrequest.




    
    ngx_int_t
    ngx_http_foo_clone(ngx_http_request_t *r)
    {
        ngx_http_request_t          *sr;
        ngx_http_post_subrequest_t  *ps;
    
        ps = ngx_palloc(r->pool, sizeof(ngx_http_post_subrequest_t));
        if (ps == NULL) {
            return NGX_ERROR;
        }
    
        ps->handler = ngx_http_foo_subrequest_done;
        ps->data = "foo";
    
        return ngx_http_subrequest(r, &r->uri, &r->args, &sr, ps,
                                   NGX_HTTP_SUBREQUEST_CLONE);
    }
    
    
    ngx_int_t
    ngx_http_foo_subrequest_done(ngx_http_request_t *r, void *data, ngx_int_t rc)
    {
        char  *msg = (char *) data;
    
        ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                      "done subrequest r:%p msg:%s rc:%i", r, msg, rc);
    
        return rc;
    }





Subrequests are normally created in a body filter, in which case their output
can be treated like the output from any explicit request.
This means that eventually the output of a subrequest is sent to the client,
after all explicit buffers that are passed before subrequest creation and
before any buffers that are passed after creation.
This ordering is preserved even for large hierarchies of subrequests.
The following example inserts output from a subrequest after all request data
buffers, but before the final buffer with the C<last_buf> flag.




    
    ngx_int_t
    ngx_http_foo_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
    {
        ngx_int_t                   rc;
        ngx_buf_t                  *b;
        ngx_uint_t                  last;
        ngx_chain_t                *cl, out;
        ngx_http_request_t         *sr;
        ngx_http_foo_filter_ctx_t  *ctx;
    
        ctx = ngx_http_get_module_ctx(r, ngx_http_foo_filter_module);
        if (ctx == NULL) {
            return ngx_http_next_body_filter(r, in);
        }
    
        last = 0;
    
        for (cl = in; cl; cl = cl->next) {
            if (cl->buf->last_buf) {
                cl->buf->last_buf = 0;
                cl->buf->last_in_chain = 1;
                cl->buf->sync = 1;
                last = 1;
            }
        }
    
        /* Output explicit output buffers */
    
        rc = ngx_http_next_body_filter(r, in);
    
        if (rc == NGX_ERROR || !last) {
            return rc;
        }
    
        /*
         * Create the subrequest.  The output of the subrequest
         * will automatically be sent after all preceding buffers,
         * but before the last_buf buffer passed later in this function.
         */
    
        if (ngx_http_subrequest(r, ctx->uri, NULL, &sr, NULL, 0) != NGX_OK) {
            return NGX_ERROR;
        }
    
        ngx_http_set_ctx(r, NULL, ngx_http_foo_filter_module);
    
        /* Output the final buffer with the last_buf flag */
    
        b = ngx_calloc_buf(r->pool);
        if (b == NULL) {
            return NGX_ERROR;
        }
    
        b->last_buf = 1;
    
        out.buf = b;
        out.next = NULL;
    
        return ngx_http_output_filter(r, &out);
    }





A subrequest can also be created for other purposes than data output.
For example, the L<ngx_http_auth_request_module|ngx_http_auth_request_module> module
creates a subrequest at the C<NGX_HTTP_ACCESS_PHASE> phase.
To disable output at this point, the
C<header_only> flag is set on the subrequest.
This prevents the subrequest body from being sent to the client.
Note that the subrequest's header is never sent to the client.
The result of the subrequest can be analyzed in the callback handler.




=head2 Request finalization



An HTTP request is finalized by calling the function
C<ngx_http_finalize_request(r, rc)>.
It is usually finalized by the content handler after all output buffers
are sent to the filter chain.
At this point all of the output might not be sent to the client,
with some of it remaining buffered somewhere along the filter chain.
If it is, the C<ngx_http_finalize_request(r, rc)> function
automatically installs a special handler C<ngx_http_writer(r)>
to finish sending the output.
A request is also finalized in case of an error or if a standard HTTP response
code needs to be returned to the client.





The function C<ngx_http_finalize_request(r, rc)> expects the
following C<rc> values:




=over




=item *

C<NGX_DONE> - Fast finalization.
Decrement the request C<count> and destroy the request if it
reaches zero.
The client connection can be used for more requests after the current request
is destroyed.



=item *

C<NGX_ERROR>, C<NGX_HTTP_REQUEST_TIME_OUT>
(C<408>), C<NGX_HTTP_CLIENT_CLOSED_REQUEST>
(C<499>) - Error finalization.
Terminate the request as soon as possible and close the client connection.



=item *

C<NGX_HTTP_CREATED> (C<201>),
C<NGX_HTTP_NO_CONTENT> (C<204>), codes greater
than or equal to C<NGX_HTTP_SPECIAL_RESPONSE>
(C<300>) - Special response finalization.
For these values nginx either sends to the client a default response page for
the code or performs the internal redirect to an
L<ngx_http_core_module> location if that
is configured for the code.



=item *

Other codes are considered successful finalization codes and might activate the
request writer to finish sending the response body.
Once the body is completely sent, the request C<count>
is decremented.
If it reaches zero, the request is destroyed, but the client connection can
still be used for other requests.
If C<count> is positive, there are unfinished activities
within the request, which will be finalized at a later point.



=back




=head2 Request body



For dealing with the body of a client request, nginx provides the
C<ngx_http_read_client_request_body(r, post_handler)> and
C<ngx_http_discard_request_body(r)> functions.
The first function reads the request body and makes it available via the
C<request_body> request field.
The second function instructs nginx to discard (read and ignore) the request
body.
One of these functions must be called for every request.
Normally, the content handler makes the call.





Reading or discarding the client request body from a subrequest is not allowed.
It must always be done in the main request.
When a subrequest is created, it inherits the parent's
C<request_body> object which can be used by the subrequest if
the main request has previously read the request body.





The function
C<ngx_http_read_client_request_body(r, post_handler)> starts
the process of reading the request body.
When the body is completely read, the C<post_handler> callback
is called to continue processing the request.
If the request body is missing or has already been read, the callback is called
immediately.
The function
C<ngx_http_read_client_request_body(r, post_handler)>
allocates the C<request_body> request field of type
C<ngx_http_request_body_t>.
The field C<bufs> of this object keeps the result as a buffer
chain.
The body can be saved in memory buffers or file buffers, if the capacity
specified by the
L<ngx_http_core_module>
directive is not enough to fit the entire body in memory.





The following example reads a client request body and returns its size.




    
    ngx_int_t
    ngx_http_foo_content_handler(ngx_http_request_t *r)
    {
        ngx_int_t  rc;
    
        rc = ngx_http_read_client_request_body(r, ngx_http_foo_init);
    
        if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
            /* error */
            return rc;
        }
    
        return NGX_DONE;
    }
    
    
    void
    ngx_http_foo_init(ngx_http_request_t *r)
    {
        off_t         len;
        ngx_buf_t    *b;
        ngx_int_t     rc;
        ngx_chain_t  *in, out;
    
        if (r->request_body == NULL) {
            ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
            return;
        }
    
        len = 0;
    
        for (in = r->request_body->bufs; in; in = in->next) {
            len += ngx_buf_size(in->buf);
        }
    
        b = ngx_create_temp_buf(r->pool, NGX_OFF_T_LEN);
        if (b == NULL) {
            ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
            return;
        }
    
        b->last = ngx_sprintf(b->pos, "%O", len);
        b->last_buf = (r == r->main) ? 1 : 0;
        b->last_in_chain = 1;
    
        r->headers_out.status = NGX_HTTP_OK;
        r->headers_out.content_length_n = b->last - b->pos;
    
        rc = ngx_http_send_header(r);
    
        if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
            ngx_http_finalize_request(r, rc);
            return;
        }
    
        out.buf = b;
        out.next = NULL;
    
        rc = ngx_http_output_filter(r, &out);
    
        ngx_http_finalize_request(r, rc);
    }





The following fields of the request determine how the request body is read:




=over




=item *

C<request_body_in_single_buf> - Read the body to a single memory
buffer.



=item *

C<request_body_in_file_only> - Always read the body to a file,
even if fits in the memory buffer.



=item *

C<request_body_in_persistent_file> - Do not unlink the file
immediately after creation.
A file with this flag can be moved to another directory.



=item *

C<request_body_in_clean_file> - Unlink the file when the
request is finalized.
This can be useful when a file was supposed to be moved to another directory
but was not moved for some reason.



=item *

C<request_body_file_group_access> - Enable group access to the
file by replacing the default 0600 access mask with 0660.



=item *

C<request_body_file_log_level> - Severity level at which to
log file errors.



=item *

C<request_body_no_buffering> - Read the request body without
buffering.



=back





The C<request_body_no_buffering> flag enables the
unbuffered mode of reading a request body.
In this mode, after calling
C<ngx_http_read_client_request_body()>, the
C<bufs> chain might keep only a part of the body.
To read the next part, call the
C<ngx_http_read_unbuffered_request_body(r)> function.
The return value C<NGX_AGAIN> and the request flag
C<reading_body> indicate that more data is available.
If C<bufs> is NULL after calling this function, there is
nothing to read at the moment.
The request callback C<read_event_handler> will be called when
the next part of request body is available.




=head2 Request body filters



After a request body part is read, it's passed to the request
body filter chain by calling the first body filter handler stored in
the C<ngx_http_top_request_body_filter> variable.
It's assumed that every body handler calls the next handler in the chain until
the final handler C<ngx_http_request_body_save_filter(r, cl)>
is called.
This handler collects the buffers in
C<r-E<gt>request_body-E<gt>bufs>
and writes them to a file if necessary.
The last request body buffer has nonzero C<last_buf> flag.





If a filter is planning to delay data buffers, it should set the flag
C<r-E<gt>request_body-E<gt>filter_need_buffering> to
C<1> when called for the first time.





Following is an example of a simple request body filter that delays request
body by one second.




    
    #include <ngx_config.h>
    #include <ngx_core.h>
    #include <ngx_http.h>
    
    
    #define NGX_HTTP_DELAY_BODY  1000
    
    
    typedef struct {
        ngx_event_t   event;
        ngx_chain_t  *out;
    } ngx_http_delay_body_ctx_t;
    
    
    static ngx_int_t ngx_http_delay_body_filter(ngx_http_request_t *r,
        ngx_chain_t *in);
    static void ngx_http_delay_body_cleanup(void *data);
    static void ngx_http_delay_body_event_handler(ngx_event_t *ev);
    static ngx_int_t ngx_http_delay_body_init(ngx_conf_t *cf);
    
    
    static ngx_http_module_t  ngx_http_delay_body_module_ctx = {
        NULL,                          /* preconfiguration */
        ngx_http_delay_body_init,      /* postconfiguration */
    
        NULL,                          /* create main configuration */
        NULL,                          /* init main configuration */
    
        NULL,                          /* create server configuration */
        NULL,                          /* merge server configuration */
    
        NULL,                          /* create location configuration */
        NULL                           /* merge location configuration */
    };
    
    
    ngx_module_t  ngx_http_delay_body_filter_module = {
        NGX_MODULE_V1,
        &ngx_http_delay_body_module_ctx, /* module context */
        NULL,                          /* module directives */
        NGX_HTTP_MODULE,               /* module type */
        NULL,                          /* init master */
        NULL,                          /* init module */
        NULL,                          /* init process */
        NULL,                          /* init thread */
        NULL,                          /* exit thread */
        NULL,                          /* exit process */
        NULL,                          /* exit master */
        NGX_MODULE_V1_PADDING
    };
    
    
    static ngx_http_request_body_filter_pt   ngx_http_next_request_body_filter;
    
    
    static ngx_int_t
    ngx_http_delay_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
    {
        ngx_int_t                   rc;
        ngx_chain_t                *cl, *ln;
        ngx_http_cleanup_t         *cln;
        ngx_http_delay_body_ctx_t  *ctx;
    
        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "delay request body filter");
    
        ctx = ngx_http_get_module_ctx(r, ngx_http_delay_body_filter_module);
    
        if (ctx == NULL) {
            ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_delay_body_ctx_t));
            if (ctx == NULL) {
                return NGX_HTTP_INTERNAL_SERVER_ERROR;
            }
    
            ngx_http_set_ctx(r, ctx, ngx_http_delay_body_filter_module);
    
            r->request_body->filter_need_buffering = 1;
        }
    
        if (ngx_chain_add_copy(r->pool, &ctx->out, in) != NGX_OK) {
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }
    
        if (!ctx->event.timedout) {
            if (!ctx->event.timer_set) {
    
                /* cleanup to remove the timer in case of abnormal termination */
    
                cln = ngx_http_cleanup_add(r, 0);
                if (cln == NULL) {
                    return NGX_HTTP_INTERNAL_SERVER_ERROR;
                }
    
                cln->handler = ngx_http_delay_body_cleanup;
                cln->data = ctx;
    
                /* add timer */
    
                ctx->event.handler = ngx_http_delay_body_event_handler;
                ctx->event.data = r;
                ctx->event.log = r->connection->log;
    
                ngx_add_timer(&ctx->event, NGX_HTTP_DELAY_BODY);
            }
    
            return ngx_http_next_request_body_filter(r, NULL);
        }
    
        rc = ngx_http_next_request_body_filter(r, ctx->out);
    
        for (cl = ctx->out; cl; /* void */) {
            ln = cl;
            cl = cl->next;
            ngx_free_chain(r->pool, ln);
        }
    
        ctx->out = NULL;
    
        return rc;
    }
    
    
    static void
    ngx_http_delay_body_cleanup(void *data)
    {
        ngx_http_delay_body_ctx_t *ctx = data;
    
        if (ctx->event.timer_set) {
            ngx_del_timer(&ctx->event);
        }
    }
    
    
    static void
    ngx_http_delay_body_event_handler(ngx_event_t *ev)
    {
        ngx_connection_t    *c;
        ngx_http_request_t  *r;
    
        r = ev->data;
        c = r->connection;
    
        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
                       "delay request body event");
    
        ngx_post_event(c->read, &ngx_posted_events);
    }
    
    
    static ngx_int_t
    ngx_http_delay_body_init(ngx_conf_t *cf)
    {
        ngx_http_next_request_body_filter = ngx_http_top_request_body_filter;
        ngx_http_top_request_body_filter = ngx_http_delay_body_filter;
    
        return NGX_OK;
    }




=head2 Response



In nginx an HTTP response is produced by sending the response header followed by
the optional response body.
Both header and body are passed through a chain of filters and eventually get
written to the client socket.
An nginx module can install its handler into the header or body filter chain
and process the output coming from the previous handler.





=head3 Response header



The C<ngx_http_send_header(r)>
function sends the output header.
Do not call this function until C<r-E<gt>headers_out>
contains all of the data  required to produce the HTTP response header.
The C<status> field in C<r-E<gt>headers_out>
must always be set.
If the response status indicates that a response body follows the header,
C<content_length_n> can be set as well.
The default value for this field is C<-1>,
which means that the body size is unknown.
In this case, chunked transfer encoding is used.
To output an arbitrary header, append the C<headers> list.




    
    static ngx_int_t
    ngx_http_foo_content_handler(ngx_http_request_t *r)
    {
        ngx_int_t         rc;
        ngx_table_elt_t  *h;
    
        /* send header */
    
        r->headers_out.status = NGX_HTTP_OK;
        r->headers_out.content_length_n = 3;
    
        /* X-Foo: foo */
    
        h = ngx_list_push(&r->headers_out.headers);
        if (h == NULL) {
            return NGX_ERROR;
        }
    
        h->hash = 1;
        ngx_str_set(&h->key, "X-Foo");
        ngx_str_set(&h->value, "foo");
    
        rc = ngx_http_send_header(r);
    
        if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
            return rc;
        }
    
        /* send body */
    
        ...
    }




=head3 Header filters



The C<ngx_http_send_header(r)> function invokes the header
filter chain by calling the first header filter handler stored in
the C<ngx_http_top_header_filter> variable.
It's assumed that every header handler calls the next handler in the chain
until the final handler C<ngx_http_header_filter(r)> is called.
The final header handler constructs the HTTP response based on
C<r-E<gt>headers_out> and passes it to the
C<ngx_http_writer_filter> for output.





To add a handler to the header filter chain, store its address in
the global variable C<ngx_http_top_header_filter>
at configuration time.
The previous handler address is normally stored in a static variable in a module
and is called by the newly added handler before exiting.





The following example of a header filter module adds the HTTP header
"C<X-Foo: foo>" to every response with status
C<200>.




    
    #include <ngx_config.h>
    #include <ngx_core.h>
    #include <ngx_http.h>
    
    
    static ngx_int_t ngx_http_foo_header_filter(ngx_http_request_t *r);
    static ngx_int_t ngx_http_foo_header_filter_init(ngx_conf_t *cf);
    
    
    static ngx_http_module_t  ngx_http_foo_header_filter_module_ctx = {
        NULL,                                   /* preconfiguration */
        ngx_http_foo_header_filter_init,        /* postconfiguration */
    
        NULL,                                   /* create main configuration */
        NULL,                                   /* init main configuration */
    
        NULL,                                   /* create server configuration */
        NULL,                                   /* merge server configuration */
    
        NULL,                                   /* create location configuration */
        NULL                                    /* merge location configuration */
    };
    
    
    ngx_module_t  ngx_http_foo_header_filter_module = {
        NGX_MODULE_V1,
        &ngx_http_foo_header_filter_module_ctx, /* module context */
        NULL,                                   /* module directives */
        NGX_HTTP_MODULE,                        /* module type */
        NULL,                                   /* init master */
        NULL,                                   /* init module */
        NULL,                                   /* init process */
        NULL,                                   /* init thread */
        NULL,                                   /* exit thread */
        NULL,                                   /* exit process */
        NULL,                                   /* exit master */
        NGX_MODULE_V1_PADDING
    };
    
    
    static ngx_http_output_header_filter_pt  ngx_http_next_header_filter;
    
    
    static ngx_int_t
    ngx_http_foo_header_filter(ngx_http_request_t *r)
    {
        ngx_table_elt_t  *h;
    
        /*
         * The filter handler adds "X-Foo: foo" header
         * to every HTTP 200 response
         */
    
        if (r->headers_out.status != NGX_HTTP_OK) {
            return ngx_http_next_header_filter(r);
        }
    
        h = ngx_list_push(&r->headers_out.headers);
        if (h == NULL) {
            return NGX_ERROR;
        }
    
        h->hash = 1;
        ngx_str_set(&h->key, "X-Foo");
        ngx_str_set(&h->value, "foo");
    
        return ngx_http_next_header_filter(r);
    }
    
    
    static ngx_int_t
    ngx_http_foo_header_filter_init(ngx_conf_t *cf)
    {
        ngx_http_next_header_filter = ngx_http_top_header_filter;
        ngx_http_top_header_filter = ngx_http_foo_header_filter;
    
        return NGX_OK;
    }




=head2 Response body



To send the response body, call the
C<ngx_http_output_filter(r, cl)> function.
The function can be called multiple times.
Each time, it sends a part of the response body in the form of a buffer chain.
Set the C<last_buf> flag in the last body buffer.





The following example produces a complete HTTP response with "foo" as its body.
For the example to work as subrequest as well as a main request,
the C<last_in_chain> flag is set in the last buffer
of the output.
The C<last_buf> flag is set only for the main request because
the last buffer for a subrequest does not end the entire output.




    
    static ngx_int_t
    ngx_http_bar_content_handler(ngx_http_request_t *r)
    {
        ngx_int_t     rc;
        ngx_buf_t    *b;
        ngx_chain_t   out;
    
        /* send header */
    
        r->headers_out.status = NGX_HTTP_OK;
        r->headers_out.content_length_n = 3;
    
        rc = ngx_http_send_header(r);
    
        if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
            return rc;
        }
    
        /* send body */
    
        b = ngx_calloc_buf(r->pool);
        if (b == NULL) {
            return NGX_ERROR;
        }
    
        b->last_buf = (r == r->main) ? 1 : 0;
        b->last_in_chain = 1;
    
        b->memory = 1;
    
        b->pos = (u_char *) "foo";
        b->last = b->pos + 3;
    
        out.buf = b;
        out.next = NULL;
    
        return ngx_http_output_filter(r, &out);
    }




=head2 Response body filters



The function C<ngx_http_output_filter(r, cl)> invokes the
body filter chain by calling the first body filter handler stored in
the C<ngx_http_top_body_filter> variable.
It's assumed that every body handler calls the next handler in the chain until
the final handler C<ngx_http_write_filter(r, cl)> is called.





A body filter handler receives a chain of buffers.
The handler is supposed to process the buffers and pass a possibly new chain to
the next handler.
It's worth noting that the chain links C<ngx_chain_t> of the
incoming chain belong to the caller, and must not be reused or changed.
Right after the handler completes, the caller can use its output chain links
to keep track of the buffers it has sent.
To save the buffer chain or to substitute some buffers before passing to the
next filter, a handler needs to allocate its own chain links.





Following is an example of a simple body filter that counts the number of
bytes in the body.
The result is available as the C<$counter> variable which can be
used in the access log.




    
    #include <ngx_config.h>
    #include <ngx_core.h>
    #include <ngx_http.h>
    
    
    typedef struct {
        off_t  count;
    } ngx_http_counter_filter_ctx_t;
    
    
    static ngx_int_t ngx_http_counter_body_filter(ngx_http_request_t *r,
        ngx_chain_t *in);
    static ngx_int_t ngx_http_counter_variable(ngx_http_request_t *r,
        ngx_http_variable_value_t *v, uintptr_t data);
    static ngx_int_t ngx_http_counter_add_variables(ngx_conf_t *cf);
    static ngx_int_t ngx_http_counter_filter_init(ngx_conf_t *cf);
    
    
    static ngx_http_module_t  ngx_http_counter_filter_module_ctx = {
        ngx_http_counter_add_variables,        /* preconfiguration */
        ngx_http_counter_filter_init,          /* postconfiguration */
    
        NULL,                                  /* create main configuration */
        NULL,                                  /* init main configuration */
    
        NULL,                                  /* create server configuration */
        NULL,                                  /* merge server configuration */
    
        NULL,                                  /* create location configuration */
        NULL                                   /* merge location configuration */
    };
    
    
    ngx_module_t  ngx_http_counter_filter_module = {
        NGX_MODULE_V1,
        &ngx_http_counter_filter_module_ctx,   /* module context */
        NULL,                                  /* module directives */
        NGX_HTTP_MODULE,                       /* module type */
        NULL,                                  /* init master */
        NULL,                                  /* init module */
        NULL,                                  /* init process */
        NULL,                                  /* init thread */
        NULL,                                  /* exit thread */
        NULL,                                  /* exit process */
        NULL,                                  /* exit master */
        NGX_MODULE_V1_PADDING
    };
    
    
    static ngx_http_output_body_filter_pt  ngx_http_next_body_filter;
    
    static ngx_str_t  ngx_http_counter_name = ngx_string("counter");
    
    
    static ngx_int_t
    ngx_http_counter_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
    {
        ngx_chain_t                    *cl;
        ngx_http_counter_filter_ctx_t  *ctx;
    
        ctx = ngx_http_get_module_ctx(r, ngx_http_counter_filter_module);
        if (ctx == NULL) {
            ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_counter_filter_ctx_t));
            if (ctx == NULL) {
                return NGX_ERROR;
            }
    
            ngx_http_set_ctx(r, ctx, ngx_http_counter_filter_module);
        }
    
        for (cl = in; cl; cl = cl->next) {
            ctx->count += ngx_buf_size(cl->buf);
        }
    
        return ngx_http_next_body_filter(r, in);
    }
    
    
    static ngx_int_t
    ngx_http_counter_variable(ngx_http_request_t *r, ngx_http_variable_value_t *v,
        uintptr_t data)
    {
        u_char                         *p;
        ngx_http_counter_filter_ctx_t  *ctx;
    
        ctx = ngx_http_get_module_ctx(r, ngx_http_counter_filter_module);
        if (ctx == NULL) {
            v->not_found = 1;
            return NGX_OK;
        }
    
        p = ngx_pnalloc(r->pool, NGX_OFF_T_LEN);
        if (p == NULL) {
            return NGX_ERROR;
        }
    
        v->data = p;
        v->len = ngx_sprintf(p, "%O", ctx->count) - p;
        v->valid = 1;
        v->no_cacheable = 0;
        v->not_found = 0;
    
        return NGX_OK;
    }
    
    
    static ngx_int_t
    ngx_http_counter_add_variables(ngx_conf_t *cf)
    {
        ngx_http_variable_t  *var;
    
        var = ngx_http_add_variable(cf, &ngx_http_counter_name, 0);
        if (var == NULL) {
            return NGX_ERROR;
        }
    
        var->get_handler = ngx_http_counter_variable;
    
        return NGX_OK;
    }
    
    
    static ngx_int_t
    ngx_http_counter_filter_init(ngx_conf_t *cf)
    {
        ngx_http_next_body_filter = ngx_http_top_body_filter;
        ngx_http_top_body_filter = ngx_http_counter_body_filter;
    
        return NGX_OK;
    }




=head2 Building filter modules



When writing a body or header filter, pay special attention to the filter's
position in the filter order.
There's a number of header and body filters registered by nginx standard
modules.
The nginx standard modules register a number of head and body filters and it's
important to register a new filter module in the right place with respect to
them.
Normally, modules register filters in their postconfiguration handlers.
The order in which filters are called during processing is obviously the
reverse of the order in which they are registered.





For third-party filter modules nginx provides a special slot
C<HTTP_AUX_FILTER_MODULES>.
To register a filter module in this slot, set
the C<ngx_module_type> variable to
C<HTTP_AUX_FILTER> in the module's configuration.





The following example shows a filter module config file assuming
for a module with just
one source file, C<ngx_http_foo_filter_module.c>.




    
    ngx_module_type=HTTP_AUX_FILTER
    ngx_module_name=ngx_http_foo_filter_module
    ngx_module_srcs="$ngx_addon_dir/ngx_http_foo_filter_module.c"
    
    . auto/module




=head2 Buffer reuse



When issuing or altering a stream of buffers, it's often desirable to reuse the
allocated buffers.
A standard and widely adopted approach in nginx code is to keep
two buffer chains for this purpose:
C<free> and C<busy>.
The C<free> chain keeps all free buffers,
which can be reused.
The C<busy> chain keeps all buffers sent by the current
module that are still in use by some other filter handler.
A buffer is considered in use if its size is greater than zero.
Normally, when a buffer is consumed by a filter, its C<pos>
(or C<file_pos> for a file buffer) is moved towards
C<last> (C<file_last> for a file buffer).
Once a buffer is completely consumed, it's ready to be reused.
To add newly freed buffers to the C<free> chain
it's enough to iterate over the C<busy> chain and move the zero
size buffers at the head of it to C<free>.
This operation is so common that there is a special function for it,
C<ngx_chain_update_chains(free, busy, out, tag)>.
The function appends the output chain C<out> to
C<busy> and moves free buffers from the top of
C<busy> to C<free>.
Only the buffers with the specified C<tag> are reused.
This lets a module reuse only the buffers that it allocated itself.





The following example is a body filter that inserts the string “foo” before each
incoming buffer.
The new buffers allocated by the module are reused if possible.
Note that for this example to work properly, setting up a
header filter
and resetting C<content_length_n> to C<-1>
is also required, but the relevant code is not provided here.




    
    typedef struct {
        ngx_chain_t  *free;
        ngx_chain_t  *busy;
    }  ngx_http_foo_filter_ctx_t;
    
    
    ngx_int_t
    ngx_http_foo_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
    {
        ngx_int_t                   rc;
        ngx_buf_t                  *b;
        ngx_chain_t                *cl, *tl, *out, **ll;
        ngx_http_foo_filter_ctx_t  *ctx;
    
        ctx = ngx_http_get_module_ctx(r, ngx_http_foo_filter_module);
        if (ctx == NULL) {
            ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_foo_filter_ctx_t));
            if (ctx == NULL) {
                return NGX_ERROR;
            }
    
            ngx_http_set_ctx(r, ctx, ngx_http_foo_filter_module);
        }
    
        /* create a new chain "out" from "in" with all the changes */
    
        ll = &out;
    
        for (cl = in; cl; cl = cl->next) {
    
            /* append "foo" in a reused buffer if possible */
    
            tl = ngx_chain_get_free_buf(r->pool, &ctx->free);
            if (tl == NULL) {
                return NGX_ERROR;
            }
    
            b = tl->buf;
            b->tag = (ngx_buf_tag_t) &ngx_http_foo_filter_module;
            b->memory = 1;
            b->pos = (u_char *) "foo";
            b->last = b->pos + 3;
    
            *ll = tl;
            ll = &tl->next;
    
            /* append the next incoming buffer */
    
            tl = ngx_alloc_chain_link(r->pool);
            if (tl == NULL) {
                return NGX_ERROR;
            }
    
            tl->buf = cl->buf;
            *ll = tl;
            ll = &tl->next;
        }
    
        *ll = NULL;
    
        /* send the new chain */
    
        rc = ngx_http_next_body_filter(r, out);
    
        /* update "busy" and "free" chains for reuse */
    
        ngx_chain_update_chains(r->pool, &ctx->free, &ctx->busy, &out,
                                (ngx_buf_tag_t) &ngx_http_foo_filter_module);
    
        return rc;
    }




=head2 Load balancing



The
L<ngx_http_upstream_module|ngx_http_upstream_module>
provides the basic functionality needed to pass requests to remote servers.
Modules that implement specific protocols, such as HTTP or FastCGI, use
this functionality.
The module also provides an interface for creating custom
load-balancing modules and implements a default round-robin method.





The L<ngx_http_upstream_module>
and L<ngx_http_upstream_module>
modules implement alternative load-balancing methods, but
are actually implemented as extensions of the upstream round-robin
module and share a lot of code with it, such as the representation
of a server group.
The L<ngx_http_upstream_module> module
is an independent module that extends upstream functionality.





The
L<ngx_http_upstream_module|ngx_http_upstream_module>
can be configured explicitly by placing the corresponding
L<ngx_http_upstream_module> block into
the configuration file, or implicitly by using directives
such as L<ngx_http_proxy_module>
that accept a URL that gets evaluated at some point into a list of servers.
The alternative load-balancing methods are available only with an explicit
upstream configuration.
The upstream module configuration has its own directive context
C<NGX_HTTP_UPS_CONF>.
The structure is defined as follows:

    
    struct ngx_http_upstream_srv_conf_s {
        ngx_http_upstream_peer_t         peer;
        void                           **srv_conf;
    
        ngx_array_t                     *servers;  /* ngx_http_upstream_server_t */
    
        ngx_uint_t                       flags;
        ngx_str_t                        host;
        u_char                          *file_name;
        ngx_uint_t                       line;
        in_port_t                        port;
        ngx_uint_t                       no_port;  /* unsigned no_port:1 */
    
    #if (NGX_HTTP_UPSTREAM_ZONE)
        ngx_shm_zone_t                  *shm_zone;
    #endif
    };




=over




=item *

C<srv_conf> — Configuration context of upstream modules.



=item *

C<servers> — Array of
C<ngx_http_upstream_server_t>, the result of parsing a set of
L<ngx_http_upstream_module> directives
in the C<upstream> block.



=item *

C<flags> — Flags that mostly mark which features
are supported by the load-balancing method.
The features are configured as parameters of
the L<ngx_http_upstream_module> directive:



=over




=item *

C<NGX_HTTP_UPSTREAM_CREATE> — Distinguishes explicitly
defined upstreams from those that are automatically created by the
L<ngx_http_proxy_module> directive
and “friends”
(FastCGI, SCGI, etc.)



=item *

C<NGX_HTTP_UPSTREAM_WEIGHT> — The “C<weight>”
parameter is supported



=item *

C<NGX_HTTP_UPSTREAM_MAX_FAILS> — The
“C<max_fails>” parameter is supported



=item *

C<NGX_HTTP_UPSTREAM_FAIL_TIMEOUT> —
The “C<fail_timeout>” parameter is supported



=item *

C<NGX_HTTP_UPSTREAM_DOWN> — The “C<down>”
parameter is supported



=item *

C<NGX_HTTP_UPSTREAM_BACKUP> — The “C<backup>”
parameter is supported



=item *

C<NGX_HTTP_UPSTREAM_MAX_CONNS> — The
“C<max_conns>” parameter is supported



=back






=item *

C<host> — Name of the upstream.



=item *

C<file_name, line> — Name of the configuration file
and the line where the C<upstream> block is located.



=item *

C<port> and C<no_port> — Not used for
explicitly defined upstream groups.



=item *

C<shm_zone> — Shared memory zone used by this upstream group,
if any.



=item *

C<peer> — object that holds generic methods for
initializing upstream configuration:


    
    typedef struct {
        ngx_http_upstream_init_pt        init_upstream;
        ngx_http_upstream_init_peer_pt   init;
        void                            *data;
    } ngx_http_upstream_peer_t;


A module that implements a load-balancing algorithm must set these
methods and initialize private C<data>.
If C<init_upstream> was not initialized during configuration
parsing, C<ngx_http_upstream_module> sets it to the default
C<ngx_http_upstream_init_round_robin> algorithm.


=over



=item *

C<init_upstream(cf, us)> — Configuration-time
method responsible for initializing a group of servers and
initializing the C<init()> method in case of success.
A typical load-balancing module uses a list of servers in the
C<upstream> block
to create an efficient data structure that it uses and saves its own
configuration to the C<data> field.



=item *

C<init(r, us)> — Initializes a per-request
C<ngx_http_upstream_peer_t.peer> structure that is used for
load balancing (not to be confused with the
C<ngx_http_upstream_srv_conf_t.peer> described above which
is per-upstream).
It is passed as the C<data> argument to all callbacks that
deal with server selection.


=back





=back







When nginx has to pass a request to another host for processing, it uses
the configured load-balancing method to obtain an address to connect to.
The method is obtained from the
C<ngx_http_upstream_t.peer> object
of type C<ngx_peer_connection_t>:

    
    struct ngx_peer_connection_s {
        ...
    
        struct sockaddr                 *sockaddr;
        socklen_t                        socklen;
        ngx_str_t                       *name;
    
        ngx_uint_t                       tries;
    
        ngx_event_get_peer_pt            get;
        ngx_event_free_peer_pt           free;
        ngx_event_notify_peer_pt         notify;
        void                            *data;
    
    #if (NGX_SSL || NGX_COMPAT)
        ngx_event_set_peer_session_pt    set_session;
        ngx_event_save_peer_session_pt   save_session;
    #endif
    
        ...
    };



The structure has the following fields:


=over



=item *

C<sockaddr>, C<socklen>,
C<name> — Address of the upstream server to connect to;
this is the output parameter of a load-balancing method.



=item *

C<data> — The per-request data of a load-balancing method;
keeps the state of the selection algorithm and usually includes the link
to the upstream configuration.
It is passed as an argument to all methods that deal with server selection
(see below).



=item *

C<tries> — Allowed
L<number|ngx_http_proxy_module>
of attempts to connect to an upstream server.



=item *

C<get>, C<free>, C<notify>,
C<set_session>, and C<save_session>
- Methods of the load-balancing module, described below.



=back








All methods accept at least two arguments: a peer connection object
C<pc> and the C<data> created by
C<ngx_http_upstream_srv_conf_t.peer.init()>.
Note that it might differ from C<pc.data> due
to “chaining” of load-balancing modules.







=over



=item *

C<get(pc, data)> — The method called when the upstream
module is ready to pass a request to an upstream server and needs to know
its address.
The method has to fill the C<sockaddr>,
C<socklen>, and C<name> fields of
C<ngx_peer_connection_t> structure.
The return is one of:


=over




=item *

C<NGX_OK> — Server was selected.



=item *

C<NGX_ERROR> — Internal error occurred.



=item *

C<NGX_BUSY> — no servers are currently available.
This can happen due to many reasons, including: the dynamic server group is
empty, all servers in the group are in the failed state, or
all servers in the group are already
handling the maximum number of connections.



=item *

C<NGX_DONE> — the underlying connection was reused and there
is no need to create a new connection to the upstream server.
This value is set by the C<keepalive> module.

=back






=item *

C<free(pc, data, state)> — The method called when an
upstream module has finished work with a particular server.
The C<state> argument is the completion status of the upstream
connection, a bitmask with the following possible values:


=over




=item *

C<NGX_PEER_FAILED> — Attempt was
L<unsuccessful|ngx_http_upstream_module>



=item *

C<NGX_PEER_NEXT> — A special case when upstream server
returns codes C<403> or C<404>,
which are not considered a
L<failure|ngx_http_upstream_module>.



=item *

C<NGX_PEER_KEEPALIVE> — Currently unused



=back



This method also decrements the C<tries> counter.




=item *

C<notify(pc, data, type)> — Currently unused
in the OSS version.



=item *

C<set_session(pc, data)> and
C<save_session(pc, data)>
— SSL-specific methods that enable caching sessions to upstream
servers.
The implementation is provided by the round-robin balancing method.



=back







=head1 Examples



The
L<nginx-dev-examples|https://github.com/nginx/nginx-dev-examples>
repository provides nginx module examples.





=head1 Code style


=head2 General rules




=over




=item *

maximum text width is 80 characters



=item *

indentation is 4 spaces



=item *

no tabs, no trailing spaces



=item *

list elements on the same line are separated with spaces



=item *

hexadecimal literals are lowercase



=item *

file names, function and type names, and global variables have the
C<ngx_> or more specific prefix such as
C<ngx_http_> and C<ngx_mail_>



=back




    
    size_t
    ngx_utf8_length(u_char *p, size_t n)
    {
        u_char  c, *last;
        size_t  len;
    
        last = p + n;
    
        for (len = 0; p < last; len++) {
    
            c = *p;
    
            if (c < 0x80) {
                p++;
                continue;
            }
    
            if (ngx_utf8_decode(&p, last - p) > 0x10ffff) {
                /* invalid UTF-8 */
                return n;
            }
        }
    
        return len;
    }







=head2 Files



A typical source file may contain the following sections separated by
two empty lines:


=over



=item *

copyright statements



=item *

includes



=item *

preprocessor definitions



=item *

type definitions



=item *

function prototypes



=item *

variable definitions



=item *

function definitions



=back







Copyright statements look like this:

    
    /*
     * Copyright (C) Author Name
     * Copyright (C) Organization, Inc.
     */


If the file is modified significantly, the list of authors should be updated,
the new author is added to the top.





The C<ngx_config.h> and C<ngx_core.h> files
are always included first, followed by one of
C<ngx_http.h>, C<ngx_stream.h>,
or C<ngx_mail.h>.
Then follow optional external header files:

    
    #include <ngx_config.h>
    #include <ngx_core.h>
    #include <ngx_http.h>
    
    #include <libxml/parser.h>
    #include <libxml/tree.h>
    #include <libxslt/xslt.h>
    
    #if (NGX_HAVE_EXSLT)
    #include <libexslt/exslt.h>
    #endif








Header files should include the so called "header protection":

    
    #ifndef _NGX_PROCESS_CYCLE_H_INCLUDED_
    #define _NGX_PROCESS_CYCLE_H_INCLUDED_
    ...
    #endif /* _NGX_PROCESS_CYCLE_H_INCLUDED_ */






=head2 Comments




=over




=item *

“C<E<sol>E<sol>>” comments are not used



=item *

text is written in English, American spelling is preferred



=item *

multi-line comments are formatted like this:

    
    /*
     * The red-black tree code is based on the algorithm described in
     * the "Introduction to Algorithms" by Cormen, Leiserson and Rivest.
     */



    
    /* find the server configuration for the address:port */





=back






=head2 Preprocessor



Macro names start from C<ngx_> or C<NGX_>
(or more specific) prefix.
Macro names for constants are uppercase.
Parameterized macros and macros for initializers are lowercase.
The macro name and value are separated by at least two spaces:

    
    #define NGX_CONF_BUFFER  4096
    
    #define ngx_buf_in_memory(b)  (b->temporary || b->memory || b->mmap)
    
    #define ngx_buf_size(b)                                                      \
        (ngx_buf_in_memory(b) ? (off_t) (b->last - b->pos):                      \
                                (b->file_last - b->file_pos))
    
    #define ngx_null_string  { 0, NULL }


Conditions are inside parentheses, negation is outside:

    
    #if (NGX_HAVE_KQUEUE)
    ...
    #elif ((NGX_HAVE_DEVPOLL && !(NGX_TEST_BUILD_DEVPOLL)) \
           || (NGX_HAVE_EVENTPORT && !(NGX_TEST_BUILD_EVENTPORT)))
    ...
    #elif (NGX_HAVE_EPOLL && !(NGX_TEST_BUILD_EPOLL))
    ...
    #elif (NGX_HAVE_POLL)
    ...
    #else /* select */
    ...
    #endif /* NGX_HAVE_KQUEUE */





=head2 Types



Type names end with the “C<_t>” suffix.
A defined type name is separated by at least two spaces:

    
    typedef ngx_uint_t  ngx_rbtree_key_t;







Structure types are defined using C<typedef>.
Inside structures, member types and names are aligned:

    
    typedef struct {
        size_t      len;
        u_char     *data;
    } ngx_str_t;


Keep alignment identical among different structures in the file.
A structure that points to itself has the name, ending with
“C<_s>”.
Adjacent structure definitions are separated with two empty lines:

    
    typedef struct ngx_list_part_s  ngx_list_part_t;
    
    struct ngx_list_part_s {
        void             *elts;
        ngx_uint_t        nelts;
        ngx_list_part_t  *next;
    };
    
    
    typedef struct {
        ngx_list_part_t  *last;
        ngx_list_part_t   part;
        size_t            size;
        ngx_uint_t        nalloc;
        ngx_pool_t       *pool;
    } ngx_list_t;


Each structure member is declared on its own line:

    
    typedef struct {
        ngx_uint_t        hash;
        ngx_str_t         key;
        ngx_str_t         value;
        u_char           *lowcase_key;
    } ngx_table_elt_t;







Function pointers inside structures have defined types ending
with “C<_pt>”:

    
    typedef ssize_t (*ngx_recv_pt)(ngx_connection_t *c, u_char *buf, size_t size);
    typedef ssize_t (*ngx_recv_chain_pt)(ngx_connection_t *c, ngx_chain_t *in,
        off_t limit);
    typedef ssize_t (*ngx_send_pt)(ngx_connection_t *c, u_char *buf, size_t size);
    typedef ngx_chain_t *(*ngx_send_chain_pt)(ngx_connection_t *c, ngx_chain_t *in,
        off_t limit);
    
    typedef struct {
        ngx_recv_pt        recv;
        ngx_recv_chain_pt  recv_chain;
        ngx_recv_pt        udp_recv;
        ngx_send_pt        send;
        ngx_send_pt        udp_send;
        ngx_send_chain_pt  udp_send_chain;
        ngx_send_chain_pt  send_chain;
        ngx_uint_t         flags;
    } ngx_os_io_t;







Enumerations have types ending with “C<_e>”:

    
    typedef enum {
        ngx_http_fastcgi_st_version = 0,
        ngx_http_fastcgi_st_type,
        ...
        ngx_http_fastcgi_st_padding
    } ngx_http_fastcgi_state_e;






=head2 Variables



Variables are declared sorted by length of a base type, then alphabetically.
Type names and variable names are aligned.
The type and name “columns” are separated with two spaces.
Large arrays are put at the end of a declaration block:

    
    u_char                      |  | *rv, *p;
    ngx_conf_t                  |  | *cf;
    ngx_uint_t                  |  |  i, j, k;
    unsigned int                |  |  len;
    struct sockaddr             |  | *sa;
    const unsigned char         |  | *data;
    ngx_peer_connection_t       |  | *pc;
    ngx_http_core_srv_conf_t    |  |**cscfp;
    ngx_http_upstream_srv_conf_t|  | *us, *uscf;
    u_char                      |  |  text[NGX_SOCKADDR_STRLEN];







Static and global variables may be initialized on declaration:

    
    static ngx_str_t  ngx_http_memcached_key = ngx_string("memcached_key");




    
    static ngx_uint_t  mday[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };




    
    static uint32_t  ngx_crc32_table16[] = {
        0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
        ...
        0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
    };







There is a bunch of commonly used typeE<sol>name combinations:

    
    u_char                        *rv;
    ngx_int_t                      rc;
    ngx_conf_t                    *cf;
    ngx_connection_t              *c;
    ngx_http_request_t            *r;
    ngx_peer_connection_t         *pc;
    ngx_http_upstream_srv_conf_t  *us, *uscf;





=head2 Functions



All functions (even static ones) should have prototypes.
Prototypes include argument names.
Long prototypes are wrapped with a single indentation on continuation lines:

    
    static char *ngx_http_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
    static ngx_int_t ngx_http_init_phases(ngx_conf_t *cf,
        ngx_http_core_main_conf_t *cmcf);
    
    static char *ngx_http_merge_servers(ngx_conf_t *cf,
        ngx_http_core_main_conf_t *cmcf, ngx_http_module_t *module,
        ngx_uint_t ctx_index);


The function name in a definition starts with a new line.
The function body opening and closing braces are on separate lines.
The body of a function is indented.
There are two empty lines between functions:

    
    static ngx_int_t
    ngx_http_find_virtual_server(ngx_http_request_t *r, u_char *host, size_t len)
    {
        ...
    }
    
    
    static ngx_int_t
    ngx_http_add_addresses(ngx_conf_t *cf, ngx_http_core_srv_conf_t *cscf,
        ngx_http_conf_port_t *port, ngx_http_listen_opt_t *lsopt)
    {
        ...
    }


There is no space after the function name and opening parenthesis.
Long function calls are wrapped such that continuation lines start
from the position of the first function argument.
If this is impossible, format the first continuation line such that it
ends at position 79:

    
    ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "http header: \"%V: %V\"",
                   &h->key, &h->value);
    
    hc->busy = ngx_palloc(r->connection->pool,
                      cscf->large_client_header_buffers.num * sizeof(ngx_buf_t *));


The C<ngx_inline> macro should be used instead of
C<inline>:

    
    static ngx_inline void ngx_cpuid(uint32_t i, uint32_t *buf);






=head2 Expressions



Binary operators except “C<.>” and “C<−E<gt>>”
should be separated from their operands by one space.
Unary operators and subscripts are not separated from their operands by spaces:

    
    width = width * 10 + (*fmt++ - '0');



    
    ch = (u_char) ((decoded << 4) + (ch - '0'));



    
    r->exten.data = &r->uri.data[i + 1];







Type casts are separated by one space from casted expressions.
An asterisk inside type cast is separated with space from type name:

    
    len = ngx_sock_ntop((struct sockaddr *) sin6, p, len, 1);







If an expression does not fit into single line, it is wrapped.
The preferred point to break a line is a binary operator.
The continuation line is lined up with the start of expression:

    
    if (status == NGX_HTTP_MOVED_PERMANENTLY
        || status == NGX_HTTP_MOVED_TEMPORARILY
        || status == NGX_HTTP_SEE_OTHER
        || status == NGX_HTTP_TEMPORARY_REDIRECT
        || status == NGX_HTTP_PERMANENT_REDIRECT)
    {
        ...
    }



    
    p->temp_file->warn = "an upstream response is buffered "
                         "to a temporary file";


As a last resort, it is possible to wrap an expression so that the
continuation line ends at position 79:

    
    hinit->hash = ngx_pcalloc(hinit->pool, sizeof(ngx_hash_wildcard_t)
                                         + size * sizeof(ngx_hash_elt_t *));


The above rules also apply to sub-expressions,
where each sub-expression has its own indentation level:

    
    if (((u->conf->cache_use_stale & NGX_HTTP_UPSTREAM_FT_UPDATING)
         || c->stale_updating) && !r->background
        && u->conf->cache_background_update)
    {
        ...
    }


Sometimes, it is convenient to wrap an expression after a cast.
In this case, the continuation line is indented:

    
    node = (ngx_rbtree_node_t *)
               ((u_char *) lr - offsetof(ngx_rbtree_node_t, color));







Pointers are explicitly compared to
C<NULL> (not C<0>):


    
    if (ptr != NULL) {
        ...
    }






=head2 Conditionals and Loops



The “C<if>” keyword is separated from the condition by
one space.
Opening brace is located on the same line, or on a
dedicated line if the condition takes several lines.
Closing brace is located on a dedicated line, optionally followed
by “C<else if> E<sol> C<else>”.
Usually, there is an empty line before the
“C<else if> E<sol> C<else>” part:

    
    if (node->left == sentinel) {
        temp = node->right;
        subst = node;
    
    } else if (node->right == sentinel) {
        temp = node->left;
        subst = node;
    
    } else {
        subst = ngx_rbtree_min(node->right, sentinel);
    
        if (subst->left != sentinel) {
            temp = subst->left;
    
        } else {
            temp = subst->right;
        }
    }







Similar formatting rules are applied to “C<do>”
and “C<while>” loops:

    
    while (p < last && *p == ' ') {
        p++;
    }




    
    do {
        ctx->node = rn;
        ctx = ctx->next;
    } while (ctx);







The “C<switch>” keyword is separated from the condition by
one space.
Opening brace is located on the same line.
Closing brace is located on a dedicated line.
The “C<case>” keywords are lined up with
“C<switch>”:

    
    switch (ch) {
    case '!':
        looked = 2;
        state = ssi_comment0_state;
        break;
    
    case '<':
        copy_end = p;
        break;
    
    default:
        copy_end = p;
        looked = 0;
        state = ssi_start_state;
        break;
    }







Most “C<for>” loops are formatted like this:

    
    for (i = 0; i < ccf->env.nelts; i++) {
        ...
    }



    
    for (q = ngx_queue_head(locations);
         q != ngx_queue_sentinel(locations);
         q = ngx_queue_next(q))
    {
        ...
    }


If some part of the “C<for>” statement is omitted,
this is indicated by the “C<E<sol>* void *E<sol>>” comment:

    
    for (i = 0; /* void */ ; i++) {
        ...
    }


A loop with an empty body is also indicated by the
“C<E<sol>* void *E<sol>>” comment which may be put on the same line:

    
    for (cl = *busy; cl->next; cl = cl->next) { /* void */ }


An endless loop looks like this:

    
    for ( ;; ) {
        ...
    }






=head2 Labels



Labels are surrounded with empty lines and are indented at the previous level:

    
        if (i == 0) {
            u->err = "host not found";
            goto failed;
        }
    
        u->addrs = ngx_pcalloc(pool, i * sizeof(ngx_addr_t));
        if (u->addrs == NULL) {
            goto failed;
        }
    
        u->naddrs = i;
    
        ...
    
        return NGX_OK;
    
    failed:
    
        freeaddrinfo(res);
        return NGX_ERROR;





=head1 Debugging memory issues



To debug memory issues such as buffer overruns or use-after-free errors, you
can use the L<AddressSanitizer|https://en.wikipedia.org/wiki/AddressSanitizer> (ASan) supported by some modern compilers.
To enable ASan with C<gcc> and C<clang>,
use the C<-fsanitize=address> compiler and linker option.
When building nginx, this can be done by adding the option to
C<--with-cc-opt> and C<--with-ld-opt>
parameters of the C<configure> script.





Since most allocations in nginx are made from nginx internal
pool, enabling ASan may not always be enough to debug
memory issues.
The internal pool allocates a big chunk of memory from the system and cuts
smaller allocations from it.
However, this mechanism can be disabled by setting the
C<NGX_DEBUG_PALLOC> macro to C<1>.
In this case, allocations are passed directly to the system allocator giving it
full control over the buffers boundaries.





The following configuration line summarizes the information provided above.
It is recommended while developing third-party modules and testing nginx on
different platforms.




    
    auto/configure --with-cc-opt='-fsanitize=address -DNGX_DEBUG_PALLOC=1'
                   --with-ld-opt=-fsanitize=address




=head1 Common Pitfalls


=head2 Writing a C module



The most common pitfall is an attempt to write a full-fledged C module
when it can be avoided.
In most cases your task can be accomplished by creating a proper configuration.
If writing a module is inevitable, try to make it
as small and simple as possible.
For example, a module can only export some
variables.





Before starting a module, consider the following questions:


=over




=item *

Is it possible to implement a desired feature using already
L<available modules|index>?



=item *

Is it possible to solve an issue using built-in scripting languages,
such as L<Perl|ngx_http_perl_module>
or L<njs|index>?



=back







=head2 C Strings



The most used string type in nginx,
ngx_str_t is not a C-Style
zero-terminated string.
You cannot pass the data to standard C library functions
such as C<strlen> or C<strstr>.
Instead, nginx counterparts
that accept either C<ngx_str_t> should be used
or pointer to data and a length.
However, there is a case when C<ngx_str_t> holds
a pointer to a zero-terminated string: strings that come as a result of
configuration file parsing are zero-terminated.




=head2 Global Variables



Avoid using global variables in your modules.
Most likely this is an error to have a global variable.
Any global data should be tied to a configuration cycle
and be allocated from the corresponding memory pool.
This allows nginx to perform graceful configuration reloads.
An attempt to use global variables will likely break this feature,
because it will be impossible to have two configurations at
the same time and get rid of them.
Sometimes global variables are required.
In this case, special attention is needed to manage reconfiguration
properly.
Also, check if libraries used by your code have implicit
global state that may be broken on reload.




=head2 Manual Memory Management



Instead of dealing with mallocE<sol>free approach which is error prone,
learn how to use nginx pools.
A pool is created and tied to an object -
configuration,
cycle,
connection,
or HTTP request.
When the object is destroyed, the associated pool is destroyed too.
So when working with an object, it is possible to allocate the amount
needed from the corresponding pool and don't care about freeing memory
even in case of errors.




=head2 Threads



It is recommended to avoid using threads in nginx because it will
definitely break things: most nginx functions are not thread-safe.
It is expected that a thread will be executing only system calls and
thread-safe library functions.
If you need to run some code that is not related to client request processing,
the proper way is to schedule a timer in the C<init_process>
module handler and perform required actions in timer handler.
Internally nginx makes use of threads to
boost IO-related operations, but this is a special case with a lot
of limitations.




=head2 Blocking Libraries



A common mistake is to use libraries that are blocking internally.
Most libraries out there are synchronous and blocking by nature.
In other words, they perform one operation at a time and waste
time waiting for response from other peer.
As a result, when a request is processed with such library, whole
nginx worker is blocked, thus destroying performance.
Use only libraries that provide asynchronous interface and don't
block whole process.




=head2 HTTP Requests to External Services



Often modules need to perform an HTTP call to some external service.
A common mistake is to use some external library, such as libcurl,
to perform the HTTP request.
It is absolutely unnecessary to bring a huge amount of external
(probably blocking!) code
for the task which can be accomplished by nginx itself.





There are two basic usage scenarios when an external request is needed:


=over




=item *

in the context of processing a client request (for example, in content handler)



=item *

in the context of a worker process (for example, timer handler)



=back








In the first case, the best is to use
subrequests API.
Instead of directly accessing external service, you declare a location
in nginx configuration and direct your subrequest to this location.
This location is not limited to
L<proxying|ngx_http_proxy_module>
requests, but may contain other nginx directives.
An example of such approach is the
L<ngx_http_auth_request_module>
directive implemented in
L<ngx_http_auth_request module|https://github.com/nginx/nginx/blob/master/src/http/modules/ngx_http_auth_request_module.c>.





For the second case, it is possible to use basic HTTP client functionality
available in nginx.
For example,
L<OCSP module|https://github.com/nginx/nginx/blob/master/src/event/ngx_event_openssl_stapling.c>
implements simple HTTP client.