=encoding utf-8 =head1 Name development_guide - Development guide =head1 Introduction =head2 Code layout =over =item * C — Build scripts =item * C =over =item * C — Basic types and functions — string, array, log, pool, etc. =item * C — Event core =over =item * C — Event notification modules: C, C, C, an optional array of integers to hold any C that are found, and the array's C. The size of the C array must be a multiple of three, as required by the L. In the example, the size is calculated from the total number of captures plus one for the matched string itself. If there are matches, captures can be accessed as follows: u_char *p; size_t size; ngx_str_t name, value; /* all captures */ for (i = 0; i < n * 2; i += 2) { value.data = input.data + captures[i]; value.len = captures[i + 1] — captures[i]; } /* accessing named captures */ size = rc.name_size; p = rc.names; for (i = 0; i < rc.named_captures; i++, p += size) { /* capture name */ name.data = &p[2]; name.len = ngx_strlen(name.data); n = 2 * ((p[0] << 8) + p[1]); /* captured value */ value.data = &input.data[captures[n]]; value.len = captures[n + 1] — captures[n]; } The C function accepts the array of C elements (which are just compiled regular expressions with associated names), a string to match, and a log. The function applies expressions from the array to the string until either a match is found or no more expressions are left. The return value is C when there is a match and C otherwise, or C in case of error. =head1 Time The C structure represents time with three separate types for seconds, milliseconds, and the GMT offset: typedef struct { time_t sec; ngx_uint_t msec; ngx_int_t gmtoff; } ngx_time_t; The C structure is an alias for C on UNIX platforms and C on Windows. To obtain the current time, it is usually sufficient to access one of the available global variables, representing the cached time value in the desired format. The available string representations are: =over =item * C — Used in error log entries: C<"1970E09E28 12:00:00"> =item * C — Used in HTTP access log entries: C<"28ESepE1970:12:00:00 +0600"> =item * C — Used in syslog entries: C<"Sep 28 12:00:00"> =item * C — Used in HTTP headers: C<"Mon, 28 Sep 1970 06:00:00 GMT"> =item * C — The ISO 8601 standard format: C<"1970-09-28T12:00:00+06:00"> =back The C and C macros return the current time value in seconds and are the preferred way to access the cached time value. To obtain the time explicitly, use C, which updates its argument (pointer to C). The time is always updated when nginx returns to the event loop from system calls. To update the time immediately, call C, or C if updating the time in the signal handler context. The following functions convert C into the indicated broken-down time representation. The first function in each pair converts C to C and the second (with the C<_libc_> infix) to C: =over =item * C — Time expressed as UTC =item * C — Time expressed relative to the local time zone =back The C function returns a string representation suitable for use in HTTP headers (for example, C<"Mon, 28 Sep 1970 06:00:00 GMT">). The C returns a string representation function returns a string representation suitable for HTTP cookies (C<"Thu, 31-Dec-37 23:55:55 GMT">). =head1 Containers =head2 Array The nginx array type C is defined as follows typedef struct { void *elts; ngx_uint_t nelts; size_t size; ngx_uint_t nalloc; ngx_pool_t *pool; } ngx_array_t; The elements of the array are available in the C field. The C field holds the number of elements. The C field holds the size of a single element and is set when the array is initialized. Use the C call to create an array in a pool, and the C call to initialize an array object that has already been allocated. ngx_array_t *a, b; /* create an array of strings with preallocated memory for 10 elements */ a = ngx_array_create(pool, 10, sizeof(ngx_str_t)); /* initialize string array for 10 elements */ ngx_array_init(&b, pool, 10, sizeof(ngx_str_t)); Use the following functions to add elements to an array: =over =item * C adds one tail element and returns pointer to it =item * C adds C tail elements and returns pointer to the first one =back If the currently allocated amount of memory is not large enough to accommodate the new elements, a new block of memory is allocated and the existing elements are copied to it. The new memory block is normally twice as large as the existing one. s = ngx_array_push(a); ss = ngx_array_push_n(&b, 3); =head2 List In nginx a list is a sequence of arrays, optimized for inserting a potentially large number of items. The C list type is defined as follows: typedef struct { ngx_list_part_t *last; ngx_list_part_t part; size_t size; ngx_uint_t nalloc; ngx_pool_t *pool; } ngx_list_t; The actual items are stored in list parts, which are defined as follows: typedef struct ngx_list_part_s ngx_list_part_t; struct ngx_list_part_s { void *elts; ngx_uint_t nelts; ngx_list_part_t *next; }; Before use, a list must be initialized by calling C or created by calling C. Both functions take as arguments the size of a single item and a number of items per list part. To add an item to a list, use the C function. To iterate over the items, directly access the list fields as shown in the example: ngx_str_t *v; ngx_uint_t i; ngx_list_t *list; ngx_list_part_t *part; list = ngx_list_create(pool, 100, sizeof(ngx_str_t)); if (list == NULL) { /* error */ } /* add items to the list */ v = ngx_list_push(list); if (v == NULL) { /* error */ } ngx_str_set(v, "foo"); v = ngx_list_push(list); if (v == NULL) { /* error */ } ngx_str_set(v, "bar"); /* iterate over the list */ part = &list->part; v = part->elts; for (i = 0; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; v = part->elts; i = 0; } ngx_do_smth(&v[i]); } Lists are primarily used for HTTP input and output headers. Lists do not support item removal. However, when needed, items can internally be marked as missing without actually being removed from the list. For example, to mark HTTP output headers (which are stored as C objects) as missing, set the C field in C to zero. Items marked in this way are explicitly skipped when the headers are iterated over. =head2 Queue In nginx a queue is an intrusive doubly linked list, with each node defined as follows: typedef struct ngx_queue_s ngx_queue_t; struct ngx_queue_s { ngx_queue_t *prev; ngx_queue_t *next; }; The head queue node is not linked with any data. Use the C call to initialize the list head before use. Queues support the following operations: =over =item * C, C — Insert a new node =item * C — Remove a queue node =item * C — Split a queue at a node, returning the queue tail in a separate queue =item * C — Add a second queue to the first queue =item * C, C — Get first or last queue node =item * C - Get a queue sentinel object to end iteration at =item * C — Get a reference to the beginning of a queue node data structure, considering the queue field offset in it =back An example: typedef struct { ngx_str_t value; ngx_queue_t queue; } ngx_foo_t; ngx_foo_t *f; ngx_queue_t values, *q; ngx_queue_init(&values); f = ngx_palloc(pool, sizeof(ngx_foo_t)); if (f == NULL) { /* error */ } ngx_str_set(&f->value, "foo"); ngx_queue_insert_tail(&values, &f->queue); /* insert more nodes here */ for (q = ngx_queue_head(&values); q != ngx_queue_sentinel(&values); q = ngx_queue_next(q)) { f = ngx_queue_data(q, ngx_foo_t, queue); ngx_do_smth(&f->value); } =head2 Red-Black tree The FcoreEngx_rbtree.h> header file provides access to the effective implementation of red-black trees. typedef struct { ngx_rbtree_t rbtree; ngx_rbtree_node_t sentinel; /* custom per-tree data here */ } my_tree_t; typedef struct { ngx_rbtree_node_t rbnode; /* custom per-node data */ foo_t val; } my_node_t; To deal with a tree as a whole, you need two nodes: root and sentinel. Typically, they are added to a custom structure, allowing you to organize your data into a tree in which the leaves contain a link to or embed your data. To initialize a tree: my_tree_t root; ngx_rbtree_init(&root.rbtree, &root.sentinel, insert_value_function); To traverse a tree and insert new values, use the "C" functions. For example, the C function deals with the C type. Its arguments are pointers to a root node of an insertion, the newly created node to be added, and a tree sentinel. void ngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp, ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel) The traversal is pretty straightforward and can be demonstrated with the following lookup function pattern: my_node_t * my_rbtree_lookup(ngx_rbtree_t *rbtree, foo_t *val, uint32_t hash) { ngx_int_t rc; my_node_t *n; ngx_rbtree_node_t *node, *sentinel; node = rbtree->root; sentinel = rbtree->sentinel; while (node != sentinel) { n = (my_node_t *) node; if (hash != node->key) { node = (hash < node->key) ? node->left : node->right; continue; } rc = compare(val, node->val); if (rc < 0) { node = node->left; continue; } if (rc > 0) { node = node->right; continue; } return n; } return NULL; } The C function is a classic comparator function that returns a value less than, equal to, or greater than zero. To speed up lookups and avoid comparing user objects that can be big, an integer hash field is used. To add a node to a tree, allocate a new node, initialize it and call C: my_node_t *my_node; ngx_rbtree_node_t *node; my_node = ngx_palloc(...); init_custom_data(&my_node->val); node = &my_node->rbnode; node->key = create_key(my_node->val); ngx_rbtree_insert(&root->rbtree, node); To remove a node, call the C function: ngx_rbtree_delete(&root->rbtree, node); =head2 Hash Hash table functions are declared in FcoreEngx_hash.h>. Both exact and wildcard matching are supported. The latter requires extra setup and is described in a separate section below. Before initializing a hash, you need to know the number of elements it will hold so that nginx can build it optimally. Two parameters that need to be configured are C and C, as detailed in a separate L. They are usually configurable by the user. Hash initialization settings are stored with the C type, and the hash itself is C: ngx_hash_t foo_hash; ngx_hash_init_t hash; hash.hash = &foo_hash; hash.key = ngx_hash_key; hash.max_size = 512; hash.bucket_size = ngx_align(64, ngx_cacheline_size); hash.name = "foo_hash"; hash.pool = cf->pool; hash.temp_pool = cf->temp_pool; The C is a pointer to a function that creates the hash integer key from a string. There are two generic key-creation functions: C and C. The latter converts a string to all lowercase characters, so the passed string must be writable. If that is not true, pass the C flag to the function, initializing the key array (see below). The hash keys are stored in C and are initialized with C: The second parameter (C) controls the amount of resources preallocated for the hash and can be either C or C. The latter is appropriate if you expect the hash to contain thousands of elements. ngx_hash_keys_arrays_t foo_keys; foo_keys.pool = cf->pool; foo_keys.temp_pool = cf->temp_pool; ngx_hash_keys_array_init(&foo_keys, NGX_HASH_SMALL); To insert keys into a hash keys array, use the C function: ngx_str_t k1 = ngx_string("key1"); ngx_str_t k2 = ngx_string("key2"); ngx_hash_add_key(&foo_keys, &k1, &my_data_ptr_1, NGX_HASH_READONLY_KEY); ngx_hash_add_key(&foo_keys, &k2, &my_data_ptr_2, NGX_HASH_READONLY_KEY); To build the hash table, call the C function: ngx_hash_init(&hash, foo_keys.keys.elts, foo_keys.keys.nelts); The function fails if C or C parameters are not big enough. When the hash is built, use the C function to look up elements: my_data_t *data; ngx_uint_t key; key = ngx_hash_key(k1.data, k1.len); data = ngx_hash_find(&foo_hash, key, k1.data, k1.len); if (data == NULL) { /* key not found */ } =head3 Wildcard matching To create a hash that works with wildcards, use the C type. It includes the hash type described above and has two additional keys arrays: C and C. The initialization of basic properties is similar to a regular hash: ngx_hash_init_t hash ngx_hash_combined_t foo_hash; hash.hash = &foo_hash.hash; hash.key = ...; It is possible to add wildcard keys using the C flag: /* k1 = ".example.org"; */ /* k2 = "foo.*"; */ ngx_hash_add_key(&foo_keys, &k1, &data1, NGX_HASH_WILDCARD_KEY); ngx_hash_add_key(&foo_keys, &k2, &data2, NGX_HASH_WILDCARD_KEY); The function recognizes wildcards and adds keys into the corresponding arrays. Please refer to the L module documentation for the description of the wildcard syntax and the matching algorithm. Depending on the contents of added keys, you may need to initialize up to three key arrays: one for exact matching (described above), and two more to enable matching starting from the head or tail of a string: if (foo_keys.dns_wc_head.nelts) { ngx_qsort(foo_keys.dns_wc_head.elts, (size_t) foo_keys.dns_wc_head.nelts, sizeof(ngx_hash_key_t), cmp_dns_wildcards); hash.hash = NULL; hash.temp_pool = pool; if (ngx_hash_wildcard_init(&hash, foo_keys.dns_wc_head.elts, foo_keys.dns_wc_head.nelts) != NGX_OK) { return NGX_ERROR; } foo_hash.wc_head = (ngx_hash_wildcard_t *) hash.hash; } The keys array needs to be sorted, and initialization results must be added to the combined hash. The initialization of C array is done similarly. The lookup in a combined hash is handled by the C: /* key = "bar.example.org"; — will match ".example.org" */ /* key = "foo.example.com"; — will match "foo.*" */ hkey = ngx_hash_key(key.data, key.len); res = ngx_hash_find_combined(&foo_hash, hkey, key.data, key.len); =head1 Memory management =head2 Heap To allocate memory from system heap, use the following functions: =over =item * C — Allocate memory from system heap. This is a wrapper around C with logging support. Allocation error and debugging information is logged to C. =item * C — Allocate memory from system heap like C, but fill memory with zeros after allocation. =item * C — Allocate aligned memory from system heap. This is a wrapper around C on those platforms that provide that function. Otherwise implementation falls back to C which provides maximum alignment. =item * C — Free allocated memory. This is a wrapper around C =back =head2 Pool Most nginx allocations are done in pools. Memory allocated in an nginx pool is freed automatically when the pool is destroyed. This provides good allocation performance and makes memory control easy. A pool internally allocates objects in continuous blocks of memory. Once a block is full, a new one is allocated and added to the pool memory block list. When the requested allocation is too large to fit into a block, the request is forwarded to the system allocator and the returned pointer is stored in the pool for further deallocation. The type for nginx pools is C. The following operations are supported: =over =item * C — Create a pool with specified block size. The pool object returned is allocated in the pool as well. The C should be at least C and a multiple of C. =item * C — Free all pool memory, including the pool object itself. =item * C — Allocate aligned memory from the specified pool. =item * C — Allocate aligned memory from the specified pool and fill it with zeroes. =item * C — Allocate unaligned memory from the specified pool. Mostly used for allocating strings. =item * C — Free memory that was previously allocated in the specified pool. Only allocations that result from requests forwarded to the system allocator can be freed. =back u_char *p; ngx_str_t *s; ngx_pool_t *pool; pool = ngx_create_pool(1024, log); if (pool == NULL) { /* error */ } s = ngx_palloc(pool, sizeof(ngx_str_t)); if (s == NULL) { /* error */ } ngx_str_set(s, "foo"); p = ngx_pnalloc(pool, 3); if (p == NULL) { /* error */ } ngx_memcpy(p, "foo", 3); Chain links (C) are actively used in nginx, so the nginx pool implementation provides a way to reuse them. The C field of C keeps a list of previously allocated links ready for reuse. For efficient allocation of a chain link in a pool, use the C function. This function looks up a free chain link in the pool list and allocates a new chain link if the pool list is empty. To free a link, call the C function. Cleanup handlers can be registered in a pool. A cleanup handler is a callback with an argument which is called when pool is destroyed. A pool is usually tied to a specific nginx object (like an HTTP request) and is destroyed when the object reaches the end of its lifetime. Registering a pool cleanup is a convenient way to release resources, close file descriptors or make final adjustments to the shared data associated with the main object. To register a pool cleanup, call C, which returns a C pointer to be filled in by the caller. Use the C argument to allocate context for the cleanup handler. ngx_pool_cleanup_t *cln; cln = ngx_pool_cleanup_add(pool, 0); if (cln == NULL) { /* error */ } cln->handler = ngx_my_cleanup; cln->data = "foo"; ... static void ngx_my_cleanup(void *data) { u_char *msg = data; ngx_do_smth(msg); } =head2 Shared memory Shared memory is used by nginx to share common data between processes. The C function adds a new shared memory entry C to a cycle. The function receives the C and C of the zone. Each shared zone must have a unique name. If a shared zone entry with the provided C and C already exists, the existing zone entry is reused. The function fails with an error if an existing entry with the same name has a different tag. Usually, the address of the module structure is passed as C, making it possible to reuse shared zones by name within one nginx module. The shared memory entry structure C has the following fields: =over =item * C — Initialization callback, called after the shared zone is mapped to actual memory =item * C — Data context, used to pass arbitrary data to the C callback =item * C — Flag that disables reuse of a shared zone from the old cycle =item * C — Shared zone tag =item * C — Platform-specific object of type C, having at least the following fields: =over =item * C — Mapped shared memory address, initially NULL =item * C — Shared memory size =item * C — Shared memory name =item * C — Shared memory log =item * C — Flag that indicates shared memory was inherited from the master process (Windows-specific) =back =back Shared zone entries are mapped to actual memory in C after the configuration is parsed. On POSIX systems, the C syscall is used to create the shared anonymous mapping. On Windows, the CE C pair is used. For allocating in shared memory, nginx provides the slab pool C type. A slab pool for allocating memory is automatically created in each nginx shared zone. The pool is located in the beginning of the shared zone and can be accessed by the expression C<(ngx_slab_pool_t *) shm_zone-Eshm.addr>. To allocate memory in a shared zone, call either C or C. To free memory, call C. Slab pool divides all shared zone into pages. Each page is used for allocating objects of the same size. The specified size must be a power of 2, and greater than the minimum size of 8 bytes. Nonconforming values are rounded up. A bitmask for each page tracks which blocks are in use and which are free for allocation. For sizes greater than a half page (which is usually 2048 bytes), allocation is done an entire page at a time To protect data in shared memory from concurrent access, use the mutex available in the C field of C. A mutex is most commonly used by the slab pool while allocating and freeing memory, but it can be used to protect any other user data structures allocated in the shared zone. To lock or unlock a mutex, call Cshpool-Emutex)> or Cshpool-Emutex)> respectively. ngx_str_t name; ngx_foo_ctx_t *ctx; ngx_shm_zone_t *shm_zone; ngx_str_set(&name, "foo"); /* allocate shared zone context */ ctx = ngx_pcalloc(cf->pool, sizeof(ngx_foo_ctx_t)); if (ctx == NULL) { /* error */ } /* add an entry for 64k shared zone */ shm_zone = ngx_shared_memory_add(cf, &name, 65536, &ngx_foo_module); if (shm_zone == NULL) { /* error */ } /* register init callback and context */ shm_zone->init = ngx_foo_init_zone; shm_zone->data = ctx; ... static ngx_int_t ngx_foo_init_zone(ngx_shm_zone_t *shm_zone, void *data) { ngx_foo_ctx_t *octx = data; size_t len; ngx_foo_ctx_t *ctx; ngx_slab_pool_t *shpool; value = shm_zone->data; if (octx) { /* reusing a shared zone from old cycle */ ctx->value = octx->value; return NGX_OK; } shpool = (ngx_slab_pool_t *) shm_zone->shm.addr; if (shm_zone->shm.exists) { /* initialize shared zone context in Windows nginx worker */ ctx->value = shpool->data; return NGX_OK; } /* initialize shared zone */ ctx->value = ngx_slab_alloc(shpool, sizeof(ngx_uint_t)); if (ctx->value == NULL) { return NGX_ERROR; } shpool->data = ctx->value; return NGX_OK; } =head1 Logging For logging nginx uses C objects. The nginx logger supports several types of output: =over =item * stderr — Logging to standard error (stderr) =item * file — Logging to a file =item * syslog — Logging to syslog =item * memory — Logging to internal memory storage for development purposes; the memory can be accessed later with a debugger =back A logger instance can be a chain of loggers, linked to each other with the C field. In this case, each message is written to all loggers in the chain. For each logger, a severity level controls which messages are written to the log (only events assigned that level or higher are logged). The following severity levels are supported: =over =item * C =item * C =item * C =item * C =item * C =item * C =item * C =item * C =back For debug logging, the debug mask is checked as well. The debug masks are: =over =item * C =item * C =item * C =item * C =item * C =item * C =item * C =back Normally, loggers are created by existing nginx code from C directives and are available at nearly every stage of processing in cycle, configuration, client connection and other objects. Nginx provides the following logging macros: =over =item * C — Error logging =item * C, C etc — Debug logging with up to eight supported formatting arguments =back A log message is formatted in a buffer of size C (currently, 2048 bytes) on stack. The message is prepended with the severity level, process ID (PID), connection ID (stored in Cconnection>), and the system error text. For non-debug messages Chandler> is called as well to prepend more specific information to the log message. HTTP module sets C function as log handler to log client and server addresses, current action (stored in Caction>), client request line, server name etc. /* specify what is currently done */ log->action = "sending mp4 to client"; /* error and debug log */ ngx_log_error(NGX_LOG_INFO, c->log, 0, "client prematurely closed connection"); ngx_log_debug2(NGX_LOG_DEBUG_HTTP, mp4->file.log, 0, "mp4 start:%ui, length:%ui", mp4->start, mp4->length); The example above results in log entries like these: 2016/09/16 22:08:52 [info] 17445#0: *1 client prematurely closed connection while sending mp4 to client, client: 127.0.0.1, server: , request: "GET /file.mp4 HTTP/1.1" 2016/09/16 23:28:33 [debug] 22140#0: *1 mp4 start:0, length:10000 =head1 Cycle A cycle object stores the nginx runtime context created from a specific configuration. Its type is C. The current cycle is referenced by the C global variable and inherited by nginx workers as they start. Each time the nginx configuration is reloaded, a new cycle is created from the new nginx configuration; the old cycle is usually deleted after the new one is successfully created. A cycle is created by the C function, which takes the previous cycle as its argument. The function locates the previous cycle's configuration file and inherits as many resources as possible from the previous cycle. A placeholder cycle called "init cycle" is created as nginx start, then is replaced by an actual cycle built from configuration. Members of the cycle include: =over =item * C — Cycle pool. Created for each new cycle. =item * C — Cycle log. Initially inherited from the old cycle, it is set to point to C after the configuration is read. =item * C — Cycle log, created by the configuration. It's affected by the root-scope C directive. =item * C, C — Array of connections of type C, created by the event module while initializing each nginx worker. The C directive in the nginx configuration sets the number of connections C. =item * C, C — List and number of currently available connections. If no connections are available, an nginx worker refuses to accept new clients or connect to upstream servers. =item * C, C — Array for mapping file descriptors to nginx connections. This mapping is used by the event modules, having the C flag (currently, it's C and C). =item * C — Array of core module configurations. The configurations are created and filled during reading of nginx configuration files. =item * C, C — Array of modules of type C, both static and dynamic, loaded by the current configuration. =item * C — Array of listening objects of type C. Listening objects are normally added by the C directive of different modules which call the C function. Listen sockets are created based on the listening objects. =item * C — Array of paths of type C. Paths are added by calling the function C from modules which are going to operate on certain directories. These directories are created by nginx after reading configuration, if missing. Moreover, two handlers can be added for each path: =over =item * path loader — Executes only once in 60 seconds after starting or reloading nginx. Normally, the loader reads the directory and stores data in nginx shared memory. The handler is called from the dedicated nginx process “nginx cache loader”. =item * path manager — Executes periodically. Normally, the manager removes old files from the directory and updates nginx memory to reflect the changes. The handler is called from the dedicated “nginx cache manager” process. =back =item * C — List of open file objects of type C, which are created by calling the function C. Currently, nginx uses this kind of open files for logging. After reading the configuration, nginx opens all files in the C list and stores each file descriptor in the object's C field. The files are opened in append mode and are created if missing. The files in the list are reopened by nginx workers upon receiving the reopen signal (most often C). In this case the descriptor in the C field is changed to a new value. =item * C — List of shared memory zones, each added by calling the C function. Shared zones are mapped to the same address range in all nginx processes and are used to share common data, for example the HTTP cache in-memory tree. =back =head1 Buffer For inputEoutput operations, nginx provides the buffer type C. Normally, it's used to hold data to be written to a destination or read from a source. A buffer can reference data in memory or in a file and it's technically possible for a buffer to reference both at the same time. Memory for the buffer is allocated separately and is not related to the buffer structure C. The C structure has the following fields: =over =item * C, C — The boundaries of the memory block allocated for the buffer. =item * C, C — The boundaries of the memory buffer; normally a subrange of C .. C. =item * C, C — The boundaries of a file buffer, expressed as offsets from the beginning of the file. =item * C — Unique value used to distinguish buffers; created by different nginx modules, usually for the purpose of buffer reuse. =item * C — File object. =item * C — Flag indicating that the buffer references writable memory. =item * C — Flag indicating that the buffer references read-only memory. =item * C — Flag indicating that the buffer references data in a file. =item * C — Flag indicating that all data prior to the buffer need to be flushed. =item * C — Flag indicating that the buffer can be reused and needs to be consumed as soon as possible. =item * C — Flag indicating that the buffer carries no data or special signal like C or C. By default nginx considers such buffers an error condition, but this flag tells nginx to skip the error check. =item * C — Flag indicating that the buffer is the last in output. =item * C — Flag indicating that there are no more data buffers in a request or subrequest. =item * C — Reference to another ("shadow") buffer related to the current buffer, usually in the sense that the buffer uses data from the shadow. When the buffer is consumed, the shadow buffer is normally also marked as consumed. =item * C — Flag indicating that the buffer is the last one that references a particular shadow buffer. =item * C — Flag indicating that the buffer is in a temporary file. =back For input and output operations buffers are linked in chains. A chain is a sequence of chain links of type C, defined as follows: typedef struct ngx_chain_s ngx_chain_t; struct ngx_chain_s { ngx_buf_t *buf; ngx_chain_t *next; }; Each chain link keeps a reference to its buffer and a reference to the next chain link. An example of using buffers and chains: ngx_chain_t * ngx_get_my_chain(ngx_pool_t *pool) { ngx_buf_t *b; ngx_chain_t *out, *cl, **ll; /* first buf */ cl = ngx_alloc_chain_link(pool); if (cl == NULL) { /* error */ } b = ngx_calloc_buf(pool); if (b == NULL) { /* error */ } b->start = (u_char *) "foo"; b->pos = b->start; b->end = b->start + 3; b->last = b->end; b->memory = 1; /* read-only memory */ cl->buf = b; out = cl; ll = &cl->next; /* second buf */ cl = ngx_alloc_chain_link(pool); if (cl == NULL) { /* error */ } b = ngx_create_temp_buf(pool, 3); if (b == NULL) { /* error */ } b->last = ngx_cpymem(b->last, "foo", 3); cl->buf = b; cl->next = NULL; *ll = cl; return out; } =head1 Networking =head2 Connection The connection type C is a wrapper around a socket descriptor. It includes the following fields: =over =item * C — Socket descriptor =item * C — Arbitrary connection context. Normally, it is a pointer to a higher-level object built on top of the connection, such as an HTTP request or a Stream session. =item * C, C — Read and write events for the connection. =item * C, C, C, C — IEO operations for the connection. =item * C — Connection pool. =item * C — Connection log. =item * C, C, C — Remote socket address in binary and text forms. =item * C, C — Local socket address in binary form. Initially, these fields are empty. Use the C function to get the local socket address. =item * C, C - PROXY protocol client address and port, if the PROXY protocol is enabled for the connection. =item * C — SSL context for the connection. =item * C — Flag indicating the connection is in a state that makes it eligible for reuse. =item * C — Flag indicating that the connection is being reused and needs to be closed. =back An nginx connection can transparently encapsulate the SSL layer. In this case the connection's C field holds a pointer to an C structure, keeping all SSL-related data for the connection, including C and C. The C, C, C, and C handlers are set to SSL-enabled functions as well. The C directive in the nginx configuration limits the number of connections per nginx worker. All connection structures are precreated when a worker starts and stored in the C field of the cycle object. To retrieve a connection structure, use the C function. It takes as its C argument a socket descriptor, which needs to be wrapped in a connection structure. Because the number of connections per worker is limited, nginx provides a way to grab connections that are currently in use. To enable or disable reuse of a connection, call the C function. Calling C sets the C flag in the connection structure and inserts the connection into the C of the cycle. Whenever C finds out there are no available connections in the cycle's C list, it calls C to release a specific number of reusable connections. For each such connection, the C flag is set and its read handler is called which is supposed to free the connection by calling C and make it available for reuse. To exit the state when a connection can be reused C is called. HTTP client connections are an example of reusable connections in nginx; they are marked as reusable until the first request byte is received from the client. =head1 Events =head2 Event Event object C in nginx provides a mechanism for notification that a specific event has occurred. Fields in C include: =over =item * C — Arbitrary event context used in event handlers, usually as pointer to a connection related to the event. =item * C — Callback function to be invoked when the event happens. =item * C — Flag indicating a write event. Absence of the flag indicates a read event. =item * C — Flag indicating that the event is registered for receiving IEO notifications, normally from notification mechanisms like C, C, C. =item * C — Flag indicating that the event has received an IEO notification. =item * C — Flag indicating that IEO is delayed due to rate limiting. =item * C — Red-black tree node for inserting the event into the timer tree. =item * C — Flag indicating that the event timer is set and not yet expired. =item * C — Flag indicating that the event timer has expired. =item * C — Flag indicating that EOF occurred while reading data. =item * C — Flag indicating that EOF is pending on the socket, even though there may be some data available before it. The flag is delivered via the C C event or C C flag. =item * C — Flag indicating that an error occurred during reading (for a read event) or writing (for a write event). =item * C — Timer event flag indicating that the event should be ignored while shutting down the worker. Graceful worker shutdown is delayed until there are no non-cancelable timer events scheduled. =item * C — Flag indicating that the event is posted to a queue. =item * C — Queue node for posting the event to a queue. =back =head2 I/O events Each connection obtained by calling the C function has two attached events, Cread> and Cwrite>, which are used for receiving notification that the socket is ready for reading or writing. All such events operate in Edge-Triggered mode, meaning that they only trigger notifications when the state of the socket changes. For example, doing a partial read on a socket does not make nginx deliver a repeated read notification until more data arrives on the socket. Even when the underlying IEO notification mechanism is essentially Level-Triggered (C, C