Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
nginx
GitHub Repository: nginx/nginx.org
Path: blob/main/xml/en/docs/dev/development_guide.xml
1 views
1
<?xml version="1.0"?>
2
3
<!--
4
Copyright (C) Nginx, Inc.
5
-->
6
7
<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd">
8
9
<article name="Development guide"
10
link="/en/docs/dev/development_guide.html"
11
lang="en"
12
rev="13">
13
14
<section name="Introduction" id="introduction">
15
16
17
<section name="Code layout" id="code_layout">
18
19
<list type="bullet">
20
<listitem>
21
<literal>auto</literal> — Build scripts
22
</listitem>
23
24
<listitem>
25
<literal>src</literal>
26
27
<list type="bullet">
28
29
<listitem>
30
<literal>core</literal> — Basic types and functions — string, array, log,
31
pool, etc.
32
</listitem>
33
34
<listitem>
35
<literal>event</literal> — Event core
36
37
<list type="bullet">
38
39
<listitem>
40
<literal>modules</literal> — Event notification modules:
41
<literal>epoll</literal>, <literal>kqueue</literal>, <literal>select</literal>
42
etc.
43
</listitem>
44
45
</list>
46
47
</listitem>
48
49
<listitem>
50
<literal>http</literal> — Core HTTP module and common code
51
52
<list type="bullet">
53
54
<listitem>
55
<literal>modules</literal> — Other HTTP modules
56
</listitem>
57
58
<listitem>
59
<literal>v2</literal> — HTTP/2
60
</listitem>
61
62
</list>
63
64
</listitem>
65
66
<listitem>
67
<literal>mail</literal> — Mail modules
68
</listitem>
69
70
<listitem>
71
<literal>os</literal> — Platform-specific code
72
73
<list type="bullet">
74
75
<listitem>
76
<literal>unix</literal>
77
</listitem>
78
79
<listitem>
80
<literal>win32</literal>
81
</listitem>
82
83
</list>
84
85
</listitem>
86
87
<listitem>
88
<literal>stream</literal> — Stream modules
89
</listitem>
90
91
</list>
92
93
</listitem>
94
95
</list>
96
97
</section>
98
99
100
<section name="Include files" id="include_files">
101
102
<para>
103
The following two <literal>#include</literal> statements must appear at the
104
beginning of every nginx file:
105
</para>
106
107
<programlisting>
108
#include &lt;ngx_config.h>
109
#include &lt;ngx_core.h>
110
</programlisting>
111
112
<para>
113
In addition to that, HTTP code should include
114
</para>
115
116
117
<programlisting>
118
#include &lt;ngx_http.h>
119
</programlisting>
120
121
<para>
122
Mail code should include
123
</para>
124
125
126
<programlisting>
127
#include &lt;ngx_mail.h>
128
</programlisting>
129
130
<para>
131
Stream code should include
132
</para>
133
134
135
<programlisting>
136
#include &lt;ngx_stream.h>
137
</programlisting>
138
139
</section>
140
141
142
<section name="Integers" id="integers">
143
144
<para>
145
For general purposes, nginx code uses two integer types,
146
<literal>ngx_int_t</literal> and <literal>ngx_uint_t</literal>, which are
147
typedefs for <literal>intptr_t</literal> and <literal>uintptr_t</literal>
148
respectively.
149
</para>
150
151
</section>
152
153
154
<section name="Common return codes" id="common_return_codes">
155
156
<para>
157
Most functions in nginx return the following codes:
158
</para>
159
160
<list type="bullet">
161
162
<listitem>
163
<literal>NGX_OK</literal> — Operation succeeded.
164
</listitem>
165
166
<listitem>
167
<literal>NGX_ERROR</literal> — Operation failed.
168
</listitem>
169
170
<listitem>
171
<literal>NGX_AGAIN</literal> — Operation incomplete; call the function again.
172
</listitem>
173
174
<listitem>
175
<literal>NGX_DECLINED</literal> — Operation rejected, for example, because it is
176
disabled in the configuration. This is never an error.
177
</listitem>
178
179
<listitem>
180
<literal>NGX_BUSY</literal> — Resource is not available.
181
</listitem>
182
183
<listitem>
184
<literal>NGX_DONE</literal> — Operation complete or continued elsewhere.
185
Also used as an alternative success code.
186
</listitem>
187
188
<listitem>
189
<literal>NGX_ABORT</literal> — Function was aborted.
190
Also used as an alternative error code.
191
</listitem>
192
193
</list>
194
195
</section>
196
197
198
<section name="Error handling" id="error_handling">
199
200
<para>
201
The <literal>ngx_errno</literal> macro returns the last system error code.
202
It's mapped to <literal>errno</literal> on POSIX platforms and to
203
<literal>GetLastError()</literal> call in Windows.
204
The <literal>ngx_socket_errno</literal> macro returns the last socket error
205
number.
206
Like the <literal>ngx_errno</literal> macro, it's mapped to
207
<literal>errno</literal> on POSIX platforms.
208
It's mapped to the <literal>WSAGetLastError()</literal> call on Windows.
209
Accessing the values of <literal>ngx_errno</literal> or
210
<literal>ngx_socket_errno</literal> more than once in a row can cause
211
performance issues.
212
If the error value might be used multiple times, store it in a local variable
213
of type <literal>ngx_err_t</literal>.
214
To set errors, use the <literal>ngx_set_errno(errno)</literal> and
215
<literal>ngx_set_socket_errno(errno)</literal> macros.
216
</para>
217
218
<para>
219
The values of <literal>ngx_errno</literal> and
220
<literal>ngx_socket_errno</literal> can be passed to the logging functions
221
<literal>ngx_log_error()</literal> and <literal>ngx_log_debugX()</literal>, in
222
which case system error text is added to the log message.
223
</para>
224
225
<para>
226
Example using <literal>ngx_errno</literal>:
227
</para>
228
229
230
<programlisting>
231
ngx_int_t
232
ngx_my_kill(ngx_pid_t pid, ngx_log_t *log, int signo)
233
{
234
ngx_err_t err;
235
236
if (kill(pid, signo) == -1) {
237
err = ngx_errno;
238
239
ngx_log_error(NGX_LOG_ALERT, log, err, "kill(%P, %d) failed", pid, signo);
240
241
if (err == NGX_ESRCH) {
242
return 2;
243
}
244
245
return 1;
246
}
247
248
return 0;
249
}
250
</programlisting>
251
252
</section>
253
254
255
</section>
256
257
258
<section name="Strings" id="strings">
259
260
261
<section name="Overview" id="string_overview">
262
263
<para>
264
For C strings, nginx uses the unsigned character type pointer
265
<literal>u_char *</literal>.
266
</para>
267
268
<para>
269
The nginx string type <literal>ngx_str_t</literal> is defined as follows:
270
</para>
271
272
273
<programlisting>
274
typedef struct {
275
size_t len;
276
u_char *data;
277
} ngx_str_t;
278
</programlisting>
279
280
<para>
281
The <literal>len</literal> field holds the string length and
282
<literal>data</literal> holds the string data.
283
The string, held in <literal>ngx_str_t</literal>, may or may not be
284
null-terminated after the <literal>len</literal> bytes.
285
In most cases it’s not.
286
However, in certain parts of the code (for example, when parsing configuration),
287
<literal>ngx_str_t</literal> objects are known to be null-terminated, which
288
simplifies string comparison and makes it easier to pass the strings to
289
syscalls.
290
</para>
291
292
<para>
293
The string operations in nginx are declared in
294
<path>src/core/ngx_string.h</path>
295
Some of them are wrappers around standard C functions:
296
</para>
297
298
<para>
299
<list type="bullet">
300
301
<listitem>
302
<literal>ngx_strcmp()</literal>
303
</listitem>
304
305
<listitem>
306
<literal>ngx_strncmp()</literal>
307
</listitem>
308
309
<listitem>
310
<literal>ngx_strstr()</literal>
311
</listitem>
312
313
<listitem>
314
<literal>ngx_strlen()</literal>
315
</listitem>
316
317
<listitem>
318
<literal>ngx_strchr()</literal>
319
</listitem>
320
321
<listitem>
322
<literal>ngx_memcmp()</literal>
323
</listitem>
324
325
<listitem>
326
<literal>ngx_memset()</literal>
327
</listitem>
328
329
<listitem>
330
<literal>ngx_memcpy()</literal>
331
</listitem>
332
333
<listitem>
334
<literal>ngx_memmove()</literal>
335
</listitem>
336
337
</list>
338
339
</para>
340
341
<para>
342
Other string functions are nginx-specific
343
</para>
344
345
<para>
346
<list type="bullet">
347
348
<listitem>
349
<literal>ngx_memzero()</literal> — Fills memory with zeroes.
350
</listitem>
351
352
<listitem>
353
<literal>ngx_explicit_memzero()</literal> — Does the same as
354
<literal>ngx_memzero()</literal>, but this call is never removed by the
355
compiler's dead store elimination optimization.
356
This function can be used to clear sensitive data such as passwords and keys.
357
</listitem>
358
359
<listitem>
360
<literal>ngx_cpymem()</literal> — Does the same as
361
<literal>ngx_memcpy()</literal>, but returns the final destination address
362
This one is handy for appending multiple strings in a row.
363
</listitem>
364
365
<listitem>
366
<literal>ngx_movemem()</literal> — Does the same as
367
<literal>ngx_memmove()</literal>, but returns the final destination address.
368
</listitem>
369
370
<listitem>
371
<literal>ngx_strlchr()</literal> — Searches for a character in a string,
372
delimited by two pointers.
373
</listitem>
374
</list>
375
</para>
376
377
<para>
378
The following functions perform case conversion and comparison:
379
</para>
380
381
<para>
382
<list type="bullet">
383
384
<listitem>
385
<literal>ngx_tolower()</literal>
386
</listitem>
387
388
<listitem>
389
<literal>ngx_toupper()</literal>
390
</listitem>
391
392
<listitem>
393
<literal>ngx_strlow()</literal>
394
</listitem>
395
396
<listitem>
397
<literal>ngx_strcasecmp()</literal>
398
</listitem>
399
400
<listitem>
401
<literal>ngx_strncasecmp()</literal>
402
</listitem>
403
404
</list>
405
</para>
406
407
<para>
408
The following macros simplify string initialization:
409
</para>
410
411
<list type="bullet">
412
413
<listitem>
414
<literal>ngx_string(text)</literal> — static initializer for the
415
<literal>ngx_str_t</literal> type from the C string literal
416
<literal>text</literal>
417
</listitem>
418
419
<listitem>
420
<literal>ngx_null_string</literal> — static empty string initializer for the
421
<literal>ngx_str_t</literal> type
422
</listitem>
423
424
<listitem>
425
<literal>ngx_str_set(str, text)</literal> — initializes string
426
<literal>str</literal> of <literal>ngx_str_t *</literal> type with the C string
427
literal <literal>text</literal>
428
</listitem>
429
430
<listitem>
431
<literal>ngx_str_null(str)</literal> — initializes string <literal>str</literal>
432
of <literal>ngx_str_t *</literal> type with the empty string
433
</listitem>
434
435
</list>
436
437
</section>
438
439
440
<section name="Formatting" id="formatting">
441
442
<para>
443
The following formatting functions support nginx-specific types:
444
</para>
445
446
447
<para>
448
<list type="bullet">
449
450
<listitem>
451
<literal>ngx_sprintf(buf, fmt, ...)</literal>
452
</listitem>
453
454
<listitem>
455
<literal>ngx_snprintf(buf, max, fmt, ...)</literal>
456
</listitem>
457
458
<listitem>
459
<literal>ngx_slprintf(buf, last, fmt, ...)</literal>
460
</listitem>
461
462
<listitem>
463
<literal>ngx_vslprintf(buf, last, fmt, args)</literal>
464
</listitem>
465
466
<listitem>
467
<literal>ngx_vsnprintf(buf, max, fmt, args)</literal>
468
</listitem>
469
470
</list>
471
</para>
472
473
<para>
474
The full list of formatting options, supported by these functions is
475
in <path>src/core/ngx_string.c</path>. Some of them are:
476
</para>
477
478
479
<list type="bullet">
480
481
<listitem>
482
<literal>%O</literal> <literal>off_t</literal>
483
</listitem>
484
485
<listitem>
486
<literal>%T</literal> <literal>time_t</literal>
487
</listitem>
488
489
<listitem>
490
<literal>%z</literal> <literal>ssize_t</literal>
491
</listitem>
492
493
<listitem>
494
<literal>%i</literal> <literal>ngx_int_t</literal>
495
</listitem>
496
497
<listitem>
498
<literal>%p</literal> <literal>void *</literal>
499
</listitem>
500
501
<listitem>
502
<literal>%V</literal> <literal>ngx_str_t *</literal>
503
</listitem>
504
505
<listitem>
506
<literal>%s</literal> <literal>u_char *</literal> (null-terminated)
507
</listitem>
508
509
<listitem>
510
<literal>%*s</literal> <literal>size_t + u_char *</literal>
511
</listitem>
512
513
</list>
514
515
516
<para>
517
You can prepend <literal>u</literal> on most types to make them unsigned.
518
To convert output to hex, use <literal>X</literal> or <literal>x</literal>.
519
</para>
520
521
<para>
522
For example:
523
524
<programlisting>
525
u_char buf[NGX_INT_T_LEN];
526
size_t len;
527
ngx_uint_t n;
528
529
/* set n here */
530
531
len = ngx_sprintf(buf, "%ui", n) — buf;
532
</programlisting>
533
534
</para>
535
536
</section>
537
538
539
<section name="Numeric conversion" id="numeric_conversion">
540
541
<para>
542
Several functions for numeric conversion are implemented in nginx.
543
The first four each convert a string of given length to a positive integer of
544
the indicated type.
545
They return <literal>NGX_ERROR</literal> on error.
546
547
<list type="bullet">
548
549
<listitem>
550
<literal>ngx_atoi(line, n)</literal> <literal>ngx_int_t</literal>
551
</listitem>
552
553
<listitem>
554
<literal>ngx_atosz(line, n)</literal> <literal>ssize_t</literal>
555
</listitem>
556
557
<listitem>
558
<literal>ngx_atoof(line, n)</literal> <literal>off_t</literal>
559
</listitem>
560
561
<listitem>
562
<literal>ngx_atotm(line, n)</literal> <literal>time_t</literal>
563
</listitem>
564
565
</list>
566
</para>
567
568
<para>
569
There are two additional numeric conversion functions.
570
Like the first four, they return <literal>NGX_ERROR</literal> on error.
571
572
<list type="bullet">
573
574
<listitem>
575
<literal>ngx_atofp(line, n, point)</literal> — Converts a fixed point floating
576
number of given length to a positive integer of type
577
<literal>ngx_int_t</literal>.
578
The result is shifted left by <literal>point</literal> decimal
579
positions.
580
The string representation of the number is expected to have no more
581
than <literal>points</literal> fractional digits.
582
For example, <literal>ngx_atofp("10.5", 4, 2)</literal> returns
583
<literal>1050</literal>.
584
</listitem>
585
586
<listitem>
587
<literal>ngx_hextoi(line, n)</literal> — Converts a hexadecimal representation
588
of a positive integer to <literal>ngx_int_t</literal>.
589
</listitem>
590
591
</list>
592
</para>
593
594
</section>
595
596
<section name="Regular expressions" id="regex">
597
598
<para>
599
The regular expressions interface in nginx is a wrapper around
600
the <link url="http://www.pcre.org">PCRE</link>
601
library.
602
The corresponding header file is <path>src/core/ngx_regex.h</path>.
603
</para>
604
605
<para>
606
To use a regular expression for string matching, it first needs to be
607
compiled, which is usually done at the configuration phase.
608
Note that since PCRE support is optional, all code using the interface must
609
be protected by the surrounding <literal>NGX_PCRE</literal> macro:
610
611
<programlisting>
612
#if (NGX_PCRE)
613
ngx_regex_t *re;
614
ngx_regex_compile_t rc;
615
616
u_char errstr[NGX_MAX_CONF_ERRSTR];
617
618
ngx_str_t value = ngx_string("message (\\d\\d\\d).*Codeword is '(?&lt;cw&gt;\\w+)'");
619
620
ngx_memzero(&amp;rc, sizeof(ngx_regex_compile_t));
621
622
rc.pattern = value;
623
rc.pool = cf->pool;
624
rc.err.len = NGX_MAX_CONF_ERRSTR;
625
rc.err.data = errstr;
626
/* rc.options can be set to NGX_REGEX_CASELESS */
627
628
if (ngx_regex_compile(&amp;rc) != NGX_OK) {
629
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V", &amp;rc.err);
630
return NGX_CONF_ERROR;
631
}
632
633
re = rc.regex;
634
#endif
635
</programlisting>
636
After successful compilation, the <literal>captures</literal> and
637
<literal>named_captures</literal> fields in the
638
<literal>ngx_regex_compile_t</literal> structure contain the count of all
639
captures and named captures, respectively, found in the regular expression.
640
</para>
641
642
<para>
643
The compiled regular expression can then be used for matching against strings:
644
<programlisting>
645
ngx_int_t n;
646
int captures[(1 + rc.captures) * 3];
647
648
ngx_str_t input = ngx_string("This is message 123. Codeword is 'foobar'.");
649
650
n = ngx_regex_exec(re, &amp;input, captures, (1 + rc.captures) * 3);
651
if (n >= 0) {
652
/* string matches expression */
653
654
} else if (n == NGX_REGEX_NO_MATCHED) {
655
/* no match was found */
656
657
} else {
658
/* some error */
659
ngx_log_error(NGX_LOG_ALERT, log, 0, ngx_regex_exec_n " failed: %i", n);
660
}
661
</programlisting>
662
The arguments to <literal>ngx_regex_exec()</literal> are the compiled regular
663
expression <literal>re</literal>, the string to match <literal>input</literal>,
664
an optional array of integers to hold any <literal>captures</literal> that are
665
found, and the array's <literal>size</literal>.
666
The size of the <literal>captures</literal> array must be a multiple of three,
667
as required by the
668
<link url="http://www.pcre.org/original/doc/html/pcreapi.html">PCRE API</link>.
669
In the example, the size is calculated from the total number of captures plus
670
one for the matched string itself.
671
</para>
672
673
<para>
674
If there are matches, captures can be accessed as follows:
675
<programlisting>
676
u_char *p;
677
size_t size;
678
ngx_str_t name, value;
679
680
/* all captures */
681
for (i = 0; i &lt; n * 2; i += 2) {
682
value.data = input.data + captures[i];
683
value.len = captures[i + 1] — captures[i];
684
}
685
686
/* accessing named captures */
687
688
size = rc.name_size;
689
p = rc.names;
690
691
for (i = 0; i &lt; rc.named_captures; i++, p += size) {
692
693
/* capture name */
694
name.data = &amp;p[2];
695
name.len = ngx_strlen(name.data);
696
697
n = 2 * ((p[0] &lt;&lt; 8) + p[1]);
698
699
/* captured value */
700
value.data = &amp;input.data[captures[n]];
701
value.len = captures[n + 1] — captures[n];
702
}
703
</programlisting>
704
</para>
705
706
<para>
707
The <literal>ngx_regex_exec_array()</literal> function accepts the array of
708
<literal>ngx_regex_elt_t</literal> elements (which are just compiled regular
709
expressions with associated names), a string to match, and a log.
710
The function applies expressions from the array to the string until
711
either a match is found or no more expressions are left.
712
The return value is <literal>NGX_OK</literal> when there is a match and
713
<literal>NGX_DECLINED</literal> otherwise, or <literal>NGX_ERROR</literal>
714
in case of error.
715
</para>
716
717
</section>
718
719
</section>
720
721
722
<section name="Time" id="time">
723
724
<para>
725
The <literal>ngx_time_t</literal> structure represents time with three separate
726
types for seconds, milliseconds, and the GMT offset:
727
<programlisting>
728
typedef struct {
729
time_t sec;
730
ngx_uint_t msec;
731
ngx_int_t gmtoff;
732
} ngx_time_t;
733
</programlisting>
734
The <literal>ngx_tm_t</literal> structure is an alias for
735
<literal>struct tm</literal> on UNIX platforms and <literal>SYSTEMTIME</literal>
736
on Windows.
737
</para>
738
739
<para>
740
To obtain the current time, it is usually sufficient to access one of the
741
available global variables, representing the cached time value in the desired
742
format.
743
</para>
744
745
<para>
746
The available string representations are:
747
748
<list type="bullet">
749
750
<listitem>
751
<literal>ngx_cached_err_log_time</literal> — Used in error log entries:
752
<literal>"1970/09/28 12:00:00"</literal>
753
</listitem>
754
755
<listitem>
756
<literal>ngx_cached_http_log_time</literal> — Used in HTTP access log entries:
757
<literal>"28/Sep/1970:12:00:00 +0600"</literal>
758
</listitem>
759
760
<listitem>
761
<literal>ngx_cached_syslog_time</literal> — Used in syslog entries:
762
<literal>"Sep 28 12:00:00"</literal>
763
</listitem>
764
765
<listitem>
766
<literal>ngx_cached_http_time</literal> — Used in HTTP headers:
767
<literal>"Mon, 28 Sep 1970 06:00:00 GMT"</literal>
768
</listitem>
769
770
<listitem>
771
<literal>ngx_cached_http_log_iso8601</literal> — The ISO 8601
772
standard format:
773
<literal>"1970-09-28T12:00:00+06:00"</literal>
774
</listitem>
775
776
</list>
777
</para>
778
779
<para>
780
The <literal>ngx_time()</literal> and <literal>ngx_timeofday()</literal> macros
781
return the current time value in seconds and are the preferred way to access
782
the cached time value.
783
</para>
784
785
<para>
786
To obtain the time explicitly, use <literal>ngx_gettimeofday()</literal>,
787
which updates its argument (pointer to
788
<literal>struct timeval</literal>).
789
The time is always updated when nginx returns to the event loop from system
790
calls.
791
To update the time immediately, call <literal>ngx_time_update()</literal>,
792
or <literal>ngx_time_sigsafe_update()</literal> if updating the time in the
793
signal handler context.
794
</para>
795
796
<para>
797
The following functions convert <literal>time_t</literal> into the indicated
798
broken-down time representation.
799
The first function in each pair converts <literal>time_t</literal> to
800
<literal>ngx_tm_t</literal> and the second (with the <literal>_libc_</literal>
801
infix) to <literal>struct tm</literal>:
802
803
<list type="bullet">
804
805
<listitem>
806
<literal>ngx_gmtime(), ngx_libc_gmtime()</literal> — Time expressed as UTC
807
</listitem>
808
809
<listitem>
810
<literal>ngx_localtime(), ngx_libc_localtime()</literal> — Time expressed
811
relative to the local time zone
812
</listitem>
813
814
</list>
815
816
The <literal>ngx_http_time(buf, time)</literal> function returns a string
817
representation suitable for use in HTTP headers (for example,
818
<literal>"Mon, 28 Sep 1970 06:00:00 GMT"</literal>).
819
The <literal>ngx_http_cookie_time(buf, time)</literal> returns a string
820
representation function returns a string representation suitable
821
for HTTP cookies (<literal>"Thu, 31-Dec-37 23:55:55 GMT"</literal>).
822
</para>
823
824
</section>
825
826
827
<section name="Containers" id="containers">
828
829
830
<section name="Array" id="array">
831
832
<para>
833
The nginx array type <literal>ngx_array_t</literal> is defined as follows
834
</para>
835
836
837
<programlisting>
838
typedef struct {
839
void *elts;
840
ngx_uint_t nelts;
841
size_t size;
842
ngx_uint_t nalloc;
843
ngx_pool_t *pool;
844
} ngx_array_t;
845
</programlisting>
846
847
<para>
848
The elements of the array are available in the <literal>elts</literal> field.
849
The <literal>nelts</literal> field holds the number of elements.
850
The <literal>size</literal> field holds the size of a single element and is set
851
when the array is initialized.
852
</para>
853
854
<para>
855
Use the <literal>ngx_array_create(pool, n, size)</literal> call to create an
856
array in a pool, and the <literal>ngx_array_init(array, pool, n, size)</literal>
857
call to initialize an array object that has already been allocated.
858
</para>
859
860
861
<programlisting>
862
ngx_array_t *a, b;
863
864
/* create an array of strings with preallocated memory for 10 elements */
865
a = ngx_array_create(pool, 10, sizeof(ngx_str_t));
866
867
/* initialize string array for 10 elements */
868
ngx_array_init(&amp;b, pool, 10, sizeof(ngx_str_t));
869
</programlisting>
870
871
<para>
872
Use the following functions to add elements to an array:
873
</para>
874
875
<para>
876
<list type="bullet">
877
878
<listitem>
879
<literal>ngx_array_push(a)</literal> adds one tail element and returns pointer
880
to it
881
</listitem>
882
883
<listitem>
884
<literal>ngx_array_push_n(a, n)</literal> adds <literal>n</literal> tail elements
885
and returns pointer to the first one
886
</listitem>
887
888
</list>
889
</para>
890
891
<para>
892
If the currently allocated amount of memory is not large enough to accommodate
893
the new elements, a new block of memory is allocated and the existing elements
894
are copied to it.
895
The new memory block is normally twice as large as the existing one.
896
</para>
897
898
899
<programlisting>
900
s = ngx_array_push(a);
901
ss = ngx_array_push_n(&amp;b, 3);
902
</programlisting>
903
904
</section>
905
906
907
<section name="List" id="list">
908
909
<para>
910
In nginx a list is a sequence of arrays, optimized for inserting a potentially
911
large number of items.
912
The <literal>ngx_list_t</literal> list type is defined as follows:
913
</para>
914
915
916
<programlisting>
917
typedef struct {
918
ngx_list_part_t *last;
919
ngx_list_part_t part;
920
size_t size;
921
ngx_uint_t nalloc;
922
ngx_pool_t *pool;
923
} ngx_list_t;
924
</programlisting>
925
926
<para>
927
The actual items are stored in list parts, which are defined as follows:
928
</para>
929
930
931
<programlisting>
932
typedef struct ngx_list_part_s ngx_list_part_t;
933
934
struct ngx_list_part_s {
935
void *elts;
936
ngx_uint_t nelts;
937
ngx_list_part_t *next;
938
};
939
</programlisting>
940
941
<para>
942
Before use, a list must be initialized by calling
943
<literal>ngx_list_init(list, pool, n, size)</literal> or created by calling
944
<literal>ngx_list_create(pool, n, size)</literal>.
945
Both functions take as arguments the size of a single item and a number of
946
items per list part.
947
To add an item to a list, use the <literal>ngx_list_push(list)</literal>
948
function.
949
To iterate over the items, directly access the list fields as shown in the
950
example:
951
</para>
952
953
954
<programlisting>
955
ngx_str_t *v;
956
ngx_uint_t i;
957
ngx_list_t *list;
958
ngx_list_part_t *part;
959
960
list = ngx_list_create(pool, 100, sizeof(ngx_str_t));
961
if (list == NULL) { /* error */ }
962
963
/* add items to the list */
964
965
v = ngx_list_push(list);
966
if (v == NULL) { /* error */ }
967
ngx_str_set(v, "foo");
968
969
v = ngx_list_push(list);
970
if (v == NULL) { /* error */ }
971
ngx_str_set(v, "bar");
972
973
/* iterate over the list */
974
975
part = &amp;list->part;
976
v = part->elts;
977
978
for (i = 0; /* void */; i++) {
979
980
if (i >= part->nelts) {
981
if (part->next == NULL) {
982
break;
983
}
984
985
part = part->next;
986
v = part->elts;
987
i = 0;
988
}
989
990
ngx_do_smth(&amp;v[i]);
991
}
992
</programlisting>
993
994
<para>
995
Lists are primarily used for HTTP input and output headers.
996
</para>
997
998
<para>
999
Lists do not support item removal.
1000
However, when needed, items can internally be marked as missing without actually
1001
being removed from the list.
1002
For example, to mark HTTP output headers (which are stored as
1003
<literal>ngx_table_elt_t</literal> objects) as missing, set the
1004
<literal>hash</literal> field in <literal>ngx_table_elt_t</literal> to
1005
zero.
1006
Items marked in this way are explicitly skipped when the headers are iterated
1007
over.
1008
</para>
1009
1010
</section>
1011
1012
1013
<section name="Queue" id="queue">
1014
1015
<para>
1016
In nginx a queue is an intrusive doubly linked list, with each node defined as
1017
follows:
1018
</para>
1019
1020
1021
<programlisting>
1022
typedef struct ngx_queue_s ngx_queue_t;
1023
1024
struct ngx_queue_s {
1025
ngx_queue_t *prev;
1026
ngx_queue_t *next;
1027
};
1028
</programlisting>
1029
1030
<para>
1031
The head queue node is not linked with any data.
1032
Use the <literal>ngx_queue_init(q)</literal> call to initialize the list head
1033
before use.
1034
Queues support the following operations:
1035
</para>
1036
1037
<para>
1038
<list type="bullet">
1039
1040
<listitem>
1041
<literal>ngx_queue_insert_head(h, x)</literal>,
1042
<literal>ngx_queue_insert_tail(h, x)</literal> — Insert a new node
1043
</listitem>
1044
1045
<listitem>
1046
<literal>ngx_queue_remove(x)</literal> — Remove a queue node
1047
</listitem>
1048
1049
<listitem>
1050
<literal>ngx_queue_split(h, q, n)</literal> — Split a queue at a node,
1051
returning the queue tail in a separate queue
1052
</listitem>
1053
1054
<listitem>
1055
<literal>ngx_queue_add(h, n)</literal> — Add a second queue to the first queue
1056
</listitem>
1057
1058
<listitem>
1059
<literal>ngx_queue_head(h)</literal>,
1060
<literal>ngx_queue_last(h)</literal> — Get first or last queue node
1061
</listitem>
1062
1063
<listitem>
1064
<literal>ngx_queue_sentinel(h)</literal> - Get a queue sentinel object to end
1065
iteration at
1066
</listitem>
1067
1068
<listitem>
1069
<literal>ngx_queue_data(q, type, link)</literal> — Get a reference to the
1070
beginning of a queue node data structure, considering the queue field offset in
1071
it
1072
</listitem>
1073
1074
</list>
1075
</para>
1076
1077
<para>
1078
An example:
1079
</para>
1080
1081
1082
<programlisting>
1083
typedef struct {
1084
ngx_str_t value;
1085
ngx_queue_t queue;
1086
} ngx_foo_t;
1087
1088
ngx_foo_t *f;
1089
ngx_queue_t values, *q;
1090
1091
ngx_queue_init(&amp;values);
1092
1093
f = ngx_palloc(pool, sizeof(ngx_foo_t));
1094
if (f == NULL) { /* error */ }
1095
ngx_str_set(&amp;f->value, "foo");
1096
1097
ngx_queue_insert_tail(&amp;values, &amp;f->queue);
1098
1099
/* insert more nodes here */
1100
1101
for (q = ngx_queue_head(&amp;values);
1102
q != ngx_queue_sentinel(&amp;values);
1103
q = ngx_queue_next(q))
1104
{
1105
f = ngx_queue_data(q, ngx_foo_t, queue);
1106
1107
ngx_do_smth(&amp;f->value);
1108
}
1109
</programlisting>
1110
1111
</section>
1112
1113
1114
<section name="Red-Black tree" id="red_black_tree">
1115
1116
<para>
1117
The <path>src/core/ngx_rbtree.h</path> header file provides access to the
1118
effective implementation of red-black trees.
1119
</para>
1120
1121
1122
<programlisting>
1123
typedef struct {
1124
ngx_rbtree_t rbtree;
1125
ngx_rbtree_node_t sentinel;
1126
1127
/* custom per-tree data here */
1128
} my_tree_t;
1129
1130
typedef struct {
1131
ngx_rbtree_node_t rbnode;
1132
1133
/* custom per-node data */
1134
foo_t val;
1135
} my_node_t;
1136
</programlisting>
1137
1138
<para>
1139
To deal with a tree as a whole, you need two nodes: root and sentinel.
1140
Typically, they are added to a custom structure, allowing you to
1141
organize your data into a tree in which the leaves contain a link to or embed
1142
your data.
1143
</para>
1144
1145
<para>
1146
To initialize a tree:
1147
</para>
1148
1149
1150
<programlisting>
1151
my_tree_t root;
1152
1153
ngx_rbtree_init(&amp;root.rbtree, &amp;root.sentinel, insert_value_function);
1154
</programlisting>
1155
1156
<para>
1157
To traverse a tree and insert new values, use the
1158
"<literal>insert_value</literal>" functions.
1159
For example, the <literal>ngx_str_rbtree_insert_value</literal> function deals
1160
with the <literal>ngx_str_t</literal> type.
1161
Its arguments are pointers to a root node of an insertion, the newly created
1162
node to be added, and a tree sentinel.
1163
</para>
1164
1165
1166
<programlisting>
1167
void ngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp,
1168
ngx_rbtree_node_t *node,
1169
ngx_rbtree_node_t *sentinel)
1170
</programlisting>
1171
1172
1173
<para>
1174
The traversal is pretty straightforward and can be demonstrated with the
1175
following lookup function pattern:
1176
</para>
1177
1178
1179
<programlisting>
1180
my_node_t *
1181
my_rbtree_lookup(ngx_rbtree_t *rbtree, foo_t *val, uint32_t hash)
1182
{
1183
ngx_int_t rc;
1184
my_node_t *n;
1185
ngx_rbtree_node_t *node, *sentinel;
1186
1187
node = rbtree->root;
1188
sentinel = rbtree->sentinel;
1189
1190
while (node != sentinel) {
1191
1192
n = (my_node_t *) node;
1193
1194
if (hash != node->key) {
1195
node = (hash &lt; node->key) ? node->left : node->right;
1196
continue;
1197
}
1198
1199
rc = compare(val, node->val);
1200
1201
if (rc &lt; 0) {
1202
node = node->left;
1203
continue;
1204
}
1205
1206
if (rc > 0) {
1207
node = node->right;
1208
continue;
1209
}
1210
1211
return n;
1212
}
1213
1214
return NULL;
1215
}
1216
</programlisting>
1217
1218
<para>
1219
The <literal>compare()</literal> function is a classic comparator function that
1220
returns a value less than, equal to, or greater than zero.
1221
To speed up lookups and avoid comparing user objects that can be big, an integer
1222
hash field is used.
1223
</para>
1224
1225
<para>
1226
To add a node to a tree, allocate a new node, initialize it and call
1227
<literal>ngx_rbtree_insert()</literal>:
1228
</para>
1229
1230
1231
<programlisting>
1232
my_node_t *my_node;
1233
ngx_rbtree_node_t *node;
1234
1235
my_node = ngx_palloc(...);
1236
init_custom_data(&amp;my_node->val);
1237
1238
node = &amp;my_node->rbnode;
1239
node->key = create_key(my_node->val);
1240
1241
ngx_rbtree_insert(&amp;root->rbtree, node);
1242
</programlisting>
1243
1244
<para>
1245
To remove a node, call the <literal>ngx_rbtree_delete()</literal> function:
1246
</para>
1247
1248
1249
<programlisting>
1250
ngx_rbtree_delete(&amp;root->rbtree, node);
1251
</programlisting>
1252
1253
</section>
1254
1255
<section name="Hash" id="hash">
1256
1257
<para>
1258
Hash table functions are declared in <path>src/core/ngx_hash.h</path>.
1259
Both exact and wildcard matching are supported.
1260
The latter requires extra setup and is described in a separate section below.
1261
</para>
1262
1263
<para>
1264
Before initializing a hash, you need to know the number of elements it will
1265
hold so that nginx can build it optimally.
1266
Two parameters that need to be configured are <literal>max_size</literal>
1267
and <literal>bucket_size</literal>, as detailed in a separate
1268
<link doc="../hash.xml">document</link>.
1269
They are usually configurable by the user.
1270
Hash initialization settings are stored with the
1271
<literal>ngx_hash_init_t</literal> type, and the hash itself is
1272
<literal>ngx_hash_t</literal>:
1273
<programlisting>
1274
ngx_hash_t foo_hash;
1275
ngx_hash_init_t hash;
1276
1277
hash.hash = &amp;foo_hash;
1278
hash.key = ngx_hash_key;
1279
hash.max_size = 512;
1280
hash.bucket_size = ngx_align(64, ngx_cacheline_size);
1281
hash.name = "foo_hash";
1282
hash.pool = cf-&gt;pool;
1283
hash.temp_pool = cf-&gt;temp_pool;
1284
</programlisting>
1285
The <literal>key</literal> is a pointer to a function that creates the hash
1286
integer key from a string.
1287
There are two generic key-creation functions:
1288
<literal>ngx_hash_key(data, len)</literal> and
1289
<literal>ngx_hash_key_lc(data, len)</literal>.
1290
The latter converts a string to all lowercase characters, so the passed string
1291
must be writable.
1292
If that is not true, pass the <literal>NGX_HASH_READONLY_KEY</literal> flag
1293
to the function, initializing the key array (see below).
1294
</para>
1295
1296
<para>
1297
The hash keys are stored in <literal>ngx_hash_keys_arrays_t</literal> and
1298
are initialized with <literal>ngx_hash_keys_array_init(arr, type)</literal>:
1299
The second parameter (<literal>type</literal>) controls the amount of resources
1300
preallocated for the hash and can be either <literal>NGX_HASH_SMALL</literal> or
1301
<literal>NGX_HASH_LARGE</literal>.
1302
The latter is appropriate if you expect the hash to contain thousands of
1303
elements.
1304
1305
<programlisting>
1306
ngx_hash_keys_arrays_t foo_keys;
1307
1308
foo_keys.pool = cf-&gt;pool;
1309
foo_keys.temp_pool = cf-&gt;temp_pool;
1310
1311
ngx_hash_keys_array_init(&amp;foo_keys, NGX_HASH_SMALL);
1312
</programlisting>
1313
</para>
1314
1315
<para>
1316
To insert keys into a hash keys array, use the
1317
<literal>ngx_hash_add_key(keys_array, key, value, flags)</literal> function:
1318
<programlisting>
1319
ngx_str_t k1 = ngx_string("key1");
1320
ngx_str_t k2 = ngx_string("key2");
1321
1322
ngx_hash_add_key(&amp;foo_keys, &amp;k1, &amp;my_data_ptr_1, NGX_HASH_READONLY_KEY);
1323
ngx_hash_add_key(&amp;foo_keys, &amp;k2, &amp;my_data_ptr_2, NGX_HASH_READONLY_KEY);
1324
</programlisting>
1325
</para>
1326
1327
<para>
1328
To build the hash table, call the
1329
<literal>ngx_hash_init(hinit, key_names, nelts)</literal> function:
1330
1331
<programlisting>
1332
ngx_hash_init(&amp;hash, foo_keys.keys.elts, foo_keys.keys.nelts);
1333
</programlisting>
1334
1335
The function fails if <literal>max_size</literal> or
1336
<literal>bucket_size</literal> parameters are not big enough.
1337
</para>
1338
1339
<para>
1340
When the hash is built, use the
1341
<literal>ngx_hash_find(hash, key, name, len)</literal> function to look up
1342
elements:
1343
<programlisting>
1344
my_data_t *data;
1345
ngx_uint_t key;
1346
1347
key = ngx_hash_key(k1.data, k1.len);
1348
1349
data = ngx_hash_find(&amp;foo_hash, key, k1.data, k1.len);
1350
if (data == NULL) {
1351
/* key not found */
1352
}
1353
</programlisting>
1354
1355
</para>
1356
1357
<section name="Wildcard matching" id="wildcard_matching">
1358
1359
<para>
1360
To create a hash that works with wildcards, use the
1361
<literal>ngx_hash_combined_t</literal> type.
1362
It includes the hash type described above and has two additional keys arrays:
1363
<literal>dns_wc_head</literal> and <literal>dns_wc_tail</literal>.
1364
The initialization of basic properties is similar to a regular hash:
1365
<programlisting>
1366
ngx_hash_init_t hash
1367
ngx_hash_combined_t foo_hash;
1368
1369
hash.hash = &amp;foo_hash.hash;
1370
hash.key = ...;
1371
</programlisting>
1372
</para>
1373
1374
<para>
1375
It is possible to add wildcard keys using the
1376
<literal>NGX_HASH_WILDCARD_KEY</literal> flag:
1377
<programlisting>
1378
/* k1 = ".example.org"; */
1379
/* k2 = "foo.*"; */
1380
ngx_hash_add_key(&amp;foo_keys, &amp;k1, &amp;data1, NGX_HASH_WILDCARD_KEY);
1381
ngx_hash_add_key(&amp;foo_keys, &amp;k2, &amp;data2, NGX_HASH_WILDCARD_KEY);
1382
</programlisting>
1383
The function recognizes wildcards and adds keys into the corresponding arrays.
1384
Please refer to the
1385
<link doc="../http/ngx_http_map_module.xml" id="map"/> module
1386
documentation for the description of the wildcard syntax and the
1387
matching algorithm.
1388
</para>
1389
1390
<para>
1391
Depending on the contents of added keys, you may need to initialize up to three
1392
key arrays: one for exact matching (described above), and two more to enable
1393
matching starting from the head or tail of a string:
1394
<programlisting>
1395
if (foo_keys.dns_wc_head.nelts) {
1396
1397
ngx_qsort(foo_keys.dns_wc_head.elts,
1398
(size_t) foo_keys.dns_wc_head.nelts,
1399
sizeof(ngx_hash_key_t),
1400
cmp_dns_wildcards);
1401
1402
hash.hash = NULL;
1403
hash.temp_pool = pool;
1404
1405
if (ngx_hash_wildcard_init(&amp;hash, foo_keys.dns_wc_head.elts,
1406
foo_keys.dns_wc_head.nelts)
1407
!= NGX_OK)
1408
{
1409
return NGX_ERROR;
1410
}
1411
1412
foo_hash.wc_head = (ngx_hash_wildcard_t *) hash.hash;
1413
}
1414
</programlisting>
1415
The keys array needs to be sorted, and initialization results must be added
1416
to the combined hash.
1417
The initialization of <literal>dns_wc_tail</literal> array is done similarly.
1418
</para>
1419
1420
<para>
1421
The lookup in a combined hash is handled by the
1422
<literal>ngx_hash_find_combined(chash, key, name, len)</literal>:
1423
<programlisting>
1424
/* key = "bar.example.org"; — will match ".example.org" */
1425
/* key = "foo.example.com"; — will match "foo.*" */
1426
1427
hkey = ngx_hash_key(key.data, key.len);
1428
res = ngx_hash_find_combined(&amp;foo_hash, hkey, key.data, key.len);
1429
</programlisting>
1430
</para>
1431
1432
</section>
1433
1434
</section>
1435
1436
</section>
1437
1438
1439
<section name="Memory management" id="memory_management">
1440
1441
1442
<section name="Heap" id="heap">
1443
1444
<para>
1445
To allocate memory from system heap, use the following functions:
1446
</para>
1447
1448
<para>
1449
<list type="bullet">
1450
1451
<listitem>
1452
<literal>ngx_alloc(size, log)</literal> — Allocate memory from system heap.
1453
This is a wrapper around <literal>malloc()</literal> with logging support.
1454
Allocation error and debugging information is logged to <literal>log</literal>.
1455
</listitem>
1456
1457
<listitem>
1458
<literal>ngx_calloc(size, log)</literal> — Allocate memory from system heap
1459
like <literal>ngx_alloc()</literal>, but fill memory with zeros after
1460
allocation.
1461
</listitem>
1462
1463
<listitem>
1464
<literal>ngx_memalign(alignment, size, log)</literal> — Allocate aligned memory
1465
from system heap.
1466
This is a wrapper around <literal>posix_memalign()</literal>
1467
on those platforms that provide that function.
1468
Otherwise implementation falls back to <literal>ngx_alloc()</literal> which
1469
provides maximum alignment.
1470
</listitem>
1471
1472
<listitem>
1473
<literal>ngx_free(p)</literal> — Free allocated memory.
1474
This is a wrapper around <literal>free()</literal>
1475
</listitem>
1476
1477
</list>
1478
</para>
1479
1480
</section>
1481
1482
1483
<section name="Pool" id="pool">
1484
1485
<para>
1486
Most nginx allocations are done in pools.
1487
Memory allocated in an nginx pool is freed automatically when the pool is
1488
destroyed.
1489
This provides good allocation performance and makes memory control easy.
1490
</para>
1491
1492
<para>
1493
A pool internally allocates objects in continuous blocks of memory.
1494
Once a block is full, a new one is allocated and added to the pool memory
1495
block list.
1496
When the requested allocation is too large to fit into a block, the request
1497
is forwarded to the system allocator and the
1498
returned pointer is stored in the pool for further deallocation.
1499
</para>
1500
1501
<para>
1502
The type for nginx pools is <literal>ngx_pool_t</literal>.
1503
The following operations are supported:
1504
</para>
1505
1506
<para>
1507
<list type="bullet">
1508
1509
<listitem>
1510
<literal>ngx_create_pool(size, log)</literal> — Create a pool with specified
1511
block size.
1512
The pool object returned is allocated in the pool as well.
1513
The <literal>size</literal>
1514
should be at least <literal>NGX_MIN_POOL_SIZE</literal>
1515
and a multiple of <literal>NGX_POOL_ALIGNMENT</literal>.
1516
</listitem>
1517
1518
<listitem>
1519
<literal>ngx_destroy_pool(pool)</literal> — Free all pool memory, including
1520
the pool object itself.
1521
</listitem>
1522
1523
<listitem>
1524
<literal>ngx_palloc(pool, size)</literal> — Allocate aligned memory from the
1525
specified pool.
1526
</listitem>
1527
1528
<listitem>
1529
<literal>ngx_pcalloc(pool, size)</literal> — Allocate aligned memory
1530
from the specified pool and fill it with zeroes.
1531
</listitem>
1532
1533
<listitem>
1534
<literal>ngx_pnalloc(pool, size)</literal> — Allocate unaligned memory from the
1535
specified pool.
1536
Mostly used for allocating strings.
1537
</listitem>
1538
1539
<listitem>
1540
<literal>ngx_pfree(pool, p)</literal> — Free memory that was previously
1541
allocated in the specified pool.
1542
Only allocations that result from requests forwarded to the system allocator
1543
can be freed.
1544
</listitem>
1545
1546
</list>
1547
</para>
1548
1549
<programlisting>
1550
u_char *p;
1551
ngx_str_t *s;
1552
ngx_pool_t *pool;
1553
1554
pool = ngx_create_pool(1024, log);
1555
if (pool == NULL) { /* error */ }
1556
1557
s = ngx_palloc(pool, sizeof(ngx_str_t));
1558
if (s == NULL) { /* error */ }
1559
ngx_str_set(s, "foo");
1560
1561
p = ngx_pnalloc(pool, 3);
1562
if (p == NULL) { /* error */ }
1563
ngx_memcpy(p, "foo", 3);
1564
</programlisting>
1565
1566
<para>
1567
Chain links (<literal>ngx_chain_t</literal>) are actively used in nginx,
1568
so the nginx pool implementation provides a way to reuse them.
1569
The <literal>chain</literal> field of <literal>ngx_pool_t</literal> keeps a
1570
list of previously allocated links ready for reuse.
1571
For efficient allocation of a chain link in a pool, use the
1572
<literal>ngx_alloc_chain_link(pool)</literal> function.
1573
This function looks up a free chain link in the pool list and allocates a new
1574
chain link if the pool list is empty.
1575
To free a link, call the <literal>ngx_free_chain(pool, cl)</literal> function.
1576
</para>
1577
1578
<para>
1579
Cleanup handlers can be registered in a pool.
1580
A cleanup handler is a callback with an argument which is called when pool is
1581
destroyed.
1582
A pool is usually tied to a specific nginx object (like an HTTP request) and is
1583
destroyed when the object reaches the end of its lifetime.
1584
Registering a pool cleanup is a convenient way to release resources, close
1585
file descriptors or make final adjustments to the shared data associated with
1586
the main object.
1587
</para>
1588
1589
<para>
1590
To register a pool cleanup, call
1591
<literal>ngx_pool_cleanup_add(pool, size)</literal>, which returns a
1592
<literal>ngx_pool_cleanup_t</literal> pointer to
1593
be filled in by the caller.
1594
Use the <literal>size</literal> argument to allocate context for the cleanup
1595
handler.
1596
</para>
1597
1598
1599
<programlisting>
1600
ngx_pool_cleanup_t *cln;
1601
1602
cln = ngx_pool_cleanup_add(pool, 0);
1603
if (cln == NULL) { /* error */ }
1604
1605
cln->handler = ngx_my_cleanup;
1606
cln->data = "foo";
1607
1608
...
1609
1610
static void
1611
ngx_my_cleanup(void *data)
1612
{
1613
u_char *msg = data;
1614
1615
ngx_do_smth(msg);
1616
}
1617
</programlisting>
1618
1619
</section>
1620
1621
1622
<section name="Shared memory" id="shared_memory">
1623
1624
<para>
1625
Shared memory is used by nginx to share common data between processes.
1626
The <literal>ngx_shared_memory_add(cf, name, size, tag)</literal> function adds
1627
a new shared memory entry <literal>ngx_shm_zone_t</literal> to a cycle.
1628
The function receives the <literal>name</literal> and <literal>size</literal>
1629
of the zone.
1630
Each shared zone must have a unique name.
1631
If a shared zone entry with the provided <literal>name</literal> and
1632
<literal>tag</literal> already exists, the existing zone entry is reused.
1633
The function fails with an error if an existing entry with the same name has a
1634
different tag.
1635
Usually, the address of the module structure is passed as
1636
<literal>tag</literal>, making it possible to reuse shared zones by name within
1637
one nginx module.
1638
</para>
1639
1640
<para>
1641
The shared memory entry structure <literal>ngx_shm_zone_t</literal> has the
1642
following fields:
1643
</para>
1644
1645
<para>
1646
<list type="bullet">
1647
1648
<listitem>
1649
<literal>init</literal> — Initialization callback, called after the shared zone
1650
is mapped to actual memory
1651
</listitem>
1652
1653
<listitem>
1654
<literal>data</literal> — Data context, used to pass arbitrary data to the
1655
<literal>init</literal> callback
1656
</listitem>
1657
1658
<listitem>
1659
<literal>noreuse</literal> — Flag that disables reuse of a shared zone from the
1660
old cycle
1661
</listitem>
1662
1663
<listitem>
1664
<literal>tag</literal> — Shared zone tag
1665
</listitem>
1666
1667
<listitem>
1668
<literal>shm</literal> — Platform-specific object of type
1669
<literal>ngx_shm_t</literal>, having at least the following fields:
1670
<list type="bullet">
1671
1672
<listitem>
1673
<literal>addr</literal> — Mapped shared memory address, initially NULL
1674
</listitem>
1675
1676
<listitem>
1677
<literal>size</literal> — Shared memory size
1678
</listitem>
1679
1680
<listitem>
1681
<literal>name</literal> — Shared memory name
1682
</listitem>
1683
1684
<listitem>
1685
<literal>log</literal> — Shared memory log
1686
</listitem>
1687
1688
<listitem>
1689
<literal>exists</literal> — Flag that indicates shared memory was inherited
1690
from the master process (Windows-specific)
1691
</listitem>
1692
1693
</list>
1694
</listitem>
1695
1696
</list>
1697
</para>
1698
1699
<para>
1700
Shared zone entries are mapped to actual memory in
1701
<literal>ngx_init_cycle()</literal> after the configuration is parsed.
1702
On POSIX systems, the <literal>mmap()</literal> syscall is used to create the
1703
shared anonymous mapping.
1704
On Windows, the <literal>CreateFileMapping()</literal>/
1705
<literal>MapViewOfFileEx()</literal> pair is used.
1706
</para>
1707
1708
<para>
1709
For allocating in shared memory, nginx provides the slab pool
1710
<literal>ngx_slab_pool_t</literal> type.
1711
A slab pool for allocating memory is automatically created in each nginx shared
1712
zone.
1713
The pool is located in the beginning of the shared zone and can be accessed by
1714
the expression <literal>(ngx_slab_pool_t *) shm_zone->shm.addr</literal>.
1715
To allocate memory in a shared zone, call either
1716
<literal>ngx_slab_alloc(pool, size)</literal> or
1717
<literal>ngx_slab_calloc(pool, size)</literal>.
1718
To free memory, call <literal>ngx_slab_free(pool, p)</literal>.
1719
</para>
1720
1721
<para>
1722
Slab pool divides all shared zone into pages.
1723
Each page is used for allocating objects of the same size.
1724
The specified size must be a power of 2, and greater than the minimum size of
1725
8 bytes.
1726
Nonconforming values are rounded up.
1727
A bitmask for each page tracks which blocks are in use and which are free for
1728
allocation.
1729
For sizes greater than a half page (which is usually 2048 bytes), allocation is
1730
done an entire page at a time
1731
</para>
1732
1733
<para>
1734
To protect data in shared memory from concurrent access, use the mutex
1735
available in the <literal>mutex</literal> field of
1736
<literal>ngx_slab_pool_t</literal>.
1737
A mutex is most commonly used by the slab pool while allocating and freeing
1738
memory, but it can be used to protect any other user data structures allocated
1739
in the shared zone.
1740
To lock or unlock a mutex, call
1741
<literal>ngx_shmtx_lock(&amp;shpool->mutex)</literal> or
1742
<literal>ngx_shmtx_unlock(&amp;shpool->mutex)</literal> respectively.
1743
</para>
1744
1745
1746
<programlisting>
1747
ngx_str_t name;
1748
ngx_foo_ctx_t *ctx;
1749
ngx_shm_zone_t *shm_zone;
1750
1751
ngx_str_set(&amp;name, "foo");
1752
1753
/* allocate shared zone context */
1754
ctx = ngx_pcalloc(cf->pool, sizeof(ngx_foo_ctx_t));
1755
if (ctx == NULL) {
1756
/* error */
1757
}
1758
1759
/* add an entry for 64k shared zone */
1760
shm_zone = ngx_shared_memory_add(cf, &amp;name, 65536, &amp;ngx_foo_module);
1761
if (shm_zone == NULL) {
1762
/* error */
1763
}
1764
1765
/* register init callback and context */
1766
shm_zone->init = ngx_foo_init_zone;
1767
shm_zone->data = ctx;
1768
1769
1770
...
1771
1772
1773
static ngx_int_t
1774
ngx_foo_init_zone(ngx_shm_zone_t *shm_zone, void *data)
1775
{
1776
ngx_foo_ctx_t *octx = data;
1777
1778
size_t len;
1779
ngx_foo_ctx_t *ctx;
1780
ngx_slab_pool_t *shpool;
1781
1782
value = shm_zone->data;
1783
1784
if (octx) {
1785
/* reusing a shared zone from old cycle */
1786
ctx->value = octx->value;
1787
return NGX_OK;
1788
}
1789
1790
shpool = (ngx_slab_pool_t *) shm_zone->shm.addr;
1791
1792
if (shm_zone->shm.exists) {
1793
/* initialize shared zone context in Windows nginx worker */
1794
ctx->value = shpool->data;
1795
return NGX_OK;
1796
}
1797
1798
/* initialize shared zone */
1799
1800
ctx->value = ngx_slab_alloc(shpool, sizeof(ngx_uint_t));
1801
if (ctx->value == NULL) {
1802
return NGX_ERROR;
1803
}
1804
1805
shpool->data = ctx->value;
1806
1807
return NGX_OK;
1808
}
1809
</programlisting>
1810
1811
</section>
1812
1813
1814
</section>
1815
1816
1817
<section name="Logging" id="logging">
1818
1819
<para>
1820
For logging nginx uses <literal>ngx_log_t</literal> objects.
1821
The nginx logger supports several types of output:
1822
1823
<list type="bullet">
1824
1825
<listitem>
1826
stderr — Logging to standard error (stderr)
1827
</listitem>
1828
1829
<listitem>
1830
file — Logging to a file
1831
</listitem>
1832
1833
<listitem>
1834
syslog — Logging to syslog
1835
</listitem>
1836
1837
<listitem>
1838
memory — Logging to internal memory storage for development purposes; the memory
1839
can be accessed later with a debugger
1840
</listitem>
1841
1842
</list>
1843
</para>
1844
1845
<para>
1846
A logger instance can be a chain of loggers, linked to each other with
1847
the <literal>next</literal> field.
1848
In this case, each message is written to all loggers in the chain.
1849
</para>
1850
1851
<para>
1852
For each logger, a severity level controls which messages are written to the
1853
log (only events assigned that level or higher are logged).
1854
The following severity levels are supported:
1855
</para>
1856
1857
<para>
1858
<list type="bullet">
1859
1860
<listitem>
1861
<literal>NGX_LOG_EMERG</literal>
1862
</listitem>
1863
1864
<listitem>
1865
<literal>NGX_LOG_ALERT</literal>
1866
</listitem>
1867
1868
<listitem>
1869
<literal>NGX_LOG_CRIT</literal>
1870
</listitem>
1871
1872
<listitem>
1873
<literal>NGX_LOG_ERR</literal>
1874
</listitem>
1875
1876
<listitem>
1877
<literal>NGX_LOG_WARN</literal>
1878
</listitem>
1879
1880
<listitem>
1881
<literal>NGX_LOG_NOTICE</literal>
1882
</listitem>
1883
1884
<listitem>
1885
<literal>NGX_LOG_INFO</literal>
1886
</listitem>
1887
1888
<listitem>
1889
<literal>NGX_LOG_DEBUG</literal>
1890
</listitem>
1891
1892
</list>
1893
</para>
1894
1895
<para>
1896
For debug logging, the debug mask is checked as well.
1897
The debug masks are:
1898
</para>
1899
1900
<para>
1901
<list type="bullet">
1902
1903
<listitem>
1904
<literal>NGX_LOG_DEBUG_CORE</literal>
1905
</listitem>
1906
1907
<listitem>
1908
<literal>NGX_LOG_DEBUG_ALLOC</literal>
1909
</listitem>
1910
1911
<listitem>
1912
<literal>NGX_LOG_DEBUG_MUTEX</literal>
1913
</listitem>
1914
1915
<listitem>
1916
<literal>NGX_LOG_DEBUG_EVENT</literal>
1917
</listitem>
1918
1919
<listitem>
1920
<literal>NGX_LOG_DEBUG_HTTP</literal>
1921
</listitem>
1922
1923
<listitem>
1924
<literal>NGX_LOG_DEBUG_MAIL</literal>
1925
</listitem>
1926
1927
<listitem>
1928
<literal>NGX_LOG_DEBUG_STREAM</literal>
1929
</listitem>
1930
1931
</list>
1932
</para>
1933
1934
<para>
1935
Normally, loggers are created by existing nginx code from
1936
<literal>error_log</literal> directives and are available at nearly every stage
1937
of processing in cycle, configuration, client connection and other objects.
1938
</para>
1939
1940
<para>
1941
Nginx provides the following logging macros:
1942
</para>
1943
1944
<para>
1945
<list type="bullet">
1946
1947
<listitem>
1948
<literal>ngx_log_error(level, log, err, fmt, ...)</literal> — Error logging
1949
</listitem>
1950
1951
<listitem>
1952
<literal>ngx_log_debug0(level, log, err, fmt)</literal>,
1953
<literal>ngx_log_debug1(level, log, err, fmt, arg1)</literal> etc — Debug
1954
logging with up to eight supported formatting arguments
1955
</listitem>
1956
1957
</list>
1958
</para>
1959
1960
<para>
1961
A log message is formatted in a buffer of size
1962
<literal>NGX_MAX_ERROR_STR</literal> (currently, 2048 bytes) on stack.
1963
The message is prepended with the severity level, process ID (PID), connection
1964
ID (stored in <literal>log->connection</literal>), and the system error text.
1965
For non-debug messages <literal>log->handler</literal> is called as well to
1966
prepend more specific information to the log message.
1967
HTTP module sets <literal>ngx_http_log_error()</literal> function as log
1968
handler to log client and server addresses, current action (stored in
1969
<literal>log->action</literal>), client request line, server name etc.
1970
</para>
1971
1972
<programlisting>
1973
/* specify what is currently done */
1974
log->action = "sending mp4 to client";
1975
1976
/* error and debug log */
1977
ngx_log_error(NGX_LOG_INFO, c->log, 0, "client prematurely
1978
closed connection");
1979
1980
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, mp4->file.log, 0,
1981
"mp4 start:%ui, length:%ui", mp4->start, mp4->length);
1982
</programlisting>
1983
1984
<para>
1985
The example above results in log entries like these:
1986
</para>
1987
1988
1989
<programlisting>
1990
2016/09/16 22:08:52 [info] 17445#0: *1 client prematurely closed connection while
1991
sending mp4 to client, client: 127.0.0.1, server: , request: "GET /file.mp4 HTTP/1.1"
1992
2016/09/16 23:28:33 [debug] 22140#0: *1 mp4 start:0, length:10000
1993
</programlisting>
1994
1995
</section>
1996
1997
1998
<section name="Cycle" id="cycle">
1999
2000
<para>
2001
A cycle object stores the nginx runtime context created from a specific
2002
configuration.
2003
Its type is <literal>ngx_cycle_t</literal>.
2004
The current cycle is referenced by the <literal>ngx_cycle</literal> global
2005
variable and inherited by nginx workers as they start.
2006
Each time the nginx configuration is reloaded, a new cycle is created from the
2007
new nginx configuration; the old cycle is usually deleted after the new one is
2008
successfully created.
2009
</para>
2010
2011
<para>
2012
A cycle is created by the <literal>ngx_init_cycle()</literal> function, which
2013
takes the previous cycle as its argument.
2014
The function locates the previous cycle's configuration file and inherits as
2015
many resources as possible from the previous cycle.
2016
A placeholder cycle called "init cycle" is created as nginx start, then is
2017
replaced by an actual cycle built from configuration.
2018
</para>
2019
2020
<para>
2021
Members of the cycle include:
2022
</para>
2023
2024
<para>
2025
<list type="bullet">
2026
2027
<listitem>
2028
<literal>pool</literal> — Cycle pool.
2029
Created for each new cycle.
2030
</listitem>
2031
2032
<listitem>
2033
<literal>log</literal> — Cycle log.
2034
Initially inherited from the old cycle, it is set to point to
2035
<literal>new_log</literal> after the configuration is read.
2036
</listitem>
2037
2038
<listitem>
2039
<literal>new_log</literal> — Cycle log, created by the configuration.
2040
It's affected by the root-scope <literal>error_log</literal> directive.
2041
</listitem>
2042
2043
<listitem>
2044
<literal>connections</literal>, <literal>connection_n</literal> 
2045
Array of connections of type <literal>ngx_connection_t</literal>, created by
2046
the event module while initializing each nginx worker.
2047
The <literal>worker_connections</literal> directive in the nginx configuration
2048
sets the number of connections <literal>connection_n</literal>.
2049
</listitem>
2050
2051
<listitem>
2052
<literal>free_connections</literal>,
2053
<literal>free_connection_n</literal> — List and number of currently available
2054
connections.
2055
If no connections are available, an nginx worker refuses to accept new clients
2056
or connect to upstream servers.
2057
</listitem>
2058
2059
<listitem>
2060
<literal>files</literal>, <literal>files_n</literal> — Array for mapping file
2061
descriptors to nginx connections.
2062
This mapping is used by the event modules, having the
2063
<literal>NGX_USE_FD_EVENT</literal> flag (currently, it's
2064
<literal>poll</literal> and <literal>devpoll</literal>).
2065
</listitem>
2066
2067
<listitem>
2068
<literal>conf_ctx</literal> — Array of core module configurations.
2069
The configurations are created and filled during reading of nginx configuration
2070
files.
2071
</listitem>
2072
2073
<listitem>
2074
<literal>modules</literal>, <literal>modules_n</literal> — Array of modules
2075
of type <literal>ngx_module_t</literal>, both static and dynamic, loaded by
2076
the current configuration.
2077
</listitem>
2078
2079
<listitem>
2080
<literal>listening</literal> — Array of listening objects of type
2081
<literal>ngx_listening_t</literal>.
2082
Listening objects are normally added by the <literal>listen</literal>
2083
directive of different modules which call the
2084
<literal>ngx_create_listening()</literal> function.
2085
Listen sockets are created based on the listening objects.
2086
</listitem>
2087
2088
<listitem>
2089
<literal>paths</literal> — Array of paths of type <literal>ngx_path_t</literal>.
2090
Paths are added by calling the function <literal>ngx_add_path()</literal> from
2091
modules which are going to operate on certain directories.
2092
These directories are created by nginx after reading configuration, if missing.
2093
Moreover, two handlers can be added for each path:
2094
2095
<list type="bullet">
2096
2097
<listitem>
2098
path loader — Executes only once in 60 seconds after starting or reloading
2099
nginx.
2100
Normally, the loader reads the directory and stores data in nginx shared
2101
memory.
2102
The handler is called from the dedicated nginx process “nginx cache loader”.
2103
</listitem>
2104
2105
<listitem>
2106
path manager — Executes periodically.
2107
Normally, the manager removes old files from the directory and updates nginx
2108
memory to reflect the changes.
2109
The handler is called from the dedicated “nginx cache manager” process.
2110
</listitem>
2111
2112
</list>
2113
</listitem>
2114
2115
<listitem>
2116
<literal>open_files</literal> — List of open file objects of type
2117
<literal>ngx_open_file_t</literal>, which are created by calling the function
2118
<literal>ngx_conf_open_file()</literal>.
2119
Currently, nginx uses this kind of open files for logging.
2120
After reading the configuration, nginx opens all files in the
2121
<literal>open_files</literal> list and stores each file descriptor in the
2122
object's <literal>fd</literal> field.
2123
The files are opened in append mode and are created if missing.
2124
The files in the list are reopened by nginx workers upon receiving the
2125
reopen signal (most often <literal>USR1</literal>).
2126
In this case the descriptor in the <literal>fd</literal> field is changed to a
2127
new value.
2128
</listitem>
2129
2130
<listitem>
2131
<literal>shared_memory</literal> — List of shared memory zones, each added by
2132
calling the <literal>ngx_shared_memory_add()</literal> function.
2133
Shared zones are mapped to the same address range in all nginx processes and
2134
are used to share common data, for example the HTTP cache in-memory tree.
2135
</listitem>
2136
2137
</list>
2138
</para>
2139
2140
</section>
2141
2142
<section name="Buffer" id="buffer">
2143
2144
<para>
2145
For input/output operations, nginx provides the buffer type
2146
<literal>ngx_buf_t</literal>.
2147
Normally, it's used to hold data to be written to a destination or read from a
2148
source.
2149
A buffer can reference data in memory or in a file and it's technically
2150
possible for a buffer to reference both at the same time.
2151
Memory for the buffer is allocated separately and is not related to the buffer
2152
structure <literal>ngx_buf_t</literal>.
2153
</para>
2154
2155
<para>
2156
The <literal>ngx_buf_t</literal> structure has the following fields:
2157
</para>
2158
2159
<para>
2160
<list type="bullet">
2161
2162
<listitem>
2163
<literal>start</literal>, <literal>end</literal> — The boundaries of the memory
2164
block allocated for the buffer.
2165
</listitem>
2166
2167
<listitem>
2168
<literal>pos</literal>, <literal>last</literal> — The boundaries of the memory
2169
buffer; normally a subrange of <literal>start</literal> ..
2170
<literal>end</literal>.
2171
</listitem>
2172
2173
<listitem>
2174
<literal>file_pos</literal>, <literal>file_last</literal> — The boundaries of a
2175
file buffer, expressed as offsets from the beginning of the file.
2176
</listitem>
2177
2178
<listitem>
2179
<literal>tag</literal> — Unique value used to distinguish buffers; created by
2180
different nginx modules, usually for the purpose of buffer reuse.
2181
</listitem>
2182
2183
<listitem>
2184
<literal>file</literal> — File object.
2185
</listitem>
2186
2187
<listitem>
2188
<literal>temporary</literal> — Flag indicating that the buffer references
2189
writable memory.
2190
</listitem>
2191
2192
<listitem>
2193
<literal>memory</literal> — Flag indicating that the buffer references read-only
2194
memory.
2195
</listitem>
2196
2197
<listitem>
2198
<literal>in_file</literal> — Flag indicating that the buffer references data
2199
in a file.
2200
</listitem>
2201
2202
<listitem>
2203
<literal>flush</literal> — Flag indicating that all data prior to the buffer
2204
need to be flushed.
2205
</listitem>
2206
2207
<listitem>
2208
<literal>recycled</literal> — Flag indicating that the buffer can be reused and
2209
needs to be consumed as soon as possible.
2210
</listitem>
2211
2212
<listitem>
2213
<literal>sync</literal> — Flag indicating that the buffer carries no data or
2214
special signal like <literal>flush</literal> or <literal>last_buf</literal>.
2215
By default nginx considers such buffers an error condition, but this flag tells
2216
nginx to skip the error check.
2217
</listitem>
2218
2219
<listitem>
2220
<literal>last_buf</literal> — Flag indicating that the buffer is the last in
2221
output.
2222
</listitem>
2223
2224
<listitem>
2225
<literal>last_in_chain</literal> — Flag indicating that there are no more data
2226
buffers in a request or subrequest.
2227
</listitem>
2228
2229
<listitem>
2230
<literal>shadow</literal> — Reference to another ("shadow") buffer related to
2231
the current buffer, usually in the sense that the buffer uses data from the
2232
shadow.
2233
When the buffer is consumed, the shadow buffer is normally also marked as
2234
consumed.
2235
</listitem>
2236
2237
<listitem>
2238
<literal>last_shadow</literal> — Flag indicating that the buffer is the last
2239
one that references a particular shadow buffer.
2240
</listitem>
2241
2242
<listitem>
2243
<literal>temp_file</literal> — Flag indicating that the buffer is in a temporary
2244
file.
2245
</listitem>
2246
2247
</list>
2248
</para>
2249
2250
<para>
2251
For input and output operations buffers are linked in chains.
2252
A chain is a sequence of chain links of type <literal>ngx_chain_t</literal>,
2253
defined as follows:
2254
</para>
2255
2256
2257
<programlisting>
2258
typedef struct ngx_chain_s ngx_chain_t;
2259
2260
struct ngx_chain_s {
2261
ngx_buf_t *buf;
2262
ngx_chain_t *next;
2263
};
2264
</programlisting>
2265
2266
<para>
2267
Each chain link keeps a reference to its buffer and a reference to the next
2268
chain link.
2269
</para>
2270
2271
<para>
2272
An example of using buffers and chains:
2273
</para>
2274
2275
2276
<programlisting>
2277
ngx_chain_t *
2278
ngx_get_my_chain(ngx_pool_t *pool)
2279
{
2280
ngx_buf_t *b;
2281
ngx_chain_t *out, *cl, **ll;
2282
2283
/* first buf */
2284
cl = ngx_alloc_chain_link(pool);
2285
if (cl == NULL) { /* error */ }
2286
2287
b = ngx_calloc_buf(pool);
2288
if (b == NULL) { /* error */ }
2289
2290
b->start = (u_char *) "foo";
2291
b->pos = b->start;
2292
b->end = b->start + 3;
2293
b->last = b->end;
2294
b->memory = 1; /* read-only memory */
2295
2296
cl->buf = b;
2297
out = cl;
2298
ll = &amp;cl->next;
2299
2300
/* second buf */
2301
cl = ngx_alloc_chain_link(pool);
2302
if (cl == NULL) { /* error */ }
2303
2304
b = ngx_create_temp_buf(pool, 3);
2305
if (b == NULL) { /* error */ }
2306
2307
b->last = ngx_cpymem(b->last, "foo", 3);
2308
2309
cl->buf = b;
2310
cl->next = NULL;
2311
*ll = cl;
2312
2313
return out;
2314
}
2315
</programlisting>
2316
2317
</section>
2318
2319
2320
<section name="Networking" id="networking">
2321
2322
2323
<!--
2324
<section name="Network data types" id="network_data_types">
2325
2326
<para>
2327
TBD: ngx_addr_t, ngx_url_t, ngx_socket_t, ngx_sockaddr_t, parse url, parse
2328
address...
2329
</para>
2330
2331
</section>
2332
-->
2333
2334
<section name="Connection" id="connection">
2335
2336
<para>
2337
The connection type <literal>ngx_connection_t</literal> is a wrapper around a
2338
socket descriptor.
2339
It includes the following fields:
2340
</para>
2341
2342
<para>
2343
<list type="bullet">
2344
2345
<listitem>
2346
<literal>fd</literal> — Socket descriptor
2347
</listitem>
2348
2349
<listitem>
2350
<literal>data</literal> — Arbitrary connection context.
2351
Normally, it is a pointer to a higher-level object built on top of the
2352
connection, such as an HTTP request or a Stream session.
2353
</listitem>
2354
2355
<listitem>
2356
<literal>read</literal>, <literal>write</literal> — Read and write events for
2357
the connection.
2358
</listitem>
2359
2360
<listitem>
2361
<literal>recv</literal>, <literal>send</literal>,
2362
<literal>recv_chain</literal>, <literal>send_chain</literal> — I/O operations
2363
for the connection.
2364
</listitem>
2365
2366
<listitem>
2367
<literal>pool</literal> — Connection pool.
2368
</listitem>
2369
2370
<listitem>
2371
<literal>log</literal> — Connection log.
2372
</listitem>
2373
2374
<listitem>
2375
<literal>sockaddr</literal>, <literal>socklen</literal>,
2376
<literal>addr_text</literal> — Remote socket address in binary and text forms.
2377
</listitem>
2378
2379
<listitem>
2380
<literal>local_sockaddr</literal>, <literal>local_socklen</literal> — Local
2381
socket address in binary form.
2382
Initially, these fields are empty.
2383
Use the <literal>ngx_connection_local_sockaddr()</literal> function to get the
2384
local socket address.
2385
</listitem>
2386
2387
<listitem>
2388
<literal>proxy_protocol_addr</literal>, <literal>proxy_protocol_port</literal>
2389
- PROXY protocol client address and port, if the PROXY protocol is enabled for
2390
the connection.
2391
</listitem>
2392
2393
<listitem>
2394
<literal>ssl</literal> — SSL context for the connection.
2395
</listitem>
2396
2397
<listitem>
2398
<literal>reusable</literal> — Flag indicating the connection is in a state that
2399
makes it eligible for reuse.
2400
</listitem>
2401
2402
<listitem>
2403
<literal>close</literal> — Flag indicating that the connection is being reused
2404
and needs to be closed.
2405
</listitem>
2406
2407
</list>
2408
</para>
2409
2410
<para>
2411
An nginx connection can transparently encapsulate the SSL layer.
2412
In this case the connection's <literal>ssl</literal> field holds a pointer to an
2413
<literal>ngx_ssl_connection_t</literal> structure, keeping all SSL-related data
2414
for the connection, including <literal>SSL_CTX</literal> and
2415
<literal>SSL</literal>.
2416
The <literal>recv</literal>, <literal>send</literal>,
2417
<literal>recv_chain</literal>, and <literal>send_chain</literal> handlers are
2418
set to SSL-enabled functions as well.
2419
</para>
2420
2421
<para>
2422
The <literal>worker_connections</literal> directive in the nginx configuration
2423
limits the number of connections per nginx worker.
2424
All connection structures are precreated when a worker starts and stored in
2425
the <literal>connections</literal> field of the cycle object.
2426
To retrieve a connection structure, use the
2427
<literal>ngx_get_connection(s, log)</literal> function.
2428
It takes as its <literal>s</literal> argument a socket descriptor, which needs
2429
to be wrapped in a connection structure.
2430
</para>
2431
2432
<para>
2433
Because the number of connections per worker is limited, nginx provides a
2434
way to grab connections that are currently in use.
2435
To enable or disable reuse of a connection, call the
2436
<literal>ngx_reusable_connection(c, reusable)</literal> function.
2437
Calling <literal>ngx_reusable_connection(c, 1)</literal> sets the
2438
<literal>reuse</literal> flag in the connection structure and inserts the
2439
connection into the <literal>reusable_connections_queue</literal> of the cycle.
2440
Whenever <literal>ngx_get_connection()</literal> finds out there are no
2441
available connections in the cycle's <literal>free_connections</literal> list,
2442
it calls <literal>ngx_drain_connections()</literal> to release a
2443
specific number of reusable connections.
2444
For each such connection, the <literal>close</literal> flag is set and its read
2445
handler is called which is supposed to free the connection by calling
2446
<literal>ngx_close_connection(c)</literal> and make it available for reuse.
2447
To exit the state when a connection can be reused
2448
<literal>ngx_reusable_connection(c, 0)</literal> is called.
2449
HTTP client connections are an example of reusable connections in nginx; they
2450
are marked as reusable until the first request byte is received from the client.
2451
</para>
2452
2453
</section>
2454
2455
2456
</section>
2457
2458
2459
<section name="Events" id="events">
2460
2461
2462
<section name="Event" id="event">
2463
2464
<para>
2465
Event object <literal>ngx_event_t</literal> in nginx provides a mechanism
2466
for notification that a specific event has occurred.
2467
</para>
2468
2469
<para>
2470
Fields in <literal>ngx_event_t</literal> include:
2471
</para>
2472
2473
<para>
2474
<list type="bullet">
2475
2476
<listitem>
2477
<literal>data</literal> — Arbitrary event context used in event handlers,
2478
usually as pointer to a connection related to the event.
2479
</listitem>
2480
2481
<listitem>
2482
<literal>handler</literal> — Callback function to be invoked when the event
2483
happens.
2484
</listitem>
2485
2486
<listitem>
2487
<literal>write</literal> — Flag indicating a write event.
2488
Absence of the flag indicates a read event.
2489
</listitem>
2490
2491
<listitem>
2492
<literal>active</literal> — Flag indicating that the event is registered for
2493
receiving I/O notifications, normally from notification mechanisms like
2494
<literal>epoll</literal>, <literal>kqueue</literal>, <literal>poll</literal>.
2495
</listitem>
2496
2497
<listitem>
2498
<literal>ready</literal> — Flag indicating that the event has received an
2499
I/O notification.
2500
</listitem>
2501
2502
<listitem>
2503
<literal>delayed</literal> — Flag indicating that I/O is delayed due to rate
2504
limiting.
2505
</listitem>
2506
2507
<listitem>
2508
<literal>timer</literal> — Red-black tree node for inserting the event into
2509
the timer tree.
2510
</listitem>
2511
2512
<listitem>
2513
<literal>timer_set</literal> — Flag indicating that the event timer is set and
2514
not yet expired.
2515
</listitem>
2516
2517
<listitem>
2518
<literal>timedout</literal> — Flag indicating that the event timer has expired.
2519
</listitem>
2520
2521
<listitem>
2522
<literal>eof</literal> — Flag indicating that EOF occurred while reading data.
2523
</listitem>
2524
2525
<listitem>
2526
<literal>pending_eof</literal> — Flag indicating that EOF is pending on the
2527
socket, even though there may be some data available before it.
2528
The flag is delivered via the <literal>EPOLLRDHUP</literal>
2529
<literal>epoll</literal> event or
2530
<literal>EV_EOF</literal> <literal>kqueue</literal> flag.
2531
</listitem>
2532
2533
<listitem>
2534
<literal>error</literal> — Flag indicating that an error occurred during
2535
reading (for a read event) or writing (for a write event).
2536
</listitem>
2537
2538
<listitem>
2539
<literal>cancelable</literal> — Timer event flag indicating that the event
2540
should be ignored while shutting down the worker.
2541
Graceful worker shutdown is delayed until there are no non-cancelable timer
2542
events scheduled.
2543
</listitem>
2544
2545
<listitem>
2546
<literal>posted</literal> — Flag indicating that the event is posted to a queue.
2547
</listitem>
2548
2549
<listitem>
2550
<literal>queue</literal> — Queue node for posting the event to a queue.
2551
</listitem>
2552
2553
</list>
2554
</para>
2555
2556
</section>
2557
2558
2559
<section name="I/O events" id="i_o_events">
2560
2561
<para>
2562
Each connection obtained by calling the <literal>ngx_get_connection()</literal>
2563
function has two attached events, <literal>c->read</literal> and
2564
<literal>c->write</literal>, which are used for receiving notification that the
2565
socket is ready for reading or writing.
2566
All such events operate in Edge-Triggered mode, meaning that they only trigger
2567
notifications when the state of the socket changes.
2568
For example, doing a partial read on a socket does not make nginx deliver a
2569
repeated read notification until more data arrives on the socket.
2570
Even when the underlying I/O notification mechanism is essentially
2571
Level-Triggered (<literal>poll</literal>, <literal>select</literal> etc), nginx
2572
converts the notifications to Edge-Triggered.
2573
To make nginx event notifications consistent across all notifications systems
2574
on different platforms, the functions
2575
<literal>ngx_handle_read_event(rev, flags)</literal> and
2576
<literal>ngx_handle_write_event(wev, lowat)</literal> must be called after
2577
handling an I/O socket notification or calling any I/O functions on that socket.
2578
Normally, the functions are called once at the end of each read or write
2579
event handler.
2580
</para>
2581
2582
</section>
2583
2584
2585
<section name="Timer events" id="timer_events">
2586
2587
<para>
2588
An event can be set to send a notification when a timeout expires.
2589
The timer used by events counts milliseconds since some unspecified point
2590
in the past truncated to <literal>ngx_msec_t</literal> type.
2591
Its current value can be obtained from the <literal>ngx_current_msec</literal>
2592
variable.
2593
</para>
2594
2595
<para>
2596
The function <literal>ngx_add_timer(ev, timer)</literal> sets a timeout for an
2597
event, <literal>ngx_del_timer(ev)</literal> deletes a previously set timeout.
2598
The global timeout red-black tree <literal>ngx_event_timer_rbtree</literal>
2599
stores all timeouts currently set.
2600
The key in the tree is of type <literal>ngx_msec_t</literal> and is the time
2601
when the event occurs.
2602
The tree structure enables fast insertion and deletion operations, as well as
2603
access to the nearest timeouts, which nginx uses to find out how long to wait
2604
for I/O events and for expiring timeout events.
2605
</para>
2606
2607
</section>
2608
2609
2610
<section name="Posted events" id="posted_events">
2611
2612
<para>
2613
An event can be posted which means that its handler will be called at some
2614
point later within the current event loop iteration.
2615
Posting events is a good practice for simplifying code and escaping stack
2616
overflows.
2617
Posted events are held in a post queue.
2618
The <literal>ngx_post_event(ev, q)</literal> macro posts the event
2619
<literal>ev</literal> to the post queue <literal>q</literal>.
2620
The <literal>ngx_delete_posted_event(ev)</literal> macro deletes the event
2621
<literal>ev</literal> from the queue it's currently posted in.
2622
Normally, events are posted to the <literal>ngx_posted_events</literal> queue,
2623
which is processed late in the event loop — after all I/O and timer
2624
events are already handled.
2625
The function <literal>ngx_event_process_posted()</literal> is called to process
2626
an event queue.
2627
It calls event handlers until the queue is empty.
2628
This means that a posted event handler can post more events to be processed
2629
within the current event loop iteration.
2630
</para>
2631
2632
<para>
2633
An example:
2634
</para>
2635
2636
2637
<programlisting>
2638
void
2639
ngx_my_connection_read(ngx_connection_t *c)
2640
{
2641
ngx_event_t *rev;
2642
2643
rev = c->read;
2644
2645
ngx_add_timer(rev, 1000);
2646
2647
rev->handler = ngx_my_read_handler;
2648
2649
ngx_my_read(rev);
2650
}
2651
2652
2653
void
2654
ngx_my_read_handler(ngx_event_t *rev)
2655
{
2656
ssize_t n;
2657
ngx_connection_t *c;
2658
u_char buf[256];
2659
2660
if (rev->timedout) { /* timeout expired */ }
2661
2662
c = rev->data;
2663
2664
while (rev->ready) {
2665
n = c->recv(c, buf, sizeof(buf));
2666
2667
if (n == NGX_AGAIN) {
2668
break;
2669
}
2670
2671
if (n == NGX_ERROR) { /* error */ }
2672
2673
/* process buf */
2674
}
2675
2676
if (ngx_handle_read_event(rev, 0) != NGX_OK) { /* error */ }
2677
}
2678
</programlisting>
2679
2680
</section>
2681
2682
2683
<section name="Event loop" id="event_loop">
2684
2685
<para>
2686
Except for the nginx master process, all nginx processes do I/O and so have an
2687
event loop.
2688
(The nginx master process instead spends most of its time in the
2689
<literal>sigsuspend()</literal> call waiting for signals to arrive.)
2690
The nginx event loop is implemented in the
2691
<literal>ngx_process_events_and_timers()</literal> function, which is called
2692
repeatedly until the process exits.
2693
</para>
2694
2695
<para>
2696
The event loop has the following stages:
2697
2698
<list type="bullet">
2699
2700
<listitem>
2701
Find the timeout that is closest to expiring, by calling
2702
<literal>ngx_event_find_timer()</literal>.
2703
This function finds the leftmost node in the timer tree and returns the
2704
number of milliseconds until the node expires.
2705
</listitem>
2706
2707
<listitem>
2708
Process I/O events by calling a handler, specific to the event notification
2709
mechanism, chosen by nginx configuration.
2710
This handler waits for at least one I/O event to happen, but only until the next
2711
timeout expires.
2712
When a read or write event occurs, the <literal>ready</literal>
2713
flag is set and the event's handler is called.
2714
For Linux, the <literal>ngx_epoll_process_events()</literal> handler
2715
is normally used, which calls <literal>epoll_wait()</literal> to wait for I/O
2716
events.
2717
</listitem>
2718
2719
<listitem>
2720
Expire timers by calling <literal>ngx_event_expire_timers()</literal>.
2721
The timer tree is iterated from the leftmost element to the right until an
2722
unexpired timeout is found.
2723
For each expired node the <literal>timedout</literal> event flag is set,
2724
the <literal>timer_set</literal> flag is reset, and the event handler is called
2725
</listitem>
2726
2727
<listitem>
2728
Process posted events by calling <literal>ngx_event_process_posted()</literal>.
2729
The function repeatedly removes the first element from the posted events
2730
queue and calls the element's handler, until the queue is empty.
2731
</listitem>
2732
2733
</list>
2734
</para>
2735
2736
<para>
2737
All nginx processes handle signals as well.
2738
Signal handlers only set global variables which are checked after the
2739
<literal>ngx_process_events_and_timers()</literal> call.
2740
</para>
2741
2742
</section>
2743
2744
2745
</section>
2746
2747
2748
<section name="Processes" id="processes">
2749
2750
<para>
2751
There are several types of processes in nginx.
2752
The type of a process is kept in the <literal>ngx_process</literal>
2753
global variable, and is one of the following:
2754
</para>
2755
2756
<list type="bullet">
2757
2758
<listitem>
2759
2760
<para>
2761
<literal>NGX_PROCESS_MASTER</literal> — The master process, which reads the
2762
NGINX configuration, creates cycles, and starts and controls child processes.
2763
It does not perform any I/O and responds only to signals.
2764
Its cycle function is <literal>ngx_master_process_cycle()</literal>.
2765
</para>
2766
2767
2768
</listitem>
2769
2770
<listitem>
2771
2772
<para>
2773
<literal>NGX_PROCESS_WORKER</literal> — The worker process, which handles client
2774
connections.
2775
It is started by the master process and responds to its signals and channel
2776
commands as well.
2777
Its cycle function is <literal>ngx_worker_process_cycle()</literal>.
2778
There can be multiple worker processes, as configured by the
2779
<literal>worker_processes</literal> directive.
2780
</para>
2781
2782
</listitem>
2783
2784
<listitem>
2785
2786
<para>
2787
<literal>NGX_PROCESS_SINGLE</literal> — The single process, which exists only in
2788
<literal>master_process off</literal> mode, and is the only process running in
2789
that mode.
2790
It creates cycles (like the master process does) and handles client connections
2791
(like the worker process does).
2792
Its cycle function is <literal>ngx_single_process_cycle()</literal>.
2793
</para>
2794
2795
</listitem>
2796
2797
<listitem>
2798
2799
<para>
2800
<literal>NGX_PROCESS_HELPER</literal> — The helper process, of which currently
2801
there are two types: cache manager and cache loader.
2802
The cycle function for both is
2803
<literal>ngx_cache_manager_process_cycle()</literal>.
2804
</para>
2805
2806
</listitem>
2807
2808
</list>
2809
2810
<para>
2811
The nginx processes handle the following signals:
2812
</para>
2813
2814
<list type="bullet">
2815
2816
<listitem>
2817
2818
<para>
2819
<literal>NGX_SHUTDOWN_SIGNAL</literal> (<literal>SIGQUIT</literal> on most
2820
systems) — Gracefully shutdown.
2821
Upon receiving this signal, the master process sends a shutdown signal to all
2822
child processes.
2823
When no child processes are left, the master destroys the cycle pool and exits.
2824
When a worker process receives this signal, it closes all listening sockets and
2825
waits until there are no non-cancelable events scheduled, then destroys the
2826
cycle pool and exits.
2827
When the cache manager or the cache loader process receives this signal, it
2828
exits immediately.
2829
The <literal>ngx_quit</literal> variable is set to <literal>1</literal> when a
2830
process receives this signal, and is immediately reset after being processed.
2831
The <literal>ngx_exiting</literal> variable is set to <literal>1</literal> while
2832
a worker process is in the shutdown state.
2833
</para>
2834
2835
</listitem>
2836
2837
<listitem>
2838
2839
<para>
2840
<literal>NGX_TERMINATE_SIGNAL</literal> (<literal>SIGTERM</literal> on most
2841
systems) — Terminate.
2842
Upon receiving this signal, the master process sends a terminate signal to all
2843
child processes.
2844
If a child process does not exit within 1 second, the master process sends the
2845
<literal>SIGKILL</literal> signal to kill it.
2846
When no child processes are left, the master process destroys the cycle pool and
2847
exits.
2848
When a worker process, the cache manager process or the cache loader process
2849
receives this signal, it destroys the cycle pool and exits.
2850
The variable <literal>ngx_terminate</literal> is set to <literal>1</literal>
2851
when this signal is received.
2852
</para>
2853
2854
</listitem>
2855
2856
<listitem>
2857
2858
<para>
2859
<literal>NGX_NOACCEPT_SIGNAL</literal> (<literal>SIGWINCH</literal> on most
2860
systems) - Shut down all worker and helper processes.
2861
Upon receiving this signal, the master process shuts down its child processes.
2862
If a previously started new nginx binary exits, the child processes of the old
2863
master are started again.
2864
When a worker process receives this signal, it shuts down in debug mode
2865
set by the <literal>debug_points</literal> directive.
2866
</para>
2867
2868
2869
</listitem>
2870
2871
<listitem>
2872
2873
<para>
2874
<literal>NGX_RECONFIGURE_SIGNAL</literal> (<literal>SIGHUP</literal> on most
2875
systems) - Reconfigure.
2876
Upon receiving this signal, the master process re-reads the configuration and
2877
creates a new cycle based on it.
2878
If the new cycle is created successfully, the old cycle is deleted and new
2879
child processes are started.
2880
Meanwhile, the old child processes receive the
2881
<literal>NGX_SHUTDOWN_SIGNAL</literal> signal.
2882
In single-process mode, nginx creates a new cycle, but keeps the old one until
2883
there are no longer clients with active connections tied to it.
2884
The worker and helper processes ignore this signal.
2885
</para>
2886
2887
</listitem>
2888
2889
<listitem>
2890
2891
<para>
2892
<literal>NGX_REOPEN_SIGNAL</literal> (<literal>SIGUSR1</literal> on most
2893
systems) — Reopen files.
2894
The master process sends this signal to workers, which reopen all
2895
<literal>open_files</literal> related to the cycle.
2896
</para>
2897
2898
</listitem>
2899
2900
<listitem>
2901
2902
<para>
2903
<literal>NGX_CHANGEBIN_SIGNAL</literal> (<literal>SIGUSR2</literal> on most
2904
systems) — Change the nginx binary.
2905
The master process starts a new nginx binary and passes in a list of all listen
2906
sockets.
2907
The text-format list, passed in the <literal>“NGINX”</literal> environment
2908
variable, consists of descriptor numbers separated with semicolons.
2909
The new nginx binary reads the <literal>“NGINX”</literal> variable and adds the
2910
sockets to its init cycle.
2911
Other processes ignore this signal.
2912
</para>
2913
2914
</listitem>
2915
2916
</list>
2917
2918
<para>
2919
While all nginx worker processes are able to receive and properly handle POSIX
2920
signals, the master process does not use the standard <literal>kill()</literal>
2921
syscall to pass signals to workers and helpers.
2922
Instead, nginx uses inter-process socket pairs which allow sending messages
2923
between all nginx processes.
2924
Currently, however, messages are only sent from the master to its children.
2925
The messages carry the standard signals.
2926
</para>
2927
2928
</section>
2929
2930
<section name="Threads" id="threads">
2931
2932
<para>
2933
It is possible to offload into a separate thread tasks that would otherwise
2934
block the nginx worker process.
2935
For example, nginx can be configured to use threads to perform
2936
<link doc="../http/ngx_http_core_module.xml" id="aio">file I/O</link>.
2937
Another use case is a library that doesn't have asynchronous interface
2938
and thus cannot be normally used with nginx.
2939
Keep in mind that the threads interface is a helper for the existing
2940
asynchronous approach to processing client connections, and by no means
2941
intended as a replacement.
2942
</para>
2943
2944
<para>
2945
To deal with synchronization, the following wrappers over
2946
<literal>pthreads</literal> primitives are available:
2947
2948
<list type="bullet">
2949
2950
<listitem>
2951
<literal>typedef pthread_mutex_t ngx_thread_mutex_t;</literal>
2952
2953
<list type="bullet">
2954
2955
<listitem>
2956
<literal>ngx_int_t
2957
ngx_thread_mutex_create(ngx_thread_mutex_t *mtx, ngx_log_t *log);</literal>
2958
</listitem>
2959
2960
<listitem>
2961
<literal>ngx_int_t
2962
ngx_thread_mutex_destroy(ngx_thread_mutex_t *mtx, ngx_log_t *log);</literal>
2963
</listitem>
2964
2965
<listitem>
2966
<literal>ngx_int_t
2967
ngx_thread_mutex_lock(ngx_thread_mutex_t *mtx, ngx_log_t *log);</literal>
2968
</listitem>
2969
2970
<listitem>
2971
<literal>ngx_int_t
2972
ngx_thread_mutex_unlock(ngx_thread_mutex_t *mtx, ngx_log_t *log);</literal>
2973
</listitem>
2974
2975
</list>
2976
2977
</listitem>
2978
2979
<listitem>
2980
<literal>typedef pthread_cond_t ngx_thread_cond_t;</literal>
2981
2982
<list type="bullet">
2983
2984
<listitem>
2985
<literal>ngx_int_t
2986
ngx_thread_cond_create(ngx_thread_cond_t *cond, ngx_log_t *log);</literal>
2987
</listitem>
2988
2989
<listitem>
2990
<literal>ngx_int_t
2991
ngx_thread_cond_destroy(ngx_thread_cond_t *cond, ngx_log_t *log);</literal>
2992
</listitem>
2993
2994
<listitem>
2995
<literal>ngx_int_t
2996
ngx_thread_cond_signal(ngx_thread_cond_t *cond, ngx_log_t *log);</literal>
2997
</listitem>
2998
2999
<listitem>
3000
<literal>ngx_int_t
3001
ngx_thread_cond_wait(ngx_thread_cond_t *cond, ngx_thread_mutex_t *mtx,
3002
ngx_log_t *log);</literal>
3003
</listitem>
3004
3005
</list>
3006
3007
</listitem>
3008
3009
</list>
3010
3011
</para>
3012
3013
<para>
3014
Instead of creating a new thread for each task, nginx implements
3015
a <link doc="../ngx_core_module.xml" id="thread_pool"/> strategy.
3016
Multiple thread pools may be configured for different purposes
3017
(for example, performing I/O on different sets of disks).
3018
Each thread pool is created at startup and contains a limited number of threads
3019
that process a queue of tasks.
3020
When a task is completed, a predefined completion handler is called.
3021
</para>
3022
3023
<para>
3024
The <literal>src/core/ngx_thread_pool.h</literal> header file contains
3025
relevant definitions:
3026
<programlisting>
3027
struct ngx_thread_task_s {
3028
ngx_thread_task_t *next;
3029
ngx_uint_t id;
3030
void *ctx;
3031
void (*handler)(void *data, ngx_log_t *log);
3032
ngx_event_t event;
3033
};
3034
3035
typedef struct ngx_thread_pool_s ngx_thread_pool_t;
3036
3037
ngx_thread_pool_t *ngx_thread_pool_add(ngx_conf_t *cf, ngx_str_t *name);
3038
ngx_thread_pool_t *ngx_thread_pool_get(ngx_cycle_t *cycle, ngx_str_t *name);
3039
3040
ngx_thread_task_t *ngx_thread_task_alloc(ngx_pool_t *pool, size_t size);
3041
ngx_int_t ngx_thread_task_post(ngx_thread_pool_t *tp, ngx_thread_task_t *task);
3042
3043
</programlisting>
3044
At configuration time, a module willing to use threads has to obtain a
3045
reference to a thread pool by calling
3046
<literal>ngx_thread_pool_add(cf, name)</literal>, which either creates a
3047
new thread pool with the given <literal>name</literal> or returns a reference
3048
to the pool with that name if it already exists.
3049
</para>
3050
3051
<para>
3052
To add a <literal>task</literal> into a queue of a specified thread pool
3053
<literal>tp</literal> at runtime, use the
3054
<literal>ngx_thread_task_post(tp, task)</literal> function.
3055
3056
To execute a function in a thread, pass parameters and setup a completion
3057
handler using the <literal>ngx_thread_task_t</literal> structure:
3058
<programlisting>
3059
typedef struct {
3060
int foo;
3061
} my_thread_ctx_t;
3062
3063
3064
static void
3065
my_thread_func(void *data, ngx_log_t *log)
3066
{
3067
my_thread_ctx_t *ctx = data;
3068
3069
/* this function is executed in a separate thread */
3070
}
3071
3072
3073
static void
3074
my_thread_completion(ngx_event_t *ev)
3075
{
3076
my_thread_ctx_t *ctx = ev->data;
3077
3078
/* executed in nginx event loop */
3079
}
3080
3081
3082
ngx_int_t
3083
my_task_offload(my_conf_t *conf)
3084
{
3085
my_thread_ctx_t *ctx;
3086
ngx_thread_task_t *task;
3087
3088
task = ngx_thread_task_alloc(conf->pool, sizeof(my_thread_ctx_t));
3089
if (task == NULL) {
3090
return NGX_ERROR;
3091
}
3092
3093
ctx = task->ctx;
3094
3095
ctx->foo = 42;
3096
3097
task->handler = my_thread_func;
3098
task->event.handler = my_thread_completion;
3099
task->event.data = ctx;
3100
3101
if (ngx_thread_task_post(conf->thread_pool, task) != NGX_OK) {
3102
return NGX_ERROR;
3103
}
3104
3105
return NGX_OK;
3106
}
3107
</programlisting>
3108
3109
</para>
3110
3111
</section>
3112
3113
3114
<section name="Modules" id="Modules">
3115
3116
<section name="Adding new modules" id="adding_new_modules">
3117
<para>
3118
Each standalone nginx module resides in a separate directory that contains
3119
at least two files:
3120
<literal>config</literal> and a file with the module source code.
3121
The <literal>config</literal> file contains all information needed for nginx to
3122
integrate the module, for example:
3123
<programlisting>
3124
ngx_module_type=CORE
3125
ngx_module_name=ngx_foo_module
3126
ngx_module_srcs="$ngx_addon_dir/ngx_foo_module.c"
3127
3128
. auto/module
3129
3130
ngx_addon_name=$ngx_module_name
3131
</programlisting>
3132
The <literal>config</literal> file is a POSIX shell script that can set
3133
and access the following variables:
3134
<list type="bullet">
3135
3136
<listitem>
3137
<literal>ngx_module_type</literal> — Type of module to build.
3138
Possible values are <literal>CORE</literal>, <literal>HTTP</literal>,
3139
<literal>HTTP_FILTER</literal>, <literal>HTTP_INIT_FILTER</literal>,
3140
<literal>HTTP_AUX_FILTER</literal>, <literal>MAIL</literal>,
3141
<literal>STREAM</literal>, or <literal>MISC</literal>.
3142
</listitem>
3143
3144
<listitem>
3145
<literal>ngx_module_name</literal> — Module names.
3146
To build multiple modules from a set of source files, specify a
3147
whitespace-separated list of names.
3148
The first name indicates the name of the output binary for the dynamic module.
3149
The names in the list must match the names used in the source code.
3150
</listitem>
3151
3152
<listitem>
3153
<literal>ngx_addon_name</literal> — Name of the module as it appears in output
3154
on the console from the configure script.
3155
</listitem>
3156
3157
<listitem>
3158
<literal>ngx_module_srcs</literal> — Whitespace-separated list of source
3159
files used to compile the module.
3160
The <literal>$ngx_addon_dir</literal> variable can be used to represent the path
3161
to the module directory.
3162
</listitem>
3163
3164
<listitem>
3165
<literal>ngx_module_incs</literal> — Include paths required to build the module
3166
</listitem>
3167
3168
<listitem>
3169
<literal>ngx_module_deps</literal> — Whitespace-separated list of the module's
3170
dependencies.
3171
Usually, it is the list of header files.
3172
</listitem>
3173
3174
<listitem>
3175
<literal>ngx_module_libs</literal> — Whitespace-separated list of libraries to
3176
link with the module.
3177
For example, use <literal>ngx_module_libs=-lpthread</literal> to link
3178
<literal>libpthread</literal> library.
3179
The following macros can be used to link against the same libraries as
3180
nginx:
3181
<literal>LIBXSLT</literal>, <literal>LIBGD</literal>, <literal>GEOIP</literal>,
3182
<literal>PCRE</literal>, <literal>OPENSSL</literal>, <literal>MD5</literal>,
3183
<literal>SHA1</literal>, <literal>ZLIB</literal>, and <literal>PERL</literal>.
3184
</listitem>
3185
3186
<listitem>
3187
<literal>ngx_module_link</literal> — Variable set by the build system to
3188
<literal>DYNAMIC</literal> for a dynamic module or <literal>ADDON</literal>
3189
for a static module and used to determine different actions to perform
3190
depending on linking type.
3191
</listitem>
3192
3193
<listitem>
3194
<literal>ngx_module_order</literal> — Load order for the module;
3195
useful for the <literal>HTTP_FILTER</literal> and
3196
<literal>HTTP_AUX_FILTER</literal> module types.
3197
The format for this option is a whitespace-separated list of modules.
3198
All modules in the list following the current module's name end up after it in
3199
the global list of modules, which sets up the order for modules initialization.
3200
For filter modules later initialization means earlier execution.
3201
3202
<para>
3203
The following modules are typically used as references.
3204
The <literal>ngx_http_copy_filter_module</literal> reads the data for other
3205
filter modules and is placed near the bottom of the list so that it is one of
3206
the first to be executed.
3207
The <literal>ngx_http_write_filter_module</literal> writes the data to the
3208
client socket and is placed near the top of the list, and is the last to be
3209
executed.
3210
</para>
3211
3212
<para>
3213
By default, filter modules are placed before the
3214
<literal>ngx_http_copy_filter</literal> in the module list so that the filter
3215
handler is executed after the copy filter handler.
3216
For other module types the default is the empty string.
3217
</para>
3218
3219
</listitem>
3220
3221
</list>
3222
3223
To compile a module into nginx statically, use the
3224
<literal>--add-module=/path/to/module</literal> argument to the configure
3225
script.
3226
To compile a module for later dynamic loading into nginx, use the
3227
<literal>--add-dynamic-module=/path/to/module</literal> argument.
3228
</para>
3229
3230
</section>
3231
3232
3233
<section name="Core Modules" id="core_modules">
3234
3235
<para>
3236
Modules are the building blocks of nginx, and most of its functionality is
3237
implemented as modules.
3238
The module source file must contain a global variable of type
3239
<literal>ngx_module_t</literal>, which is defined as follows:
3240
<programlisting>
3241
struct ngx_module_s {
3242
3243
/* private part is omitted */
3244
3245
void *ctx;
3246
ngx_command_t *commands;
3247
ngx_uint_t type;
3248
3249
ngx_int_t (*init_master)(ngx_log_t *log);
3250
3251
ngx_int_t (*init_module)(ngx_cycle_t *cycle);
3252
3253
ngx_int_t (*init_process)(ngx_cycle_t *cycle);
3254
ngx_int_t (*init_thread)(ngx_cycle_t *cycle);
3255
void (*exit_thread)(ngx_cycle_t *cycle);
3256
void (*exit_process)(ngx_cycle_t *cycle);
3257
3258
void (*exit_master)(ngx_cycle_t *cycle);
3259
3260
/* stubs for future extensions are omitted */
3261
};
3262
</programlisting>
3263
The omitted private part includes the module version and a signature and is
3264
filled using the predefined macro <literal>NGX_MODULE_V1</literal>.
3265
</para>
3266
3267
<para>
3268
Each module keeps its private data in the <literal>ctx</literal> field,
3269
recognizes the configuration directives, specified in the
3270
<literal>commands</literal> array, and can be invoked at certain stages of
3271
nginx lifecycle.
3272
The module lifecycle consists of the following events:
3273
3274
<list type="bullet">
3275
3276
<listitem>
3277
Configuration directive handlers are called as they appear
3278
in configuration files in the context of the master process.
3279
</listitem>
3280
3281
<listitem>
3282
After the configuration is parsed successfully, <literal>init_module</literal>
3283
handler is called in the context of the master process.
3284
The <literal>init_module</literal> handler is called in the master process each
3285
time a configuration is loaded.
3286
</listitem>
3287
3288
<listitem>
3289
The master process creates one or more worker processes and the
3290
<literal>init_process</literal> handler is called in each of them.
3291
</listitem>
3292
3293
<listitem>
3294
When a worker process receives the shutdown or terminate command from the
3295
master, it invokes the <literal>exit_process</literal> handler.
3296
</listitem>
3297
3298
<listitem>
3299
The master process calls the <literal>exit_master</literal> handler before
3300
exiting.
3301
</listitem>
3302
3303
</list>
3304
3305
Because threads are used in nginx only as a supplementary I/O facility with its
3306
own API, <literal>init_thread</literal> and <literal>exit_thread</literal>
3307
handlers are not currently called.
3308
There is also no <literal>init_master</literal> handler, because it would be
3309
unnecessary overhead.
3310
</para>
3311
3312
<para>
3313
The module <literal>type</literal> defines exactly what is stored in the
3314
<literal>ctx</literal> field.
3315
Its value is one of the following types:
3316
<list type="bullet">
3317
<listitem><literal>NGX_CORE_MODULE</literal></listitem>
3318
<listitem><literal>NGX_EVENT_MODULE</literal></listitem>
3319
<listitem><literal>NGX_HTTP_MODULE</literal></listitem>
3320
<listitem><literal>NGX_MAIL_MODULE</literal></listitem>
3321
<listitem><literal>NGX_STREAM_MODULE</literal></listitem>
3322
</list>
3323
The <literal>NGX_CORE_MODULE</literal> is the most basic and thus the most
3324
generic and most low-level type of module.
3325
The other module types are implemented on top of it and provide a more
3326
convenient way to deal with corresponding domains, like handling events or HTTP
3327
requests.
3328
</para>
3329
3330
<para>
3331
The set of core modules includes <literal>ngx_core_module</literal>,
3332
<literal>ngx_errlog_module</literal>, <literal>ngx_regex_module</literal>,
3333
<literal>ngx_thread_pool_module</literal> and
3334
<literal>ngx_openssl_module</literal> modules.
3335
The HTTP module, the stream module, the mail module and event modules are core
3336
modules too.
3337
The context of a core module is defined as:
3338
<programlisting>
3339
typedef struct {
3340
ngx_str_t name;
3341
void *(*create_conf)(ngx_cycle_t *cycle);
3342
char *(*init_conf)(ngx_cycle_t *cycle, void *conf);
3343
} ngx_core_module_t;
3344
</programlisting>
3345
where the <literal>name</literal> is a module name string,
3346
<literal>create_conf</literal> and <literal>init_conf</literal>
3347
are pointers to functions that create and initialize module configuration
3348
respectively.
3349
For core modules, nginx calls <literal>create_conf</literal> before parsing
3350
a new configuration and <literal>init_conf</literal> after all configuration
3351
is parsed successfully.
3352
The typical <literal>create_conf</literal> function allocates memory for the
3353
configuration and sets default values.
3354
</para>
3355
3356
<para>
3357
For example, a simplistic module called <literal>ngx_foo_module</literal> might
3358
look like this:
3359
<programlisting>
3360
/*
3361
* Copyright (C) Author.
3362
*/
3363
3364
3365
#include &lt;ngx_config.h&gt;
3366
#include &lt;ngx_core.h&gt;
3367
3368
3369
typedef struct {
3370
ngx_flag_t enable;
3371
} ngx_foo_conf_t;
3372
3373
3374
static void *ngx_foo_create_conf(ngx_cycle_t *cycle);
3375
static char *ngx_foo_init_conf(ngx_cycle_t *cycle, void *conf);
3376
3377
static char *ngx_foo_enable(ngx_conf_t *cf, void *post, void *data);
3378
static ngx_conf_post_t ngx_foo_enable_post = { ngx_foo_enable };
3379
3380
3381
static ngx_command_t ngx_foo_commands[] = {
3382
3383
{ ngx_string("foo_enabled"),
3384
NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_FLAG,
3385
ngx_conf_set_flag_slot,
3386
0,
3387
offsetof(ngx_foo_conf_t, enable),
3388
&amp;ngx_foo_enable_post },
3389
3390
ngx_null_command
3391
};
3392
3393
3394
static ngx_core_module_t ngx_foo_module_ctx = {
3395
ngx_string("foo"),
3396
ngx_foo_create_conf,
3397
ngx_foo_init_conf
3398
};
3399
3400
3401
ngx_module_t ngx_foo_module = {
3402
NGX_MODULE_V1,
3403
&amp;ngx_foo_module_ctx, /* module context */
3404
ngx_foo_commands, /* module directives */
3405
NGX_CORE_MODULE, /* module type */
3406
NULL, /* init master */
3407
NULL, /* init module */
3408
NULL, /* init process */
3409
NULL, /* init thread */
3410
NULL, /* exit thread */
3411
NULL, /* exit process */
3412
NULL, /* exit master */
3413
NGX_MODULE_V1_PADDING
3414
};
3415
3416
3417
static void *
3418
ngx_foo_create_conf(ngx_cycle_t *cycle)
3419
{
3420
ngx_foo_conf_t *fcf;
3421
3422
fcf = ngx_pcalloc(cycle->pool, sizeof(ngx_foo_conf_t));
3423
if (fcf == NULL) {
3424
return NULL;
3425
}
3426
3427
fcf->enable = NGX_CONF_UNSET;
3428
3429
return fcf;
3430
}
3431
3432
3433
static char *
3434
ngx_foo_init_conf(ngx_cycle_t *cycle, void *conf)
3435
{
3436
ngx_foo_conf_t *fcf = conf;
3437
3438
ngx_conf_init_value(fcf->enable, 0);
3439
3440
return NGX_CONF_OK;
3441
}
3442
3443
3444
static char *
3445
ngx_foo_enable(ngx_conf_t *cf, void *post, void *data)
3446
{
3447
ngx_flag_t *fp = data;
3448
3449
if (*fp == 0) {
3450
return NGX_CONF_OK;
3451
}
3452
3453
ngx_log_error(NGX_LOG_NOTICE, cf->log, 0, "Foo Module is enabled");
3454
3455
return NGX_CONF_OK;
3456
}
3457
</programlisting>
3458
</para>
3459
3460
</section>
3461
3462
3463
<section name="Configuration Directives" id="config_directives">
3464
3465
<para>
3466
The <literal>ngx_command_t</literal> type defines a single configuration
3467
directive.
3468
Each module that supports configuration provides an array of such structures
3469
that describe how to process arguments and what handlers to call:
3470
<programlisting>
3471
typedef struct ngx_command_s ngx_command_t;
3472
3473
struct ngx_command_s {
3474
ngx_str_t name;
3475
ngx_uint_t type;
3476
char *(*set)(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
3477
ngx_uint_t conf;
3478
ngx_uint_t offset;
3479
void *post;
3480
};
3481
</programlisting>
3482
Terminate the array with the special value <literal>ngx_null_command</literal>.
3483
The <literal>name</literal> is the name of a directive as it appears
3484
in the configuration file, for example "worker_processes" or "listen".
3485
The <literal>type</literal> is a bit-field of flags that specify the number of
3486
arguments the directive takes, its type, and the context in which it appears.
3487
The flags are:
3488
3489
<list type="bullet">
3490
3491
<listitem>
3492
<literal>NGX_CONF_NOARGS</literal> — Directive takes no arguments.
3493
</listitem>
3494
3495
<listitem>
3496
<literal>NGX_CONF_1MORE</literal> — Directive takes one or more arguments.
3497
</listitem>
3498
3499
<listitem>
3500
<literal>NGX_CONF_2MORE</literal> — Directive takes two or more arguments.
3501
</listitem>
3502
3503
<listitem>
3504
<literal>NGX_CONF_TAKE1</literal>..<literal>NGX_CONF_TAKE7</literal> 
3505
Directive takes exactly the indicated number of arguments.
3506
</listitem>
3507
3508
<listitem>
3509
<literal>NGX_CONF_TAKE12</literal>, <literal>NGX_CONF_TAKE13</literal>,
3510
<literal>NGX_CONF_TAKE23</literal>, <literal>NGX_CONF_TAKE123</literal>,
3511
<literal>NGX_CONF_TAKE1234</literal> — Directive may take different number of
3512
arguments.
3513
Options are limited to the given numbers.
3514
For example, <literal>NGX_CONF_TAKE12</literal> means it takes one or two
3515
arguments.
3516
</listitem>
3517
3518
</list>
3519
3520
The flags for directive types are:
3521
3522
<list type="bullet">
3523
3524
<listitem>
3525
<literal>NGX_CONF_BLOCK</literal> — Directive is a block, that is, it can
3526
contain other directives within its opening and closing braces, or even
3527
implement its own parser to handle contents inside.
3528
</listitem>
3529
3530
<listitem>
3531
<literal>NGX_CONF_FLAG</literal> — Directive takes a boolean value, either
3532
<literal>on</literal> or <literal>off</literal>.
3533
</listitem>
3534
3535
</list>
3536
3537
A directive's context defines where it may appear in the configuration:
3538
3539
<list type="bullet">
3540
3541
<listitem>
3542
<literal>NGX_MAIN_CONF</literal> — In the top level context.
3543
</listitem>
3544
3545
<listitem>
3546
<literal>NGX_HTTP_MAIN_CONF</literal> — In the <literal>http</literal> block.
3547
</listitem>
3548
3549
<listitem>
3550
<literal>NGX_HTTP_SRV_CONF</literal> — In a <literal>server</literal> block
3551
within the <literal>http</literal> block.
3552
</listitem>
3553
3554
<listitem>
3555
<literal>NGX_HTTP_LOC_CONF</literal> — In a <literal>location</literal> block
3556
within the <literal>http</literal> block.
3557
</listitem>
3558
3559
<listitem>
3560
<literal>NGX_HTTP_UPS_CONF</literal> — In an <literal>upstream</literal> block
3561
within the <literal>http</literal> block.
3562
</listitem>
3563
3564
<listitem>
3565
<literal>NGX_HTTP_SIF_CONF</literal> — In an <literal>if</literal> block within
3566
a <literal>server</literal> block in the <literal>http</literal> block.
3567
</listitem>
3568
3569
<listitem>
3570
<literal>NGX_HTTP_LIF_CONF</literal> — In an <literal>if</literal> block within
3571
a <literal>location</literal> block in the <literal>http</literal> block.
3572
</listitem>
3573
3574
<listitem>
3575
<literal>NGX_HTTP_LMT_CONF</literal> — In a <literal>limit_except</literal>
3576
block within the <literal>http</literal> block.
3577
</listitem>
3578
3579
<listitem>
3580
<literal>NGX_STREAM_MAIN_CONF</literal> — In the <literal>stream</literal>
3581
block.
3582
</listitem>
3583
3584
<listitem>
3585
<literal>NGX_STREAM_SRV_CONF</literal> — In a <literal>server</literal> block
3586
within the <literal>stream</literal> block.
3587
</listitem>
3588
3589
<listitem>
3590
<literal>NGX_STREAM_UPS_CONF</literal> — In an <literal>upstream</literal> block
3591
within the <literal>stream</literal> block.
3592
</listitem>
3593
3594
<listitem>
3595
<literal>NGX_MAIL_MAIN_CONF</literal> — In the <literal>mail</literal> block.
3596
</listitem>
3597
3598
<listitem>
3599
<literal>NGX_MAIL_SRV_CONF</literal> — In a <literal>server</literal> block
3600
within the <literal>mail</literal> block.
3601
</listitem>
3602
3603
<listitem>
3604
<literal>NGX_EVENT_CONF</literal> — In the <literal>event</literal> block.
3605
</listitem>
3606
3607
<listitem>
3608
<literal>NGX_DIRECT_CONF</literal> — Used by modules that don't
3609
create a hierarchy of contexts and only have one global configuration.
3610
This configuration is passed to the handler as the <literal>conf</literal>
3611
argument.
3612
</listitem>
3613
</list>
3614
3615
The configuration parser uses these flags to throw an error in case of
3616
a misplaced directive and calls directive handlers supplied with a proper
3617
configuration pointer, so that the same directives in different locations can
3618
store their values in distinct places.
3619
</para>
3620
3621
<para>
3622
The <literal>set</literal> field defines a handler that processes a directive
3623
and stores parsed values into the corresponding configuration.
3624
There's a number of functions that perform common conversions:
3625
3626
<list type="bullet">
3627
3628
<listitem>
3629
<literal>ngx_conf_set_flag_slot</literal> — Converts the literal strings
3630
<literal>on</literal> and <literal>off</literal> into an
3631
<literal>ngx_flag_t</literal> value with values 1 or 0, respectively.
3632
</listitem>
3633
3634
<listitem>
3635
<literal>ngx_conf_set_str_slot</literal> — Stores a string as a value of the
3636
<literal>ngx_str_t</literal> type.
3637
</listitem>
3638
3639
<listitem>
3640
<literal>ngx_conf_set_str_array_slot</literal> — Appends a value to an array
3641
<literal>ngx_array_t</literal> of strings <literal>ngx_str_t</literal>.
3642
The array is created if does not already exist.
3643
</listitem>
3644
3645
<listitem>
3646
<literal>ngx_conf_set_keyval_slot</literal> — Appends a key-value pair to an
3647
array <literal>ngx_array_t</literal> of key-value pairs
3648
<literal>ngx_keyval_t</literal>.
3649
The first string becomes the key and the second the value.
3650
The array is created if it does not already exist.
3651
</listitem>
3652
3653
<listitem>
3654
<literal>ngx_conf_set_num_slot</literal> — Converts a directive's argument
3655
to an <literal>ngx_int_t</literal> value.
3656
</listitem>
3657
3658
<listitem>
3659
<literal>ngx_conf_set_size_slot</literal> — Converts a
3660
<link doc="../syntax.xml">size</link> to a <literal>size_t</literal> value
3661
expressed in bytes.
3662
</listitem>
3663
3664
<listitem>
3665
<literal>ngx_conf_set_off_slot</literal> — Converts an
3666
<link doc="../syntax.xml">offset</link> to an <literal>off_t</literal> value
3667
expressed in bytes.
3668
</listitem>
3669
3670
<listitem>
3671
<literal>ngx_conf_set_msec_slot</literal> — Converts a
3672
<link doc="../syntax.xml">time</link> to an <literal>ngx_msec_t</literal> value
3673
expressed in milliseconds.
3674
</listitem>
3675
3676
<listitem>
3677
<literal>ngx_conf_set_sec_slot</literal> — Converts a
3678
<link doc="../syntax.xml">time</link> to a <literal>time_t</literal> value
3679
expressed in in seconds.
3680
</listitem>
3681
3682
<listitem>
3683
<literal>ngx_conf_set_bufs_slot</literal> — Converts the two supplied arguments
3684
into an <literal>ngx_bufs_t</literal> object that holds the number and
3685
<link doc="../syntax.xml">size</link> of buffers.
3686
</listitem>
3687
3688
<listitem>
3689
<literal>ngx_conf_set_enum_slot</literal> — Converts the supplied argument
3690
into an <literal>ngx_uint_t</literal> value.
3691
The null-terminated array of <literal>ngx_conf_enum_t</literal> passed in the
3692
<literal>post</literal> field defines the acceptable strings and corresponding
3693
integer values.
3694
</listitem>
3695
3696
<listitem>
3697
<literal>ngx_conf_set_bitmask_slot</literal> — Converts the supplied arguments
3698
into an <literal>ngx_uint_t</literal> value.
3699
The mask values for each argument are ORed producing the result.
3700
The null-terminated array of <literal>ngx_conf_bitmask_t</literal> passed in the
3701
<literal>post</literal> field defines the acceptable strings and corresponding
3702
mask values.
3703
</listitem>
3704
3705
<listitem>
3706
<literal>set_path_slot</literal> — Converts the supplied arguments to an
3707
<literal>ngx_path_t</literal> value and performs all required initializations.
3708
For details, see the documentation for the
3709
<link doc="../http/ngx_http_proxy_module.xml" id="proxy_temp_path">
3710
proxy_temp_path</link> directive.
3711
</listitem>
3712
3713
<listitem>
3714
<literal>set_access_slot</literal> — Converts the supplied arguments to a file
3715
permissions mask.
3716
For details, see the documentation for the
3717
<link doc="../http/ngx_http_proxy_module.xml" id="proxy_store_access">
3718
proxy_store_access</link> directive.
3719
</listitem>
3720
3721
</list>
3722
3723
</para>
3724
3725
<para>
3726
The <literal>conf</literal> field defines which configuration structure is
3727
passed to the directory handler.
3728
Core modules only have the global configuration and set
3729
<literal>NGX_DIRECT_CONF</literal> flag to access it.
3730
Modules like HTTP, Stream or Mail create hierarchies of configurations.
3731
For example, a module's configuration is created for <literal>server</literal>,
3732
<literal>location</literal> and <literal>if</literal> scopes.
3733
3734
<list type="bullet">
3735
<listitem>
3736
<literal>NGX_HTTP_MAIN_CONF_OFFSET</literal> — Configuration for the
3737
<literal>http</literal> block.
3738
</listitem>
3739
3740
<listitem>
3741
<literal>NGX_HTTP_SRV_CONF_OFFSET</literal> — Configuration for a
3742
<literal>server</literal> block within the <literal>http</literal> block.
3743
</listitem>
3744
3745
<listitem>
3746
<literal>NGX_HTTP_LOC_CONF_OFFSET</literal> — Configuration for a
3747
<literal>location</literal> block within the <literal>http</literal>.
3748
</listitem>
3749
3750
<listitem>
3751
<literal>NGX_STREAM_MAIN_CONF_OFFSET</literal> — Configuration for the
3752
<literal>stream</literal> block.
3753
</listitem>
3754
3755
<listitem>
3756
<literal>NGX_STREAM_SRV_CONF_OFFSET</literal> — Configuration for a
3757
<literal>server</literal> block within the <literal>stream</literal> block.
3758
</listitem>
3759
3760
<listitem>
3761
<literal>NGX_MAIL_MAIN_CONF_OFFSET</literal> — Configuration for the
3762
<literal>mail</literal> block.
3763
</listitem>
3764
3765
<listitem>
3766
<literal>NGX_MAIL_SRV_CONF_OFFSET</literal> — Configuration for a
3767
<literal>server</literal> block within the <literal>mail</literal> block.
3768
</listitem>
3769
3770
</list>
3771
3772
</para>
3773
3774
<para>
3775
The <literal>offset</literal> defines the offset of a field in a module
3776
configuration structure that holds values for this particular directive.
3777
The typical use is to employ the <literal>offsetof()</literal> macro.
3778
</para>
3779
3780
<para>
3781
The <literal>post</literal> field has two purposes: it may be used to define
3782
a handler to be called after the main handler has completed, or to pass
3783
additional data to the main handler.
3784
In the first case, the <literal>ngx_conf_post_t</literal> structure needs to
3785
be initialized with a pointer to the handler, for example:
3786
<programlisting>
3787
static char *ngx_do_foo(ngx_conf_t *cf, void *post, void *data);
3788
static ngx_conf_post_t ngx_foo_post = { ngx_do_foo };
3789
</programlisting>
3790
The <literal>post</literal> argument is the <literal>ngx_conf_post_t</literal>
3791
object itself, and the <literal>data</literal> is a pointer to the value,
3792
converted from arguments by the main handler with the appropriate type.
3793
</para>
3794
3795
</section>
3796
3797
</section>
3798
3799
3800
<section name="HTTP" id="http">
3801
3802
3803
<section name="Connection" id="http_connection">
3804
3805
<para>
3806
Each HTTP client connection runs through the following stages:
3807
</para>
3808
3809
<list type="bullet">
3810
3811
<listitem>
3812
<literal>ngx_event_accept()</literal> accepts a client TCP connection.
3813
This handler is called in response to a read notification on a listen socket.
3814
A new <literal>ngx_connection_t</literal> object is created at this stage
3815
to wrap the newly accepted client socket.
3816
Each nginx listener provides a handler to pass the new connection object to.
3817
For HTTP connections it's <literal>ngx_http_init_connection(c)</literal>.
3818
</listitem>
3819
3820
<listitem>
3821
<literal>ngx_http_init_connection()</literal> performs early initialization of
3822
the HTTP connection.
3823
At this stage an <literal>ngx_http_connection_t</literal> object is created for
3824
the connection and its reference is stored in the connection's
3825
<literal>data</literal> field.
3826
Later it will be replaced by an HTTP request object.
3827
A PROXY protocol parser and the SSL handshake are started at
3828
this stage as well.
3829
</listitem>
3830
3831
<listitem>
3832
<literal>ngx_http_wait_request_handler()</literal> read event handler
3833
is called when data is available on the client socket.
3834
At this stage an HTTP request object <literal>ngx_http_request_t</literal> is
3835
created and set to the connection's <literal>data</literal> field.
3836
</listitem>
3837
3838
<listitem>
3839
<literal>ngx_http_process_request_line()</literal> read event handler
3840
reads client request line.
3841
The handler is set by <literal>ngx_http_wait_request_handler()</literal>.
3842
The data is read into connection's <literal>buffer</literal>.
3843
The size of the buffer is initially set by the directive
3844
<link doc="../http/ngx_http_core_module.xml" id="client_header_buffer_size"/>.
3845
The entire client header is supposed to fit in the buffer.
3846
If the initial size is not sufficient, a bigger buffer is allocated,
3847
with the capacity set by the <literal>large_client_header_buffers</literal>
3848
directive.
3849
</listitem>
3850
3851
<listitem>
3852
<literal>ngx_http_process_request_headers()</literal> read event handler,
3853
is set after <literal>ngx_http_process_request_line()</literal> to read
3854
the client request header.
3855
</listitem>
3856
3857
<listitem>
3858
<literal>ngx_http_core_run_phases()</literal> is called when the request header
3859
is completely read and parsed.
3860
This function runs request phases from
3861
<literal>NGX_HTTP_POST_READ_PHASE</literal> to
3862
<literal>NGX_HTTP_CONTENT_PHASE</literal>.
3863
The last phase is intended to generate a response and pass it along the filter
3864
chain.
3865
The response is not necessarily sent to the client at this phase.
3866
It might remain buffered and be sent at the finalization stage.
3867
</listitem>
3868
3869
<listitem>
3870
<literal>ngx_http_finalize_request()</literal> is usually called when the
3871
request has generated all the output or produced an error.
3872
In the latter case an appropriate error page is looked up and used as the
3873
response.
3874
If the response is not completely sent to the client by this point, an
3875
HTTP writer <literal>ngx_http_writer()</literal> is activated to finish
3876
sending outstanding data.
3877
</listitem>
3878
3879
<listitem>
3880
<literal>ngx_http_finalize_connection()</literal> is called when the complete
3881
response has been sent to the client and the request can be destroyed.
3882
If the client connection keepalive feature is enabled,
3883
<literal>ngx_http_set_keepalive()</literal> is called, which destroys the
3884
current request and waits for the next request on the connection.
3885
Otherwise, <literal>ngx_http_close_request()</literal> destroys both the
3886
request and the connection.
3887
</listitem>
3888
3889
</list>
3890
3891
</section>
3892
3893
3894
<section name="Request" id="http_request">
3895
3896
<para>
3897
For each client HTTP request the <literal>ngx_http_request_t</literal> object is
3898
created. Some of the fields of this object are:
3899
</para>
3900
3901
<list type="bullet">
3902
3903
<listitem>
3904
3905
<para>
3906
<literal>connection</literal> — Pointer to a <literal>ngx_connection_t</literal>
3907
client connection object.
3908
Several requests can reference the same connection object at the same time -
3909
one main request and its subrequests.
3910
After a request is deleted, a new request can be created on the same connection.
3911
</para>
3912
3913
<para>
3914
Note that for HTTP connections <literal>ngx_connection_t</literal>'s
3915
<literal>data</literal> field points back to the request.
3916
Such requests are called active, as opposed to the other requests tied to the
3917
connection.
3918
An active request is used to handle client connection events and is allowed to
3919
output its response to the client.
3920
Normally, each request becomes active at some point so that it can send its
3921
output.
3922
</para>
3923
3924
</listitem>
3925
3926
<listitem>
3927
3928
<para>
3929
<literal>ctx</literal> — Array of HTTP module contexts.
3930
Each module of type <literal>NGX_HTTP_MODULE</literal> can store any value
3931
(normally, a pointer to a structure) in the request.
3932
The value is stored in the <literal>ctx</literal> array at the module's
3933
<literal>ctx_index</literal> position.
3934
The following macros provide a convenient way to get and set request contexts:
3935
</para>
3936
3937
<list type="bullet">
3938
3939
<listitem>
3940
<literal>ngx_http_get_module_ctx(r, module)</literal> — Returns
3941
the <literal>module</literal>'s context
3942
</listitem>
3943
3944
<listitem>
3945
<literal>ngx_http_set_ctx(r, c, module)</literal> — Sets <literal>c</literal>
3946
as the <literal>module</literal>'s context
3947
</listitem>
3948
3949
</list>
3950
3951
</listitem>
3952
3953
<listitem>
3954
<literal>main_conf</literal>, <literal>srv_conf</literal>,
3955
<literal>loc_conf</literal> — Arrays of current request
3956
configurations.
3957
Configurations are stored at the module's <literal>ctx_index</literal>
3958
positions.
3959
</listitem>
3960
3961
<listitem>
3962
<literal>read_event_handler</literal>, <literal>write_event_handler</literal> -
3963
Read and write event handlers for the request.
3964
Normally, both the read and write event handlers for an HTTP connection
3965
are set to <literal>ngx_http_request_handler()</literal>.
3966
This function calls the <literal>read_event_handler</literal> and
3967
<literal>write_event_handler</literal> handlers for the currently
3968
active request.
3969
</listitem>
3970
3971
<listitem>
3972
<literal>cache</literal> — Request cache object for caching the
3973
upstream response.
3974
</listitem>
3975
3976
<listitem>
3977
<literal>upstream</literal> — Request upstream object for proxying.
3978
</listitem>
3979
3980
<listitem>
3981
<literal>pool</literal> — Request pool.
3982
The request object itself is allocated in this pool, which is destroyed when
3983
the request is deleted.
3984
For allocations that need to be available throughout the client connection's
3985
lifetime, use <literal>ngx_connection_t</literal>'s pool instead.
3986
</listitem>
3987
3988
<listitem>
3989
<literal>header_in</literal> — Buffer into which the client HTTP request
3990
header is read.
3991
</listitem>
3992
3993
<listitem>
3994
<literal>headers_in</literal>, <literal>headers_out</literal> — Input and
3995
output HTTP headers objects.
3996
Both objects contain the <literal>headers</literal> field of type
3997
<literal>ngx_list_t</literal> for keeping the raw list of headers.
3998
In addition to that, specific headers are available for getting and setting as
3999
separate fields, for example <literal>content_length_n</literal>,
4000
<literal>status</literal> etc.
4001
</listitem>
4002
4003
<listitem>
4004
<literal>request_body</literal> — Client request body object.
4005
</listitem>
4006
4007
<listitem>
4008
<literal>start_sec</literal>, <literal>start_msec</literal> — Time point when
4009
the request was created, used for tracking request duration.
4010
</listitem>
4011
4012
<listitem>
4013
<literal>method</literal>, <literal>method_name</literal> — Numeric and text
4014
representation of the client HTTP request method.
4015
Numeric values for methods are defined in
4016
<literal>src/http/ngx_http_request.h</literal> with the macros
4017
<literal>NGX_HTTP_GET</literal>, <literal>NGX_HTTP_HEAD</literal>,
4018
<literal>NGX_HTTP_POST</literal>, etc.
4019
</listitem>
4020
4021
<listitem>
4022
<literal>http_protocol</literal>  — Client HTTP protocol version in its
4023
original text form (“HTTP/1.0”, “HTTP/1.1” etc).
4024
</listitem>
4025
4026
<listitem>
4027
<literal>http_version</literal>  — Client HTTP protocol version in
4028
numeric form (<literal>NGX_HTTP_VERSION_10</literal>,
4029
<literal>NGX_HTTP_VERSION_11</literal>, etc.).
4030
</listitem>
4031
4032
<listitem>
4033
<literal>http_major</literal>, <literal>http_minor</literal>  — Client HTTP
4034
protocol version in numeric form split into major and minor parts.
4035
</listitem>
4036
4037
<listitem>
4038
<literal>request_line</literal>, <literal>unparsed_uri</literal> — Request line
4039
and URI in the original client request.
4040
</listitem>
4041
4042
<listitem>
4043
<literal>uri</literal>, <literal>args</literal>, <literal>exten</literal> 
4044
URI, arguments and file extension for the current request.
4045
The URI value here might differ from the original URI sent by the client due to
4046
normalization.
4047
Throughout request processing, these values can change as internal redirects
4048
are performed.
4049
</listitem>
4050
4051
<listitem>
4052
<literal>main</literal> — Pointer to a main request object.
4053
This object is created to process a client HTTP request, as opposed to
4054
subrequests, which are created to perform a specific subtask within the main
4055
request.
4056
</listitem>
4057
4058
<listitem>
4059
<literal>parent</literal> — Pointer to the parent request of a subrequest.
4060
</listitem>
4061
4062
<listitem>
4063
<literal>postponed</literal> — List of output buffers and subrequests, in the
4064
order in which they are sent and created.
4065
The list is used by the postpone filter to provide consistent request output
4066
when parts of it are created by subrequests.
4067
</listitem>
4068
4069
<listitem>
4070
<literal>post_subrequest</literal> — Pointer to a handler with the context
4071
to be called when a subrequest gets finalized.
4072
Unused for main requests.
4073
</listitem>
4074
4075
<listitem>
4076
4077
<para>
4078
<literal>posted_requests</literal> — List of requests to be started or
4079
resumed, which is done by calling the request's
4080
<literal>write_event_handler</literal>.
4081
Normally, this handler holds the request main function, which at first runs
4082
request phases and then produces the output.
4083
</para>
4084
4085
<para>
4086
A request is usually posted by the
4087
<literal>ngx_http_post_request(r, NULL)</literal> call.
4088
It is always posted to the main request <literal>posted_requests</literal> list.
4089
The function <literal>ngx_http_run_posted_requests(c)</literal> runs all
4090
requests that are posted in the main request of the passed
4091
connection's active request.
4092
All event handlers call <literal>ngx_http_run_posted_requests</literal>,
4093
which can lead to new posted requests.
4094
Normally, it is called after invoking a request's read or write handler.
4095
</para>
4096
4097
</listitem>
4098
4099
<listitem>
4100
<literal>phase_handler</literal> — Index of current request phase.
4101
</listitem>
4102
4103
<listitem>
4104
<literal>ncaptures</literal>, <literal>captures</literal>,
4105
<literal>captures_data</literal> — Regex captures produced
4106
by the last regex match of the request.
4107
A regex match can occur at a number of places during request processing:
4108
map lookup, server lookup by SNI or HTTP Host, rewrite, proxy_redirect, etc.
4109
Captures produced by a lookup are stored in the above mentioned fields.
4110
The field <literal>ncaptures</literal> holds the number of captures,
4111
<literal>captures</literal> holds captures boundaries and
4112
<literal>captures_data</literal> holds the string against which the regex was
4113
matched and which is used to extract captures.
4114
After each new regex match, request captures are reset to hold new values.
4115
</listitem>
4116
4117
<listitem>
4118
<literal>count</literal> — Request reference counter.
4119
The field only makes sense for the main request.
4120
Increasing the counter is done by simple <literal>r->main->count++</literal>.
4121
To decrease the counter, call
4122
<literal>ngx_http_finalize_request(r, rc)</literal>.
4123
Creating of a subrequest and running the request body read process both
4124
increment the counter.
4125
</listitem>
4126
4127
<listitem>
4128
<literal>subrequests</literal> — Current subrequest nesting level.
4129
Each subrequest inherits its parent's nesting level, decreased by one.
4130
An error is generated if the value reaches zero.
4131
The value for the main request is defined by the
4132
<literal>NGX_HTTP_MAX_SUBREQUESTS</literal> constant.
4133
</listitem>
4134
4135
<listitem>
4136
<literal>uri_changes</literal> — Number of URI changes remaining for
4137
the request.
4138
The total number of times a request can change its URI is limited by the
4139
<literal>NGX_HTTP_MAX_URI_CHANGES</literal> constant.
4140
With each change the value is decremented until it reaches zero, at which time
4141
an error is generated.
4142
Rewrites and internal redirects to normal or named locations are considered URI
4143
changes.
4144
</listitem>
4145
4146
<listitem>
4147
<literal>blocked</literal> — Counter of blocks held on the request.
4148
While this value is non-zero, the request cannot be terminated.
4149
Currently, this value is increased by pending AIO operations (POSIX AIO and
4150
thread operations) and active cache lock.
4151
</listitem>
4152
4153
<listitem>
4154
<literal>buffered</literal> — Bitmask showing which modules have buffered the
4155
output produced by the request.
4156
A number of filters can buffer output; for example, sub_filter can buffer data
4157
because of a partial string match, copy filter can buffer data because of the
4158
lack of free output buffers etc.
4159
As long as this value is non-zero, the request is not finalized
4160
pending the flush.
4161
</listitem>
4162
4163
<listitem>
4164
<literal>header_only</literal> — Flag indicating that the output does not
4165
require a body.
4166
For example, this flag is used by HTTP HEAD requests.
4167
</listitem>
4168
4169
<listitem>
4170
<para>
4171
<literal>keepalive</literal> — Flag indicating whether client connection
4172
keepalive is supported.
4173
The value is inferred from the HTTP version and the value of the
4174
<header>Connection</header> header.
4175
</para>
4176
</listitem>
4177
4178
<listitem>
4179
<literal>header_sent</literal> — Flag indicating that the output header
4180
has already been sent by the request.
4181
</listitem>
4182
4183
<listitem>
4184
<literal>internal</literal> — Flag indicating that the current request
4185
is internal.
4186
To enter the internal state, a request must pass through an internal
4187
redirect or be a subrequest.
4188
Internal requests are allowed to enter internal locations.
4189
</listitem>
4190
4191
<listitem>
4192
<literal>allow_ranges</literal> — Flag indicating that a partial response
4193
can be sent to the client, as requested by the HTTP Range header.
4194
</listitem>
4195
4196
<listitem>
4197
<literal>subrequest_ranges</literal> — Flag indicating that a partial response
4198
can be sent while a subrequest is being processed.
4199
</listitem>
4200
4201
<listitem>
4202
<literal>single_range</literal> — Flag indicating that only a single continuous
4203
range of output data can be sent to the client.
4204
This flag is usually set when sending a stream of data, for example from a
4205
proxied server, and the entire response is not available in one buffer.
4206
</listitem>
4207
4208
<listitem>
4209
<literal>main_filter_need_in_memory</literal>,
4210
<literal>filter_need_in_memory</literal> — Flags
4211
requesting that the output produced in memory buffers rather than files.
4212
This is a signal to the copy filter to read data from file buffers even if
4213
sendfile is enabled.
4214
The difference between the two flags is the location of the filter modules that
4215
set them.
4216
Filters called before the postpone filter in the filter chain set
4217
<literal>filter_need_in_memory</literal>, requesting that only the current
4218
request output come in memory buffers.
4219
Filters called later in the filter chain set
4220
<literal>main_filter_need_in_memory</literal>, requesting that
4221
both the main request and all subrequests read files in memory
4222
while sending output.
4223
</listitem>
4224
4225
<listitem>
4226
<literal>filter_need_temporary</literal> — Flag requesting that the request
4227
output be produced in temporary buffers, but not in readonly memory buffers or
4228
file buffers.
4229
This is used by filters which may change output directly in the buffers where
4230
it's sent.</listitem>
4231
4232
</list>
4233
4234
</section>
4235
4236
4237
<section name="Configuration" id="http_conf">
4238
4239
<para>
4240
Each HTTP module can have three types of configuration:
4241
</para>
4242
4243
<list type="bullet">
4244
4245
<listitem>
4246
Main configuration — Applies to the entire <literal>http</literal> block.
4247
Functions as global settings for a module.
4248
</listitem>
4249
4250
<listitem>
4251
Server configuration — Applies to a single <literal>server</literal> block.
4252
Functions as server-specific settings for a module.
4253
</listitem>
4254
4255
<listitem>
4256
Location configuration — Applies to a single <literal>location</literal>,
4257
<literal>if</literal> or <literal>limit_except</literal> block.
4258
Functions as location-specific settings for a module.
4259
</listitem>
4260
4261
</list>
4262
4263
<para>
4264
Configuration structures are created at the nginx configuration stage by
4265
calling functions, which allocate the structures, initialize them
4266
and merge them.
4267
The following example shows how to create a simple location
4268
configuration for a module.
4269
The configuration has one setting, <literal>foo</literal>, of type
4270
unsigned integer.
4271
</para>
4272
4273
<programlisting>
4274
typedef struct {
4275
ngx_uint_t foo;
4276
} ngx_http_foo_loc_conf_t;
4277
4278
4279
static ngx_http_module_t ngx_http_foo_module_ctx = {
4280
NULL, /* preconfiguration */
4281
NULL, /* postconfiguration */
4282
4283
NULL, /* create main configuration */
4284
NULL, /* init main configuration */
4285
4286
NULL, /* create server configuration */
4287
NULL, /* merge server configuration */
4288
4289
ngx_http_foo_create_loc_conf, /* create location configuration */
4290
ngx_http_foo_merge_loc_conf /* merge location configuration */
4291
};
4292
4293
4294
static void *
4295
ngx_http_foo_create_loc_conf(ngx_conf_t *cf)
4296
{
4297
ngx_http_foo_loc_conf_t *conf;
4298
4299
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_foo_loc_conf_t));
4300
if (conf == NULL) {
4301
return NULL;
4302
}
4303
4304
conf->foo = NGX_CONF_UNSET_UINT;
4305
4306
return conf;
4307
}
4308
4309
4310
static char *
4311
ngx_http_foo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
4312
{
4313
ngx_http_foo_loc_conf_t *prev = parent;
4314
ngx_http_foo_loc_conf_t *conf = child;
4315
4316
ngx_conf_merge_uint_value(conf->foo, prev->foo, 1);
4317
}
4318
</programlisting>
4319
4320
<para>
4321
As seen in the example, the <literal>ngx_http_foo_create_loc_conf()</literal>
4322
function creates a new configuration structure, and
4323
<literal>ngx_http_foo_merge_loc_conf()</literal> merges a configuration with
4324
configuration from a higher level.
4325
In fact, server and location configuration do not exist only at the server and
4326
location levels, but are also created for all levels above them.
4327
Specifically, a server configuration is also created at the main level and
4328
location configurations are created at the main, server, and location levels.
4329
These configurations make it possible to specify server- and location-specific
4330
settings at any level of an nginx configuration file.
4331
Eventually configurations are merged down.
4332
A number of macros like <literal>NGX_CONF_UNSET</literal> and
4333
<literal>NGX_CONF_UNSET_UINT</literal> are provided
4334
for indicating a missing setting and ignoring it while merging.
4335
Standard nginx merge macros like <literal>ngx_conf_merge_value()</literal> and
4336
<literal>ngx_conf_merge_uint_value()</literal> provide a convenient way to
4337
merge a setting and set the default value if none of the configurations
4338
provided an explicit value.
4339
For complete list of macros for different types, see
4340
<literal>src/core/ngx_conf_file.h</literal>.
4341
</para>
4342
4343
<para>
4344
The following macros are available.
4345
for accessing configuration for HTTP modules at configuration time.
4346
They all take <literal>ngx_conf_t</literal> reference as the first argument.
4347
</para>
4348
4349
<list type="bullet">
4350
4351
<listitem>
4352
<literal>ngx_http_conf_get_module_main_conf(cf, module)</literal>
4353
</listitem>
4354
4355
<listitem>
4356
<literal>ngx_http_conf_get_module_srv_conf(cf, module)</literal>
4357
</listitem>
4358
4359
<listitem>
4360
<literal>ngx_http_conf_get_module_loc_conf(cf, module)</literal>
4361
</listitem>
4362
4363
</list>
4364
4365
<para>
4366
The following example gets a pointer to a location configuration of
4367
standard nginx core module
4368
<link doc="../http/ngx_http_core_module.xml">ngx_http_core_module</link>
4369
and replaces the location content handler kept
4370
in the <literal>handler</literal> field of the structure.
4371
</para>
4372
4373
<programlisting>
4374
static ngx_int_t ngx_http_foo_handler(ngx_http_request_t *r);
4375
4376
4377
static ngx_command_t ngx_http_foo_commands[] = {
4378
4379
{ ngx_string("foo"),
4380
NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
4381
ngx_http_foo,
4382
0,
4383
0,
4384
NULL },
4385
4386
ngx_null_command
4387
};
4388
4389
4390
static char *
4391
ngx_http_foo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
4392
{
4393
ngx_http_core_loc_conf_t *clcf;
4394
4395
clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
4396
clcf->handler = ngx_http_bar_handler;
4397
4398
return NGX_CONF_OK;
4399
}
4400
</programlisting>
4401
4402
<para>
4403
The following macros are available for accessing configuration for HTTP
4404
modules at runtime.
4405
</para>
4406
4407
<list type="bullet">
4408
4409
<listitem>
4410
<literal>ngx_http_get_module_main_conf(r, module)</literal>
4411
</listitem>
4412
4413
<listitem>
4414
<literal>ngx_http_get_module_srv_conf(r, module)</literal>
4415
</listitem>
4416
4417
<listitem>
4418
<literal>ngx_http_get_module_loc_conf(r, module)</literal>
4419
</listitem>
4420
4421
</list>
4422
4423
<para>
4424
These macros receive a reference to an HTTP request
4425
<literal>ngx_http_request_t</literal>.
4426
The main configuration of a request never changes.
4427
Server configuration can change from the default after
4428
the virtual server for the request is chosen.
4429
Location configuration selected for processing a request can change multiple
4430
times as a result of a rewrite operation or internal redirect.
4431
The following example shows how to access a module's HTTP configuration at
4432
runtime.
4433
</para>
4434
4435
<programlisting>
4436
static ngx_int_t
4437
ngx_http_foo_handler(ngx_http_request_t *r)
4438
{
4439
ngx_http_foo_loc_conf_t *flcf;
4440
4441
flcf = ngx_http_get_module_loc_conf(r, ngx_http_foo_module);
4442
4443
...
4444
}
4445
</programlisting>
4446
4447
</section>
4448
4449
4450
<section name="Phases" id="http_phases">
4451
4452
<para>
4453
Each HTTP request passes through a sequence of phases.
4454
In each phase a distinct type of processing is performed on the request.
4455
Module-specific handlers can be registered in most phases,
4456
and many standard nginx modules register their phase handlers as a way
4457
to get called at a specific stage of request processing.
4458
Phases are processed successively and the phase handlers are called
4459
once the request reaches the phase.
4460
Following is the list of nginx HTTP phases.
4461
</para>
4462
4463
<list type="bullet">
4464
4465
<listitem>
4466
<literal>NGX_HTTP_POST_READ_PHASE</literal> — First phase.
4467
The <link doc="../http/ngx_http_realip_module.xml">ngx_http_realip_module</link>
4468
registers its handler at this phase to enable
4469
substitution of client addresses before any other module is invoked.
4470
</listitem>
4471
4472
<listitem>
4473
<literal>NGX_HTTP_SERVER_REWRITE_PHASE</literal> — Phase where
4474
rewrite directives defined in a <literal>server</literal> block
4475
(but outside a <literal>location</literal> block) are processed.
4476
The
4477
<link doc="../http/ngx_http_rewrite_module.xml">ngx_http_rewrite_module</link>
4478
installs its handler at this phase.
4479
</listitem>
4480
4481
<listitem>
4482
<literal>NGX_HTTP_FIND_CONFIG_PHASE</literal> — Special phase
4483
where a location is chosen based on the request URI.
4484
Before this phase, the default location for the relevant virtual server
4485
is assigned to the request, and any module requesting a location configuration
4486
receives the configuration for the default server location.
4487
This phase assigns a new location to the request.
4488
No additional handlers can be registered at this phase.
4489
</listitem>
4490
4491
<listitem>
4492
<literal>NGX_HTTP_REWRITE_PHASE</literal> — Same as
4493
<literal>NGX_HTTP_SERVER_REWRITE_PHASE</literal>, but for
4494
rewrite rules defined in the location, chosen in the previous phase.
4495
</listitem>
4496
4497
<listitem>
4498
<literal>NGX_HTTP_POST_REWRITE_PHASE</literal> — Special phase
4499
where the request is redirected to a new location if its URI changed
4500
during a rewrite.
4501
This is implemented by the request going through
4502
the <literal>NGX_HTTP_FIND_CONFIG_PHASE</literal> again.
4503
No additional handlers can be registered at this phase.
4504
</listitem>
4505
4506
<listitem>
4507
<literal>NGX_HTTP_PREACCESS_PHASE</literal> — A common phase for different
4508
types of handlers, not associated with access control.
4509
The standard nginx modules
4510
<link doc="../http/ngx_http_limit_conn_module.xml">ngx_http_limit_conn_module
4511
</link> and
4512
<link doc="../http/ngx_http_limit_req_module.xml">
4513
ngx_http_limit_req_module</link> register their handlers at this phase.
4514
</listitem>
4515
4516
<listitem>
4517
<literal>NGX_HTTP_ACCESS_PHASE</literal> — Phase where it is verified
4518
that the client is authorized to make the request.
4519
Standard nginx modules such as
4520
<link doc="../http/ngx_http_access_module.xml">ngx_http_access_module</link> and
4521
<link doc="../http/ngx_http_auth_basic_module.xml">ngx_http_auth_basic_module
4522
</link> register their handlers at this phase.
4523
By default the client must pass the authorization check of all handlers
4524
registered at this phase for the request to continue to the next phase.
4525
The <link doc="../http/ngx_http_core_module.xml" id="satisfy"/> directive,
4526
can be used to permit processing to continue if any of the phase handlers
4527
authorizes the client.
4528
</listitem>
4529
4530
<listitem>
4531
<literal>NGX_HTTP_POST_ACCESS_PHASE</literal> — Special phase where the
4532
<link doc="../http/ngx_http_core_module.xml" id="satisfy">satisfy any</link>
4533
directive is processed.
4534
If some access phase handlers denied access and none explicitly allowed it, the
4535
request is finalized.
4536
No additional handlers can be registered at this phase.
4537
</listitem>
4538
4539
<listitem>
4540
<literal>NGX_HTTP_PRECONTENT_PHASE</literal> — Phase for handlers to be called
4541
prior to generating content.
4542
Standard modules such as
4543
<link doc="../http/ngx_http_core_module.xml" id="try_files">
4544
ngx_http_try_files_module</link> and
4545
<link doc="../http/ngx_http_mirror_module.xml">ngx_http_mirror_module</link>
4546
register their handlers at this phase.
4547
</listitem>
4548
4549
<listitem>
4550
<literal>NGX_HTTP_CONTENT_PHASE</literal> — Phase where the response
4551
is normally generated.
4552
Multiple nginx standard modules register their handlers at this phase,
4553
including
4554
<link doc="../http/ngx_http_index_module.xml">ngx_http_index_module</link> or
4555
<literal>ngx_http_static_module</literal>.
4556
They are called sequentially until one of them produces
4557
the output.
4558
It's also possible to set content handlers on a per-location basis.
4559
If the
4560
<link doc="../http/ngx_http_core_module.xml">ngx_http_core_module</link>'s
4561
location configuration has <literal>handler</literal> set, it is
4562
called as the content handler and the handlers installed at this phase
4563
are ignored.
4564
</listitem>
4565
4566
<listitem>
4567
<literal>NGX_HTTP_LOG_PHASE</literal> — Phase where request logging
4568
is performed.
4569
Currently, only the
4570
<link doc="../http/ngx_http_log_module.xml">ngx_http_log_module</link>
4571
registers its handler
4572
at this stage for access logging.
4573
Log phase handlers are called at the very end of request processing, right
4574
before freeing the request.
4575
</listitem>
4576
4577
</list>
4578
4579
<para>
4580
Following is the example of a preaccess phase handler.
4581
</para>
4582
4583
<programlisting>
4584
static ngx_http_module_t ngx_http_foo_module_ctx = {
4585
NULL, /* preconfiguration */
4586
ngx_http_foo_init, /* postconfiguration */
4587
4588
NULL, /* create main configuration */
4589
NULL, /* init main configuration */
4590
4591
NULL, /* create server configuration */
4592
NULL, /* merge server configuration */
4593
4594
NULL, /* create location configuration */
4595
NULL /* merge location configuration */
4596
};
4597
4598
4599
static ngx_int_t
4600
ngx_http_foo_handler(ngx_http_request_t *r)
4601
{
4602
ngx_table_elt_t *ua;
4603
4604
ua = r->headers_in.user_agent;
4605
4606
if (ua == NULL) {
4607
return NGX_DECLINED;
4608
}
4609
4610
/* reject requests with "User-Agent: foo" */
4611
if (ua->value.len == 3 &amp;&amp; ngx_strncmp(ua->value.data, "foo", 3) == 0) {
4612
return NGX_HTTP_FORBIDDEN;
4613
}
4614
4615
return NGX_DECLINED;
4616
}
4617
4618
4619
static ngx_int_t
4620
ngx_http_foo_init(ngx_conf_t *cf)
4621
{
4622
ngx_http_handler_pt *h;
4623
ngx_http_core_main_conf_t *cmcf;
4624
4625
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
4626
4627
h = ngx_array_push(&amp;cmcf->phases[NGX_HTTP_PREACCESS_PHASE].handlers);
4628
if (h == NULL) {
4629
return NGX_ERROR;
4630
}
4631
4632
*h = ngx_http_foo_handler;
4633
4634
return NGX_OK;
4635
}
4636
</programlisting>
4637
4638
<para>
4639
Phase handlers are expected to return specific codes:
4640
</para>
4641
4642
<list type="bullet">
4643
4644
<listitem>
4645
<literal>NGX_OK</literal> — Proceed to the next phase.
4646
</listitem>
4647
4648
<listitem>
4649
<literal>NGX_DECLINED</literal> — Proceed to the next handler of the current
4650
phase.
4651
If the current handler is the last in the current phase,
4652
move to the next phase.
4653
</listitem>
4654
4655
<listitem>
4656
<literal>NGX_AGAIN</literal>, <literal>NGX_DONE</literal> — Suspend
4657
phase handling until some future event which can be
4658
an asynchronous I/O operation or just a delay, for example.
4659
It is assumed, that phase handling will be resumed later by calling
4660
<literal>ngx_http_core_run_phases()</literal>.
4661
</listitem>
4662
4663
<listitem>
4664
Any other value returned by the phase handler is treated as a request
4665
finalization code, in particular, an HTTP response code.
4666
The request is finalized with the code provided.
4667
</listitem>
4668
4669
</list>
4670
4671
<para>
4672
For some phases, return codes are treated in a slightly different way.
4673
At the content phase, any return code other that
4674
<literal>NGX_DECLINED</literal> is considered a finalization code.
4675
Any return code from the location content handlers is considered a
4676
finalization code.
4677
At the access phase, in
4678
<link doc="../http/ngx_http_core_module.xml" id="satisfy">satisfy any</link>
4679
mode,
4680
any return code other than <literal>NGX_OK</literal>,
4681
<literal>NGX_DECLINED</literal>, <literal>NGX_AGAIN</literal>,
4682
<literal>NGX_DONE</literal> is considered a denial.
4683
If no subsequent access handlers allow or deny access with a different
4684
code, the denial code will become the finalization code.
4685
</para>
4686
4687
</section>
4688
4689
4690
<section name="Variables" id="http_variables">
4691
4692
<section name="Accessing existing variables" id="http_existing_variables">
4693
4694
<para>
4695
Variables can be referenced by index (this is the most common method)
4696
or name (see <link id="http_creating_variables">below</link>).
4697
The index is created at configuration stage, when a variable is added
4698
to the configuration.
4699
To obtain the variable index, use
4700
<literal>ngx_http_get_variable_index()</literal>:
4701
<programlisting>
4702
ngx_str_t name; /* ngx_string("foo") */
4703
ngx_int_t index;
4704
4705
index = ngx_http_get_variable_index(cf, &amp;name);
4706
</programlisting>
4707
Here, <literal>cf</literal> is a pointer to nginx configuration and
4708
<literal>name</literal> points to a string containing the variable name.
4709
The function returns <literal>NGX_ERROR</literal> on error or a valid index
4710
otherwise, which is typically stored somewhere in the module's
4711
configuration for future use.
4712
</para>
4713
4714
<para>
4715
All HTTP variables are evaluated in the context of a given HTTP request,
4716
and results are specific to and cached in that HTTP request.
4717
All functions that evaluate variables return the
4718
<literal>ngx_http_variable_value_t</literal> type, representing
4719
the variable value:
4720
<programlisting>
4721
typedef ngx_variable_value_t ngx_http_variable_value_t;
4722
4723
typedef struct {
4724
unsigned len:28;
4725
4726
unsigned valid:1;
4727
unsigned no_cacheable:1;
4728
unsigned not_found:1;
4729
unsigned escape:1;
4730
4731
u_char *data;
4732
} ngx_variable_value_t;
4733
</programlisting>
4734
where:
4735
<list type="bullet">
4736
4737
<listitem>
4738
<literal>len</literal> — The length of the value
4739
</listitem>
4740
4741
<listitem>
4742
<literal>data</literal> — The value itself
4743
</listitem>
4744
4745
<listitem>
4746
<literal>valid</literal> — The value is valid
4747
</listitem>
4748
4749
<listitem>
4750
<literal>not_found</literal> — The variable was not found and thus
4751
the <literal>data</literal> and <literal>len</literal> fields are irrelevant;
4752
this can happen, for example, with variables like <var>$arg_foo</var>
4753
when a corresponding argument was not passed in a request
4754
</listitem>
4755
4756
<listitem>
4757
<literal>no_cacheable</literal> — Do not cache result
4758
</listitem>
4759
4760
<listitem>
4761
<literal>escape</literal> — Used internally by the logging module to mark
4762
values that require escaping on output.
4763
</listitem>
4764
4765
</list>
4766
</para>
4767
4768
<para>
4769
The <literal>ngx_http_get_flushed_variable()</literal>
4770
and <literal>ngx_http_get_indexed_variable()</literal> functions
4771
are used to obtain the value of a variable.
4772
They have the same interface - accepting an HTTP request <literal>r</literal>
4773
as a context for evaluating the variable and an <literal>index</literal>
4774
that identifies it.
4775
An example of typical usage:
4776
<programlisting>
4777
ngx_http_variable_value_t *v;
4778
4779
v = ngx_http_get_flushed_variable(r, index);
4780
4781
if (v == NULL || v->not_found) {
4782
/* we failed to get value or there is no such variable, handle it */
4783
return NGX_ERROR;
4784
}
4785
4786
/* some meaningful value is found */
4787
</programlisting>
4788
The difference between functions is that the
4789
<literal>ngx_http_get_indexed_variable()</literal> returns a cached value
4790
and <literal>ngx_http_get_flushed_variable()</literal> flushes the cache for
4791
non-cacheable variables.
4792
</para>
4793
4794
<para>
4795
Some modules, such as SSI and Perl, need to deal with variables for which the
4796
name is not known at configuration time.
4797
An index therefore cannot be used to access them, but the
4798
<literal>ngx_http_get_variable(r, name, key)</literal> function
4799
is available.
4800
It searches for a variable with a given
4801
<literal>name</literal> and its hash <literal>key</literal> derived
4802
from the name.
4803
</para>
4804
4805
</section>
4806
4807
4808
<section name="Creating variables" id="http_creating_variables">
4809
4810
<para>
4811
To create a variable, use the <literal>ngx_http_add_variable()</literal>
4812
function.
4813
It takes as arguments a configuration (where the variable is registered),
4814
the variable name and flags that control the function's behaviour:
4815
4816
<list type="bullet">
4817
<listitem><literal>NGX_HTTP_VAR_CHANGEABLE</literal> — Enables redefinition of
4818
the variable: there is no conflict if another module defines a variable with
4819
the same name.
4820
This allows the
4821
<link doc="../http/ngx_http_rewrite_module.xml" id="set"/> directive
4822
to override variables.
4823
</listitem>
4824
4825
<listitem><literal>NGX_HTTP_VAR_NOCACHEABLE</literal> — Disables caching,
4826
which is useful for variables such as <literal>$time_local</literal>.
4827
</listitem>
4828
4829
<listitem><literal>NGX_HTTP_VAR_NOHASH</literal> — Indicates that
4830
this variable is only accessible by index, not by name.
4831
This is a small optimization for use when it is known that the
4832
variable is not needed in modules like SSI or Perl.
4833
</listitem>
4834
4835
<listitem><literal>NGX_HTTP_VAR_PREFIX</literal> — The name of the
4836
variable is a prefix.
4837
In this case, a handler must implement additional logic to obtain the value
4838
of a specific variable.
4839
For example, all “<literal>arg_</literal>” variables are processed by the
4840
same handler, which performs lookup in request arguments and returns the value
4841
of a specific argument.
4842
</listitem>
4843
4844
</list>
4845
4846
The function returns NULL in case of error or a pointer to
4847
<literal>ngx_http_variable_t</literal> otherwise:
4848
<programlisting>
4849
struct ngx_http_variable_s {
4850
ngx_str_t name;
4851
ngx_http_set_variable_pt set_handler;
4852
ngx_http_get_variable_pt get_handler;
4853
uintptr_t data;
4854
ngx_uint_t flags;
4855
ngx_uint_t index;
4856
};
4857
</programlisting>
4858
4859
The <literal>get</literal> and <literal>set</literal> handlers
4860
are called to obtain or set the variable value,
4861
<literal>data</literal> is passed to variable handlers, and
4862
<literal>index</literal> holds assigned variable index used to reference
4863
the variable.
4864
</para>
4865
4866
<para>
4867
Usually, a null-terminated static array of
4868
<literal>ngx_http_variable_t</literal> structures is created
4869
by a module and processed at the preconfiguration stage to add variables
4870
into the configuration, for example:
4871
<programlisting>
4872
static ngx_http_variable_t ngx_http_foo_vars[] = {
4873
4874
{ ngx_string("foo_v1"), NULL, ngx_http_foo_v1_variable, 0, 0, 0 },
4875
4876
ngx_http_null_variable
4877
};
4878
4879
static ngx_int_t
4880
ngx_http_foo_add_variables(ngx_conf_t *cf)
4881
{
4882
ngx_http_variable_t *var, *v;
4883
4884
for (v = ngx_http_foo_vars; v->name.len; v++) {
4885
var = ngx_http_add_variable(cf, &amp;v->name, v->flags);
4886
if (var == NULL) {
4887
return NGX_ERROR;
4888
}
4889
4890
var->get_handler = v->get_handler;
4891
var->data = v->data;
4892
}
4893
4894
return NGX_OK;
4895
}
4896
</programlisting>
4897
This function in the example is used to initialize
4898
the <literal>preconfiguration</literal>
4899
field of the HTTP module context and is called before the parsing of HTTP
4900
configuration, so that the parser can refer to these variables.
4901
</para>
4902
4903
<para>
4904
The <literal>get</literal> handler is responsible for evaluating a variable
4905
in the context of a specific request, for example:
4906
<programlisting>
4907
static ngx_int_t
4908
ngx_http_variable_connection(ngx_http_request_t *r,
4909
ngx_http_variable_value_t *v, uintptr_t data)
4910
{
4911
u_char *p;
4912
4913
p = ngx_pnalloc(r->pool, NGX_ATOMIC_T_LEN);
4914
if (p == NULL) {
4915
return NGX_ERROR;
4916
}
4917
4918
v->len = ngx_sprintf(p, "%uA", r->connection->number) - p;
4919
v->valid = 1;
4920
v->no_cacheable = 0;
4921
v->not_found = 0;
4922
v->data = p;
4923
4924
return NGX_OK;
4925
}
4926
</programlisting>
4927
It returns <literal>NGX_ERROR</literal> in case of internal error
4928
(for example, failed memory allocation) or <literal>NGX_OK</literal> otherwise.
4929
To learn the status of variable evaluation, inspect the flags
4930
in <literal>ngx_http_variable_value_t</literal> (see the description
4931
<link id="http_existing_variables">above</link>).
4932
</para>
4933
4934
<para>
4935
The <literal>set</literal> handler allows setting the property
4936
referenced by the variable.
4937
For example, the set handler of the <literal>$limit_rate</literal> variable
4938
modifies the request's <literal>limit_rate</literal> field:
4939
<programlisting>
4940
...
4941
{ ngx_string("limit_rate"), ngx_http_variable_request_set_size,
4942
ngx_http_variable_request_get_size,
4943
offsetof(ngx_http_request_t, limit_rate),
4944
NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 },
4945
...
4946
4947
static void
4948
ngx_http_variable_request_set_size(ngx_http_request_t *r,
4949
ngx_http_variable_value_t *v, uintptr_t data)
4950
{
4951
ssize_t s, *sp;
4952
ngx_str_t val;
4953
4954
val.len = v->len;
4955
val.data = v->data;
4956
4957
s = ngx_parse_size(&amp;val);
4958
4959
if (s == NGX_ERROR) {
4960
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
4961
"invalid size \"%V\"", &amp;val);
4962
return;
4963
}
4964
4965
sp = (ssize_t *) ((char *) r + data);
4966
4967
*sp = s;
4968
4969
return;
4970
}
4971
</programlisting>
4972
4973
</para>
4974
4975
</section>
4976
4977
</section>
4978
4979
4980
<section name="Complex values" id="http_complex_values">
4981
4982
<para>
4983
A complex value, despite its name, provides an easy way to evaluate
4984
expressions which can contain text, variables, and their combination.
4985
</para>
4986
4987
<para>
4988
The complex value description in
4989
<literal>ngx_http_compile_complex_value</literal> is compiled at the
4990
configuration stage into <literal>ngx_http_complex_value_t</literal>
4991
which is used at runtime to obtain results of expression evaluation.
4992
4993
<programlisting>
4994
ngx_str_t *value;
4995
ngx_http_complex_value_t cv;
4996
ngx_http_compile_complex_value_t ccv;
4997
4998
value = cf->args->elts; /* directive arguments */
4999
5000
ngx_memzero(&amp;ccv, sizeof(ngx_http_compile_complex_value_t));
5001
5002
ccv.cf = cf;
5003
ccv.value = &amp;value[1];
5004
ccv.complex_value = &amp;cv;
5005
ccv.zero = 1;
5006
ccv.conf_prefix = 1;
5007
5008
if (ngx_http_compile_complex_value(&amp;ccv) != NGX_OK) {
5009
return NGX_CONF_ERROR;
5010
}
5011
</programlisting>
5012
5013
Here, <literal>ccv</literal> holds all parameters that are required to
5014
initialize the complex value <literal>cv</literal>:
5015
5016
<list type="bullet">
5017
5018
<listitem>
5019
<literal>cf</literal> — Configuration pointer
5020
</listitem>
5021
5022
<listitem>
5023
<literal>value</literal> — String to be parsed (input)
5024
</listitem>
5025
5026
<listitem>
5027
<literal>complex_value</literal> — Compiled value (output)
5028
</listitem>
5029
5030
<listitem>
5031
<literal>zero</literal> — Flag that enables zero-terminating value
5032
</listitem>
5033
5034
<listitem>
5035
<literal>conf_prefix</literal> — Prefixes the result with the
5036
configuration prefix (the directory where nginx is currently looking for
5037
configuration)
5038
</listitem>
5039
5040
<listitem>
5041
<literal>root_prefix</literal> — Prefixes the result with the root prefix
5042
(the normal nginx installation prefix)
5043
</listitem>
5044
5045
</list>
5046
The <literal>zero</literal> flag is useful when results are to be passed to
5047
libraries that require zero-terminated strings, and prefixes are handy when
5048
dealing with filenames.
5049
</para>
5050
5051
<para>
5052
Upon successful compilation, <literal>cv.lengths</literal>
5053
contains information about the presence of variables
5054
in the expression.
5055
The NULL value means that the expression contained static text only,
5056
and so can be stored in a simple string rather than as a complex value.
5057
</para>
5058
5059
<para>
5060
The <literal>ngx_http_set_complex_value_slot()</literal> is a convenient
5061
function used to initialize a complex value completely in the directive
5062
declaration itself.
5063
</para>
5064
5065
<para>
5066
At runtime, a complex value can be calculated using the
5067
<literal>ngx_http_complex_value()</literal> function:
5068
<programlisting>
5069
ngx_str_t res;
5070
5071
if (ngx_http_complex_value(r, &amp;cv, &amp;res) != NGX_OK) {
5072
return NGX_ERROR;
5073
}
5074
</programlisting>
5075
Given the request <literal>r</literal> and previously compiled
5076
value <literal>cv</literal>, the function evaluates the
5077
expression and writes the result to <literal>res</literal>.
5078
</para>
5079
5080
</section>
5081
5082
5083
<section name="Request redirection" id="http_request_redirection">
5084
5085
<para>
5086
An HTTP request is always connected to a location via the
5087
<literal>loc_conf</literal> field of the <literal>ngx_http_request_t</literal>
5088
structure.
5089
This means that at any point the location configuration of any module can be
5090
retrieved from the request by calling
5091
<literal>ngx_http_get_module_loc_conf(r, module)</literal>.
5092
Request location can change several times during the request's lifetime.
5093
Initially, a default server location of the default server is assigned to a
5094
request.
5095
If the request switches to a different server (chosen by the HTTP
5096
<header>Host</header> header or SSL SNI extension), the request switches to the
5097
default location of that server as well.
5098
The next change of the location takes place at the
5099
<literal>NGX_HTTP_FIND_CONFIG_PHASE</literal> request phase.
5100
At this phase a location is chosen by request URI among all non-named locations
5101
configured for the server.
5102
The
5103
<link doc="../http/ngx_http_rewrite_module.xml">ngx_http_rewrite_module</link>
5104
can change the request URI at the
5105
<literal>NGX_HTTP_REWRITE_PHASE</literal> request phase as a result of
5106
the <link doc="../http/ngx_http_rewrite_module.xml" id="rewrite">rewrite</link>
5107
directive and send the request back
5108
to the <literal>NGX_HTTP_FIND_CONFIG_PHASE</literal> phase for selection of a
5109
new location based on the new URI.
5110
</para>
5111
5112
<para>
5113
It is also possible to redirect a request to a new location at any point by
5114
calling one of
5115
<literal>ngx_http_internal_redirect(r, uri, args)</literal> or
5116
<literal>ngx_http_named_location(r, name)</literal>.
5117
</para>
5118
5119
<para>
5120
The <literal>ngx_http_internal_redirect(r, uri, args)</literal> function changes
5121
the request URI and returns the request to the
5122
<literal>NGX_HTTP_SERVER_REWRITE_PHASE</literal> phase.
5123
The request proceeds with a server default location.
5124
Later at <literal>NGX_HTTP_FIND_CONFIG_PHASE</literal> a new location is chosen
5125
based on the new request URI.
5126
</para>
5127
5128
<para>
5129
The following example performs an internal redirect with the new request
5130
arguments.
5131
</para>
5132
5133
<programlisting>
5134
ngx_int_t
5135
ngx_http_foo_redirect(ngx_http_request_t *r)
5136
{
5137
ngx_str_t uri, args;
5138
5139
ngx_str_set(&amp;uri, "/foo");
5140
ngx_str_set(&amp;args, "bar=1");
5141
5142
return ngx_http_internal_redirect(r, &amp;uri, &amp;args);
5143
}
5144
</programlisting>
5145
5146
<para>
5147
The function <literal>ngx_http_named_location(r, name)</literal> redirects
5148
a request to a named location. The name of the location is passed as the
5149
argument.
5150
The location is looked up among all named locations of the current
5151
server, after which the requests switches to the
5152
<literal>NGX_HTTP_REWRITE_PHASE</literal> phase.
5153
</para>
5154
5155
<para>
5156
The following example performs a redirect to a named location @foo.
5157
</para>
5158
5159
<programlisting>
5160
ngx_int_t
5161
ngx_http_foo_named_redirect(ngx_http_request_t *r)
5162
{
5163
ngx_str_t name;
5164
5165
ngx_str_set(&amp;name, "foo");
5166
5167
return ngx_http_named_location(r, &amp;name);
5168
}
5169
</programlisting>
5170
5171
<para>
5172
Both functions - <literal>ngx_http_internal_redirect(r, uri, args)</literal>
5173
and <literal>ngx_http_named_location(r, name)</literal> can be called when
5174
nginx modules have already stored some contexts in a request's
5175
<literal>ctx</literal> field.
5176
It's possible for these contexts to become inconsistent with the new
5177
location configuration.
5178
To prevent inconsistency, all request contexts are
5179
erased by both redirect functions.
5180
</para>
5181
5182
<para>
5183
Calling <literal>ngx_http_internal_redirect(r, uri, args)</literal>
5184
or <literal>ngx_http_named_location(r, name)</literal> increases the request
5185
<literal>count</literal>.
5186
For consistent request reference counting, call
5187
<literal>ngx_http_finalize_request(r, NGX_DONE)</literal> after redirecting the
5188
request.
5189
This will finalize current request code path and decrease the counter.
5190
</para>
5191
5192
<para>
5193
Redirected and rewritten requests become internal and can access the
5194
<link doc="../http/ngx_http_core_module.xml" id="internal">internal</link>
5195
locations.
5196
Internal requests have the <literal>internal</literal> flag set.
5197
</para>
5198
5199
</section>
5200
5201
5202
<section name="Subrequests" id="http_subrequests">
5203
5204
<para>
5205
Subrequests are primarily used to insert output of one request into another,
5206
possibly mixed with other data.
5207
A subrequest looks like a normal request, but shares some data with its parent.
5208
In particular, all fields related to client input are shared
5209
because a subrequest does not receive any other input from the client.
5210
The request field <literal>parent</literal> for a subrequest contains a link
5211
to its parent request and is NULL for the main request.
5212
The field <literal>main</literal> contains a link to the main request in
5213
a group of requests.
5214
</para>
5215
5216
<para>
5217
A subrequest starts in the <literal>NGX_HTTP_SERVER_REWRITE_PHASE</literal>
5218
phase.
5219
It passes through the same subsequent phases as a normal request and is
5220
assigned a location based on its own URI.
5221
</para>
5222
5223
<para>
5224
The output header in a subrequest is always ignored.
5225
The <literal>ngx_http_postpone_filter</literal> places the subrequest's
5226
output body in the right position relative to other data produced
5227
by the parent request.
5228
</para>
5229
5230
<para>
5231
Subrequests are related to the concept of active requests.
5232
A request <literal>r</literal> is considered active if
5233
<literal>c->data == r</literal>, where <literal>c</literal> is the client
5234
connection object.
5235
At any given point, only the active request in a request group is allowed
5236
to output its buffers to the client.
5237
An inactive request can still send its output to the filter chain, but it
5238
does not pass beyond the <literal>ngx_http_postpone_filter</literal> and
5239
remains buffered by that filter until the request becomes active.
5240
Here are some rules of request activation:
5241
</para>
5242
5243
<list type="bullet">
5244
5245
<listitem>
5246
Initially, the main request is active.
5247
</listitem>
5248
5249
<listitem>
5250
The first subrequest of an active request becomes active right after creation.
5251
</listitem>
5252
5253
<listitem>
5254
The <literal>ngx_http_postpone_filter</literal> activates the next request
5255
in the active request's subrequest list, once all data prior to that request
5256
are sent.
5257
</listitem>
5258
5259
<listitem>
5260
When a request is finalized, its parent is activated.
5261
</listitem>
5262
5263
</list>
5264
5265
<para>
5266
Create a subrequest by calling the function
5267
<literal>ngx_http_subrequest(r, uri, args, psr, ps, flags)</literal>, where
5268
<literal>r</literal> is the parent request, <literal>uri</literal> and
5269
<literal>args</literal> are the URI and arguments of the
5270
subrequest, <literal>psr</literal> is the output parameter, which receives the
5271
newly created subrequest reference, <literal>ps</literal> is a callback object
5272
for notifying the parent request that the subrequest is being finalized, and
5273
<literal>flags</literal> is bitmask of flags.
5274
The following flags are available:
5275
</para>
5276
5277
<list type="bullet">
5278
5279
<listitem>
5280
<literal>NGX_HTTP_SUBREQUEST_IN_MEMORY</literal> - Output is not
5281
sent to the client, but rather stored in memory.
5282
The flag only affects subrequests which are processed by one of the proxying
5283
modules.
5284
After a subrequest is finalized its output is available in
5285
<literal>r->out</literal> of type <literal>ngx_buf_t</literal>.
5286
</listitem>
5287
5288
<listitem>
5289
<literal>NGX_HTTP_SUBREQUEST_WAITED</literal> - The subrequest's
5290
<literal>done</literal> flag is set even if the subrequest is not active when
5291
it is finalized.
5292
This subrequest flag is used by the SSI filter.
5293
</listitem>
5294
5295
<listitem>
5296
<literal>NGX_HTTP_SUBREQUEST_CLONE</literal> - The subrequest is created as a
5297
clone of its parent.
5298
It is started at the same location and proceeds from the same phase as the
5299
parent request.
5300
</listitem>
5301
5302
</list>
5303
5304
<para>
5305
The following example creates a subrequest with the URI
5306
of <literal>/foo</literal>.
5307
</para>
5308
5309
<programlisting>
5310
ngx_int_t rc;
5311
ngx_str_t uri;
5312
ngx_http_request_t *sr;
5313
5314
...
5315
5316
ngx_str_set(&amp;uri, "/foo");
5317
5318
rc = ngx_http_subrequest(r, &amp;uri, NULL, &amp;sr, NULL, 0);
5319
if (rc == NGX_ERROR) {
5320
/* error */
5321
}
5322
</programlisting>
5323
5324
<para>
5325
This example clones the current request and sets a finalization callback for the
5326
subrequest.
5327
</para>
5328
5329
<programlisting>
5330
ngx_int_t
5331
ngx_http_foo_clone(ngx_http_request_t *r)
5332
{
5333
ngx_http_request_t *sr;
5334
ngx_http_post_subrequest_t *ps;
5335
5336
ps = ngx_palloc(r->pool, sizeof(ngx_http_post_subrequest_t));
5337
if (ps == NULL) {
5338
return NGX_ERROR;
5339
}
5340
5341
ps->handler = ngx_http_foo_subrequest_done;
5342
ps->data = "foo";
5343
5344
return ngx_http_subrequest(r, &amp;r->uri, &amp;r->args, &amp;sr, ps,
5345
NGX_HTTP_SUBREQUEST_CLONE);
5346
}
5347
5348
5349
ngx_int_t
5350
ngx_http_foo_subrequest_done(ngx_http_request_t *r, void *data, ngx_int_t rc)
5351
{
5352
char *msg = (char *) data;
5353
5354
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
5355
"done subrequest r:%p msg:%s rc:%i", r, msg, rc);
5356
5357
return rc;
5358
}
5359
</programlisting>
5360
5361
<para>
5362
Subrequests are normally created in a body filter, in which case their output
5363
can be treated like the output from any explicit request.
5364
This means that eventually the output of a subrequest is sent to the client,
5365
after all explicit buffers that are passed before subrequest creation and
5366
before any buffers that are passed after creation.
5367
This ordering is preserved even for large hierarchies of subrequests.
5368
The following example inserts output from a subrequest after all request data
5369
buffers, but before the final buffer with the <literal>last_buf</literal> flag.
5370
</para>
5371
5372
<programlisting>
5373
ngx_int_t
5374
ngx_http_foo_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
5375
{
5376
ngx_int_t rc;
5377
ngx_buf_t *b;
5378
ngx_uint_t last;
5379
ngx_chain_t *cl, out;
5380
ngx_http_request_t *sr;
5381
ngx_http_foo_filter_ctx_t *ctx;
5382
5383
ctx = ngx_http_get_module_ctx(r, ngx_http_foo_filter_module);
5384
if (ctx == NULL) {
5385
return ngx_http_next_body_filter(r, in);
5386
}
5387
5388
last = 0;
5389
5390
for (cl = in; cl; cl = cl->next) {
5391
if (cl->buf->last_buf) {
5392
cl->buf->last_buf = 0;
5393
cl->buf->last_in_chain = 1;
5394
cl->buf->sync = 1;
5395
last = 1;
5396
}
5397
}
5398
5399
/* Output explicit output buffers */
5400
5401
rc = ngx_http_next_body_filter(r, in);
5402
5403
if (rc == NGX_ERROR || !last) {
5404
return rc;
5405
}
5406
5407
/*
5408
* Create the subrequest. The output of the subrequest
5409
* will automatically be sent after all preceding buffers,
5410
* but before the last_buf buffer passed later in this function.
5411
*/
5412
5413
if (ngx_http_subrequest(r, ctx->uri, NULL, &amp;sr, NULL, 0) != NGX_OK) {
5414
return NGX_ERROR;
5415
}
5416
5417
ngx_http_set_ctx(r, NULL, ngx_http_foo_filter_module);
5418
5419
/* Output the final buffer with the last_buf flag */
5420
5421
b = ngx_calloc_buf(r->pool);
5422
if (b == NULL) {
5423
return NGX_ERROR;
5424
}
5425
5426
b->last_buf = 1;
5427
5428
out.buf = b;
5429
out.next = NULL;
5430
5431
return ngx_http_output_filter(r, &amp;out);
5432
}
5433
</programlisting>
5434
5435
<para>
5436
A subrequest can also be created for other purposes than data output.
5437
For example, the <link doc="../http/ngx_http_auth_request_module.xml">
5438
ngx_http_auth_request_module</link> module
5439
creates a subrequest at the <literal>NGX_HTTP_ACCESS_PHASE</literal> phase.
5440
To disable output at this point, the
5441
<literal>header_only</literal> flag is set on the subrequest.
5442
This prevents the subrequest body from being sent to the client.
5443
Note that the subrequest's header is never sent to the client.
5444
The result of the subrequest can be analyzed in the callback handler.
5445
</para>
5446
5447
</section>
5448
5449
5450
<section name="Request finalization" id="http_request_finalization">
5451
5452
<para>
5453
An HTTP request is finalized by calling the function
5454
<literal>ngx_http_finalize_request(r, rc)</literal>.
5455
It is usually finalized by the content handler after all output buffers
5456
are sent to the filter chain.
5457
At this point all of the output might not be sent to the client,
5458
with some of it remaining buffered somewhere along the filter chain.
5459
If it is, the <literal>ngx_http_finalize_request(r, rc)</literal> function
5460
automatically installs a special handler <literal>ngx_http_writer(r)</literal>
5461
to finish sending the output.
5462
A request is also finalized in case of an error or if a standard HTTP response
5463
code needs to be returned to the client.
5464
</para>
5465
5466
<para>
5467
The function <literal>ngx_http_finalize_request(r, rc)</literal> expects the
5468
following <literal>rc</literal> values:
5469
</para>
5470
5471
<list type="bullet">
5472
5473
<listitem>
5474
<literal>NGX_DONE</literal> - Fast finalization.
5475
Decrement the request <literal>count</literal> and destroy the request if it
5476
reaches zero.
5477
The client connection can be used for more requests after the current request
5478
is destroyed.
5479
</listitem>
5480
5481
<listitem>
5482
<literal>NGX_ERROR</literal>, <literal>NGX_HTTP_REQUEST_TIME_OUT</literal>
5483
(<literal>408</literal>), <literal>NGX_HTTP_CLIENT_CLOSED_REQUEST</literal>
5484
(<literal>499</literal>) - Error finalization.
5485
Terminate the request as soon as possible and close the client connection.
5486
</listitem>
5487
5488
<listitem>
5489
<literal>NGX_HTTP_CREATED</literal> (<literal>201</literal>),
5490
<literal>NGX_HTTP_NO_CONTENT</literal> (<literal>204</literal>), codes greater
5491
than or equal to <literal>NGX_HTTP_SPECIAL_RESPONSE</literal>
5492
(<literal>300</literal>) - Special response finalization.
5493
For these values nginx either sends to the client a default response page for
5494
the code or performs the internal redirect to an
5495
<link doc="../http/ngx_http_core_module.xml" id="error_page"/> location if that
5496
is configured for the code.
5497
</listitem>
5498
5499
<listitem>
5500
Other codes are considered successful finalization codes and might activate the
5501
request writer to finish sending the response body.
5502
Once the body is completely sent, the request <literal>count</literal>
5503
is decremented.
5504
If it reaches zero, the request is destroyed, but the client connection can
5505
still be used for other requests.
5506
If <literal>count</literal> is positive, there are unfinished activities
5507
within the request, which will be finalized at a later point.
5508
</listitem>
5509
5510
</list>
5511
5512
</section>
5513
5514
5515
<section name="Request body" id="http_request_body">
5516
5517
<para>
5518
For dealing with the body of a client request, nginx provides the
5519
<literal>ngx_http_read_client_request_body(r, post_handler)</literal> and
5520
<literal>ngx_http_discard_request_body(r)</literal> functions.
5521
The first function reads the request body and makes it available via the
5522
<literal>request_body</literal> request field.
5523
The second function instructs nginx to discard (read and ignore) the request
5524
body.
5525
One of these functions must be called for every request.
5526
Normally, the content handler makes the call.
5527
</para>
5528
5529
<para>
5530
Reading or discarding the client request body from a subrequest is not allowed.
5531
It must always be done in the main request.
5532
When a subrequest is created, it inherits the parent's
5533
<literal>request_body</literal> object which can be used by the subrequest if
5534
the main request has previously read the request body.
5535
</para>
5536
5537
<para>
5538
The function
5539
<literal>ngx_http_read_client_request_body(r, post_handler)</literal> starts
5540
the process of reading the request body.
5541
When the body is completely read, the <literal>post_handler</literal> callback
5542
is called to continue processing the request.
5543
If the request body is missing or has already been read, the callback is called
5544
immediately.
5545
In unbuffered mode, the callback can be called before the whole body is read.
5546
The function
5547
<literal>ngx_http_read_client_request_body(r, post_handler)</literal>
5548
allocates the <literal>request_body</literal> request field of type
5549
<literal>ngx_http_request_body_t</literal>.
5550
The field <literal>bufs</literal> of this object keeps the result as a buffer
5551
chain.
5552
The body can be saved in memory buffers or file buffers, if the capacity
5553
specified by the
5554
<link doc="../http/ngx_http_core_module.xml" id="client_body_buffer_size"/>
5555
directive is not enough to fit the entire body in memory.
5556
</para>
5557
5558
<para>
5559
The following example reads a client request body and returns its size.
5560
</para>
5561
5562
<programlisting>
5563
ngx_int_t
5564
ngx_http_foo_content_handler(ngx_http_request_t *r)
5565
{
5566
ngx_int_t rc;
5567
5568
rc = ngx_http_read_client_request_body(r, ngx_http_foo_init);
5569
5570
if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
5571
/* error */
5572
return rc;
5573
}
5574
5575
return NGX_DONE;
5576
}
5577
5578
5579
void
5580
ngx_http_foo_init(ngx_http_request_t *r)
5581
{
5582
off_t len;
5583
ngx_buf_t *b;
5584
ngx_int_t rc;
5585
ngx_chain_t *in, out;
5586
5587
if (r->request_body == NULL) {
5588
ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
5589
return;
5590
}
5591
5592
len = 0;
5593
5594
for (in = r->request_body->bufs; in; in = in->next) {
5595
len += ngx_buf_size(in->buf);
5596
}
5597
5598
b = ngx_create_temp_buf(r->pool, NGX_OFF_T_LEN);
5599
if (b == NULL) {
5600
ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
5601
return;
5602
}
5603
5604
b->last = ngx_sprintf(b->pos, "%O", len);
5605
b->last_buf = (r == r->main) ? 1 : 0;
5606
b->last_in_chain = 1;
5607
5608
r->headers_out.status = NGX_HTTP_OK;
5609
r->headers_out.content_length_n = b->last - b->pos;
5610
5611
rc = ngx_http_send_header(r);
5612
5613
if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
5614
ngx_http_finalize_request(r, rc);
5615
return;
5616
}
5617
5618
out.buf = b;
5619
out.next = NULL;
5620
5621
rc = ngx_http_output_filter(r, &amp;out);
5622
5623
ngx_http_finalize_request(r, rc);
5624
}
5625
</programlisting>
5626
5627
<para>
5628
The following fields of the request determine how the request body is read:
5629
</para>
5630
5631
<list type="bullet">
5632
5633
<listitem>
5634
<literal>request_body_in_single_buf</literal> - Read the body to a single memory
5635
buffer.
5636
</listitem>
5637
5638
<listitem>
5639
<literal>request_body_in_file_only</literal> - Always read the body to a file,
5640
even if fits in the memory buffer.
5641
</listitem>
5642
5643
<listitem>
5644
<literal>request_body_in_persistent_file</literal> - Do not unlink the file
5645
immediately after creation.
5646
A file with this flag can be moved to another directory.
5647
</listitem>
5648
5649
<listitem>
5650
<literal>request_body_in_clean_file</literal> - Unlink the file when the
5651
request is finalized.
5652
This can be useful when a file was supposed to be moved to another directory
5653
but was not moved for some reason.
5654
</listitem>
5655
5656
<listitem>
5657
<literal>request_body_file_group_access</literal> - Enable group access to the
5658
file by replacing the default 0600 access mask with 0660.
5659
</listitem>
5660
5661
<listitem>
5662
<literal>request_body_file_log_level</literal> - Severity level at which to
5663
log file errors.
5664
</listitem>
5665
5666
<listitem>
5667
<literal>request_body_no_buffering</literal> - Read the request body without
5668
buffering.
5669
</listitem>
5670
5671
</list>
5672
5673
<para>
5674
The <literal>request_body_no_buffering</literal> flag enables the
5675
unbuffered mode of reading a request body.
5676
In this mode, after calling
5677
<literal>ngx_http_read_client_request_body()</literal>, the
5678
<literal>bufs</literal> chain might keep only a part of the body.
5679
The request flag <literal>reading_body</literal> indicates that the request body
5680
reading is still in progress.
5681
To read the next part, call the
5682
<literal>ngx_http_read_unbuffered_request_body(r)</literal> function.
5683
The return value <literal>NGX_AGAIN</literal> indicates that more body data
5684
or buffer space is needed.
5685
If <literal>bufs</literal> is NULL after calling this function, no body data is
5686
available at the moment.
5687
The request callback <literal>read_event_handler</literal> will be called when
5688
more client body data is available.
5689
</para>
5690
5691
</section>
5692
5693
5694
<section name="Request body filters" id="http_request_body_filters">
5695
5696
<para>
5697
After a request body part is read, it's passed to the request
5698
body filter chain by calling the first body filter handler stored in
5699
the <literal>ngx_http_top_request_body_filter</literal> variable.
5700
It's assumed that every body handler calls the next handler in the chain until
5701
the final handler <literal>ngx_http_request_body_save_filter(r, cl)</literal>
5702
is called.
5703
This handler collects the buffers in
5704
<literal>r->request_body->bufs</literal>
5705
and writes them to a file if necessary.
5706
The last request body buffer has nonzero <literal>last_buf</literal> flag.
5707
</para>
5708
5709
<para>
5710
If a filter is planning to delay data buffers, it should set the flag
5711
<literal>r->request_body->filter_need_buffering</literal> to
5712
<literal>1</literal> when called for the first time.
5713
</para>
5714
5715
<para>
5716
Following is an example of a simple request body filter that delays request
5717
body by one second.
5718
</para>
5719
5720
<programlisting>
5721
#include &lt;ngx_config.h&gt;
5722
#include &lt;ngx_core.h&gt;
5723
#include &lt;ngx_http.h&gt;
5724
5725
5726
#define NGX_HTTP_DELAY_BODY 1000
5727
5728
5729
typedef struct {
5730
ngx_event_t event;
5731
ngx_chain_t *out;
5732
} ngx_http_delay_body_ctx_t;
5733
5734
5735
static ngx_int_t ngx_http_delay_body_filter(ngx_http_request_t *r,
5736
ngx_chain_t *in);
5737
static void ngx_http_delay_body_cleanup(void *data);
5738
static void ngx_http_delay_body_event_handler(ngx_event_t *ev);
5739
static ngx_int_t ngx_http_delay_body_init(ngx_conf_t *cf);
5740
5741
5742
static ngx_http_module_t ngx_http_delay_body_module_ctx = {
5743
NULL, /* preconfiguration */
5744
ngx_http_delay_body_init, /* postconfiguration */
5745
5746
NULL, /* create main configuration */
5747
NULL, /* init main configuration */
5748
5749
NULL, /* create server configuration */
5750
NULL, /* merge server configuration */
5751
5752
NULL, /* create location configuration */
5753
NULL /* merge location configuration */
5754
};
5755
5756
5757
ngx_module_t ngx_http_delay_body_filter_module = {
5758
NGX_MODULE_V1,
5759
&amp;ngx_http_delay_body_module_ctx, /* module context */
5760
NULL, /* module directives */
5761
NGX_HTTP_MODULE, /* module type */
5762
NULL, /* init master */
5763
NULL, /* init module */
5764
NULL, /* init process */
5765
NULL, /* init thread */
5766
NULL, /* exit thread */
5767
NULL, /* exit process */
5768
NULL, /* exit master */
5769
NGX_MODULE_V1_PADDING
5770
};
5771
5772
5773
static ngx_http_request_body_filter_pt ngx_http_next_request_body_filter;
5774
5775
5776
static ngx_int_t
5777
ngx_http_delay_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
5778
{
5779
ngx_int_t rc;
5780
ngx_chain_t *cl, *ln;
5781
ngx_http_cleanup_t *cln;
5782
ngx_http_delay_body_ctx_t *ctx;
5783
5784
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
5785
"delay request body filter");
5786
5787
ctx = ngx_http_get_module_ctx(r, ngx_http_delay_body_filter_module);
5788
5789
if (ctx == NULL) {
5790
ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_delay_body_ctx_t));
5791
if (ctx == NULL) {
5792
return NGX_HTTP_INTERNAL_SERVER_ERROR;
5793
}
5794
5795
ngx_http_set_ctx(r, ctx, ngx_http_delay_body_filter_module);
5796
5797
r->request_body->filter_need_buffering = 1;
5798
}
5799
5800
if (ngx_chain_add_copy(r->pool, &amp;ctx->out, in) != NGX_OK) {
5801
return NGX_HTTP_INTERNAL_SERVER_ERROR;
5802
}
5803
5804
if (!ctx->event.timedout) {
5805
if (!ctx->event.timer_set) {
5806
5807
/* cleanup to remove the timer in case of abnormal termination */
5808
5809
cln = ngx_http_cleanup_add(r, 0);
5810
if (cln == NULL) {
5811
return NGX_HTTP_INTERNAL_SERVER_ERROR;
5812
}
5813
5814
cln->handler = ngx_http_delay_body_cleanup;
5815
cln->data = ctx;
5816
5817
/* add timer */
5818
5819
ctx->event.handler = ngx_http_delay_body_event_handler;
5820
ctx->event.data = r;
5821
ctx->event.log = r->connection->log;
5822
5823
ngx_add_timer(&amp;ctx->event, NGX_HTTP_DELAY_BODY);
5824
}
5825
5826
return ngx_http_next_request_body_filter(r, NULL);
5827
}
5828
5829
rc = ngx_http_next_request_body_filter(r, ctx->out);
5830
5831
for (cl = ctx->out; cl; /* void */) {
5832
ln = cl;
5833
cl = cl->next;
5834
ngx_free_chain(r->pool, ln);
5835
}
5836
5837
ctx->out = NULL;
5838
5839
return rc;
5840
}
5841
5842
5843
static void
5844
ngx_http_delay_body_cleanup(void *data)
5845
{
5846
ngx_http_delay_body_ctx_t *ctx = data;
5847
5848
if (ctx->event.timer_set) {
5849
ngx_del_timer(&amp;ctx->event);
5850
}
5851
}
5852
5853
5854
static void
5855
ngx_http_delay_body_event_handler(ngx_event_t *ev)
5856
{
5857
ngx_connection_t *c;
5858
ngx_http_request_t *r;
5859
5860
r = ev->data;
5861
c = r->connection;
5862
5863
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
5864
"delay request body event");
5865
5866
ngx_post_event(c->read, &amp;ngx_posted_events);
5867
}
5868
5869
5870
static ngx_int_t
5871
ngx_http_delay_body_init(ngx_conf_t *cf)
5872
{
5873
ngx_http_next_request_body_filter = ngx_http_top_request_body_filter;
5874
ngx_http_top_request_body_filter = ngx_http_delay_body_filter;
5875
5876
return NGX_OK;
5877
}
5878
</programlisting>
5879
5880
</section>
5881
5882
5883
<section name="Response" id="http_response">
5884
5885
<para>
5886
In nginx an HTTP response is produced by sending the response header followed by
5887
the optional response body.
5888
Both header and body are passed through a chain of filters and eventually get
5889
written to the client socket.
5890
An nginx module can install its handler into the header or body filter chain
5891
and process the output coming from the previous handler.
5892
</para>
5893
5894
5895
<section name="Response header" id="http_response_header">
5896
5897
<para>
5898
The <literal>ngx_http_send_header(r)</literal>
5899
function sends the output header.
5900
Do not call this function until <literal>r->headers_out</literal>
5901
contains all of the data required to produce the HTTP response header.
5902
The <literal>status</literal> field in <literal>r->headers_out</literal>
5903
must always be set.
5904
If the response status indicates that a response body follows the header,
5905
<literal>content_length_n</literal> can be set as well.
5906
The default value for this field is <literal>-1</literal>,
5907
which means that the body size is unknown.
5908
In this case, chunked transfer encoding is used.
5909
To output an arbitrary header, append the <literal>headers</literal> list.
5910
</para>
5911
5912
<programlisting>
5913
static ngx_int_t
5914
ngx_http_foo_content_handler(ngx_http_request_t *r)
5915
{
5916
ngx_int_t rc;
5917
ngx_table_elt_t *h;
5918
5919
/* send header */
5920
5921
r->headers_out.status = NGX_HTTP_OK;
5922
r->headers_out.content_length_n = 3;
5923
5924
/* X-Foo: foo */
5925
5926
h = ngx_list_push(&amp;r->headers_out.headers);
5927
if (h == NULL) {
5928
return NGX_ERROR;
5929
}
5930
5931
h->hash = 1;
5932
ngx_str_set(&amp;h->key, "X-Foo");
5933
ngx_str_set(&amp;h->value, "foo");
5934
5935
rc = ngx_http_send_header(r);
5936
5937
if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
5938
return rc;
5939
}
5940
5941
/* send body */
5942
5943
...
5944
}
5945
</programlisting>
5946
5947
</section>
5948
5949
5950
<section name="Header filters" id="http_header_filters">
5951
5952
<para>
5953
The <literal>ngx_http_send_header(r)</literal> function invokes the header
5954
filter chain by calling the first header filter handler stored in
5955
the <literal>ngx_http_top_header_filter</literal> variable.
5956
It's assumed that every header handler calls the next handler in the chain
5957
until the final handler <literal>ngx_http_header_filter(r)</literal> is called.
5958
The final header handler constructs the HTTP response based on
5959
<literal>r->headers_out</literal> and passes it to the
5960
<literal>ngx_http_writer_filter</literal> for output.
5961
</para>
5962
5963
<para>
5964
To add a handler to the header filter chain, store its address in
5965
the global variable <literal>ngx_http_top_header_filter</literal>
5966
at configuration time.
5967
The previous handler address is normally stored in a static variable in a module
5968
and is called by the newly added handler before exiting.
5969
</para>
5970
5971
<para>
5972
The following example of a header filter module adds the HTTP header
5973
"<literal>X-Foo: foo</literal>" to every response with status
5974
<literal>200</literal>.
5975
</para>
5976
5977
<programlisting>
5978
#include &lt;ngx_config.h&gt;
5979
#include &lt;ngx_core.h&gt;
5980
#include &lt;ngx_http.h&gt;
5981
5982
5983
static ngx_int_t ngx_http_foo_header_filter(ngx_http_request_t *r);
5984
static ngx_int_t ngx_http_foo_header_filter_init(ngx_conf_t *cf);
5985
5986
5987
static ngx_http_module_t ngx_http_foo_header_filter_module_ctx = {
5988
NULL, /* preconfiguration */
5989
ngx_http_foo_header_filter_init, /* postconfiguration */
5990
5991
NULL, /* create main configuration */
5992
NULL, /* init main configuration */
5993
5994
NULL, /* create server configuration */
5995
NULL, /* merge server configuration */
5996
5997
NULL, /* create location configuration */
5998
NULL /* merge location configuration */
5999
};
6000
6001
6002
ngx_module_t ngx_http_foo_header_filter_module = {
6003
NGX_MODULE_V1,
6004
&amp;ngx_http_foo_header_filter_module_ctx, /* module context */
6005
NULL, /* module directives */
6006
NGX_HTTP_MODULE, /* module type */
6007
NULL, /* init master */
6008
NULL, /* init module */
6009
NULL, /* init process */
6010
NULL, /* init thread */
6011
NULL, /* exit thread */
6012
NULL, /* exit process */
6013
NULL, /* exit master */
6014
NGX_MODULE_V1_PADDING
6015
};
6016
6017
6018
static ngx_http_output_header_filter_pt ngx_http_next_header_filter;
6019
6020
6021
static ngx_int_t
6022
ngx_http_foo_header_filter(ngx_http_request_t *r)
6023
{
6024
ngx_table_elt_t *h;
6025
6026
/*
6027
* The filter handler adds "X-Foo: foo" header
6028
* to every HTTP 200 response
6029
*/
6030
6031
if (r->headers_out.status != NGX_HTTP_OK) {
6032
return ngx_http_next_header_filter(r);
6033
}
6034
6035
h = ngx_list_push(&amp;r->headers_out.headers);
6036
if (h == NULL) {
6037
return NGX_ERROR;
6038
}
6039
6040
h->hash = 1;
6041
ngx_str_set(&amp;h->key, "X-Foo");
6042
ngx_str_set(&amp;h->value, "foo");
6043
6044
return ngx_http_next_header_filter(r);
6045
}
6046
6047
6048
static ngx_int_t
6049
ngx_http_foo_header_filter_init(ngx_conf_t *cf)
6050
{
6051
ngx_http_next_header_filter = ngx_http_top_header_filter;
6052
ngx_http_top_header_filter = ngx_http_foo_header_filter;
6053
6054
return NGX_OK;
6055
}
6056
</programlisting>
6057
6058
</section>
6059
6060
</section>
6061
6062
6063
<section name="Response body" id="http_response_body">
6064
6065
<para>
6066
To send the response body, call the
6067
<literal>ngx_http_output_filter(r, cl)</literal> function.
6068
The function can be called multiple times.
6069
Each time, it sends a part of the response body in the form of a buffer chain.
6070
Set the <literal>last_buf</literal> flag in the last body buffer.
6071
</para>
6072
6073
<para>
6074
The following example produces a complete HTTP response with "foo" as its body.
6075
For the example to work as subrequest as well as a main request,
6076
the <literal>last_in_chain</literal> flag is set in the last buffer
6077
of the output.
6078
The <literal>last_buf</literal> flag is set only for the main request because
6079
the last buffer for a subrequest does not end the entire output.
6080
</para>
6081
6082
<programlisting>
6083
static ngx_int_t
6084
ngx_http_bar_content_handler(ngx_http_request_t *r)
6085
{
6086
ngx_int_t rc;
6087
ngx_buf_t *b;
6088
ngx_chain_t out;
6089
6090
/* send header */
6091
6092
r->headers_out.status = NGX_HTTP_OK;
6093
r->headers_out.content_length_n = 3;
6094
6095
rc = ngx_http_send_header(r);
6096
6097
if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
6098
return rc;
6099
}
6100
6101
/* send body */
6102
6103
b = ngx_calloc_buf(r->pool);
6104
if (b == NULL) {
6105
return NGX_ERROR;
6106
}
6107
6108
b->last_buf = (r == r->main) ? 1 : 0;
6109
b->last_in_chain = 1;
6110
6111
b->memory = 1;
6112
6113
b->pos = (u_char *) "foo";
6114
b->last = b->pos + 3;
6115
6116
out.buf = b;
6117
out.next = NULL;
6118
6119
return ngx_http_output_filter(r, &amp;out);
6120
}
6121
</programlisting>
6122
6123
</section>
6124
6125
6126
<section name="Response body filters" id="http_response_body_filters">
6127
6128
<para>
6129
The function <literal>ngx_http_output_filter(r, cl)</literal> invokes the
6130
body filter chain by calling the first body filter handler stored in
6131
the <literal>ngx_http_top_body_filter</literal> variable.
6132
It's assumed that every body handler calls the next handler in the chain until
6133
the final handler <literal>ngx_http_write_filter(r, cl)</literal> is called.
6134
</para>
6135
6136
<para>
6137
A body filter handler receives a chain of buffers.
6138
The handler is supposed to process the buffers and pass a possibly new chain to
6139
the next handler.
6140
It's worth noting that the chain links <literal>ngx_chain_t</literal> of the
6141
incoming chain belong to the caller, and must not be reused or changed.
6142
Right after the handler completes, the caller can use its output chain links
6143
to keep track of the buffers it has sent.
6144
To save the buffer chain or to substitute some buffers before passing to the
6145
next filter, a handler needs to allocate its own chain links.
6146
</para>
6147
6148
<para>
6149
Following is an example of a simple body filter that counts the number of
6150
bytes in the body.
6151
The result is available as the <literal>$counter</literal> variable which can be
6152
used in the access log.
6153
</para>
6154
6155
<programlisting>
6156
#include &lt;ngx_config.h&gt;
6157
#include &lt;ngx_core.h&gt;
6158
#include &lt;ngx_http.h&gt;
6159
6160
6161
typedef struct {
6162
off_t count;
6163
} ngx_http_counter_filter_ctx_t;
6164
6165
6166
static ngx_int_t ngx_http_counter_body_filter(ngx_http_request_t *r,
6167
ngx_chain_t *in);
6168
static ngx_int_t ngx_http_counter_variable(ngx_http_request_t *r,
6169
ngx_http_variable_value_t *v, uintptr_t data);
6170
static ngx_int_t ngx_http_counter_add_variables(ngx_conf_t *cf);
6171
static ngx_int_t ngx_http_counter_filter_init(ngx_conf_t *cf);
6172
6173
6174
static ngx_http_module_t ngx_http_counter_filter_module_ctx = {
6175
ngx_http_counter_add_variables, /* preconfiguration */
6176
ngx_http_counter_filter_init, /* postconfiguration */
6177
6178
NULL, /* create main configuration */
6179
NULL, /* init main configuration */
6180
6181
NULL, /* create server configuration */
6182
NULL, /* merge server configuration */
6183
6184
NULL, /* create location configuration */
6185
NULL /* merge location configuration */
6186
};
6187
6188
6189
ngx_module_t ngx_http_counter_filter_module = {
6190
NGX_MODULE_V1,
6191
&amp;ngx_http_counter_filter_module_ctx, /* module context */
6192
NULL, /* module directives */
6193
NGX_HTTP_MODULE, /* module type */
6194
NULL, /* init master */
6195
NULL, /* init module */
6196
NULL, /* init process */
6197
NULL, /* init thread */
6198
NULL, /* exit thread */
6199
NULL, /* exit process */
6200
NULL, /* exit master */
6201
NGX_MODULE_V1_PADDING
6202
};
6203
6204
6205
static ngx_http_output_body_filter_pt ngx_http_next_body_filter;
6206
6207
static ngx_str_t ngx_http_counter_name = ngx_string("counter");
6208
6209
6210
static ngx_int_t
6211
ngx_http_counter_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
6212
{
6213
ngx_chain_t *cl;
6214
ngx_http_counter_filter_ctx_t *ctx;
6215
6216
ctx = ngx_http_get_module_ctx(r, ngx_http_counter_filter_module);
6217
if (ctx == NULL) {
6218
ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_counter_filter_ctx_t));
6219
if (ctx == NULL) {
6220
return NGX_ERROR;
6221
}
6222
6223
ngx_http_set_ctx(r, ctx, ngx_http_counter_filter_module);
6224
}
6225
6226
for (cl = in; cl; cl = cl->next) {
6227
ctx->count += ngx_buf_size(cl->buf);
6228
}
6229
6230
return ngx_http_next_body_filter(r, in);
6231
}
6232
6233
6234
static ngx_int_t
6235
ngx_http_counter_variable(ngx_http_request_t *r, ngx_http_variable_value_t *v,
6236
uintptr_t data)
6237
{
6238
u_char *p;
6239
ngx_http_counter_filter_ctx_t *ctx;
6240
6241
ctx = ngx_http_get_module_ctx(r, ngx_http_counter_filter_module);
6242
if (ctx == NULL) {
6243
v->not_found = 1;
6244
return NGX_OK;
6245
}
6246
6247
p = ngx_pnalloc(r->pool, NGX_OFF_T_LEN);
6248
if (p == NULL) {
6249
return NGX_ERROR;
6250
}
6251
6252
v->data = p;
6253
v->len = ngx_sprintf(p, "%O", ctx->count) - p;
6254
v->valid = 1;
6255
v->no_cacheable = 0;
6256
v->not_found = 0;
6257
6258
return NGX_OK;
6259
}
6260
6261
6262
static ngx_int_t
6263
ngx_http_counter_add_variables(ngx_conf_t *cf)
6264
{
6265
ngx_http_variable_t *var;
6266
6267
var = ngx_http_add_variable(cf, &amp;ngx_http_counter_name, 0);
6268
if (var == NULL) {
6269
return NGX_ERROR;
6270
}
6271
6272
var->get_handler = ngx_http_counter_variable;
6273
6274
return NGX_OK;
6275
}
6276
6277
6278
static ngx_int_t
6279
ngx_http_counter_filter_init(ngx_conf_t *cf)
6280
{
6281
ngx_http_next_body_filter = ngx_http_top_body_filter;
6282
ngx_http_top_body_filter = ngx_http_counter_body_filter;
6283
6284
return NGX_OK;
6285
}
6286
</programlisting>
6287
6288
</section>
6289
6290
6291
<section name="Building filter modules" id="http_building_filter_modules">
6292
6293
<para>
6294
When writing a body or header filter, pay special attention to the filter's
6295
position in the filter order.
6296
There's a number of header and body filters registered by nginx standard
6297
modules.
6298
The nginx standard modules register a number of head and body filters and it's
6299
important to register a new filter module in the right place with respect to
6300
them.
6301
Normally, modules register filters in their postconfiguration handlers.
6302
The order in which filters are called during processing is obviously the
6303
reverse of the order in which they are registered.
6304
</para>
6305
6306
<para>
6307
For third-party filter modules nginx provides a special slot
6308
<literal>HTTP_AUX_FILTER_MODULES</literal>.
6309
To register a filter module in this slot, set
6310
the <literal>ngx_module_type</literal> variable to
6311
<literal>HTTP_AUX_FILTER</literal> in the module's configuration.
6312
</para>
6313
6314
<para>
6315
The following example shows a filter module config file assuming
6316
for a module with just
6317
one source file, <literal>ngx_http_foo_filter_module.c</literal>.
6318
</para>
6319
6320
<programlisting>
6321
ngx_module_type=HTTP_AUX_FILTER
6322
ngx_module_name=ngx_http_foo_filter_module
6323
ngx_module_srcs="$ngx_addon_dir/ngx_http_foo_filter_module.c"
6324
6325
. auto/module
6326
</programlisting>
6327
6328
</section>
6329
6330
6331
<section name="Buffer reuse" id="http_body_buffers_reuse">
6332
6333
<para>
6334
When issuing or altering a stream of buffers, it's often desirable to reuse the
6335
allocated buffers.
6336
A standard and widely adopted approach in nginx code is to keep
6337
two buffer chains for this purpose:
6338
<literal>free</literal> and <literal>busy</literal>.
6339
The <literal>free</literal> chain keeps all free buffers,
6340
which can be reused.
6341
The <literal>busy</literal> chain keeps all buffers sent by the current
6342
module that are still in use by some other filter handler.
6343
A buffer is considered in use if its size is greater than zero.
6344
Normally, when a buffer is consumed by a filter, its <literal>pos</literal>
6345
(or <literal>file_pos</literal> for a file buffer) is moved towards
6346
<literal>last</literal> (<literal>file_last</literal> for a file buffer).
6347
Once a buffer is completely consumed, it's ready to be reused.
6348
To add newly freed buffers to the <literal>free</literal> chain
6349
it's enough to iterate over the <literal>busy</literal> chain and move the zero
6350
size buffers at the head of it to <literal>free</literal>.
6351
This operation is so common that there is a special function for it,
6352
<literal>ngx_chain_update_chains(free, busy, out, tag)</literal>.
6353
The function appends the output chain <literal>out</literal> to
6354
<literal>busy</literal> and moves free buffers from the top of
6355
<literal>busy</literal> to <literal>free</literal>.
6356
Only the buffers with the specified <literal>tag</literal> are reused.
6357
This lets a module reuse only the buffers that it allocated itself.
6358
</para>
6359
6360
<para>
6361
The following example is a body filter that inserts the string “foo” before each
6362
incoming buffer.
6363
The new buffers allocated by the module are reused if possible.
6364
Note that for this example to work properly, setting up a
6365
<link id="http_header_filters">header filter</link>
6366
and resetting <literal>content_length_n</literal> to <literal>-1</literal>
6367
is also required, but the relevant code is not provided here.
6368
</para>
6369
6370
<programlisting>
6371
typedef struct {
6372
ngx_chain_t *free;
6373
ngx_chain_t *busy;
6374
} ngx_http_foo_filter_ctx_t;
6375
6376
6377
ngx_int_t
6378
ngx_http_foo_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
6379
{
6380
ngx_int_t rc;
6381
ngx_buf_t *b;
6382
ngx_chain_t *cl, *tl, *out, **ll;
6383
ngx_http_foo_filter_ctx_t *ctx;
6384
6385
ctx = ngx_http_get_module_ctx(r, ngx_http_foo_filter_module);
6386
if (ctx == NULL) {
6387
ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_foo_filter_ctx_t));
6388
if (ctx == NULL) {
6389
return NGX_ERROR;
6390
}
6391
6392
ngx_http_set_ctx(r, ctx, ngx_http_foo_filter_module);
6393
}
6394
6395
/* create a new chain "out" from "in" with all the changes */
6396
6397
ll = &amp;out;
6398
6399
for (cl = in; cl; cl = cl->next) {
6400
6401
/* append "foo" in a reused buffer if possible */
6402
6403
tl = ngx_chain_get_free_buf(r->pool, &amp;ctx->free);
6404
if (tl == NULL) {
6405
return NGX_ERROR;
6406
}
6407
6408
b = tl->buf;
6409
b->tag = (ngx_buf_tag_t) &amp;ngx_http_foo_filter_module;
6410
b->memory = 1;
6411
b->pos = (u_char *) "foo";
6412
b->last = b->pos + 3;
6413
6414
*ll = tl;
6415
ll = &amp;tl->next;
6416
6417
/* append the next incoming buffer */
6418
6419
tl = ngx_alloc_chain_link(r->pool);
6420
if (tl == NULL) {
6421
return NGX_ERROR;
6422
}
6423
6424
tl->buf = cl->buf;
6425
*ll = tl;
6426
ll = &amp;tl->next;
6427
}
6428
6429
*ll = NULL;
6430
6431
/* send the new chain */
6432
6433
rc = ngx_http_next_body_filter(r, out);
6434
6435
/* update "busy" and "free" chains for reuse */
6436
6437
ngx_chain_update_chains(r->pool, &amp;ctx->free, &amp;ctx->busy, &amp;out,
6438
(ngx_buf_tag_t) &amp;ngx_http_foo_filter_module);
6439
6440
return rc;
6441
}
6442
</programlisting>
6443
6444
</section>
6445
6446
6447
<section name="Load balancing" id="http_load_balancing">
6448
6449
<para>
6450
The
6451
<link doc="../http/ngx_http_upstream_module.xml">ngx_http_upstream_module</link>
6452
provides the basic functionality needed to pass requests to remote servers.
6453
Modules that implement specific protocols, such as HTTP or FastCGI, use
6454
this functionality.
6455
The module also provides an interface for creating custom
6456
load-balancing modules and implements a default round-robin method.
6457
</para>
6458
6459
<para>
6460
The <link doc="../http/ngx_http_upstream_module.xml" id="least_conn"/>
6461
and <link doc="../http/ngx_http_upstream_module.xml" id="hash"/>
6462
modules implement alternative load-balancing methods, but
6463
are actually implemented as extensions of the upstream round-robin
6464
module and share a lot of code with it, such as the representation
6465
of a server group.
6466
The <link doc="../http/ngx_http_upstream_module.xml" id="keepalive"/> module
6467
is an independent module that extends upstream functionality.
6468
</para>
6469
6470
<para>
6471
The
6472
<link doc="../http/ngx_http_upstream_module.xml">ngx_http_upstream_module</link>
6473
can be configured explicitly by placing the corresponding
6474
<link doc="../http/ngx_http_upstream_module.xml" id="upstream"/> block into
6475
the configuration file, or implicitly by using directives
6476
such as <link doc="../http/ngx_http_proxy_module.xml" id="proxy_pass"/>
6477
that accept a URL that gets evaluated at some point into a list of servers.
6478
The alternative load-balancing methods are available only with an explicit
6479
upstream configuration.
6480
The upstream module configuration has its own directive context
6481
<literal>NGX_HTTP_UPS_CONF</literal>.
6482
The structure is defined as follows:
6483
<programlisting>
6484
struct ngx_http_upstream_srv_conf_s {
6485
ngx_http_upstream_peer_t peer;
6486
void **srv_conf;
6487
6488
ngx_array_t *servers; /* ngx_http_upstream_server_t */
6489
6490
ngx_uint_t flags;
6491
ngx_str_t host;
6492
u_char *file_name;
6493
ngx_uint_t line;
6494
in_port_t port;
6495
ngx_uint_t no_port; /* unsigned no_port:1 */
6496
6497
#if (NGX_HTTP_UPSTREAM_ZONE)
6498
ngx_shm_zone_t *shm_zone;
6499
#endif
6500
};
6501
</programlisting>
6502
6503
<list type="bullet">
6504
6505
<listitem>
6506
<literal>srv_conf</literal> — Configuration context of upstream modules.
6507
</listitem>
6508
6509
<listitem>
6510
<literal>servers</literal> — Array of
6511
<literal>ngx_http_upstream_server_t</literal>, the result of parsing a set of
6512
<link doc="../http/ngx_http_upstream_module.xml" id="server"/> directives
6513
in the <literal>upstream</literal> block.
6514
</listitem>
6515
6516
<listitem>
6517
<literal>flags</literal> — Flags that mostly mark which features
6518
are supported by the load-balancing method.
6519
The features are configured as parameters of
6520
the <link doc="../http/ngx_http_upstream_module.xml" id="server"/> directive:
6521
6522
6523
<list type="bullet">
6524
6525
<listitem>
6526
<literal>NGX_HTTP_UPSTREAM_CREATE</literal> — Distinguishes explicitly
6527
defined upstreams from those that are automatically created by the
6528
<link doc="../http/ngx_http_proxy_module.xml" id="proxy_pass"/> directive
6529
and “friends”
6530
(FastCGI, SCGI, etc.)
6531
</listitem>
6532
6533
<listitem>
6534
<literal>NGX_HTTP_UPSTREAM_WEIGHT</literal> — The “<literal>weight</literal>
6535
parameter is supported
6536
</listitem>
6537
6538
<listitem>
6539
<literal>NGX_HTTP_UPSTREAM_MAX_FAILS</literal> — The
6540
<literal>max_fails</literal>” parameter is supported
6541
</listitem>
6542
6543
<listitem>
6544
<literal>NGX_HTTP_UPSTREAM_FAIL_TIMEOUT</literal> 
6545
The “<literal>fail_timeout</literal>” parameter is supported
6546
</listitem>
6547
6548
<listitem>
6549
<literal>NGX_HTTP_UPSTREAM_DOWN</literal> — The “<literal>down</literal>
6550
parameter is supported
6551
</listitem>
6552
6553
<listitem>
6554
<literal>NGX_HTTP_UPSTREAM_BACKUP</literal> — The “<literal>backup</literal>
6555
parameter is supported
6556
</listitem>
6557
6558
<listitem>
6559
<literal>NGX_HTTP_UPSTREAM_MAX_CONNS</literal> — The
6560
<literal>max_conns</literal>” parameter is supported
6561
</listitem>
6562
6563
</list>
6564
6565
</listitem>
6566
6567
<listitem>
6568
<literal>host</literal> — Name of the upstream.
6569
</listitem>
6570
6571
<listitem>
6572
<literal>file_name, line</literal> — Name of the configuration file
6573
and the line where the <literal>upstream</literal> block is located.
6574
</listitem>
6575
6576
<listitem>
6577
<literal>port</literal> and <literal>no_port</literal> — Not used for
6578
explicitly defined upstream groups.
6579
</listitem>
6580
6581
<listitem>
6582
<literal>shm_zone</literal> — Shared memory zone used by this upstream group,
6583
if any.
6584
</listitem>
6585
6586
<listitem>
6587
<literal>peer</literal> — object that holds generic methods for
6588
initializing upstream configuration:
6589
6590
<programlisting>
6591
typedef struct {
6592
ngx_http_upstream_init_pt init_upstream;
6593
ngx_http_upstream_init_peer_pt init;
6594
void *data;
6595
} ngx_http_upstream_peer_t;
6596
</programlisting>
6597
A module that implements a load-balancing algorithm must set these
6598
methods and initialize private <literal>data</literal>.
6599
If <literal>init_upstream</literal> was not initialized during configuration
6600
parsing, <literal>ngx_http_upstream_module</literal> sets it to the default
6601
<literal>ngx_http_upstream_init_round_robin</literal> algorithm.
6602
6603
<list type="bullet">
6604
<listitem>
6605
<literal>init_upstream(cf, us)</literal> — Configuration-time
6606
method responsible for initializing a group of servers and
6607
initializing the <literal>init()</literal> method in case of success.
6608
A typical load-balancing module uses a list of servers in the
6609
<literal>upstream</literal> block
6610
to create an efficient data structure that it uses and saves its own
6611
configuration to the <literal>data</literal> field.
6612
</listitem>
6613
6614
<listitem>
6615
<literal>init(r, us)</literal> — Initializes a per-request
6616
<literal>ngx_http_upstream_peer_t.peer</literal> structure that is used for
6617
load balancing (not to be confused with the
6618
<literal>ngx_http_upstream_srv_conf_t.peer</literal> described above which
6619
is per-upstream).
6620
It is passed as the <literal>data</literal> argument to all callbacks that
6621
deal with server selection.
6622
</listitem>
6623
</list>
6624
6625
</listitem>
6626
</list>
6627
</para>
6628
6629
<para>
6630
When nginx has to pass a request to another host for processing, it uses
6631
the configured load-balancing method to obtain an address to connect to.
6632
The method is obtained from the
6633
<literal>ngx_http_upstream_t.peer</literal> object
6634
of type <literal>ngx_peer_connection_t</literal>:
6635
<programlisting>
6636
struct ngx_peer_connection_s {
6637
...
6638
6639
struct sockaddr *sockaddr;
6640
socklen_t socklen;
6641
ngx_str_t *name;
6642
6643
ngx_uint_t tries;
6644
6645
ngx_event_get_peer_pt get;
6646
ngx_event_free_peer_pt free;
6647
ngx_event_notify_peer_pt notify;
6648
void *data;
6649
6650
#if (NGX_SSL || NGX_COMPAT)
6651
ngx_event_set_peer_session_pt set_session;
6652
ngx_event_save_peer_session_pt save_session;
6653
#endif
6654
6655
...
6656
};
6657
</programlisting>
6658
6659
The structure has the following fields:
6660
6661
<list type="bullet">
6662
<listitem>
6663
<literal>sockaddr</literal>, <literal>socklen</literal>,
6664
<literal>name</literal> — Address of the upstream server to connect to;
6665
this is the output parameter of a load-balancing method.
6666
</listitem>
6667
6668
<listitem>
6669
<literal>data</literal> — The per-request data of a load-balancing method;
6670
keeps the state of the selection algorithm and usually includes the link
6671
to the upstream configuration.
6672
It is passed as an argument to all methods that deal with server selection
6673
(see <link id="lb_method_get">below</link>).
6674
</listitem>
6675
6676
<listitem>
6677
<literal>tries</literal> — Allowed
6678
<link doc="../http/ngx_http_proxy_module.xml" id="proxy_next_upstream_tries">number</link>
6679
of attempts to connect to an upstream server.
6680
</listitem>
6681
6682
<listitem>
6683
<literal>get</literal>, <literal>free</literal>, <literal>notify</literal>,
6684
<literal>set_session</literal>, and <literal>save_session</literal>
6685
- Methods of the load-balancing module, described below.
6686
</listitem>
6687
6688
</list>
6689
6690
</para>
6691
6692
<para>
6693
All methods accept at least two arguments: a peer connection object
6694
<literal>pc</literal> and the <literal>data</literal> created by
6695
<literal>ngx_http_upstream_srv_conf_t.peer.init()</literal>.
6696
Note that it might differ from <literal>pc.data</literal> due
6697
to “chaining” of load-balancing modules.
6698
</para>
6699
6700
<para>
6701
6702
<list type="bullet">
6703
<listitem id="lb_method_get">
6704
<literal>get(pc, data)</literal> — The method called when the upstream
6705
module is ready to pass a request to an upstream server and needs to know
6706
its address.
6707
The method has to fill the <literal>sockaddr</literal>,
6708
<literal>socklen</literal>, and <literal>name</literal> fields of
6709
<literal>ngx_peer_connection_t</literal> structure.
6710
The return is one of:
6711
6712
<list type="bullet">
6713
6714
<listitem>
6715
<literal>NGX_OK</literal> — Server was selected.
6716
</listitem>
6717
6718
<listitem>
6719
<literal>NGX_ERROR</literal> — Internal error occurred.
6720
</listitem>
6721
6722
<listitem>
6723
<literal>NGX_BUSY</literal> — no servers are currently available.
6724
This can happen due to many reasons, including: the dynamic server group is
6725
empty, all servers in the group are in the failed state, or
6726
all servers in the group are already
6727
handling the maximum number of connections.
6728
</listitem>
6729
6730
<listitem>
6731
<literal>NGX_DONE</literal> — the underlying connection was reused and there
6732
is no need to create a new connection to the upstream server.
6733
This value is set by the <literal>keepalive</literal> module.
6734
</listitem>
6735
6736
<!--
6737
<listitem>
6738
<literal>NGX_ABORT</literal> — the request was queued and the further
6739
processing of this request should be postponed.
6740
This value is set by the <literal>queue</literal> module.
6741
</listitem>
6742
-->
6743
6744
</list>
6745
6746
</listitem>
6747
6748
<listitem>
6749
<literal>free(pc, data, state)</literal> — The method called when an
6750
upstream module has finished work with a particular server.
6751
The <literal>state</literal> argument is the completion status of the upstream
6752
connection, a bitmask with the following possible values:
6753
6754
<list type="bullet">
6755
6756
<listitem>
6757
<literal>NGX_PEER_FAILED</literal> — Attempt was
6758
<link doc="../http/ngx_http_upstream_module.xml" id="max_fails">unsuccessful</link>
6759
</listitem>
6760
6761
<listitem>
6762
<literal>NGX_PEER_NEXT</literal> — A special case when upstream server
6763
returns codes <literal>403</literal> or <literal>404</literal>,
6764
which are not considered a
6765
<link doc="../http/ngx_http_upstream_module.xml" id="max_fails">failure</link>.
6766
</listitem>
6767
6768
<listitem>
6769
<literal>NGX_PEER_KEEPALIVE</literal> — Currently unused
6770
</listitem>
6771
6772
</list>
6773
6774
This method also decrements the <literal>tries</literal> counter.
6775
6776
</listitem>
6777
6778
<listitem>
6779
<literal>notify(pc, data, type)</literal> — Currently unused
6780
in the OSS version.
6781
</listitem>
6782
6783
<listitem>
6784
<literal>set_session(pc, data)</literal> and
6785
<literal>save_session(pc, data)</literal>
6786
— SSL-specific methods that enable caching sessions to upstream
6787
servers.
6788
The implementation is provided by the round-robin balancing method.
6789
</listitem>
6790
6791
</list>
6792
6793
</para>
6794
6795
</section>
6796
6797
</section>
6798
6799
<section name="Examples" id="examples">
6800
6801
<para>
6802
The
6803
<link url="https://github.com/nginx/nginx-dev-examples">nginx-dev-examples</link>
6804
repository provides nginx module examples.
6805
6806
</para>
6807
6808
</section>
6809
6810
6811
<section name="Code style" id="code_style">
6812
6813
<section name="General rules" id="code_style_general_rules">
6814
6815
<para>
6816
<list type="bullet">
6817
6818
<listitem>
6819
maximum text width is 80 characters
6820
</listitem>
6821
6822
<listitem>
6823
indentation is 4 spaces
6824
</listitem>
6825
6826
<listitem>
6827
no tabs, no trailing spaces
6828
</listitem>
6829
6830
<listitem>
6831
list elements on the same line are separated with spaces
6832
</listitem>
6833
6834
<listitem>
6835
hexadecimal literals are lowercase
6836
</listitem>
6837
6838
<listitem>
6839
file names, function and type names, and global variables have the
6840
<literal>ngx_</literal> or more specific prefix such as
6841
<literal>ngx_http_</literal> and <literal>ngx_mail_</literal>
6842
</listitem>
6843
6844
</list>
6845
6846
<programlisting>
6847
size_t
6848
ngx_utf8_length(u_char *p, size_t n)
6849
{
6850
u_char c, *last;
6851
size_t len;
6852
6853
last = p + n;
6854
6855
for (len = 0; p &lt; last; len++) {
6856
6857
c = *p;
6858
6859
if (c &lt; 0x80) {
6860
p++;
6861
continue;
6862
}
6863
6864
if (ngx_utf8_decode(&amp;p, last - p) > 0x10ffff) {
6865
/* invalid UTF-8 */
6866
return n;
6867
}
6868
}
6869
6870
return len;
6871
}
6872
</programlisting>
6873
6874
</para>
6875
6876
</section>
6877
6878
6879
<section name="Files" id="code_style_files">
6880
6881
<para>
6882
A typical source file may contain the following sections separated by
6883
two empty lines:
6884
6885
<list type="bullet">
6886
<listitem>
6887
copyright statements
6888
</listitem>
6889
6890
<listitem>
6891
includes
6892
</listitem>
6893
6894
<listitem>
6895
preprocessor definitions
6896
</listitem>
6897
6898
<listitem>
6899
type definitions
6900
</listitem>
6901
6902
<listitem>
6903
function prototypes
6904
</listitem>
6905
6906
<listitem>
6907
variable definitions
6908
</listitem>
6909
6910
<listitem>
6911
function definitions
6912
</listitem>
6913
6914
</list>
6915
</para>
6916
6917
<para>
6918
Copyright statements look like this:
6919
<programlisting>
6920
/*
6921
* Copyright (C) Author Name
6922
* Copyright (C) Organization, Inc.
6923
*/
6924
</programlisting>
6925
If the file is modified significantly, the list of authors should be updated,
6926
the new author is added to the top.
6927
</para>
6928
6929
<para>
6930
The <literal>ngx_config.h</literal> and <literal>ngx_core.h</literal> files
6931
are always included first, followed by one of
6932
<literal>ngx_http.h</literal>, <literal>ngx_stream.h</literal>,
6933
or <literal>ngx_mail.h</literal>.
6934
Then follow optional external header files:
6935
<programlisting>
6936
#include &lt;ngx_config.h>
6937
#include &lt;ngx_core.h>
6938
#include &lt;ngx_http.h>
6939
6940
#include &lt;libxml/parser.h>
6941
#include &lt;libxml/tree.h>
6942
#include &lt;libxslt/xslt.h>
6943
6944
#if (NGX_HAVE_EXSLT)
6945
#include &lt;libexslt/exslt.h>
6946
#endif
6947
</programlisting>
6948
6949
</para>
6950
6951
<para>
6952
Header files should include the so called "header protection":
6953
<programlisting>
6954
#ifndef _NGX_PROCESS_CYCLE_H_INCLUDED_
6955
#define _NGX_PROCESS_CYCLE_H_INCLUDED_
6956
...
6957
#endif /* _NGX_PROCESS_CYCLE_H_INCLUDED_ */
6958
</programlisting>
6959
</para>
6960
6961
</section>
6962
6963
6964
<section name="Comments" id="code_style_comments">
6965
<para>
6966
<list type="bullet">
6967
6968
<listitem>
6969
<literal>//</literal>” comments are not used
6970
</listitem>
6971
6972
<listitem>
6973
text is written in English, American spelling is preferred
6974
</listitem>
6975
6976
<listitem>
6977
multi-line comments are formatted like this:
6978
<programlisting>
6979
/*
6980
* The red-black tree code is based on the algorithm described in
6981
* the "Introduction to Algorithms" by Cormen, Leiserson and Rivest.
6982
*/
6983
</programlisting>
6984
<programlisting>
6985
/* find the server configuration for the address:port */
6986
</programlisting>
6987
</listitem>
6988
6989
</list>
6990
</para>
6991
6992
</section>
6993
6994
6995
<section name="Preprocessor" id="code_style_preprocessor">
6996
<para>
6997
Macro names start from <literal>ngx_</literal> or <literal>NGX_</literal>
6998
(or more specific) prefix.
6999
Macro names for constants are uppercase.
7000
Parameterized macros and macros for initializers are lowercase.
7001
The macro name and value are separated by at least two spaces:
7002
<programlisting>
7003
#define NGX_CONF_BUFFER 4096
7004
7005
#define ngx_buf_in_memory(b) (b->temporary || b->memory || b->mmap)
7006
7007
#define ngx_buf_size(b) \
7008
(ngx_buf_in_memory(b) ? (off_t) (b->last - b->pos): \
7009
(b->file_last - b->file_pos))
7010
7011
#define ngx_null_string { 0, NULL }
7012
</programlisting>
7013
Conditions are inside parentheses, negation is outside:
7014
<programlisting>
7015
#if (NGX_HAVE_KQUEUE)
7016
...
7017
#elif ((NGX_HAVE_DEVPOLL &amp;&amp; !(NGX_TEST_BUILD_DEVPOLL)) \
7018
|| (NGX_HAVE_EVENTPORT &amp;&amp; !(NGX_TEST_BUILD_EVENTPORT)))
7019
...
7020
#elif (NGX_HAVE_EPOLL &amp;&amp; !(NGX_TEST_BUILD_EPOLL))
7021
...
7022
#elif (NGX_HAVE_POLL)
7023
...
7024
#else /* select */
7025
...
7026
#endif /* NGX_HAVE_KQUEUE */
7027
</programlisting>
7028
</para>
7029
</section>
7030
7031
7032
<section name="Types" id="code_style_types">
7033
7034
<para>
7035
Type names end with the “<literal>_t</literal>” suffix.
7036
A defined type name is separated by at least two spaces:
7037
<programlisting>
7038
typedef ngx_uint_t ngx_rbtree_key_t;
7039
</programlisting>
7040
</para>
7041
7042
<para>
7043
Structure types are defined using <literal>typedef</literal>.
7044
Inside structures, member types and names are aligned:
7045
<programlisting>
7046
typedef struct {
7047
size_t len;
7048
u_char *data;
7049
} ngx_str_t;
7050
</programlisting>
7051
Keep alignment identical among different structures in the file.
7052
A structure that points to itself has the name, ending with
7053
<literal>_s</literal>”.
7054
Adjacent structure definitions are separated with two empty lines:
7055
<programlisting>
7056
typedef struct ngx_list_part_s ngx_list_part_t;
7057
7058
struct ngx_list_part_s {
7059
void *elts;
7060
ngx_uint_t nelts;
7061
ngx_list_part_t *next;
7062
};
7063
7064
7065
typedef struct {
7066
ngx_list_part_t *last;
7067
ngx_list_part_t part;
7068
size_t size;
7069
ngx_uint_t nalloc;
7070
ngx_pool_t *pool;
7071
} ngx_list_t;
7072
</programlisting>
7073
Each structure member is declared on its own line:
7074
<programlisting>
7075
typedef struct {
7076
ngx_uint_t hash;
7077
ngx_str_t key;
7078
ngx_str_t value;
7079
u_char *lowcase_key;
7080
} ngx_table_elt_t;
7081
</programlisting>
7082
</para>
7083
7084
<para>
7085
Function pointers inside structures have defined types ending
7086
with “<literal>_pt</literal>”:
7087
<programlisting>
7088
typedef ssize_t (*ngx_recv_pt)(ngx_connection_t *c, u_char *buf, size_t size);
7089
typedef ssize_t (*ngx_recv_chain_pt)(ngx_connection_t *c, ngx_chain_t *in,
7090
off_t limit);
7091
typedef ssize_t (*ngx_send_pt)(ngx_connection_t *c, u_char *buf, size_t size);
7092
typedef ngx_chain_t *(*ngx_send_chain_pt)(ngx_connection_t *c, ngx_chain_t *in,
7093
off_t limit);
7094
7095
typedef struct {
7096
ngx_recv_pt recv;
7097
ngx_recv_chain_pt recv_chain;
7098
ngx_recv_pt udp_recv;
7099
ngx_send_pt send;
7100
ngx_send_pt udp_send;
7101
ngx_send_chain_pt udp_send_chain;
7102
ngx_send_chain_pt send_chain;
7103
ngx_uint_t flags;
7104
} ngx_os_io_t;
7105
</programlisting>
7106
</para>
7107
7108
<para>
7109
Enumerations have types ending with “<literal>_e</literal>”:
7110
<programlisting>
7111
typedef enum {
7112
ngx_http_fastcgi_st_version = 0,
7113
ngx_http_fastcgi_st_type,
7114
...
7115
ngx_http_fastcgi_st_padding
7116
} ngx_http_fastcgi_state_e;
7117
</programlisting>
7118
</para>
7119
7120
</section>
7121
7122
7123
<section name="Variables" id="code_style_variables">
7124
7125
<para>
7126
Variables are declared sorted by length of a base type, then alphabetically.
7127
Type names and variable names are aligned.
7128
The type and name “columns” are separated with two spaces.
7129
Large arrays are put at the end of a declaration block:
7130
<programlisting>
7131
u_char | | *rv, *p;
7132
ngx_conf_t | | *cf;
7133
ngx_uint_t | | i, j, k;
7134
unsigned int | | len;
7135
struct sockaddr | | *sa;
7136
const unsigned char | | *data;
7137
ngx_peer_connection_t | | *pc;
7138
ngx_http_core_srv_conf_t | |**cscfp;
7139
ngx_http_upstream_srv_conf_t| | *us, *uscf;
7140
u_char | | text[NGX_SOCKADDR_STRLEN];
7141
</programlisting>
7142
</para>
7143
7144
<para>
7145
Static and global variables may be initialized on declaration:
7146
<programlisting>
7147
static ngx_str_t ngx_http_memcached_key = ngx_string("memcached_key");
7148
</programlisting>
7149
7150
<programlisting>
7151
static ngx_uint_t mday[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
7152
</programlisting>
7153
7154
<programlisting>
7155
static uint32_t ngx_crc32_table16[] = {
7156
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
7157
...
7158
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
7159
};
7160
</programlisting>
7161
</para>
7162
7163
<para>
7164
There is a bunch of commonly used type/name combinations:
7165
<programlisting>
7166
u_char *rv;
7167
ngx_int_t rc;
7168
ngx_conf_t *cf;
7169
ngx_connection_t *c;
7170
ngx_http_request_t *r;
7171
ngx_peer_connection_t *pc;
7172
ngx_http_upstream_srv_conf_t *us, *uscf;
7173
</programlisting>
7174
</para>
7175
</section>
7176
7177
7178
<section name="Functions" id="code_style_functions">
7179
7180
<para>
7181
All functions (even static ones) should have prototypes.
7182
Prototypes include argument names.
7183
Long prototypes are wrapped with a single indentation on continuation lines:
7184
<programlisting>
7185
static char *ngx_http_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
7186
static ngx_int_t ngx_http_init_phases(ngx_conf_t *cf,
7187
ngx_http_core_main_conf_t *cmcf);
7188
7189
static char *ngx_http_merge_servers(ngx_conf_t *cf,
7190
ngx_http_core_main_conf_t *cmcf, ngx_http_module_t *module,
7191
ngx_uint_t ctx_index);
7192
</programlisting>
7193
The function name in a definition starts with a new line.
7194
The function body opening and closing braces are on separate lines.
7195
The body of a function is indented.
7196
There are two empty lines between functions:
7197
<programlisting>
7198
static ngx_int_t
7199
ngx_http_find_virtual_server(ngx_http_request_t *r, u_char *host, size_t len)
7200
{
7201
...
7202
}
7203
7204
7205
static ngx_int_t
7206
ngx_http_add_addresses(ngx_conf_t *cf, ngx_http_core_srv_conf_t *cscf,
7207
ngx_http_conf_port_t *port, ngx_http_listen_opt_t *lsopt)
7208
{
7209
...
7210
}
7211
</programlisting>
7212
There is no space after the function name and opening parenthesis.
7213
Long function calls are wrapped such that continuation lines start
7214
from the position of the first function argument.
7215
If this is impossible, format the first continuation line such that it
7216
ends at position 79:
7217
<programlisting>
7218
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
7219
"http header: \"%V: %V\"",
7220
&amp;h->key, &amp;h->value);
7221
7222
hc->busy = ngx_palloc(r->connection->pool,
7223
cscf->large_client_header_buffers.num * sizeof(ngx_buf_t *));
7224
</programlisting>
7225
The <literal>ngx_inline</literal> macro should be used instead of
7226
<literal>inline</literal>:
7227
<programlisting>
7228
static ngx_inline void ngx_cpuid(uint32_t i, uint32_t *buf);
7229
</programlisting>
7230
</para>
7231
7232
</section>
7233
7234
7235
<section name="Expressions" id="code_style_expressions">
7236
7237
<para>
7238
Binary operators except “<literal>.</literal>” and “<literal>−></literal>
7239
should be separated from their operands by one space.
7240
Unary operators and subscripts are not separated from their operands by spaces:
7241
<programlisting>
7242
width = width * 10 + (*fmt++ - '0');
7243
</programlisting>
7244
<programlisting>
7245
ch = (u_char) ((decoded &lt;&lt; 4) + (ch - '0'));
7246
</programlisting>
7247
<programlisting>
7248
r->exten.data = &amp;r->uri.data[i + 1];
7249
</programlisting>
7250
</para>
7251
7252
<para>
7253
Type casts are separated by one space from casted expressions.
7254
An asterisk inside type cast is separated with space from type name:
7255
<programlisting>
7256
len = ngx_sock_ntop((struct sockaddr *) sin6, p, len, 1);
7257
</programlisting>
7258
</para>
7259
7260
<para>
7261
If an expression does not fit into single line, it is wrapped.
7262
The preferred point to break a line is a binary operator.
7263
The continuation line is lined up with the start of expression:
7264
<programlisting>
7265
if (status == NGX_HTTP_MOVED_PERMANENTLY
7266
|| status == NGX_HTTP_MOVED_TEMPORARILY
7267
|| status == NGX_HTTP_SEE_OTHER
7268
|| status == NGX_HTTP_TEMPORARY_REDIRECT
7269
|| status == NGX_HTTP_PERMANENT_REDIRECT)
7270
{
7271
...
7272
}
7273
</programlisting>
7274
<programlisting>
7275
p->temp_file->warn = "an upstream response is buffered "
7276
"to a temporary file";
7277
</programlisting>
7278
As a last resort, it is possible to wrap an expression so that the
7279
continuation line ends at position 79:
7280
<programlisting>
7281
hinit->hash = ngx_pcalloc(hinit->pool, sizeof(ngx_hash_wildcard_t)
7282
+ size * sizeof(ngx_hash_elt_t *));
7283
</programlisting>
7284
The above rules also apply to sub-expressions,
7285
where each sub-expression has its own indentation level:
7286
<programlisting>
7287
if (((u->conf->cache_use_stale &amp; NGX_HTTP_UPSTREAM_FT_UPDATING)
7288
|| c->stale_updating) &amp;&amp; !r->background
7289
&amp;&amp; u->conf->cache_background_update)
7290
{
7291
...
7292
}
7293
</programlisting>
7294
Sometimes, it is convenient to wrap an expression after a cast.
7295
In this case, the continuation line is indented:
7296
<programlisting>
7297
node = (ngx_rbtree_node_t *)
7298
((u_char *) lr - offsetof(ngx_rbtree_node_t, color));
7299
</programlisting>
7300
</para>
7301
7302
<para>
7303
Pointers are explicitly compared to
7304
<literal>NULL</literal> (not <literal>0</literal>):
7305
7306
<programlisting>
7307
if (ptr != NULL) {
7308
...
7309
}
7310
</programlisting>
7311
</para>
7312
7313
</section>
7314
7315
7316
<section name="Conditionals and Loops" id="code_style_conditionals_and_loops">
7317
7318
<para>
7319
The “<literal>if</literal>” keyword is separated from the condition by
7320
one space.
7321
Opening brace is located on the same line, or on a
7322
dedicated line if the condition takes several lines.
7323
Closing brace is located on a dedicated line, optionally followed
7324
by “<literal>else if</literal> / <literal>else</literal>”.
7325
Usually, there is an empty line before the
7326
<literal>else if</literal> / <literal>else</literal>” part:
7327
<programlisting>
7328
if (node->left == sentinel) {
7329
temp = node->right;
7330
subst = node;
7331
7332
} else if (node->right == sentinel) {
7333
temp = node->left;
7334
subst = node;
7335
7336
} else {
7337
subst = ngx_rbtree_min(node->right, sentinel);
7338
7339
if (subst->left != sentinel) {
7340
temp = subst->left;
7341
7342
} else {
7343
temp = subst->right;
7344
}
7345
}
7346
</programlisting>
7347
</para>
7348
7349
<para>
7350
Similar formatting rules are applied to “<literal>do</literal>
7351
and “<literal>while</literal>” loops:
7352
<programlisting>
7353
while (p &lt; last &amp;&amp; *p == ' ') {
7354
p++;
7355
}
7356
</programlisting>
7357
7358
<programlisting>
7359
do {
7360
ctx->node = rn;
7361
ctx = ctx->next;
7362
} while (ctx);
7363
</programlisting>
7364
</para>
7365
7366
<para>
7367
The “<literal>switch</literal>” keyword is separated from the condition by
7368
one space.
7369
Opening brace is located on the same line.
7370
Closing brace is located on a dedicated line.
7371
The “<literal>case</literal>” keywords are lined up with
7372
<literal>switch</literal>”:
7373
<programlisting>
7374
switch (ch) {
7375
case '!':
7376
looked = 2;
7377
state = ssi_comment0_state;
7378
break;
7379
7380
case '&lt;':
7381
copy_end = p;
7382
break;
7383
7384
default:
7385
copy_end = p;
7386
looked = 0;
7387
state = ssi_start_state;
7388
break;
7389
}
7390
</programlisting>
7391
</para>
7392
7393
<para>
7394
Most “<literal>for</literal>” loops are formatted like this:
7395
<programlisting>
7396
for (i = 0; i &lt; ccf->env.nelts; i++) {
7397
...
7398
}
7399
</programlisting>
7400
<programlisting>
7401
for (q = ngx_queue_head(locations);
7402
q != ngx_queue_sentinel(locations);
7403
q = ngx_queue_next(q))
7404
{
7405
...
7406
}
7407
</programlisting>
7408
If some part of the “<literal>for</literal>” statement is omitted,
7409
this is indicated by the “<literal>/* void */</literal>” comment:
7410
<programlisting>
7411
for (i = 0; /* void */ ; i++) {
7412
...
7413
}
7414
</programlisting>
7415
A loop with an empty body is also indicated by the
7416
<literal>/* void */</literal>” comment which may be put on the same line:
7417
<programlisting>
7418
for (cl = *busy; cl->next; cl = cl->next) { /* void */ }
7419
</programlisting>
7420
An endless loop looks like this:
7421
<programlisting>
7422
for ( ;; ) {
7423
...
7424
}
7425
</programlisting>
7426
</para>
7427
7428
</section>
7429
7430
7431
<section name="Labels" id="code_style_labels">
7432
7433
<para>
7434
Labels are surrounded with empty lines and are indented at the previous level:
7435
<programlisting>
7436
if (i == 0) {
7437
u->err = "host not found";
7438
goto failed;
7439
}
7440
7441
u->addrs = ngx_pcalloc(pool, i * sizeof(ngx_addr_t));
7442
if (u->addrs == NULL) {
7443
goto failed;
7444
}
7445
7446
u->naddrs = i;
7447
7448
...
7449
7450
return NGX_OK;
7451
7452
failed:
7453
7454
freeaddrinfo(res);
7455
return NGX_ERROR;
7456
</programlisting>
7457
</para>
7458
</section>
7459
</section>
7460
7461
<section name="Debugging memory issues" id="debug_memory">
7462
7463
<para>
7464
To debug memory issues such as buffer overruns or use-after-free errors, you
7465
can use the <link url="https://en.wikipedia.org/wiki/AddressSanitizer">
7466
AddressSanitizer</link> (ASan) supported by some modern compilers.
7467
To enable ASan with <literal>gcc</literal> and <literal>clang</literal>,
7468
use the <literal>-fsanitize=address</literal> compiler and linker option.
7469
When building nginx, this can be done by adding the option to
7470
<literal>--with-cc-opt</literal> and <literal>--with-ld-opt</literal>
7471
parameters of the <literal>configure</literal> script.
7472
</para>
7473
7474
<para>
7475
Since most allocations in nginx are made from nginx internal
7476
<link id="pool">pool</link>, enabling ASan may not always be enough to debug
7477
memory issues.
7478
The internal pool allocates a big chunk of memory from the system and cuts
7479
smaller allocations from it.
7480
However, this mechanism can be disabled by setting the
7481
<literal>NGX_DEBUG_PALLOC</literal> macro to <literal>1</literal>.
7482
In this case, allocations are passed directly to the system allocator giving it
7483
full control over the buffers boundaries.
7484
</para>
7485
7486
<para>
7487
The following configuration line summarizes the information provided above.
7488
It is recommended while developing third-party modules and testing nginx on
7489
different platforms.
7490
</para>
7491
7492
<programlisting>
7493
auto/configure --with-cc-opt='-fsanitize=address -DNGX_DEBUG_PALLOC=1'
7494
--with-ld-opt=-fsanitize=address
7495
</programlisting>
7496
7497
</section>
7498
7499
<section name="Common Pitfalls" id="common_pitfals">
7500
7501
<section name="Writing a C module" id="module_pitfall">
7502
7503
<para>
7504
The most common pitfall is an attempt to write a full-fledged C module
7505
when it can be avoided.
7506
In most cases your task can be accomplished by creating a proper configuration.
7507
If writing a module is inevitable, try to make it
7508
as small and simple as possible.
7509
For example, a module can only export some
7510
<link id="http_variables">variables</link>.
7511
</para>
7512
7513
<para>
7514
Before starting a module, consider the following questions:
7515
7516
<list type="bullet">
7517
7518
<listitem>
7519
Is it possible to implement a desired feature using already
7520
<link doc="../../docs/index.xml">available modules</link>?
7521
</listitem>
7522
7523
<listitem>
7524
Is it possible to solve an issue using built-in scripting languages,
7525
such as <link doc="../http/ngx_http_perl_module.xml">Perl</link>
7526
or <link doc="../njs/index.xml">njs</link>?
7527
</listitem>
7528
7529
</list>
7530
7531
</para>
7532
7533
</section>
7534
7535
<section name="C Strings" id="c_strings">
7536
7537
<para>
7538
The most used string type in nginx,
7539
<link id="string_overview">ngx_str_t</link> is not a C-Style
7540
zero-terminated string.
7541
You cannot pass the data to standard C library functions
7542
such as <c-func>strlen</c-func> or <c-func>strstr</c-func>.
7543
Instead, nginx <link id="string_overview">counterparts</link>
7544
that accept either <literal>ngx_str_t</literal> should be used
7545
or pointer to data and a length.
7546
However, there is a case when <literal>ngx_str_t</literal> holds
7547
a pointer to a zero-terminated string: strings that come as a result of
7548
configuration file parsing are zero-terminated.
7549
</para>
7550
7551
</section>
7552
7553
<section name="Global Variables" id="global_variables">
7554
7555
<para>
7556
Avoid using global variables in your modules.
7557
Most likely this is an error to have a global variable.
7558
Any global data should be tied to a <link id="cycle">configuration cycle</link>
7559
and be allocated from the corresponding <link id="pool">memory pool</link>.
7560
This allows nginx to perform graceful configuration reloads.
7561
An attempt to use global variables will likely break this feature,
7562
because it will be impossible to have two configurations at
7563
the same time and get rid of them.
7564
Sometimes global variables are required.
7565
In this case, special attention is needed to manage reconfiguration
7566
properly.
7567
Also, check if libraries used by your code have implicit
7568
global state that may be broken on reload.
7569
</para>
7570
7571
</section>
7572
7573
<section name="Manual Memory Management" id="manual_memory_management">
7574
7575
<para>
7576
Instead of dealing with malloc/free approach which is error prone,
7577
learn how to use nginx <link id="pool">pools</link>.
7578
A pool is created and tied to an object -
7579
<link id="http_conf">configuration</link>,
7580
<link id="cycle">cycle</link>,
7581
<link id="connection">connection</link>,
7582
or <link id="http_request">HTTP request</link>.
7583
When the object is destroyed, the associated pool is destroyed too.
7584
So when working with an object, it is possible to allocate the amount
7585
needed from the corresponding pool and don't care about freeing memory
7586
even in case of errors.
7587
</para>
7588
7589
</section>
7590
7591
<section name="Threads" id="threads_pitfalls">
7592
7593
<para>
7594
It is recommended to avoid using threads in nginx because it will
7595
definitely break things: most nginx functions are not thread-safe.
7596
It is expected that a thread will be executing only system calls and
7597
thread-safe library functions.
7598
If you need to run some code that is not related to client request processing,
7599
the proper way is to schedule a timer in the <literal>init_process</literal>
7600
module handler and perform required actions in timer handler.
7601
Internally nginx makes use of <link id="threads">threads</link> to
7602
boost IO-related operations, but this is a special case with a lot
7603
of limitations.
7604
</para>
7605
7606
</section>
7607
7608
<section name="Blocking Libraries" id="libraries">
7609
7610
<para>
7611
A common mistake is to use libraries that are blocking internally.
7612
Most libraries out there are synchronous and blocking by nature.
7613
In other words, they perform one operation at a time and waste
7614
time waiting for response from other peer.
7615
As a result, when a request is processed with such library, whole
7616
nginx worker is blocked, thus destroying performance.
7617
Use only libraries that provide asynchronous interface and don't
7618
block whole process.
7619
</para>
7620
7621
</section>
7622
7623
7624
<section name="HTTP Requests to External Services" id="http_requests_to_ext">
7625
7626
<para>
7627
Often modules need to perform an HTTP call to some external service.
7628
A common mistake is to use some external library, such as libcurl,
7629
to perform the HTTP request.
7630
It is absolutely unnecessary to bring a huge amount of external
7631
(probably <link id="using_libraries">blocking</link>!) code
7632
for the task which can be accomplished by nginx itself.
7633
</para>
7634
7635
<para>
7636
There are two basic usage scenarios when an external request is needed:
7637
7638
<list type="bullet">
7639
7640
<listitem>
7641
in the context of processing a client request (for example, in content handler)
7642
</listitem>
7643
7644
<listitem>
7645
in the context of a worker process (for example, timer handler)
7646
</listitem>
7647
7648
</list>
7649
7650
</para>
7651
7652
<para>
7653
In the first case, the best is to use
7654
<link id="http_subrequests">subrequests API</link>.
7655
Instead of directly accessing external service, you declare a location
7656
in nginx configuration and direct your subrequest to this location.
7657
This location is not limited to
7658
<link doc="../http/ngx_http_proxy_module.xml" id="proxy_pass">proxying</link>
7659
requests, but may contain other nginx directives.
7660
An example of such approach is the
7661
<link doc="../http/ngx_http_auth_request_module.xml" id="auth_request"/>
7662
directive implemented in
7663
<link url="https://github.com/nginx/nginx/blob/master/src/http/modules/ngx_http_auth_request_module.c">ngx_http_auth_request module</link>.
7664
</para>
7665
7666
<para>
7667
For the second case, it is possible to use basic HTTP client functionality
7668
available in nginx.
7669
For example,
7670
<link url="https://github.com/nginx/nginx/blob/master/src/event/ngx_event_openssl_stapling.c">OCSP module</link>
7671
implements simple HTTP client.
7672
</para>
7673
7674
</section>
7675
7676
</section>
7677
7678
</article>
7679
7680