diff --git a/echo-nginx-module/.gitattributes b/echo-nginx-module/.gitattributes new file mode 100644 index 00000000..6fe6f35c --- /dev/null +++ b/echo-nginx-module/.gitattributes @@ -0,0 +1 @@ +*.t linguist-language=Text diff --git a/echo-nginx-module/.gitignore b/echo-nginx-module/.gitignore new file mode 100644 index 00000000..a9948e48 --- /dev/null +++ b/echo-nginx-module/.gitignore @@ -0,0 +1,65 @@ +.libs +*.swp +*.slo +*.la +*.swo +*.lo +*.mobi +genmobi.sh +*~ +*.o +print.txt +.rsync +*.tar.gz +dist +build[789] +build +tags +update-readme +*.tmp +test/Makefile +test/blib +test.sh +t.sh +t/t.sh +test/t/servroot/ +releng +reset +*.t_ +reindex +src/location.h +src/filter.c +src/subrequest.h +src/sleep.h +src/util.c +src/echo.c +src/info.c +src/util.h +src/var.h +src/filter.h +src/sleep.c +src/var.c +src/timer.c +src/module.h +src/echo.h +src/info.h +src/foreach.c +src/location.c +src/timer.h +src/module.c +src/subrequest.c +src/handler.h +src/foreach.h +src/handler.c +nginx +*.html +ctags +t/servroot +all +buildroot/ +go +Changes +build1[0-9] +analyze +Makefile +*.plist diff --git a/echo-nginx-module/.travis.yml b/echo-nginx-module/.travis.yml new file mode 100644 index 00000000..ec95f919 --- /dev/null +++ b/echo-nginx-module/.travis.yml @@ -0,0 +1,40 @@ +sudo: required +dist: trusty + +os: linux + +language: c + +compiler: + - gcc + - clang + +env: + global: + - LUAJIT_LIB=/usr/lib64/libluajit-5.1.so + - LUAJIT_INC=/usr/include/luajit-2.0 + matrix: + - NGINX_VERSION=1.9.15 + - NGINX_VERSION=1.10.0 + +before_install: + - sudo apt-get install -qq -y cpanminus libluajit-5.1-dev libgd-dev + - sudo cpanm -v --notest Test::Nginx > build.log 2>&1 || (cat build.log && exit 1) + +install: + - wget http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz && tar -xzf nginx-${NGINX_VERSION}.tar.gz + - git clone https://github.com/simpl/ngx_devel_kit.git + - git clone https://github.com/openresty/set-misc-nginx-module.git + - git clone https://github.com/openresty/xss-nginx-module.git + - git clone https://github.com/openresty/rds-json-nginx-module.git + - git clone https://github.com/openresty/headers-more-nginx-module.git + - git clone https://github.com/openresty/lua-nginx-module.git + - git clone https://github.com/openresty/nginx-eval-module.git + +script: + - cd nginx-${NGINX_VERSION}/ + - ./configure --without-http_ssi_module --with-debug --with-select_module --with-poll_module --with-http_stub_status_module --with-http_image_filter_module --add-module=../ngx_devel_kit --add-module=../set-misc-nginx-module --add-module=../nginx-eval-module --add-module=../xss-nginx-module --add-module=../rds-json-nginx-module --add-module=../headers-more-nginx-module --add-module=../lua-nginx-module --add-module=.. > build.log 2>&1 || (cat build.log && exit 1) + - make -j2 > build.log 2>&1 || (cat build.log && exit 1) + - export PATH=$PATH:`pwd`/objs + - cd .. + - prove -r t diff --git a/echo-nginx-module/LICENSE b/echo-nginx-module/LICENSE new file mode 100644 index 00000000..6feffbf8 --- /dev/null +++ b/echo-nginx-module/LICENSE @@ -0,0 +1,25 @@ +Copyright (C) 2009-2014, Yichun "agentzh" Zhang . +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/echo-nginx-module/README.markdown b/echo-nginx-module/README.markdown new file mode 100644 index 00000000..71ac080d --- /dev/null +++ b/echo-nginx-module/README.markdown @@ -0,0 +1,1846 @@ +Name +==== + +**ngx_echo** - Brings "echo", "sleep", "time", "exec" and more shell-style goodies to Nginx config file. + +*This module is not distributed with the Nginx source.* See [the installation instructions](#installation). + +Table of Contents +================= + +* [Name](#name) +* [Status](#status) +* [Version](#version) +* [Synopsis](#synopsis) +* [Description](#description) +* [Content Handler Directives](#content-handler-directives) + * [echo](#echo) + * [echo_duplicate](#echo_duplicate) + * [echo_flush](#echo_flush) + * [echo_sleep](#echo_sleep) + * [echo_blocking_sleep](#echo_blocking_sleep) + * [echo_reset_timer](#echo_reset_timer) + * [echo_read_request_body](#echo_read_request_body) + * [echo_location_async](#echo_location_async) + * [echo_location](#echo_location) + * [echo_subrequest_async](#echo_subrequest_async) + * [echo_subrequest](#echo_subrequest) + * [echo_foreach_split](#echo_foreach_split) + * [echo_end](#echo_end) + * [echo_request_body](#echo_request_body) + * [echo_exec](#echo_exec) + * [echo_status](#echo_status) +* [Filter Directives](#filter-directives) + * [echo_before_body](#echo_before_body) + * [echo_after_body](#echo_after_body) +* [Variables](#variables) + * [$echo_it](#echo_it) + * [$echo_timer_elapsed](#echo_timer_elapsed) + * [$echo_request_body](#echo_request_body) + * [$echo_request_method](#echo_request_method) + * [$echo_client_request_method](#echo_client_request_method) + * [$echo_client_request_headers](#echo_client_request_headers) + * [$echo_cacheable_request_uri](#echo_cacheable_request_uri) + * [$echo_request_uri](#echo_request_uri) + * [$echo_incr](#echo_incr) + * [$echo_response_status](#echo_response_status) +* [Installation](#installation) +* [Compatibility](#compatibility) +* [Modules that use this module for testing](#modules-that-use-this-module-for-testing) +* [Community](#community) + * [English Mailing List](#english-mailing-list) + * [Chinese Mailing List](#chinese-mailing-list) +* [Report Bugs](#report-bugs) +* [Source Repository](#source-repository) +* [Changes](#changes) +* [Test Suite](#test-suite) +* [TODO](#todo) +* [Getting involved](#getting-involved) +* [Author](#author) +* [Copyright & License](#copyright--license) +* [See Also](#see-also) + +Status +====== + +This module is production ready. + +Version +======= + +This document describes ngx_echo [v0.61](https://github.com/openresty/echo-nginx-module/tags) released on 8 August 2017. + +Synopsis +======== + +```nginx + + location /hello { + echo "hello, world!"; + } +``` + +```nginx + + location /hello { + echo -n "hello, "; + echo "world!"; + } +``` + +```nginx + + location /timed_hello { + echo_reset_timer; + echo hello world; + echo "'hello world' takes about $echo_timer_elapsed sec."; + echo hiya igor; + echo "'hiya igor' takes about $echo_timer_elapsed sec."; + } +``` + +```nginx + + location /echo_with_sleep { + echo hello; + echo_flush; # ensure the client can see previous output immediately + echo_sleep 2.5; # in sec + echo world; + } +``` + +```nginx + + # in the following example, accessing /echo yields + # hello + # world + # blah + # hiya + # igor + location /echo { + echo_before_body hello; + echo_before_body world; + proxy_pass $scheme://127.0.0.1:$server_port$request_uri/more; + echo_after_body hiya; + echo_after_body igor; + } + location /echo/more { + echo blah; + } +``` + +```nginx + + # the output of /main might be + # hello + # world + # took 0.000 sec for total. + # and the whole request would take about 2 sec to complete. + location /main { + echo_reset_timer; + + # subrequests in parallel + echo_location_async /sub1; + echo_location_async /sub2; + + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_sleep 2; + echo hello; + } + location /sub2 { + echo_sleep 1; + echo world; + } +``` + +```nginx + + # the output of /main might be + # hello + # world + # took 3.003 sec for total. + # and the whole request would take about 3 sec to complete. + location /main { + echo_reset_timer; + + # subrequests in series (chained by CPS) + echo_location /sub1; + echo_location /sub2; + + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_sleep 2; + echo hello; + } + location /sub2 { + echo_sleep 1; + echo world; + } +``` + +```nginx + + # Accessing /dup gives + # ------ END ------ + location /dup { + echo_duplicate 3 "--"; + echo_duplicate 1 " END "; + echo_duplicate 3 "--"; + echo; + } +``` + +```nginx + + # /bighello will generate 1000,000,000 hello's. + location /bighello { + echo_duplicate 1000_000_000 'hello'; + } +``` + +```nginx + + # echo back the client request + location /echoback { + echo_duplicate 1 $echo_client_request_headers; + echo "\r"; + + echo_read_request_body; + + echo_request_body; + } +``` + +```nginx + + # GET /multi will yields + # querystring: foo=Foo + # method: POST + # body: hi + # content length: 2 + # /// + # querystring: bar=Bar + # method: PUT + # body: hello + # content length: 5 + # /// + location /multi { + echo_subrequest_async POST '/sub' -q 'foo=Foo' -b 'hi'; + echo_subrequest_async PUT '/sub' -q 'bar=Bar' -b 'hello'; + } + location /sub { + echo "querystring: $query_string"; + echo "method: $echo_request_method"; + echo "body: $echo_request_body"; + echo "content length: $http_content_length"; + echo '///'; + } +``` + +```nginx + + # GET /merge?/foo.js&/bar/blah.js&/yui/baz.js will merge the .js resources together + location /merge { + default_type 'text/javascript'; + echo_foreach_split '&' $query_string; + echo "/* JS File $echo_it */"; + echo_location_async $echo_it; + echo; + echo_end; + } +``` + +```nginx + + # accessing /if?val=abc yields the "hit" output + # while /if?val=bcd yields "miss": + location ^~ /if { + set $res miss; + if ($arg_val ~* '^a') { + set $res hit; + echo $res; + } + echo $res; + } +``` + +[Back to TOC](#table-of-contents) + +Description +=========== + +This module wraps lots of Nginx internal APIs for streaming input and output, parallel/sequential subrequests, timers and sleeping, as well as various meta data accessing. + +Basically it provides various utilities that help testing and debugging of other modules by trivially emulating different kinds of faked subrequest locations. + +People will also find it useful in real-world applications that need to + +1. serve static contents directly from memory (loading from the Nginx config file). +1. wrap the upstream response with custom header and footer (kinda like the [addition module](http://nginx.org/en/docs/http/ngx_http_addition_module.html) but with contents read directly from the config file and Nginx variables). +1. merge contents of various "Nginx locations" (i.e., subrequests) together in a single main request (using [echo_location](#echo_location) and its friends). + +This is a special dual-role module that can *lazily* serve as a content handler or register itself as an output filter only upon demand. By default, this module does not do anything at all. + +Technically, this module has also demonstrated the following techniques that might be helpful for module writers: + +1. Issue parallel subrequests directly from content handler. +1. Issue chained subrequests directly from content handler, by passing continuation along the subrequest chain. +1. Issue subrequests with all HTTP 1.1 methods and even an optional faked HTTP request body. +1. Interact with the Nginx event model directly from content handler using custom events and timers, and resume the content handler back if necessary. +1. Dual-role module that can (lazily) serve as a content handler or an output filter or both. +1. Nginx config file variable creation and interpolation. +1. Streaming output control using output_chain, flush and its friends. +1. Read client request body from the content handler, and returns back (asynchronously) to the content handler after completion. +1. Use Perl-based declarative [test suite](#test-suite) to drive the development of Nginx C modules. + +[Back to TOC](#table-of-contents) + +Content Handler Directives +========================== + +Use of the following directives register this module to the current Nginx location as a content handler. If you want to use another module, like the [standard proxy module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html), as the content handler, use the [filter directives](#filter-directives) provided by this module. + +All the content handler directives can be mixed together in a single Nginx location and they're supposed to run sequentially just as in the Bash scripting language. + +Every content handler directive supports variable interpolation in its arguments (if any). + +The MIME type set by the [standard default_type directive](http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type) is respected by this module, as in: + +```nginx + + location /hello { + default_type text/plain; + echo hello; + } +``` + +Then on the client side: + +```bash + + $ curl -I 'http://localhost/echo' + HTTP/1.1 200 OK + Server: nginx/0.8.20 + Date: Sat, 17 Oct 2009 03:40:19 GMT + Content-Type: text/plain + Connection: keep-alive +``` + +Since the [v0.22](#v022) release, all of the directives are allowed in the [rewrite module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [if](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#if) directive block, for instance: + +```nginx + + location ^~ /if { + set $res miss; + if ($arg_val ~* '^a') { + set $res hit; + echo $res; + } + echo $res; + } +``` + +[Back to TOC](#table-of-contents) + +echo +---- +**syntax:** *echo \[options\] <string>...* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Sends arguments joined by spaces, along with a trailing newline, out to the client. + +Note that the data might be buffered by Nginx's underlying buffer. To force the output data flushed immediately, use the [echo_flush](#echo_flush) command just after `echo`, as in + +```nginx + + echo hello world; + echo_flush; +``` + +When no argument is specified, *echo* emits the trailing newline alone, just like the *echo* command in shell. + +Variables may appear in the arguments. An example is + +```nginx + + echo The current request uri is $request_uri; +``` + +where [$request_uri](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_uri) is a variable exposed by the [ngx_http_core_module](http://nginx.org/en/docs/http/ngx_http_core_module.html). + +This command can be used multiple times in a single location configuration, as in + +```nginx + + location /echo { + echo hello; + echo world; + } +``` + +The output on the client side looks like this + +```bash + + $ curl 'http://localhost/echo' + hello + world +``` + +Special characters like newlines (`\n`) and tabs (`\t`) can be escaped using C-style escaping sequences. But a notable exception is the dollar sign (`$`). As of Nginx 0.8.20, there's still no clean way to escape this character. (A work-around might be to use a `$echo_dollor` variable that is always evaluated to the constant `$` character. This feature will possibly be introduced in a future version of this module.) + +As of the echo [v0.28](#v028) release, one can suppress the trailing newline character in the output by using the `-n` option, as in + +```nginx + + location /echo { + echo -n "hello, "; + echo "world"; + } +``` + +Accessing `/echo` gives + +```bash + + $ curl 'http://localhost/echo' + hello, world +``` + +Leading `-n` in variable values won't take effect and will be emitted literally, as in + +```nginx + + location /echo { + set $opt -n; + echo $opt "hello,"; + echo "world"; + } +``` + +This gives the following output + +```bash + + $ curl 'http://localhost/echo' + -n hello, + world +``` + +One can output leading `-n` literals and other options using the special `--` option like this + +```nginx + + location /echo { + echo -- -n is an option; + } +``` + +which yields + +```bash + + $ curl 'http://localhost/echo' + -n is an option +``` + +Use this form when you want to output anything leading with a dash (`-`). + +[Back to TOC](#table-of-contents) + +echo_duplicate +-------------- +**syntax:** *echo_duplicate <count> <string>* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Outputs duplication of a string indicated by the second argument, using the count specified in the first argument. + +For instance, + +```nginx + + location /dup { + echo_duplicate 3 "abc"; + } +``` + +will lead to the output of `"abcabcabc"`. + +Underscores are allowed in the count number, just like in Perl. For example, to emit 1000,000,000 instances of `"hello, world"`: + +```nginx + + location /many_hellos { + echo_duplicate 1000_000_000 "hello, world"; + } +``` + +The `count` argument could be zero, but not negative. The second `string` argument could be an empty string ("") likewise. + +Unlike the [echo](#echo) directive, no trailing newline is appended to the result. So it's possible to "abuse" this directive as a no-trailing-newline version of [echo](#echo) by using "count" 1, as in + +```nginx + + location /echo_art { + echo_duplicate 2 '---'; + echo_duplicate 1 ' END '; # we don't want a trailing newline here + echo_duplicate 2 '---'; + echo; # we want a trailing newline here... + } +``` + +You get + +```bash + ------ END ------ +``` + +But use of the `-n` option in [echo](#echo) is more appropriate for this purpose. + +This directive was first introduced in [version 0.11](#v011). + +[Back to TOC](#table-of-contents) + +echo_flush +---------- +**syntax:** *echo_flush* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Forces the data potentially buffered by underlying Nginx output filters to send immediately to the client side via socket. + +Note that techically the command just emits a ngx_buf_t object with `flush` slot set to 1, so certain weird third-party output filter module could still block it before it reaches Nginx's (last) write filter. + +This directive does not take any argument. + +Consider the following example: + +```nginx + + location /flush { + echo hello; + + echo_flush; + + echo_sleep 1; + echo world; + } +``` + +Then on the client side, using curl to access `/flush`, you'll see the "hello" line immediately, but only after 1 second, the last "world" line. Without calling `echo_flush` in the example above, you'll most likely see no output until 1 second is elapsed due to the internal buffering of Nginx. + +This directive will fail to flush the output buffer in case of subrequests get involved. Consider the following example: + +```nginx + + location /main { + echo_location_async /sub; + echo hello; + echo_flush; + } + location /sub { + echo_sleep 1; + } +``` + +Then the client won't see "hello" appear even if `echo_flush` has been executed before the subrequest to `/sub` has actually started executing. The outputs of `/main` that are sent *after* [echo_location_async](#echo_location_async) will be postponed and buffered firmly. + +This does *not* apply to outputs sent before the subrequest initiated. For a modified version of the example given above: + +```nginx + + location /main { + echo hello; + echo_flush; + echo_location_async /sub; + } + location /sub { + echo_sleep 1; + } +``` + +The client will immediately see "hello" before `/sub` enters sleeping. + +See also [echo](#echo), [echo_sleep](#echo_sleep), and [echo_location_async](#echo_location_async). + +[Back to TOC](#table-of-contents) + +echo_sleep +---------- +**syntax:** *echo_sleep <seconds>* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Sleeps for the time period specified by the argument, which is in seconds. + +This operation is non-blocking on server side, so unlike the [echo_blocking_sleep](#echo_blocking_sleep) directive, it won't block the whole Nginx worker process. + +The period might takes three digits after the decimal point and must be greater than 0.001. + +An example is + +```nginx + + location /echo_after_sleep { + echo_sleep 1.234; + echo resumed!; + } +``` + +Behind the scene, it sets up a per-request "sleep" ngx_event_t object, and adds a timer using that custom event to the Nginx event model and just waits for a timeout on that event. Because the "sleep" event is per-request, this directive can work in parallel subrequests. + +[Back to TOC](#table-of-contents) + +echo_blocking_sleep +------------------- +**syntax:** *echo_blocking_sleep <seconds>* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +This is a blocking version of the [echo_sleep](#echo_sleep) directive. + +See the documentation of [echo_sleep](#echo_sleep) for more detail. + +Behind the curtain, it calls the ngx_msleep macro provided by the Nginx core which maps to usleep on POSIX-compliant systems. + +Note that this directive will block the current Nginx worker process completely while being executed, so never use it in production environment. + +[Back to TOC](#table-of-contents) + +echo_reset_timer +---------------- +**syntax:** *echo_reset_timer* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Reset the timer begin time to *now*, i.e., the time when this command is executed during request. + +The timer begin time is default to the starting time of the current request and can be overridden by this directive, potentially multiple times in a single location. For example: + +```nginx + + location /timed_sleep { + echo_sleep 0.03; + echo "$echo_timer_elapsed sec elapsed."; + + echo_reset_timer; + + echo_sleep 0.02; + echo "$echo_timer_elapsed sec elapsed."; + } +``` + +The output on the client side might be + +```bash + + $ curl 'http://localhost/timed_sleep' + 0.032 sec elapsed. + 0.020 sec elapsed. +``` + +The actual figures you get on your side may vary a bit due to your system's current activities. + +Invocation of this directive will force the underlying Nginx timer to get updated to the current system time (regardless the timer resolution specified elsewhere in the config file). Furthermore, references of the [$echo_timer_elapsed](#echo_timer_elapsed) variable will also trigger timer update forcibly. + +See also [echo_sleep](#echo_sleep) and [$echo_timer_elapsed](#echo_timer_elapsed). + +[Back to TOC](#table-of-contents) + +echo_read_request_body +---------------------- +**syntax:** *echo_read_request_body* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Explicitly reads request body so that the [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file). + +Note that this might not be the original client request body because the current request might be a subrequest with a "artificial" body specified by its parent. + +This directive does not generate any output itself, just like [echo_sleep](#echo_sleep). + +Here's an example for echo'ing back the original HTTP client request (both headers and body are included): + +```nginx + + location /echoback { + echo_duplicate 1 $echo_client_request_headers; + echo "\r"; + echo_read_request_body; + echo $request_body; + } +``` + +The content of `/echoback` looks like this on my side (I was using Perl's LWP utility to access this location on the server): + +```bash + + $ (echo hello; echo world) | lwp-request -m POST 'http://localhost/echoback' + POST /echoback HTTP/1.1 + TE: deflate,gzip;q=0.3 + Connection: TE, close + Host: localhost + User-Agent: lwp-request/5.818 libwww-perl/5.820 + Content-Length: 12 + Content-Type: application/x-www-form-urlencoded + + hello + world +``` + +Because `/echoback` is the main request, [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) holds the original client request body. + +Before Nginx 0.7.56, it makes no sense to use this directive because [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) was first introduced in Nginx 0.7.58. + +This directive itself was first introduced in the echo module's [v0.14 release](#v014). + +[Back to TOC](#table-of-contents) + +echo_location_async +------------------- +**syntax:** *echo_location_async <location> [<url_args>]* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Issue GET subrequest to the location specified (first argument) with optional url arguments specified in the second argument. + +As of Nginx 0.8.20, the `location` argument does *not* support named location, due to a limitation in the `ngx_http_subrequest` function. The same is true for its brother, the [echo_location](#echo_location) directive. + +A very simple example is + +```nginx + + location /main { + echo_location_async /sub; + echo world; + } + location /sub { + echo hello; + } +``` + +Accessing `/main` gets + +```bash + + hello + world +``` + +Calling multiple locations in parallel is also possible: + +```nginx + + location /main { + echo_reset_timer; + echo_location_async /sub1; + echo_location_async /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_sleep 2; # sleeps 2 sec + echo hello; + } + location /sub2 { + echo_sleep 1; # sleeps 1 sec + echo world; + } +``` + +Accessing `/main` yields + +```bash + + $ time curl 'http://localhost/main' + hello + world + took 0.000 sec for total. + + real 0m2.006s + user 0m0.000s + sys 0m0.004s +``` + +You can see that the main handler `/main` does *not* wait the subrequests `/sub1` and `/sub2` to complete and quickly goes on, hence the "0.000 sec" timing result. The whole request, however takes approximately 2 sec in total to complete because `/sub1` and `/sub2` run in parallel (or "concurrently" to be more accurate). + +If you use [echo_blocking_sleep](#echo_blocking_sleep) in the previous example instead, then you'll get the same output, but with 3 sec total response time, because "blocking sleep" blocks the whole Nginx worker process. + +Locations can also take an optional querystring argument, for instance + +```nginx + + location /main { + echo_location_async /sub 'foo=Foo&bar=Bar'; + } + location /sub { + echo $arg_foo $arg_bar; + } +``` + +Accessing `/main` yields + +```bash + + $ curl 'http://localhost/main' + Foo Bar +``` + +Querystrings is *not* allowed to be concatenated onto the `location` argument with "?" directly, for example, `/sub?foo=Foo&bar=Bar` is an invalid location, and shouldn't be fed as the first argument to this directive. + +Technically speaking, this directive is an example that Nginx content handler issues one or more subrequests directly. AFAIK, the [fancyindex module](https://connectical.com/projects/ngx-fancyindex/wiki) also does such kind of things ;) + +Nginx named locations like `@foo` is *not* supported here. + +This directive is logically equivalent to the GET version of [echo_subrequest_async](#echo_subrequest_async). For example, + +```nginx + + echo_location_async /foo 'bar=Bar'; +``` + +is logically equivalent to + +```nginx + + echo_subrequest_async GET /foo -q 'bar=Bar'; +``` + +But calling this directive is slightly faster than calling [echo_subrequest_async](#echo_subrequest_async) using `GET` because we don't have to parse the HTTP method names like `GET` and options like `-q`. + +This directive is first introduced in [version 0.09](#v009) of this module and requires at least Nginx 0.7.46. + +[Back to TOC](#table-of-contents) + +echo_location +------------- +**syntax:** *echo_location <location> [<url_args>]* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Just like the [echo_location_async](#echo_location_async) directive, but `echo_location` issues subrequests *in series* rather than in parallel. That is, the content handler directives following this directive won't be executed until the subrequest issued by this directive completes. + +The final response body is almost always equivalent to the case when [echo_location_async](#echo_location_async) is used instead, only if timing variables is used in the outputs. + +Consider the following example: + +```nginx + + location /main { + echo_reset_timer; + echo_location /sub1; + echo_location /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_sleep 2; + echo hello; + } + location /sub2 { + echo_sleep 1; + echo world; + } +``` + +The location `/main` above will take for total 3 sec to complete (compared to 2 sec if [echo_location_async](#echo_location_async) is used instead here). Here's the result in action on my machine: + +```bash + + $ curl 'http://localhost/main' + hello + world + took 3.003 sec for total. + + real 0m3.027s + user 0m0.020s + sys 0m0.004s +``` + +This directive is logically equivalent to the GET version of [echo_subrequest](#echo_subrequest). For example, + +```nginx + + echo_location /foo 'bar=Bar'; +``` + +is logically equivalent to + +```nginx + + echo_subrequest GET /foo -q 'bar=Bar'; +``` + +But calling this directive is slightly faster than calling [echo_subrequest](#echo_subrequest) using `GET` because we don't have to parse the HTTP method names like `GET` and options like `-q`. + +Behind the scene, it creates an `ngx_http_post_subrequest_t` object as a *continuation* and passes it into the `ngx_http_subrequest` function call. Nginx will later reopen this "continuation" in the subrequest's `ngx_http_finalize_request` function call. We resumes the execution of the parent-request's content handler and starts to run the next directive (command) if any. + +Nginx named locations like `@foo` is *not* supported here. + +This directive was first introduced in the [release v0.12](#v012). + +See also [echo_location_async](#echo_location_async) for more details about the meaning of the arguments. + +[Back to TOC](#table-of-contents) + +echo_subrequest_async +--------------------- +**syntax:** *echo_subrequest_async <HTTP_method> <location> [-q <url_args>] [-b <request_body>] [-f <request_body_path>]* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Initiate an asynchronous subrequest using HTTP method, an optional url arguments (or querystring) and an optional request body which can be defined as a string or as a path to a file which contains the body. + +This directive is very much like a generalized version of the [echo_location_async](#echo_location_async) directive. + +Here's a small example demonstrating its usage: + +```nginx + + location /multi { + # body defined as string + echo_subrequest_async POST '/sub' -q 'foo=Foo' -b 'hi'; + # body defined as path to a file, relative to nginx prefix path if not absolute + echo_subrequest_async PUT '/sub' -q 'bar=Bar' -f '/tmp/hello.txt'; + } + location /sub { + echo "querystring: $query_string"; + echo "method: $echo_request_method"; + echo "body: $echo_request_body"; + echo "content length: $http_content_length"; + echo '///'; + } +``` + +Then on the client side: + +```bash + + $ echo -n hello > /tmp/hello.txt + $ curl 'http://localhost/multi' + querystring: foo=Foo + method: POST + body: hi + content length: 2 + /// + querystring: bar=Bar + method: PUT + body: hello + content length: 5 + /// +``` + +Here's more funny example using the standard [proxy module](#httpproxymodule) to handle the subrequest: + +```nginx + + location /main { + echo_subrequest_async POST /sub -b 'hello, world'; + } + location /sub { + proxy_pass $scheme://127.0.0.1:$server_port/proxied; + } + location /proxied { + echo "method: $echo_request_method."; + + # we need to read body explicitly here...or $echo_request_body + # will evaluate to empty ("") + echo_read_request_body; + + echo "body: $echo_request_body."; + } +``` + +Then on the client side, we can see that + +```bash + + $ curl 'http://localhost/main' + method: POST. + body: hello, world. +``` + +Nginx named locations like `@foo` is *not* supported here. + +This directive takes several options: + + + -q Specify the URL arguments (or URL querystring) for the subrequest. + + -f Specify the path for the file whose content will be serve as the + subrequest's request body. + + -b Specify the request body data + + +This directive was first introduced in the [release v0.15](#v015). + +The `-f` option to define a file path for the body was introduced in the [release v0.35](#v035). + +See also the [echo_subrequest](#echo_subrequest) and [echo_location_async](#echo_location_async) directives. + +[Back to TOC](#table-of-contents) + +echo_subrequest +--------------- +**syntax:** *echo_subrequest <HTTP_method> <location> [-q <url_args>] [-b <request_body>] [-f <request_body_path>]* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +This is the synchronous version of the [echo_subrequest_async](#echo_subrequest_async) directive. And just like [echo_location](#echo_location), it does not block the Nginx worker process (while [echo_blocking_sleep](#echo_blocking_sleep) does), rather, it uses continuation to pass control along the subrequest chain. + +See [echo_subrequest_async](#echo_subrequest_async) for more details. + +Nginx named locations like `@foo` is *not* supported here. + +This directive was first introduced in the [release v0.15](#v015). + +[Back to TOC](#table-of-contents) + +echo_foreach_split +------------------ +**syntax:** *echo_foreach_split <delimiter> <string>* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Split the second argument `string` using the delimiter specified in the first argument, and then iterate through the resulting items. For instance: + +```nginx + + location /loop { + echo_foreach_split ',' $arg_list; + echo "item: $echo_it"; + echo_end; + } +``` + +Accessing /main yields + +```bash + + $ curl 'http://localhost/loop?list=cat,dog,mouse' + item: cat + item: dog + item: mouse +``` + +As seen in the previous example, this directive should always be accompanied by an [echo_end](#echo_end) directive. + +Parallel `echo_foreach_split` loops are allowed, but nested ones are currently forbidden. + +The `delimiter` argument could contain *multiple* arbitrary characters, like + +```nginx + + # this outputs "cat\ndog\nmouse\n" + echo_foreach_split -- '-a-' 'cat-a-dog-a-mouse'; + echo $echo_it; + echo_end; +``` + +Logically speaking, this looping structure is just the `foreach` loop combined with a `split` function call in Perl (using the previous example): + +```perl + + foreach (split ',', $arg_list) { + print "item $_\n"; + } +``` + +People will also find it useful in merging multiple `.js` or `.css` resources into a whole. Here's an example: + +```nginx + + location /merge { + default_type 'text/javascript'; + + echo_foreach_split '&' $query_string; + echo "/* JS File $echo_it */"; + echo_location_async $echo_it; + echo; + echo_end; + } +``` + +Then accessing /merge to merge the `.js` resources specified in the query string: + +```bash + + $ curl 'http://localhost/merge?/foo/bar.js&/yui/blah.js&/baz.js' +``` + +One can also use third-party Nginx cache module to cache the merged response generated by the `/merge` location in the previous example. + +This directive was first introduced in the [release v0.17](#v017). + +[Back to TOC](#table-of-contents) + +echo_end +-------- +**syntax:** *echo_end* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +This directive is used to terminate the body of looping and conditional control structures like [echo_foreach_split](#echo_foreach_split). + +This directive was first introduced in the [release v0.17](#v017). + +[Back to TOC](#table-of-contents) + +echo_request_body +----------------- +**syntax:** *echo_request_body* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Outputs the contents of the request body previous read. + +Behind the scene, it's implemented roughly like this: + +```C + + if (r->request_body && r->request_body->bufs) { + return ngx_http_output_filter(r, r->request_body->bufs); + } +``` + +Unlike the [$echo_request_body](#echo_request_body) and $request_body variables, this directive will show the whole request body even if some parts or all parts of it are saved in temporary files on the disk. + +It is a "no-op" if no request body has been read yet. + +This directive was first introduced in the [release v0.18](#v018). + +See also [echo_read_request_body](#echo_read_request_body) and the [chunkin module](http://github.com/agentzh/chunkin-nginx-module). + +[Back to TOC](#table-of-contents) + +echo_exec +--------- +**syntax:** *echo_exec <location> [<query_string>]* + +**syntax:** *echo_exec <named_location>* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *content* + +Does an internal redirect to the location specified. An optional query string can be specified for normal locations, as in + +```nginx + + location /foo { + echo_exec /bar weight=5; + } + location /bar { + echo $arg_weight; + } +``` + +Or equivalently + +```nginx + + location /foo { + echo_exec /bar?weight=5; + } + location /bar { + echo $arg_weight; + } +``` + +Named locations are also supported. Here's an example: + +```nginx + + location /foo { + echo_exec @bar; + } + location @bar { + # you'll get /foo rather than @bar + # due to a potential bug in nginx. + echo $echo_request_uri; + } +``` + +But query string (if any) will always be ignored for named location redirects due to a limitation in the `ngx_http_named_location` function. + +Never try to echo things before the `echo_exec` directive or you won't see the proper response of the location you want to redirect to. Because any echoing will cause the original location handler to send HTTP headers before the redirection happens. + +Technically speaking, this directive exposes the Nginx internal API functions `ngx_http_internal_redirect` and `ngx_http_named_location`. + +This directive was first introduced in the [v0.21 release](#v021). + +[Back to TOC](#table-of-contents) + +echo_status +----------- +**syntax:** *echo_status <status-num>* + +**default:** *echo_status 200* + +**context:** *location, location if* + +**phase:** *content* + +Specify the default response status code. Default to `200`. This directive is declarative and the relative order with other echo-like directives is not important. + +Here is an example, + +```nginx + + location = /bad { + echo_status 404; + echo "Something is missing..."; + } +``` + +then we get a response like this: + + + HTTP/1.1 404 Not Found + Server: nginx/1.2.1 + Date: Sun, 24 Jun 2012 03:58:18 GMT + Content-Type: text/plain + Transfer-Encoding: chunked + Connection: keep-alive + + Something is missing... + + +This directive was first introduced in the `v0.40` release. + +[Back to TOC](#table-of-contents) + +Filter Directives +================= + +Use of the following directives trigger the filter registration of this module. By default, no filter will be registered by this module. + +Every filter directive supports variable interpolation in its arguments (if any). + +[Back to TOC](#table-of-contents) + +echo_before_body +---------------- +**syntax:** *echo_before_body \[options\] \[argument\]...* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *output filter* + +It's the filter version of the [echo](#echo) directive, and prepends its output to the beginning of the original outputs generated by the underlying content handler. + +An example is + +```nginx + + location /echo { + echo_before_body hello; + proxy_pass $scheme://127.0.0.1:$server_port$request_uri/more; + } + location /echo/more { + echo world + } +``` + +Accessing `/echo` from the client side yields + +```bash + + hello + world +``` + +In the previous sample, we borrow the [standard proxy module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) to serve as the underlying content handler that generates the "main contents". + +Multiple instances of this filter directive are also allowed, as in: + +```nginx + + location /echo { + echo_before_body hello; + echo_before_body world; + echo !; + } +``` + +On the client side, the output is like + +```bash + + $ curl 'http://localhost/echo' + hello + world + ! +``` + +In this example, we also use the [content handler directives](#content-handler-directives) provided by this module as the underlying content handler. + +This directive also supports the `-n` and `--` options like the [echo](#echo) directive. + +This directive can be mixed with its brother directive [echo_after_body](#echo_after_body). + +[Back to TOC](#table-of-contents) + +echo_after_body +--------------- +**syntax:** *echo_after_body \[argument\]...* + +**default:** *no* + +**context:** *location, location if* + +**phase:** *output filter* + +It's very much like the [echo_before_body](#echo_before_body) directive, but *appends* its output to the end of the original outputs generated by the underlying content handler. + +Here's a simple example: + +```nginx + + location /echo { + echo_after_body hello; + proxy_pass http://127.0.0.1:$server_port$request_uri/more; + } + location /echo/more { + echo world + } +``` + +Accessing `/echo` from the client side yields + + + world + hello + + +Multiple instances are allowed, as in: + +```nginx + + location /echo { + echo_after_body hello; + echo_after_body world; + echo i; + echo say; + } +``` + +The output on the client side while accessing the `/echo` location looks like + + + i + say + hello + world + + +This directive also supports the `-n` and `--` options like the [echo](#echo) directive. + +This directive can be mixed with its brother directive [echo_before_body](#echo_before_body). + +[Back to TOC](#table-of-contents) + +Variables +========= + +[Back to TOC](#table-of-contents) + +$echo_it +-------- + +This is a "topic variable" used by [echo_foreach_split](#echo_foreach_split), just like the `$_` variable in Perl. + +[Back to TOC](#table-of-contents) + +$echo_timer_elapsed +------------------- + +This variable holds the seconds elapsed since the start of the current request (might be a subrequest though) or the last invocation of the [echo_reset_timer](#echo_reset_timer) command. + +The timing result takes three digits after the decimal point. + +References of this variable will force the underlying Nginx timer to update to the current system time, regardless the timer resolution settings elsewhere in the config file, just like the [echo_reset_timer](#echo_reset_timer) directive. + +[Back to TOC](#table-of-contents) + +$echo_request_body +------------------ + +Evaluates to the current (sub)request's request body previously read if no part of the body has been saved to a temporary file. To always show the request body even if it's very large, use the [echo_request_body](#echo_request_body) directive. + +[Back to TOC](#table-of-contents) + +$echo_request_method +-------------------- + +Evaluates to the HTTP request method of the current request (it can be a subrequest). + +Behind the scene, it just takes the string data stored in `r->method_name`. + +Compare it to the [$echo_client_request_method](#echo_client_request_method) variable. + +At least for Nginx 0.8.20 and older, the [$request_method](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_method) variable provided by the [http core module](http://nginx.org/en/docs/http/ngx_http_core_module.html) is actually doing what our [$echo_client_request_method](#echo_client_request_method) is doing. + +This variable was first introduced in our [v0.15 release](#v015). + +[Back to TOC](#table-of-contents) + +$echo_client_request_method +--------------------------- + +Always evaluates to the main request's HTTP method even if the current request is a subrequest. + +Behind the scene, it just takes the string data stored in `r->main->method_name`. + +Compare it to the [$echo_request_method](#echo_request_method) variable. + +This variable was first introduced in our [v0.15 release](#v015). + +[Back to TOC](#table-of-contents) + +$echo_client_request_headers +---------------------------- + +Evaluates to the original client request's headers. + +Just as the name suggests, it will always take the main request (or the client request) even if it's currently executed in a subrequest. + +A simple example is below: + +```nginx + + location /echoback { + echo "headers are:" + echo $echo_client_request_headers; + } +``` + +Accessing `/echoback` yields + +```bash + + $ curl 'http://localhost/echoback' + headers are + GET /echoback HTTP/1.1 + User-Agent: curl/7.18.2 (i486-pc-linux-gnu) libcurl/7.18.2 OpenSSL/0.9.8g + Host: localhost:1984 + Accept: */* +``` + +Behind the scene, it recovers `r->main->header_in` (or the large header buffers, if any) on the C level and does not construct the headers itself by traversing parsed results in the request object. + +This varible is always evaluated to an empty value in HTTP/2 requests for now due to the current implementation. + +This variable was first introduced in [version 0.15](#v015). + +[Back to TOC](#table-of-contents) + +$echo_cacheable_request_uri +--------------------------- + +Evaluates to the parsed form of the URI (usually led by `/`) of the current (sub-)request. Unlike the [$echo_request_uri](#echo_request_uri) variable, it is cacheable. + +See [$echo_request_uri](#echo_request_uri) for more details. + +This variable was first introduced in [version 0.17](#v017). + +[Back to TOC](#table-of-contents) + +$echo_request_uri +----------------- + +Evaluates to the parsed form of the URI (usually led by `/`) of the current (sub-)request. Unlike the [$echo_cacheable_request_uri](#echo_cacheable_request_uri) variable, it is *not* cacheable. + +This is quite different from the [$request_uri](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_uri) variable exported by the [ngx_http_core_module](http://nginx.org/en/docs/http/ngx_http_core_module.html), because `$request_uri` is the *unparsed* form of the current request's URI. + +This variable was first introduced in [version 0.17](#v017). + +[Back to TOC](#table-of-contents) + +$echo_incr +---------- + +It is a counter that always generate the current counting number, starting from 1. The counter is always associated with the main request even if it is accessed within a subrequest. + +Consider the following example + +```Nginx + + location /main { + echo "main pre: $echo_incr"; + echo_location_async /sub; + echo_location_async /sub; + echo "main post: $echo_incr"; + } + location /sub { + echo "sub: $echo_incr"; + } +``` + +Accessing `/main` yields + + main pre: 1 + sub: 3 + sub: 4 + main post: 2 + +This directive was first introduced in the [v0.18 release](#v018). + +[Back to TOC](#table-of-contents) + +$echo_response_status +--------------------- + +Evaluates to the status code of the current (sub)request, null if not any. + +Behind the scene, it's just the textual representation of `r->headers_out->status`. + +This directive was first introduced in the [v0.23 release](#v023). + +[Back to TOC](#table-of-contents) + +Installation +============ + +You're recommended to install this module (as well as the Nginx core and many other goodies) via the [OpenResty bundle](http://openresty.org). See [the detailed instructions](http://openresty.org/#Installation) for downloading and installing OpenResty into your system. This is the easiest and most safe way to set things up. + +Alternatively, you can install this module manually with the Nginx source: + +Grab the nginx source code from [nginx.org](http://nginx.org/), for example, +the version 1.11.2 (see [nginx compatibility](#compatibility)), and then build the source with this module: + +```bash + + $ wget 'http://nginx.org/download/nginx-1.11.2.tar.gz' + $ tar -xzvf nginx-1.11.2.tar.gz + $ cd nginx-1.11.2/ + + # Here we assume you would install you nginx under /opt/nginx/. + $ ./configure --prefix=/opt/nginx \ + --add-module=/path/to/echo-nginx-module + + $ make -j2 + $ make install +``` + +Download the latest version of the release tarball of this module from [echo-nginx-module file list](https://github.com/openresty/echo-nginx-module/tags). + +Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the `--add-dynamic-module=PATH` option instead of `--add-module=PATH` on the +`./configure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load_module](http://nginx.org/en/docs/ngx_core_module.html#load_module) +directive, for example, + +```nginx +load_module /path/to/modules/ngx_http_echo_module.so; +``` + +Also, this module is included and enabled by default in the [OpenResty bundle](http://openresty.org). + +[Back to TOC](#table-of-contents) + +Compatibility +============= + +The following versions of Nginx should work with this module: + +* **1.11.x** (last tested: 1.11.2) +* **1.10.x** +* **1.9.x** (last tested: 1.9.15) +* **1.8.x** +* **1.7.x** (last tested: 1.7.10) +* **1.6.x** +* **1.5.x** (last tested: 1.5.12) +* **1.4.x** (last tested: 1.4.4) +* **1.3.x** (last tested: 1.3.7) +* **1.2.x** (last tested: 1.2.9) +* **1.1.x** (last tested: 1.1.5) +* **1.0.x** (last tested: 1.0.11) +* **0.9.x** (last tested: 0.9.4) +* **0.8.x** (last tested: 0.8.54) +* **0.7.x >= 0.7.21** (last tested: 0.7.68) + +In particular, + +* the directive [echo_location_async](#echo_location_async) and its brother [echo_subrequest_async](#echo_subrequest_async) do *not* work with **0.7.x < 0.7.46**. +* the [echo_after_body](#echo_after_body) directive does *not* work at all with nginx **< 0.8.7**. +* the [echo_sleep](#echo_sleep) directive cannot be used after [echo_location](#echo_location) or [echo_subrequest](#echo_subrequest) for nginx **< 0.8.11**. + +Earlier versions of Nginx like 0.6.x and 0.5.x will *not* work at all. + +If you find that any particular version of Nginx above 0.7.21 does not work with this module, please consider [reporting a bug](#report-bugs). + +[Back to TOC](#table-of-contents) + +Modules that use this module for testing +======================================== + +The following modules take advantage of this `echo` module in their test suite: + +* The [memc](http://github.com/openresty/memc-nginx-module) module that supports almost the whole memcached TCP protocol. +* The [chunkin](http://github.com/agentzh/chunkin-nginx-module) module that adds HTTP 1.1 chunked input support to Nginx. +* The [headers_more](http://github.com/openresty/headers-more-nginx-module) module that allows you to add, set, and clear input and output headers under the conditions that you specify. +* The `echo` module itself. + +Please mail me other modules that use `echo` in any form and I'll add them to the list above :) + +[Back to TOC](#table-of-contents) + +Community +========= + +[Back to TOC](#table-of-contents) + +English Mailing List +-------------------- + +The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers. + +[Back to TOC](#table-of-contents) + +Chinese Mailing List +-------------------- + +The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers. + +[Back to TOC](#table-of-contents) + +Report Bugs +=========== + +Although a lot of effort has been put into testing and code tuning, there must be some serious bugs lurking somewhere in this module. So whenever you are bitten by any quirks, please don't hesitate to + +1. create a ticket on the [issue tracking interface](https://github.com/openresty/echo-nginx-module/issues) provided by GitHub, +1. or send a bug report, questions, or even patches to the [OpenResty Community](#community). + +[Back to TOC](#table-of-contents) + +Source Repository +================= + +Available on github at [openresty/echo-nginx-module](https://github.com/openresty/echo-nginx-module). + +[Back to TOC](#table-of-contents) + +Changes +======= + +The changes of every release of this module can be obtained from the OpenResty bundle's change logs: + + + +[Back to TOC](#table-of-contents) + +Test Suite +========== + +This module comes with a Perl-driven test suite. The [test cases](https://github.com/openresty/echo-nginx-module/tree/master/t/) are +[declarative](https://github.com/openresty/echo-nginx-module/blob/master/t/echo.t) too. Thanks to the [Test::Nginx](http://search.cpan.org/perldoc?Test::Nginx) module in the Perl world. + +To run it on your side: + +```bash + + $ PATH=/path/to/your/nginx-with-echo-module:$PATH prove -r t +``` + +You need to terminate any Nginx processes before running the test suite if you have changed the Nginx server binary. + +Because a single nginx server (by default, `localhost:1984`) is used across all the test scripts (`.t` files), it's meaningless to run the test suite in parallel by specifying `-jN` when invoking the `prove` utility. + +Some parts of the test suite requires standard modules [proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html), [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html) and [SSI](http://nginx.org/en/docs/http/ngx_http_ssi_module.html) to be enabled as well when building Nginx. + +[Back to TOC](#table-of-contents) + +TODO +==== + +* Fix the [echo_after_body](#echo_after_body) directive in subrequests. +* Add directives *echo_read_client_request_body* and *echo_request_headers*. +* Add new directive *echo_log* to use Nginx's logging facility directly from the config file and specific loglevel can be specified, as in + +```nginx + + echo_log debug "I am being called."; +``` + +* Add support for options `-h` and `-t` to [echo_subrequest_async](#echo_subrequest_async) and [echo_subrequest](#echo_subrequest). For example + +```nginx + + echo_subrequest POST /sub -q 'foo=Foo&bar=Bar' -b 'hello' -t 'text/plan' -h 'X-My-Header: blah blah' +``` + +* Add options to control whether a subrequest should inherit cached variables from its parent request (i.e. the current request that is calling the subrequest in question). Currently none of the subrequests issued by this module inherit the cached variables from the parent request. +* Add new variable *$echo_active_subrequests* to show `r->main->count - 1`. +* Add the *echo_file* and *echo_cached_file* directives. +* Add new varaible *$echo_request_headers* to accompany the existing [$echo_client_request_headers](#echo_client_request_headers) variable. +* Add new directive *echo_foreach*, as in + +```nginx + + echo_foreach 'cat' 'dog' 'mouse'; + echo_location_async "/animals/$echo_it"; + echo_end; +``` + +* Add new directive *echo_foreach_range*, as in + +```nginx + + echo_foreach_range '[1..100]' '[a-zA-z0-9]'; + echo_location_async "/item/$echo_it"; + echo_end; +``` + +* Add new directive *echo_repeat*, as in + +```nginx + + echo_repeat 10 $i { + echo "Page $i"; + echo_location "/path/to/page/$i"; + } +``` + +This is just another way of saying + +```nginx + + echo_foreach_range $i [1..10]; + echo "Page $i"; + echo_location "/path/to/page/$i"; + echo_end; +``` + +Thanks Marcus Clyne for providing this idea. + +* Add new variable $echo_random which always returns a random non-negative integer with the lower/upper limit specified by the new directives `echo_random_min` and `echo_random_max`. For example, + +```nginx + + echo_random_min 10 + echo_random_max 200 + echo "random number: $echo_random"; +``` + +Thanks Marcus Clyne for providing this idea. + +[Back to TOC](#table-of-contents) + +Getting involved +================ + +You'll be very welcomed to submit patches to the [author](#author) or just ask for a commit bit to the [source repository](#source-repository) on GitHub. + +[Back to TOC](#table-of-contents) + +Author +====== + +Yichun "agentzh" Zhang (章亦春) *<agentzh@gmail.com>*, OpenResty Inc. + +This wiki page is also maintained by the author himself, and everybody is encouraged to improve this page as well. + +[Back to TOC](#table-of-contents) + +Copyright & License +=================== + +Copyright (c) 2009-2017, Yichun "agentzh" Zhang (章亦春) , OpenResty Inc. + +This module is licensed under the terms of the BSD license. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +[Back to TOC](#table-of-contents) + +See Also +======== + +* The original [blog post](http://agentzh.blogspot.com/2009/10/hacking-on-nginx-echo-module.html) about this module's initial development. +* The standard [addition filter module](http://nginx.org/en/docs/http/ngx_http_addition_module.html). +* The standard [proxy module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html). +* The [OpenResty](http://openresty.org) bundle. + +[Back to TOC](#table-of-contents) + diff --git a/echo-nginx-module/config b/echo-nginx-module/config new file mode 100644 index 00000000..32b54bf7 --- /dev/null +++ b/echo-nginx-module/config @@ -0,0 +1,60 @@ +ngx_addon_name=ngx_http_echo_module + +ECHO_SRCS=" \ + $ngx_addon_dir/src/ngx_http_echo_module.c \ + $ngx_addon_dir/src/ngx_http_echo_util.c \ + $ngx_addon_dir/src/ngx_http_echo_timer.c \ + $ngx_addon_dir/src/ngx_http_echo_var.c \ + $ngx_addon_dir/src/ngx_http_echo_handler.c \ + $ngx_addon_dir/src/ngx_http_echo_filter.c \ + $ngx_addon_dir/src/ngx_http_echo_sleep.c \ + $ngx_addon_dir/src/ngx_http_echo_location.c \ + $ngx_addon_dir/src/ngx_http_echo_echo.c \ + $ngx_addon_dir/src/ngx_http_echo_request_info.c \ + $ngx_addon_dir/src/ngx_http_echo_subrequest.c \ + $ngx_addon_dir/src/ngx_http_echo_foreach.c \ + " + +ECHO_DEPS=" \ + $ngx_addon_dir/src/ddebug.h \ + $ngx_addon_dir/src/ngx_http_echo_module.h \ + $ngx_addon_dir/src/ngx_http_echo_handler.h \ + $ngx_addon_dir/src/ngx_http_echo_util.h \ + $ngx_addon_dir/src/ngx_http_echo_sleep.h \ + $ngx_addon_dir/src/ngx_http_echo_filter.h \ + $ngx_addon_dir/src/ngx_http_echo_var.h \ + $ngx_addon_dir/src/ngx_http_echo_location.h \ + $ngx_addon_dir/src/ngx_http_echo_echo.h \ + $ngx_addon_dir/src/ngx_http_echo_request_info.h \ + $ngx_addon_dir/src/ngx_http_echo_subrequest.h \ + $ngx_addon_dir/src/ngx_http_echo_foreach.h \ + " + +# nginx won't have HTTP_POSTPONE_FILTER_MODULE & HTTP_POSTPONE_FILTER_SRCS +# defined since 1.9.11 +if test -z "$HTTP_POSTPONE_FILTER_MODULE"; then + HTTP_POSTPONE_FILTER_MODULE=ngx_http_postpone_filter_module + HTTP_POSTPONE_FILTER_SRCS=src/http/ngx_http_postpone_filter_module.c +fi + +# This module depends upon the postpone filter being activated +if [ $HTTP_POSTPONE != YES ]; then + HTTP_FILTER_MODULES="$HTTP_FILTER_MODULES $HTTP_POSTPONE_FILTER_MODULE" + HTTP_SRCS="$HTTP_SRCS $HTTP_POSTPONE_FILTER_SRCS" + HTTP_POSTPONE=YES +fi + +if test -n "$ngx_module_link"; then + ngx_module_type=HTTP_AUX_FILTER + ngx_module_name=$ngx_addon_name + ngx_module_incs= + ngx_module_deps="$ECHO_DEPS" + ngx_module_srcs="$ECHO_SRCS" + ngx_module_libs= + + . auto/module +else + HTTP_AUX_FILTER_MODULES="$HTTP_AUX_FILTER_MODULES $ngx_addon_name" + NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ECHO_SRCS" + NGX_ADDON_DEPS="$NGX_ADDON_DEPS $ECHO_DEPS" +fi diff --git a/echo-nginx-module/src/ddebug.h b/echo-nginx-module/src/ddebug.h new file mode 100644 index 00000000..a92d7a72 --- /dev/null +++ b/echo-nginx-module/src/ddebug.h @@ -0,0 +1,114 @@ +#ifndef DDEBUG_H +#define DDEBUG_H + +#include +#include +#include + +#if defined(DDEBUG) && (DDEBUG) + +# if (NGX_HAVE_VARIADIC_MACROS) + +# define dd(...) fprintf(stderr, "echo *** %s: ", __func__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, " at %s line %d.\n", __FILE__, __LINE__) + +# else + +#include +#include + +#include + +static ngx_inline void +dd(const char * fmt, ...) { +} + +# endif + +# if DDEBUG > 1 + +# define dd_enter() dd_enter_helper(r, __func__) + +static ngx_inline void +dd_enter_helper(ngx_http_request_t *r, const char *func) { + ngx_http_posted_request_t *pr; + + fprintf(stderr, ">enter %s %.*s %.*s?%.*s c:%d m:%p r:%p ar:%p pr:%p", + func, + (int) r->method_name.len, r->method_name.data, + (int) r->uri.len, r->uri.data, + (int) r->args.len, r->args.data, + 0/*(int) r->main->count*/, r->main, + r, r->connection->data, r->parent); + + if (r->posted_requests) { + fprintf(stderr, " posted:"); + + for (pr = r->posted_requests; pr; pr = pr->next) { + fprintf(stderr, "%p,", pr); + } + } + + fprintf(stderr, "\n"); +} + +# else + +# define dd_enter() + +# endif + +#else + +# if (NGX_HAVE_VARIADIC_MACROS) + +# define dd(...) + +# define dd_enter() + +# else + +#include + +static ngx_inline void +dd(const char * fmt, ...) { +} + +static ngx_inline void +dd_enter() { +} + +# endif + +#endif + +#if defined(DDEBUG) && (DDEBUG) + +#define dd_check_read_event_handler(r) \ + dd("r->read_event_handler = %s", \ + r->read_event_handler == ngx_http_block_reading ? \ + "ngx_http_block_reading" : \ + r->read_event_handler == ngx_http_test_reading ? \ + "ngx_http_test_reading" : \ + r->read_event_handler == ngx_http_request_empty_handler ? \ + "ngx_http_request_empty_handler" : "UNKNOWN") + +#define dd_check_write_event_handler(r) \ + dd("r->write_event_handler = %s", \ + r->write_event_handler == ngx_http_handler ? \ + "ngx_http_handler" : \ + r->write_event_handler == ngx_http_core_run_phases ? \ + "ngx_http_core_run_phases" : \ + r->write_event_handler == ngx_http_request_empty_handler ? \ + "ngx_http_request_empty_handler" : "UNKNOWN") + +#else + +#define dd_check_read_event_handler(r) +#define dd_check_write_event_handler(r) + +#endif + +#endif /* DDEBUG_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_echo.c b/echo-nginx-module/src/ngx_http_echo_echo.c new file mode 100644 index 00000000..f5789f5d --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_echo.c @@ -0,0 +1,342 @@ +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + +#include "ngx_http_echo_echo.h" +#include "ngx_http_echo_util.h" +#include "ngx_http_echo_filter.h" + +#include + +static ngx_buf_t ngx_http_echo_space_buf; + +static ngx_buf_t ngx_http_echo_newline_buf; + + +ngx_int_t +ngx_http_echo_echo_init(ngx_conf_t *cf) +{ + static u_char space_str[] = " "; + static u_char newline_str[] = "\n"; + + dd("global init..."); + + ngx_memzero(&ngx_http_echo_space_buf, sizeof(ngx_buf_t)); + + ngx_http_echo_space_buf.memory = 1; + + ngx_http_echo_space_buf.start = + ngx_http_echo_space_buf.pos = + space_str; + + ngx_http_echo_space_buf.end = + ngx_http_echo_space_buf.last = + space_str + sizeof(space_str) - 1; + + ngx_memzero(&ngx_http_echo_newline_buf, sizeof(ngx_buf_t)); + + ngx_http_echo_newline_buf.memory = 1; + + ngx_http_echo_newline_buf.start = + ngx_http_echo_newline_buf.pos = + newline_str; + + ngx_http_echo_newline_buf.end = + ngx_http_echo_newline_buf.last = + newline_str + sizeof(newline_str) - 1; + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_exec_echo_sync(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx) +{ + ngx_buf_t *buf; + ngx_chain_t *cl = NULL; /* the head of the chain link */ + + buf = ngx_calloc_buf(r->pool); + if (buf == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + buf->sync = 1; + + cl = ngx_alloc_chain_link(r->pool); + if (cl == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + cl->buf = buf; + cl->next = NULL; + + return ngx_http_echo_send_chain_link(r, ctx, cl); +} + + +ngx_int_t +ngx_http_echo_exec_echo(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args, + ngx_flag_t in_filter, ngx_array_t *opts) +{ + ngx_uint_t i; + + ngx_buf_t *space_buf; + ngx_buf_t *newline_buf; + ngx_buf_t *buf; + + ngx_str_t *computed_arg; + ngx_str_t *computed_arg_elts; + ngx_str_t *opt; + + ngx_chain_t *cl = NULL; /* the head of the chain link */ + ngx_chain_t **ll = &cl; /* always point to the address of the last link */ + + dd_enter(); + + if (computed_args == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + computed_arg_elts = computed_args->elts; + for (i = 0; i < computed_args->nelts; i++) { + computed_arg = &computed_arg_elts[i]; + + if (computed_arg->len == 0) { + buf = NULL; + + } else { + buf = ngx_calloc_buf(r->pool); + if (buf == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + buf->start = buf->pos = computed_arg->data; + buf->last = buf->end = computed_arg->data + + computed_arg->len; + + buf->memory = 1; + } + + if (cl == NULL) { + cl = ngx_alloc_chain_link(r->pool); + if (cl == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + cl->buf = buf; + cl->next = NULL; + ll = &cl->next; + + } else { + /* append a space first */ + *ll = ngx_alloc_chain_link(r->pool); + + if (*ll == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + space_buf = ngx_calloc_buf(r->pool); + + if (space_buf == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + /* nginx clears buf flags at the end of each request handling, + * so we have to make a clone here. */ + *space_buf = ngx_http_echo_space_buf; + + (*ll)->buf = space_buf; + (*ll)->next = NULL; + + ll = &(*ll)->next; + + /* then append the buf only if it's non-empty */ + if (buf) { + *ll = ngx_alloc_chain_link(r->pool); + if (*ll == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + (*ll)->buf = buf; + (*ll)->next = NULL; + + ll = &(*ll)->next; + } + } + } /* end for */ + + if (cl && cl->buf == NULL) { + cl = cl->next; + } + + if (opts && opts->nelts > 0) { + opt = opts->elts; + /* FIXME handle other unrecognized options here */ + if (opt[0].len == 1 && opt[0].data[0] == 'n') { + goto done; + } + } + + /* append the newline character */ + + newline_buf = ngx_calloc_buf(r->pool); + + if (newline_buf == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + *newline_buf = ngx_http_echo_newline_buf; + + if (cl == NULL) { + cl = ngx_alloc_chain_link(r->pool); + + if (cl == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + cl->buf = newline_buf; + cl->next = NULL; + /* ll = &cl->next; */ + + } else { + *ll = ngx_alloc_chain_link(r->pool); + + if (*ll == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + (*ll)->buf = newline_buf; + (*ll)->next = NULL; + /* ll = &(*ll)->next; */ + } + +done: + + if (cl == NULL || cl->buf == NULL) { + return NGX_OK; + } + + if (in_filter) { + return ngx_http_echo_next_body_filter(r, cl); + } + + return ngx_http_echo_send_chain_link(r, ctx, cl); +} + + +ngx_int_t +ngx_http_echo_exec_echo_flush(ngx_http_request_t *r, ngx_http_echo_ctx_t *ctx) +{ + return ngx_http_send_special(r, NGX_HTTP_FLUSH); +} + + +ngx_int_t +ngx_http_echo_exec_echo_request_body(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx) +{ + ngx_buf_t *b; + ngx_chain_t *out, *cl, **ll; + + if (r->request_body == NULL || r->request_body->bufs == NULL) { + return NGX_OK; + } + + out = NULL; + ll = &out; + + for (cl = r->request_body->bufs; cl; cl = cl->next) { + if (ngx_buf_special(cl->buf)) { + /* we do not want to create zero-size bufs */ + continue; + } + + *ll = ngx_alloc_chain_link(r->pool); + if (*ll == NULL) { + return NGX_ERROR; + } + + b = ngx_alloc_buf(r->pool); + if (b == NULL) { + return NGX_ERROR; + } + + (*ll)->buf = b; + (*ll)->next = NULL; + + ngx_memcpy(b, cl->buf, sizeof(ngx_buf_t)); + b->tag = (ngx_buf_tag_t) &ngx_http_echo_exec_echo_request_body; + b->last_buf = 0; + b->last_in_chain = 0; + + ll = &(*ll)->next; + } + + if (out == NULL) { + return NGX_OK; + } + + return ngx_http_echo_send_chain_link(r, ctx, out); +} + + +ngx_int_t +ngx_http_echo_exec_echo_duplicate(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_str_t *computed_arg; + ngx_str_t *computed_arg_elts; + ssize_t i, count; + ngx_str_t *str; + u_char *p; + ngx_int_t rc; + ngx_buf_t *buf; + ngx_chain_t *cl; + + dd_enter(); + + computed_arg_elts = computed_args->elts; + + computed_arg = &computed_arg_elts[0]; + + count = ngx_http_echo_atosz(computed_arg->data, computed_arg->len); + + if (count == NGX_ERROR) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "invalid size specified: \"%V\"", computed_arg); + + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + str = &computed_arg_elts[1]; + + if (count == 0 || str->len == 0) { + rc = ngx_http_echo_send_header_if_needed(r, ctx); + if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { + return rc; + } + + return NGX_OK; + } + + buf = ngx_create_temp_buf(r->pool, count * str->len); + if (buf == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + p = buf->pos; + for (i = 0; i < count; i++) { + p = ngx_copy(p, str->data, str->len); + } + buf->last = p; + + cl = ngx_alloc_chain_link(r->pool); + if (cl == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + cl->next = NULL; + cl->buf = buf; + + return ngx_http_echo_send_chain_link(r, ctx, cl); +} diff --git a/echo-nginx-module/src/ngx_http_echo_echo.h b/echo-nginx-module/src/ngx_http_echo_echo.h new file mode 100644 index 00000000..896f1ed5 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_echo.h @@ -0,0 +1,25 @@ +#ifndef ECHO_ECHO_H +#define ECHO_ECHO_H + +#include "ngx_http_echo_module.h" + +ngx_int_t ngx_http_echo_echo_init(ngx_conf_t *cf); + +ngx_int_t ngx_http_echo_exec_echo_sync(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx); + +ngx_int_t ngx_http_echo_exec_echo(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args, + ngx_flag_t in_filter, ngx_array_t *opts); + +ngx_int_t ngx_http_echo_exec_echo_request_body(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx); + +ngx_int_t ngx_http_echo_exec_echo_flush(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx); + +ngx_int_t ngx_http_echo_exec_echo_duplicate(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args); + +#endif /* ECHO_ECHO_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_filter.c b/echo-nginx-module/src/ngx_http_echo_filter.c new file mode 100644 index 00000000..689b52e8 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_filter.c @@ -0,0 +1,282 @@ +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + +#include "ngx_http_echo_filter.h" +#include "ngx_http_echo_util.h" +#include "ngx_http_echo_echo.h" + +#include + + + +ngx_http_output_header_filter_pt ngx_http_echo_next_header_filter; + +ngx_http_output_body_filter_pt ngx_http_echo_next_body_filter; + +static ngx_int_t ngx_http_echo_header_filter(ngx_http_request_t *r); + +static ngx_int_t ngx_http_echo_body_filter(ngx_http_request_t *r, + ngx_chain_t *in); + +/* filter handlers */ +static ngx_int_t ngx_http_echo_exec_filter_cmds(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *cmds, ngx_uint_t *iterator); + + +static volatile ngx_cycle_t *ngx_http_echo_prev_cycle = NULL; + + +ngx_int_t +ngx_http_echo_filter_init(ngx_conf_t *cf) +{ + int multi_http_blocks; + ngx_http_echo_main_conf_t *emcf; + + emcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_echo_module); + + if (ngx_http_echo_prev_cycle != ngx_cycle) { + ngx_http_echo_prev_cycle = ngx_cycle; + multi_http_blocks = 0; + + } else { + multi_http_blocks = 1; + } + + if (multi_http_blocks || emcf->requires_filter) { + dd("top header filter: %ld", + (unsigned long) ngx_http_top_header_filter); + + ngx_http_echo_next_header_filter = ngx_http_top_header_filter; + ngx_http_top_header_filter = ngx_http_echo_header_filter; + + dd("top body filter: %ld", (unsigned long) ngx_http_top_body_filter); + + ngx_http_echo_next_body_filter = ngx_http_top_body_filter; + ngx_http_top_body_filter = ngx_http_echo_body_filter; + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_echo_header_filter(ngx_http_request_t *r) +{ + ngx_http_echo_loc_conf_t *conf; + ngx_http_echo_ctx_t *ctx; + + ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "echo header filter, uri \"%V?%V\"", &r->uri, &r->args); + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + + /* XXX we should add option to insert contents for responses + * of non-200 status code here... */ + /* + if (r->headers_out.status != NGX_HTTP_OK) { + if (ctx != NULL) { + ctx->skip_filter = 1; + } + return ngx_http_echo_next_header_filter(r); + } + */ + + conf = ngx_http_get_module_loc_conf(r, ngx_http_echo_module); + if (conf->before_body_cmds == NULL && conf->after_body_cmds == NULL) { + if (ctx != NULL) { + ctx->skip_filter = 1; + } + return ngx_http_echo_next_header_filter(r); + } + + if (ctx == NULL) { + ctx = ngx_http_echo_create_ctx(r); + if (ctx == NULL) { + return NGX_ERROR; + } + + ngx_http_set_ctx(r, ctx, ngx_http_echo_module); + } + + /* enable streaming here (use chunked encoding) */ + ngx_http_clear_content_length(r); + ngx_http_clear_accept_ranges(r); + + return ngx_http_echo_next_header_filter(r); +} + + +static ngx_int_t +ngx_http_echo_body_filter(ngx_http_request_t *r, ngx_chain_t *in) +{ + ngx_http_echo_ctx_t *ctx; + ngx_int_t rc; + ngx_http_echo_loc_conf_t *conf; + unsigned last; + ngx_chain_t *cl; + ngx_buf_t *b; + + ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "echo body filter, uri \"%V?%V\"", &r->uri, &r->args); + + if (in == NULL || r->header_only) { + return ngx_http_echo_next_body_filter(r, in); + } + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + + if (ctx == NULL || ctx->skip_filter) { + return ngx_http_echo_next_body_filter(r, in); + } + + conf = ngx_http_get_module_loc_conf(r, ngx_http_echo_module); + + if (!ctx->before_body_sent) { + ctx->before_body_sent = 1; + + if (conf->before_body_cmds != NULL) { + rc = ngx_http_echo_exec_filter_cmds(r, ctx, conf->before_body_cmds, + &ctx->next_before_body_cmd); + if (rc != NGX_OK) { + return NGX_ERROR; + } + } + } + + if (conf->after_body_cmds == NULL) { + ctx->skip_filter = 1; + return ngx_http_echo_next_body_filter(r, in); + } + + last = 0; + + for (cl = in; cl; cl = cl->next) { + dd("cl %p, special %d", cl, ngx_buf_special(cl->buf)); + + if (cl->buf->last_buf || cl->buf->last_in_chain) { + cl->buf->last_buf = 0; + cl->buf->last_in_chain = 0; + cl->buf->sync = 1; + last = 1; + } + } + + dd("in %p, last %d", in, (int) last); + + if (in) { + rc = ngx_http_echo_next_body_filter(r, in); + +#if 0 + if (rc == NGX_AGAIN) { + return NGX_ERROR; + } +#endif + + dd("next filter returns %d, last %d", (int) rc, (int) last); + + if (rc == NGX_ERROR || rc > NGX_OK || !last) { + return rc; + } + } + + dd("exec filter cmds for after body cmds"); + + rc = ngx_http_echo_exec_filter_cmds(r, ctx, conf->after_body_cmds, + &ctx->next_after_body_cmd); + if (rc == NGX_ERROR || rc > NGX_OK) { + dd("FAILED: exec filter cmds for after body cmds"); + return NGX_ERROR; + } + + ctx->skip_filter = 1; + + dd("after body cmds executed...terminating..."); + + /* XXX we can NOT use + * ngx_http_send_special(r, NGX_HTTP_LAST) here + * because we should bypass the upstream filters. */ + + b = ngx_calloc_buf(r->pool); + if (b == NULL) { + return NGX_ERROR; + } + + if (r == r->main && !r->post_action) { + b->last_buf = 1; + + } else { + b->sync = 1; + b->last_in_chain = 1; + } + + cl = ngx_alloc_chain_link(r->pool); + if (cl == NULL) { + return NGX_ERROR; + } + + cl->next = NULL; + cl->buf = b; + + return ngx_http_echo_next_body_filter(r, cl); +} + + +static ngx_int_t +ngx_http_echo_exec_filter_cmds(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *cmds, ngx_uint_t *iterator) +{ + ngx_int_t rc; + ngx_array_t *opts = NULL; + ngx_array_t *computed_args = NULL; + ngx_http_echo_cmd_t *cmd; + ngx_http_echo_cmd_t *cmd_elts; + + for (cmd_elts = cmds->elts; *iterator < cmds->nelts; (*iterator)++) { + cmd = &cmd_elts[*iterator]; + + /* evaluate arguments for the current cmd (if any) */ + if (cmd->args) { + computed_args = ngx_array_create(r->pool, cmd->args->nelts, + sizeof(ngx_str_t)); + if (computed_args == NULL) { + return NGX_ERROR; + } + + opts = ngx_array_create(r->pool, 1, sizeof(ngx_str_t)); + if (opts == NULL) { + return NGX_ERROR; + } + + rc = ngx_http_echo_eval_cmd_args(r, cmd, computed_args, opts); + + if (rc != NGX_OK) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "Failed to evaluate arguments for " + "the directive."); + return rc; + } + } + + /* do command dispatch based on the opcode */ + switch (cmd->opcode) { + case echo_opcode_echo_before_body: + case echo_opcode_echo_after_body: + dd("exec echo_before_body or echo_after_body..."); + + rc = ngx_http_echo_exec_echo(r, ctx, computed_args, + 1 /* in filter */, opts); + + if (rc == NGX_ERROR || rc > NGX_OK) { + return rc; + } + + break; + default: + break; + } + } + + return NGX_OK; +} diff --git a/echo-nginx-module/src/ngx_http_echo_filter.h b/echo-nginx-module/src/ngx_http_echo_filter.h new file mode 100644 index 00000000..ea5115d4 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_filter.h @@ -0,0 +1,15 @@ +#ifndef ECHO_FILTER_H +#define ECHO_FILTER_H + +#include "ngx_http_echo_module.h" + + +extern ngx_http_output_header_filter_pt ngx_http_echo_next_header_filter; + +extern ngx_http_output_body_filter_pt ngx_http_echo_next_body_filter; + + +ngx_int_t ngx_http_echo_filter_init (ngx_conf_t *cf); + +#endif /* ECHO_FILTER_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_foreach.c b/echo-nginx-module/src/ngx_http_echo_foreach.c new file mode 100644 index 00000000..a4a2b546 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_foreach.c @@ -0,0 +1,183 @@ +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + +#include "ngx_http_echo_foreach.h" +#include "ngx_http_echo_util.h" + +#include + + +ngx_int_t +ngx_http_echo_it_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + ngx_http_echo_ctx_t *ctx; + ngx_uint_t i; + ngx_array_t *choices; + ngx_str_t *choice_elts, *choice; + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + + if (ctx && ctx->foreach != NULL) { + + choices = ctx->foreach->choices; + i = ctx->foreach->next_choice; + + if (i < choices->nelts) { + choice_elts = choices->elts; + choice = &choice_elts[i]; + + v->len = choice->len; + v->data = choice->data; + v->valid = 1; + v->no_cacheable = 1; + v->not_found = 0; + + return NGX_OK; + } + } + + v->not_found = 1; + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_exec_echo_foreach_split(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_http_echo_loc_conf_t *elcf; + ngx_str_t *delimiter, *compound; + u_char *pos, *last, *end; + ngx_str_t *choice; + ngx_str_t *computed_arg_elts; + ngx_array_t *cmds; + ngx_http_echo_cmd_t *cmd; + ngx_http_echo_cmd_t *cmd_elts; + + if (ctx->foreach != NULL) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "Nested echo_foreach not supported yet."); + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + if (computed_args->nelts < 2) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "echo_foreach should take at least two arguments. " + "(if your delimiter starts with \"-\", preceding it " + "with a \"--\".)"); + + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + computed_arg_elts = computed_args->elts; + + compound = &computed_arg_elts[1]; + + dd("HEY coumpound len: %u", (int) compound->len); + + ctx->foreach = ngx_palloc(r->pool, sizeof(ngx_http_echo_foreach_ctx_t)); + + if (ctx->foreach == NULL) { + return NGX_ERROR; + } + + ctx->foreach->cmd_index = ctx->next_handler_cmd; + + ctx->foreach->next_choice = 0; + + ctx->foreach->choices = ngx_array_create(r->pool, 10, sizeof(ngx_str_t)); + if (ctx->foreach->choices == NULL) { + return NGX_ERROR; + } + + delimiter = &computed_arg_elts[0]; + + pos = compound->data; + end = compound->data + compound->len; + + while ((last = ngx_http_echo_strlstrn(pos, end, delimiter->data, + delimiter->len - 1)) != NULL) + { + dd("entered the loop"); + + if (last == pos) { + dd("!!! len == 0"); + pos = last + delimiter->len; + continue; + } + + choice = ngx_array_push(ctx->foreach->choices); + if (choice == NULL) { + return NGX_ERROR; + } + + choice->data = pos; + choice->len = last - pos; + pos = last + delimiter->len; + } + + if (pos < end) { + choice = ngx_array_push(ctx->foreach->choices); + if (choice == NULL) { + return NGX_ERROR; + } + + choice->data = pos; + choice->len = end - pos; + } + + if (ctx->foreach->choices->nelts == 0) { + /* skip the foreach body entirely */ + elcf = ngx_http_get_module_loc_conf(r, ngx_http_echo_module); + cmds = elcf->handler_cmds; + cmd_elts = cmds->elts; + for (/* void */; ctx->next_handler_cmd < cmds->nelts; + ctx->next_handler_cmd++) + { + cmd = &cmd_elts[ctx->next_handler_cmd + 1]; + if (cmd->opcode == echo_opcode_echo_end) { + return NGX_OK; + } + } + + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_exec_echo_end(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx) +{ + if (ctx->foreach == NULL) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "Found a echo_end that has no corresponding echo_foreach " + "before it."); + return NGX_ERROR; + } + + ctx->foreach->next_choice++; + + if (ctx->foreach->next_choice >= ctx->foreach->choices->nelts) { + /* TODO We need to explicitly free the foreach ctx from + * the pool */ + ctx->foreach = NULL; + + return NGX_OK; + } + + dd("echo_end: ++ next_choice (total: %u): %u", + (unsigned) ctx->foreach->choices->nelts, + (unsigned) ctx->foreach->next_choice); + + /* the main handler dispatcher loop will increment + * ctx->next_handler_cmd for us anyway. */ + ctx->next_handler_cmd = ctx->foreach->cmd_index; + + return NGX_OK; +} diff --git a/echo-nginx-module/src/ngx_http_echo_foreach.h b/echo-nginx-module/src/ngx_http_echo_foreach.h new file mode 100644 index 00000000..49592f41 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_foreach.h @@ -0,0 +1,16 @@ +#ifndef ECHO_FOREACH_H +#define ECHO_FOREACH_H + +#include "ngx_http_echo_module.h" + +ngx_int_t ngx_http_echo_exec_echo_foreach_split(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args); + +ngx_int_t ngx_http_echo_exec_echo_end(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx); + +ngx_int_t ngx_http_echo_it_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +#endif /* ECHO_FOREACH_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_handler.c b/echo-nginx-module/src/ngx_http_echo_handler.c new file mode 100644 index 00000000..00933a45 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_handler.c @@ -0,0 +1,429 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_echo_filter.h" +#include "ngx_http_echo_handler.h" +#include "ngx_http_echo_echo.h" +#include "ngx_http_echo_util.h" +#include "ngx_http_echo_sleep.h" +#include "ngx_http_echo_var.h" +#include "ngx_http_echo_timer.h" +#include "ngx_http_echo_location.h" +#include "ngx_http_echo_subrequest.h" +#include "ngx_http_echo_request_info.h" +#include "ngx_http_echo_foreach.h" + +#include +#include + + +void +ngx_http_echo_wev_handler(ngx_http_request_t *r) +{ + ngx_int_t rc; + ngx_http_echo_ctx_t *ctx; + + dd("wev handler"); + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + + if (ctx == NULL) { + ngx_http_finalize_request(r, NGX_ERROR); + return; + } + + dd("waiting: %d, done: %d", (int) ctx->waiting, (int) ctx->done); + + if (ctx->waiting && ! ctx->done) { + + if (r == r->connection->data && r->postponed) { + + if (r->postponed->request) { + r->connection->data = r->postponed->request; + +#if defined(nginx_version) && nginx_version >= 8012 + ngx_http_post_request(r->postponed->request, NULL); +#else + ngx_http_post_request(r->postponed->request); +#endif + + } else { + ngx_http_echo_flush_postponed_outputs(r); + } + } + + return; + } + + ctx->done = 0; + + ctx->next_handler_cmd++; + + rc = ngx_http_echo_run_cmds(r); + + dd("rc: %d", (int) rc); + + if (rc == NGX_ERROR || rc == NGX_DONE) { + ngx_http_finalize_request(r, rc); + return; + } + + if (rc == NGX_AGAIN) { + dd("mark busy %d for %.*s", (int) ctx->next_handler_cmd, + (int) r->uri.len, + r->uri.data); + + ctx->waiting = 1; + ctx->done = 0; + + } else { + dd("mark ready %d", (int) ctx->next_handler_cmd); + ctx->waiting = 0; + ctx->done = 1; + + dd("finalizing with rc %d", (int) rc); + + dd("finalize request %.*s with %d", (int) r->uri.len, r->uri.data, + (int) rc); + + ngx_http_finalize_request(r, rc); + } +} + + +ngx_int_t +ngx_http_echo_handler(ngx_http_request_t *r) +{ + ngx_int_t rc; + ngx_http_echo_ctx_t *ctx; + + dd("subrequest in memory: %d", (int) r->subrequest_in_memory); + + rc = ngx_http_echo_run_cmds(r); + + dd("run cmds returned %d", (int) rc); + + if (rc == NGX_ERROR + || rc == NGX_OK + || rc == NGX_DONE + || rc == NGX_DECLINED) + { + return rc; + } + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + + if (rc >= NGX_HTTP_SPECIAL_RESPONSE) { + if (ctx && r->header_sent) { + return NGX_ERROR; + } + + return rc; + } + + /* rc == NGX_AGAIN */ + +#if defined(nginx_version) && nginx_version >= 8011 + r->main->count++; +#endif + + dd("%d", r->connection->destroyed); + dd("%d", r->done); + + if (ctx) { + dd("mark busy %d for %.*s", (int) ctx->next_handler_cmd, + (int) r->uri.len, + r->uri.data); + + ctx->waiting = 1; + ctx->done = 0; + } + + return NGX_DONE; +} + + +ngx_int_t +ngx_http_echo_run_cmds(ngx_http_request_t *r) +{ + ngx_http_echo_loc_conf_t *elcf; + ngx_http_echo_ctx_t *ctx; + ngx_int_t rc; + ngx_array_t *cmds; + ngx_array_t *computed_args = NULL; + ngx_http_echo_cmd_t *cmd; + ngx_http_echo_cmd_t *cmd_elts; + ngx_array_t *opts = NULL; + + elcf = ngx_http_get_module_loc_conf(r, ngx_http_echo_module); + cmds = elcf->handler_cmds; + if (cmds == NULL) { + return NGX_DECLINED; + } + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + if (ctx == NULL) { + ctx = ngx_http_echo_create_ctx(r); + if (ctx == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + ngx_http_set_ctx(r, ctx, ngx_http_echo_module); + } + + dd("exec handler: %.*s: %i", (int) r->uri.len, r->uri.data, + (int) ctx->next_handler_cmd); + + cmd_elts = cmds->elts; + + for (; ctx->next_handler_cmd < cmds->nelts; ctx->next_handler_cmd++) { + + cmd = &cmd_elts[ctx->next_handler_cmd]; + + /* evaluate arguments for the current cmd (if any) */ + if (cmd->args) { + computed_args = ngx_array_create(r->pool, cmd->args->nelts, + sizeof(ngx_str_t)); + + if (computed_args == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + opts = ngx_array_create(r->pool, 1, sizeof(ngx_str_t)); + + if (opts == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + rc = ngx_http_echo_eval_cmd_args(r, cmd, computed_args, opts); + if (rc != NGX_OK) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "Failed to evaluate arguments for " + "the directive."); + return rc; + } + } + + /* do command dispatch based on the opcode */ + + switch (cmd->opcode) { + + case echo_opcode_echo_sync: + rc = ngx_http_echo_exec_echo_sync(r, ctx); + break; + + case echo_opcode_echo: + /* XXX moved the following code to a separate + * function */ + dd("found echo opcode"); + rc = ngx_http_echo_exec_echo(r, ctx, computed_args, + 0 /* in filter */, opts); + break; + + case echo_opcode_echo_request_body: + rc = ngx_http_echo_exec_echo_request_body(r, ctx); + break; + + case echo_opcode_echo_location_async: + if (!r->request_body) { + /* we require reading the request body before doing + * subrequests */ + + ctx->next_handler_cmd--; /* re-run the current cmd */ + goto read_request_body; + } + + dd("found opcode echo location async..."); + rc = ngx_http_echo_exec_echo_location_async(r, ctx, + computed_args); + break; + + case echo_opcode_echo_location: + if (!r->request_body) { + /* we require reading the request body before doing + * subrequests */ + + ctx->next_handler_cmd--; /* re-run the current cmd */ + goto read_request_body; + } + + return ngx_http_echo_exec_echo_location(r, ctx, computed_args); + + case echo_opcode_echo_subrequest_async: + if (!r->request_body) { + /* we require reading the request body before doing + * subrequests */ + + ctx->next_handler_cmd--; /* re-run the current cmd */ + goto read_request_body; + } + + dd("found opcode echo subrequest async..."); + rc = ngx_http_echo_exec_echo_subrequest_async(r, ctx, + computed_args); + break; + + case echo_opcode_echo_subrequest: + if (!r->request_body) { + /* we require reading the request body before doing + * subrequests */ + + ctx->next_handler_cmd--; /* re-run the current cmd */ + goto read_request_body; + } + + return ngx_http_echo_exec_echo_subrequest(r, ctx, computed_args); + + case echo_opcode_echo_sleep: + return ngx_http_echo_exec_echo_sleep(r, ctx, computed_args); + + case echo_opcode_echo_flush: + rc = ngx_http_echo_exec_echo_flush(r, ctx); + break; + + case echo_opcode_echo_blocking_sleep: + rc = ngx_http_echo_exec_echo_blocking_sleep(r, ctx, + computed_args); + break; + + case echo_opcode_echo_reset_timer: + rc = ngx_http_echo_exec_echo_reset_timer(r, ctx); + break; + + case echo_opcode_echo_duplicate: + rc = ngx_http_echo_exec_echo_duplicate(r, ctx, computed_args); + break; + + case echo_opcode_echo_read_request_body: + +read_request_body: + + ctx->wait_read_request_body = 0; + + rc = ngx_http_echo_exec_echo_read_request_body(r, ctx); + + if (rc == NGX_ERROR) { + return NGX_ERROR; + } + + if (rc >= NGX_HTTP_SPECIAL_RESPONSE) { +#if (nginx_version >= 8011 && nginx_version < 1002006) \ + || (nginx_version >= 1003000 && nginx_version < 1003009) + r->main->count--; +#endif + return rc; + } + +#if nginx_version >= 8011 + r->main->count--; +#endif + dd("read request body: %d", (int) rc); + + if (rc == NGX_OK) { + continue; + } + + /* rc == NGX_AGAIN */ + ctx->wait_read_request_body = 1; + return NGX_AGAIN; + + case echo_opcode_echo_foreach_split: + rc = ngx_http_echo_exec_echo_foreach_split(r, ctx, computed_args); + break; + + case echo_opcode_echo_end: + rc = ngx_http_echo_exec_echo_end(r, ctx); + break; + + case echo_opcode_echo_exec: + dd("echo_exec"); + return ngx_http_echo_exec_exec(r, ctx, computed_args); + + default: + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "unknown opcode: %d", cmd->opcode); + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { + return rc; + } + } + + rc = ngx_http_echo_send_chain_link(r, ctx, NULL /* indicate LAST */); + + if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { + return rc; + } + + if (!r->request_body) { + if (ngx_http_discard_request_body(r) != NGX_OK) { + return NGX_ERROR; + } + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_post_subrequest(ngx_http_request_t *r, + void *data, ngx_int_t rc) +{ + ngx_http_echo_ctx_t *ctx = data; + ngx_http_request_t *pr; + ngx_http_echo_ctx_t *pr_ctx; + + dd("echo post_subrequest: %.*s", (int) r->uri.len, r->uri.data); + + if (ctx->run_post_subrequest) { + dd("already run post_subrequest: %p: %.*s", ctx, + (int) r->uri.len, r->uri.data); + + return rc; + } + + dd("setting run_post_subrequest to 1 for %p for %.*s", ctx, + (int) r->uri.len, r->uri.data); + + ctx->run_post_subrequest = 1; + + pr = r->parent; + + pr_ctx = ngx_http_get_module_ctx(pr, ngx_http_echo_module); + if (pr_ctx == NULL) { + return NGX_ERROR; + } + + dd("mark ready %d", (int) pr_ctx->next_handler_cmd); + + pr_ctx->waiting = 0; + pr_ctx->done = 1; + + pr->write_event_handler = ngx_http_echo_wev_handler; + + /* work-around issues in nginx's event module */ + + if (r != r->connection->data + && r->postponed + && (r->main->posted_requests == NULL + || r->main->posted_requests->request != pr)) + { +#if defined(nginx_version) && nginx_version >= 8012 + ngx_http_post_request(pr, NULL); +#else + ngx_http_post_request(pr); +#endif + } + + return rc; +} diff --git a/echo-nginx-module/src/ngx_http_echo_handler.h b/echo-nginx-module/src/ngx_http_echo_handler.h new file mode 100644 index 00000000..afc06668 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_handler.h @@ -0,0 +1,18 @@ +#ifndef ECHO_HANDLER_H +#define ECHO_HANDLER_H + +#include "ngx_http_echo_module.h" + + +void ngx_http_echo_wev_handler(ngx_http_request_t *r); + +ngx_int_t ngx_http_echo_handler(ngx_http_request_t *r); + +ngx_int_t ngx_http_echo_run_cmds(ngx_http_request_t *r); + +ngx_int_t ngx_http_echo_post_subrequest(ngx_http_request_t *r, + void *data, ngx_int_t rc); + + +#endif /* ECHO_HANDLER_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_location.c b/echo-nginx-module/src/ngx_http_echo_location.c new file mode 100644 index 00000000..bfabb5ec --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_location.c @@ -0,0 +1,178 @@ +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + +#include "ngx_http_echo_util.h" +#include "ngx_http_echo_location.h" +#include "ngx_http_echo_handler.h" + +#include + + +static ngx_int_t ngx_http_echo_adjust_subrequest(ngx_http_request_t *sr); + + +ngx_int_t +ngx_http_echo_exec_echo_location_async(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_int_t rc; + ngx_http_request_t *sr; /* subrequest object */ + ngx_str_t *computed_arg_elts; + ngx_str_t location; + ngx_str_t *url_args; + ngx_str_t args; + ngx_uint_t flags = 0; + + dd_enter(); + + computed_arg_elts = computed_args->elts; + + location = computed_arg_elts[0]; + + if (location.len == 0) { + return NGX_ERROR; + } + + if (computed_args->nelts > 1) { + url_args = &computed_arg_elts[1]; + } else { + url_args = NULL; + } + + args.data = NULL; + args.len = 0; + + if (ngx_http_parse_unsafe_uri(r, &location, &args, &flags) != NGX_OK) { + ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "echo_location_async sees unsafe uri: \"%V\"", + &location); + return NGX_ERROR; + } + + if (args.len > 0 && url_args == NULL) { + url_args = &args; + } + + rc = ngx_http_echo_send_header_if_needed(r, ctx); + if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { + return rc; + } + + rc = ngx_http_subrequest(r, &location, url_args, &sr, NULL, 0); + + if (rc != NGX_OK) { + return NGX_ERROR; + } + + rc = ngx_http_echo_adjust_subrequest(sr); + if (rc != NGX_OK) { + return NGX_ERROR; + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_exec_echo_location(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_int_t rc; + ngx_http_request_t *sr; /* subrequest object */ + ngx_str_t *computed_arg_elts; + ngx_str_t location; + ngx_str_t *url_args; + ngx_http_post_subrequest_t *psr; + ngx_str_t args; + ngx_uint_t flags = 0; + ngx_http_echo_ctx_t *sr_ctx; + + computed_arg_elts = computed_args->elts; + + location = computed_arg_elts[0]; + + if (location.len == 0) { + return NGX_ERROR; + } + + if (computed_args->nelts > 1) { + url_args = &computed_arg_elts[1]; + + } else { + url_args = NULL; + } + + args.data = NULL; + args.len = 0; + + if (ngx_http_parse_unsafe_uri(r, &location, &args, &flags) != NGX_OK) { + ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "echo_location sees unsafe uri: \"%V\"", + &location); + return NGX_ERROR; + } + + if (args.len > 0 && url_args == NULL) { + url_args = &args; + } + + rc = ngx_http_echo_send_header_if_needed(r, ctx); + if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { + return rc; + } + + sr_ctx = ngx_http_echo_create_ctx(r); + + psr = ngx_palloc(r->pool, sizeof(ngx_http_post_subrequest_t)); + if (psr == NULL) { + return NGX_ERROR; + } + + psr->handler = ngx_http_echo_post_subrequest; + psr->data = sr_ctx; + + rc = ngx_http_subrequest(r, &location, url_args, &sr, psr, 0); + + if (rc != NGX_OK) { + return NGX_ERROR; + } + + rc = ngx_http_echo_adjust_subrequest(sr); + + if (rc != NGX_OK) { + return NGX_ERROR; + } + + return NGX_AGAIN; +} + + +static ngx_int_t +ngx_http_echo_adjust_subrequest(ngx_http_request_t *sr) +{ + ngx_http_core_main_conf_t *cmcf; + ngx_http_request_t *r; + + /* we do not inherit the parent request's variables */ + cmcf = ngx_http_get_module_main_conf(sr, ngx_http_core_module); + + r = sr->parent; + + sr->header_in = r->header_in; + + /* XXX work-around a bug in ngx_http_subrequest */ + if (r->headers_in.headers.last == &r->headers_in.headers.part) { + sr->headers_in.headers.last = &sr->headers_in.headers.part; + } + + sr->variables = ngx_pcalloc(sr->pool, cmcf->variables.nelts + * sizeof(ngx_http_variable_value_t)); + + if (sr->variables == NULL) { + return NGX_ERROR; + } + + return NGX_OK; +} diff --git a/echo-nginx-module/src/ngx_http_echo_location.h b/echo-nginx-module/src/ngx_http_echo_location.h new file mode 100644 index 00000000..6bc0e031 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_location.h @@ -0,0 +1,13 @@ +#ifndef ECHO_LOCATION_H +#define ECHO_LOCATION_H + +#include "ngx_http_echo_module.h" + +ngx_int_t ngx_http_echo_exec_echo_location_async(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args); + +ngx_int_t ngx_http_echo_exec_echo_location(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args); + +#endif /* ECHO_LOCATION_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_module.c b/echo-nginx-module/src/ngx_http_echo_module.c new file mode 100644 index 00000000..8d736d7c --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_module.c @@ -0,0 +1,682 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_echo_handler.h" +#include "ngx_http_echo_filter.h" +#include "ngx_http_echo_echo.h" +#include "ngx_http_echo_request_info.h" +#include "ngx_http_echo_var.h" +#include "ngx_http_echo_util.h" + + +#include +#include +#include + + +/* config init handler */ +static void *ngx_http_echo_create_loc_conf(ngx_conf_t *cf); +static char *ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, + void *child); +static void *ngx_http_echo_create_main_conf(ngx_conf_t *cf); +static ngx_int_t ngx_http_echo_post_config(ngx_conf_t *cf); + +/* config directive handlers */ +static char *ngx_http_echo_echo(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf); +static char *ngx_http_echo_echo_request_body(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_sleep(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf); +static char *ngx_http_echo_echo_flush(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf); +static char *ngx_http_echo_echo_blocking_sleep(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_reset_timer(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_before_body(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_after_body(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_location_async(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_location(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_subrequest_async(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_subrequest(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_duplicate(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_read_request_body(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_foreach_split(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_end(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_abort_parent(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_echo_exec(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); +static char *ngx_http_echo_helper(ngx_http_echo_opcode_t opcode, + ngx_http_echo_cmd_category_t cat, + ngx_conf_t *cf, ngx_command_t *cmd, void *conf); + + +static ngx_http_module_t ngx_http_echo_module_ctx = { + NULL, /* preconfiguration */ + ngx_http_echo_post_config, /* postconfiguration */ + + ngx_http_echo_create_main_conf, /* create main configuration */ + NULL, /* init main configuration */ + + NULL, /* create server configuration */ + NULL, /* merge server configuration */ + + ngx_http_echo_create_loc_conf, /* create location configuration */ + ngx_http_echo_merge_loc_conf /* merge location configuration */ +}; + + +static ngx_command_t ngx_http_echo_commands[] = { + + { ngx_string("echo"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_ANY, + ngx_http_echo_echo, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_request_body"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_NOARGS, + ngx_http_echo_echo_request_body, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_sleep"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE1, + ngx_http_echo_echo_sleep, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_flush"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_NOARGS, + ngx_http_echo_echo_flush, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_blocking_sleep"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE1, + ngx_http_echo_echo_blocking_sleep, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_reset_timer"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_NOARGS, + ngx_http_echo_echo_reset_timer, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_before_body"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_ANY, + ngx_http_echo_echo_before_body, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, before_body_cmds), + NULL }, + + { ngx_string("echo_after_body"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_ANY, + ngx_http_echo_echo_after_body, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, after_body_cmds), + NULL }, + + { ngx_string("echo_location_async"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE12, + ngx_http_echo_echo_location_async, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_location"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE12, + ngx_http_echo_echo_location, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_subrequest_async"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_2MORE, + ngx_http_echo_echo_subrequest_async, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_subrequest"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_2MORE, + ngx_http_echo_echo_subrequest, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_duplicate"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_2MORE, + ngx_http_echo_echo_duplicate, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_read_request_body"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_NOARGS, + ngx_http_echo_echo_read_request_body, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_foreach_split"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_2MORE, + ngx_http_echo_echo_foreach_split, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_end"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_NOARGS, + ngx_http_echo_echo_end, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_abort_parent"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_NOARGS, + ngx_http_echo_echo_abort_parent, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_exec"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE12, + ngx_http_echo_echo_exec, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, handler_cmds), + NULL }, + + { ngx_string("echo_status"), + NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE1, + ngx_conf_set_num_slot, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_echo_loc_conf_t, status), + NULL }, + + ngx_null_command +}; + + +ngx_module_t ngx_http_echo_module = { + NGX_MODULE_V1, + &ngx_http_echo_module_ctx, /* module context */ + ngx_http_echo_commands, /* module directives */ + NGX_HTTP_MODULE, /* module type */ + NULL, /* init master */ + NULL, /* init module */ + NULL, /* init process */ + NULL, /* init thread */ + NULL, /* exit thread */ + NULL, /* exit process */ + NULL, /* exit master */ + NGX_MODULE_V1_PADDING +}; + + +static void * +ngx_http_echo_create_loc_conf(ngx_conf_t *cf) +{ + ngx_http_echo_loc_conf_t *conf; + + conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_echo_loc_conf_t)); + if (conf == NULL) { + return NULL; + } + + /* set by ngx_pcalloc + * conf->handler_cmds = NULL + * conf->before_body_cmds = NULL + * conf->after_body_cmds = NULL + * conf->seen_leading_output = 0 + * conf->seen_trailing_output = 0 + */ + + conf->status = NGX_CONF_UNSET; + + return conf; +} + + +static char * +ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child) +{ + ngx_http_echo_loc_conf_t *prev = parent; + ngx_http_echo_loc_conf_t *conf = child; + + if (conf->handler_cmds == NULL) { + conf->handler_cmds = prev->handler_cmds; + conf->seen_leading_output = prev->seen_leading_output; + } + + if (conf->before_body_cmds == NULL) { + conf->before_body_cmds = prev->before_body_cmds; + } + + if (conf->after_body_cmds == NULL) { + conf->after_body_cmds = prev->after_body_cmds; + } + + ngx_conf_merge_value(conf->status, prev->status, 200); + + return NGX_CONF_OK; +} + + +static char * +ngx_http_echo_helper(ngx_http_echo_opcode_t opcode, + ngx_http_echo_cmd_category_t cat, + ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + ngx_str_t *raw_args; + ngx_uint_t i, n; + ngx_array_t **args_ptr; + ngx_array_t **cmds_ptr; + ngx_http_echo_cmd_t *echo_cmd; + ngx_http_core_loc_conf_t *clcf; + ngx_http_script_compile_t sc; + ngx_http_echo_main_conf_t *emcf; + ngx_http_echo_arg_template_t *arg; + + emcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_echo_module); + + /* cmds_ptr points to ngx_http_echo_loc_conf_t's + * handler_cmds, before_body_cmds, or after_body_cmds + * array, depending on the actual offset */ + cmds_ptr = (ngx_array_t **) (((u_char *) conf) + cmd->offset); + + if (*cmds_ptr == NULL) { + *cmds_ptr = ngx_array_create(cf->pool, 1, + sizeof(ngx_http_echo_cmd_t)); + + if (*cmds_ptr == NULL) { + return NGX_CONF_ERROR; + } + + if (cat == echo_handler_cmd) { + dd("registering the content handler"); + /* register the content handler */ + clcf = ngx_http_conf_get_module_loc_conf(cf, + ngx_http_core_module); + + dd("registering the content handler (2)"); + clcf->handler = ngx_http_echo_handler; + + } else { + dd("filter used = 1"); + emcf->requires_filter = 1; + } + } + + echo_cmd = ngx_array_push(*cmds_ptr); + + if (echo_cmd == NULL) { + return NGX_CONF_ERROR; + } + + echo_cmd->opcode = opcode; + + args_ptr = &echo_cmd->args; + *args_ptr = ngx_array_create(cf->pool, 1, + sizeof(ngx_http_echo_arg_template_t)); + + if (*args_ptr == NULL) { + return NGX_CONF_ERROR; + } + + raw_args = cf->args->elts; + + /* we skip the first arg and start from the second */ + + for (i = 1 ; i < cf->args->nelts; i++) { + arg = ngx_array_push(*args_ptr); + + if (arg == NULL) { + return NGX_CONF_ERROR; + } + + arg->raw_value = raw_args[i]; + + dd("found raw arg %s", raw_args[i].data); + + arg->lengths = NULL; + arg->values = NULL; + + n = ngx_http_script_variables_count(&arg->raw_value); + + if (n > 0) { + ngx_memzero(&sc, sizeof(ngx_http_script_compile_t)); + + sc.cf = cf; + sc.source = &arg->raw_value; + sc.lengths = &arg->lengths; + sc.values = &arg->values; + sc.variables = n; + sc.complete_lengths = 1; + sc.complete_values = 1; + + if (ngx_http_script_compile(&sc) != NGX_OK) { + return NGX_CONF_ERROR; + } + } + } /* end for */ + + return NGX_CONF_OK; +} + + +static char * +ngx_http_echo_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + ngx_http_echo_loc_conf_t *elcf = conf; + + if (!elcf->seen_leading_output) { + elcf->seen_leading_output = 1; + } + + dd("in echo_echo..."); + return ngx_http_echo_helper(echo_opcode_echo, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_request_body(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf) +{ + ngx_http_echo_loc_conf_t *elcf = conf; + + if (!elcf->seen_leading_output) { + elcf->seen_leading_output = 1; + } + + dd("in echo_echo_request_body..."); + return ngx_http_echo_helper(echo_opcode_echo_request_body, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_sleep(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + dd("in echo_sleep..."); + return ngx_http_echo_helper(echo_opcode_echo_sleep, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_flush(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + ngx_http_echo_loc_conf_t *elcf = conf; + + if (!elcf->seen_leading_output) { + elcf->seen_leading_output = 1; + } + + dd("in echo_flush..."); + return ngx_http_echo_helper(echo_opcode_echo_flush, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_blocking_sleep(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf) +{ + dd("in echo_blocking_sleep..."); + return ngx_http_echo_helper(echo_opcode_echo_blocking_sleep, + echo_handler_cmd, cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_reset_timer(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + return ngx_http_echo_helper(echo_opcode_echo_reset_timer, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_before_body(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + dd("processing echo_before_body directive..."); + return ngx_http_echo_helper(echo_opcode_echo_before_body, echo_filter_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_after_body(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + return ngx_http_echo_helper(echo_opcode_echo_after_body, echo_filter_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_location_async(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf) +{ + ngx_http_echo_loc_conf_t *elcf = conf; + char *ret; + + if (!elcf->seen_leading_output) { + elcf->seen_leading_output = 1; + + ret = ngx_http_echo_helper(echo_opcode_echo_sync, echo_handler_cmd, + cf, cmd, conf); + + if (ret != NGX_CONF_OK) { + return ret; + } + } + + return ngx_http_echo_helper(echo_opcode_echo_location_async, + echo_handler_cmd, cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_location(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + ngx_http_echo_loc_conf_t *elcf = conf; + char *ret; + + if (!elcf->seen_leading_output) { + elcf->seen_leading_output = 1; + + ret = ngx_http_echo_helper(echo_opcode_echo_sync, echo_handler_cmd, + cf, cmd, conf); + + if (ret != NGX_CONF_OK) { + return ret; + } + } + + return ngx_http_echo_helper(echo_opcode_echo_location, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_subrequest_async(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf) +{ + char *ret; + ngx_http_echo_loc_conf_t *elcf = conf; + + if (!elcf->seen_leading_output) { + elcf->seen_leading_output = 1; + + ret = ngx_http_echo_helper(echo_opcode_echo_sync, echo_handler_cmd, + cf, cmd, conf); + + if (ret != NGX_CONF_OK) { + return ret; + } + } + + return ngx_http_echo_helper(echo_opcode_echo_subrequest_async, + echo_handler_cmd, cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_subrequest(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf) +{ + ngx_http_echo_loc_conf_t *elcf = conf; + char *ret; + + if (!elcf->seen_leading_output) { + elcf->seen_leading_output = 1; + + ret = ngx_http_echo_helper(echo_opcode_echo_sync, echo_handler_cmd, + cf, cmd, conf); + + if (ret != NGX_CONF_OK) { + return ret; + } + } + + return ngx_http_echo_helper(echo_opcode_echo_subrequest, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_duplicate(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + ngx_http_echo_loc_conf_t *elcf = conf; + + if (!elcf->seen_leading_output) { + elcf->seen_leading_output = 1; + } + + return ngx_http_echo_helper(echo_opcode_echo_duplicate, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_read_request_body(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf) +{ + return ngx_http_echo_helper(echo_opcode_echo_read_request_body, + echo_handler_cmd, cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_foreach_split(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + return ngx_http_echo_helper(echo_opcode_echo_foreach_split, + echo_handler_cmd, cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_end(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + return ngx_http_echo_helper(echo_opcode_echo_end, echo_handler_cmd, cf, + cmd, conf); +} + + +static char * +ngx_http_echo_echo_abort_parent(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + return ngx_http_echo_helper(echo_opcode_echo_abort_parent, echo_handler_cmd, + cf, cmd, conf); +} + + +static char * +ngx_http_echo_echo_exec(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + return ngx_http_echo_helper(echo_opcode_echo_exec, echo_handler_cmd, + cf, cmd, conf); +} + + +static void * +ngx_http_echo_create_main_conf(ngx_conf_t *cf) +{ +#if nginx_version >= 1011011 + ngx_pool_cleanup_t *cln; +#endif + ngx_http_echo_main_conf_t *emcf; + + emcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_echo_main_conf_t)); + if (emcf == NULL) { + return NULL; + } + + /* set by ngx_pcalloc: + * hmcf->requires_filter = 0; + */ + +#if nginx_version >= 1011011 + cln = ngx_pool_cleanup_add(cf->pool, 0); + if (cln == NULL) { + return NULL; + } + + cln->data = emcf; + cln->handler = ngx_http_echo_request_headers_cleanup; +#endif + + return emcf; +} + + +static ngx_int_t +ngx_http_echo_post_config(ngx_conf_t *cf) +{ + ngx_int_t rc; + + rc = ngx_http_echo_filter_init(cf); + if (rc != NGX_OK) { + return rc; + } + + rc = ngx_http_echo_echo_init(cf); + if (rc != NGX_OK) { + return rc; + } + + ngx_http_echo_content_length_hash = + ngx_http_echo_hash_literal("content-length"); + + return ngx_http_echo_add_variables(cf); +} diff --git a/echo-nginx-module/src/ngx_http_echo_module.h b/echo-nginx-module/src/ngx_http_echo_module.h new file mode 100644 index 00000000..ce0a3053 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_module.h @@ -0,0 +1,151 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef NGX_HTTP_ECHO_MODULE_H +#define NGX_HTTP_ECHO_MODULE_H + + +#include +#include +#include + + +extern ngx_module_t ngx_http_echo_module; + + +/* config directive's opcode */ +typedef enum { + echo_opcode_echo_sync, + echo_opcode_echo, + echo_opcode_echo_request_body, + echo_opcode_echo_sleep, + echo_opcode_echo_flush, + echo_opcode_echo_blocking_sleep, + echo_opcode_echo_reset_timer, + echo_opcode_echo_before_body, + echo_opcode_echo_after_body, + echo_opcode_echo_location_async, + echo_opcode_echo_location, + echo_opcode_echo_subrequest_async, + echo_opcode_echo_subrequest, + echo_opcode_echo_duplicate, + echo_opcode_echo_read_request_body, + echo_opcode_echo_foreach_split, + echo_opcode_echo_end, + echo_opcode_echo_abort_parent, + echo_opcode_echo_exec +} ngx_http_echo_opcode_t; + + +/* all the various config directives (or commands) are + * divided into two categories: "handler commands", + * and "filter commands". For instance, the "echo" + * directive is a handler command while + * "echo_before_body" is a filter one. */ +typedef enum { + echo_handler_cmd, + echo_filter_cmd + +} ngx_http_echo_cmd_category_t; + + +/* compiled form of a config directive argument's value */ +typedef struct { + /* holds the raw string of the argument value */ + ngx_str_t raw_value; + + /* fields "lengths" and "values" are set by + * the function ngx_http_script_compile, + * iff the argument value indeed contains + * nginx variables like "$foo" */ + ngx_array_t *lengths; + ngx_array_t *values; + +} ngx_http_echo_arg_template_t; + + +/* represent a config directive (or command) like "echo". */ +typedef struct { + ngx_http_echo_opcode_t opcode; + + /* each argument is of type echo_arg_template_t: */ + ngx_array_t *args; +} ngx_http_echo_cmd_t; + + +/* location config struct */ +typedef struct { + /* elements of the following arrays are of type + * ngx_http_echo_cmd_t */ + ngx_array_t *handler_cmds; + ngx_array_t *before_body_cmds; + ngx_array_t *after_body_cmds; + + unsigned seen_leading_output; + + ngx_int_t status; +} ngx_http_echo_loc_conf_t; + + +typedef struct { + ngx_int_t requires_filter; +#if nginx_version >= 1011011 + ngx_buf_t **busy_buf_ptrs; + ngx_int_t busy_buf_ptr_count; +#endif +} ngx_http_echo_main_conf_t; + + +typedef struct { + ngx_array_t *choices; /* items after splitting */ + ngx_uint_t next_choice; /* current item index */ + ngx_uint_t cmd_index; /* cmd index for the echo_foreach direcitve */ +} ngx_http_echo_foreach_ctx_t; + + +/* context struct in the request handling cycle, holding + * the current states of the command evaluator */ +typedef struct { + /* index of the next handler command in + * ngx_http_echo_loc_conf_t's "handler_cmds" array. */ + ngx_uint_t next_handler_cmd; + + /* index of the next before-body filter command in + * ngx_http_echo_loc_conf_t's "before_body_cmds" array. */ + ngx_uint_t next_before_body_cmd; + + /* index of the next after-body filter command in + * ngx_http_echo_loc_conf_t's "after_body_cmds" array. */ + ngx_uint_t next_after_body_cmd; + + ngx_http_echo_foreach_ctx_t *foreach; + + ngx_time_t timer_begin; + + ngx_event_t sleep; + + ngx_uint_t counter; + + unsigned before_body_sent:1; + unsigned skip_filter:1; + + unsigned wait_read_request_body:1; + + unsigned waiting:1; + unsigned done:1; + + unsigned run_post_subrequest:1; + unsigned header_sent:1; /* r->header_sent is not sufficient + * because special header filters like + * ngx_http_image_filter_module's may + * intercept the whole header filter chain + * leaving r->header_sent unset. So we + * should always test both flags. */ + +} ngx_http_echo_ctx_t; + + +#endif /* NGX_HTTP_ECHO_MODULE_H */ diff --git a/echo-nginx-module/src/ngx_http_echo_request_info.c b/echo-nginx-module/src/ngx_http_echo_request_info.c new file mode 100644 index 00000000..7dd36834 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_request_info.c @@ -0,0 +1,522 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + +#include "ngx_http_echo_request_info.h" +#include "ngx_http_echo_util.h" +#include "ngx_http_echo_handler.h" + +#include + + +static void ngx_http_echo_post_read_request_body(ngx_http_request_t *r); +#if nginx_version >= 1011011 +void ngx_http_echo_request_headers_cleanup(void *data); +#endif + + +ngx_int_t +ngx_http_echo_exec_echo_read_request_body(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx) +{ + return ngx_http_read_client_request_body(r, + ngx_http_echo_post_read_request_body); +} + + +static void +ngx_http_echo_post_read_request_body(ngx_http_request_t *r) +{ + ngx_http_echo_ctx_t *ctx; + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + + dd("wait read request body %d", (int) ctx->wait_read_request_body); + + if (ctx->wait_read_request_body) { + ctx->waiting = 0; + ctx->done = 1; + + r->write_event_handler = ngx_http_echo_wev_handler; + + ngx_http_echo_wev_handler(r); + } +} + + +/* this function's implementation is borrowed from nginx 0.8.20 + * and modified a bit to work with subrequests. + * Copyrighted (C) by Igor Sysoev */ +ngx_int_t +ngx_http_echo_request_method_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + if (r->method_name.data) { + v->len = r->method_name.len; + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + v->data = r->method_name.data; + + } else { + v->not_found = 1; + } + + return NGX_OK; +} + + +/* this function's implementation is borrowed from nginx 0.8.20 + * and modified a bit to work with subrequests. + * Copyrighted (C) by Igor Sysoev */ +ngx_int_t +ngx_http_echo_client_request_method_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + if (r->main->method_name.data) { + v->len = r->main->method_name.len; + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + v->data = r->main->method_name.data; + + } else { + v->not_found = 1; + } + + return NGX_OK; +} + + +/* this function's implementation is borrowed from nginx 0.8.20 + * and modified a bit to work with subrequests. + * Copyrighted (C) by Igor Sysoev */ +ngx_int_t +ngx_http_echo_request_body_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + u_char *p; + size_t len; + ngx_buf_t *b; + ngx_chain_t *cl; + ngx_chain_t *in; + + if (r->request_body == NULL + || r->request_body->bufs == NULL + || r->request_body->temp_file) + { + v->not_found = 1; + + return NGX_OK; + } + + in = r->request_body->bufs; + + len = 0; + for (cl = in; cl; cl = cl->next) { + b = cl->buf; + + if (!ngx_buf_in_memory(b)) { + if (b->in_file) { + ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "variable echo_request_body sees in-file only " + "buffers and discard the whole body data"); + + v->not_found = 1; + + return NGX_OK; + } + + } else { + len += b->last - b->pos; + } + } + + p = ngx_pnalloc(r->pool, len); + if (p == NULL) { + return NGX_ERROR; + } + + v->data = p; + + for (cl = in; cl; cl = cl->next) { + b = cl->buf; + + if (ngx_buf_in_memory(b)) { + p = ngx_copy(p, b->pos, b->last - b->pos); + } + } + + if (p - v->data != (ssize_t) len) { + ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "variable echo_request_body: buffer error"); + + v->not_found = 1; + + return NGX_OK; + } + + v->len = len; + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_client_request_headers_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + int line_break_len; + size_t size; + u_char *p, *last, *pos; + ngx_int_t i, j; + ngx_buf_t *b, *first = NULL; + unsigned found; +#if nginx_version >= 1011011 + ngx_buf_t **bb; + ngx_chain_t *cl; + ngx_http_echo_main_conf_t *emcf; +#endif + ngx_connection_t *c; + ngx_http_request_t *mr; + ngx_http_connection_t *hc; + + mr = r->main; + hc = r->main->http_connection; + c = mr->connection; + +#if (NGX_HTTP_V2) + /* TODO */ + if (mr->stream) { + v->not_found = 1; + return NGX_OK; + } +#endif + +#if nginx_version >= 1011011 + emcf = ngx_http_get_module_main_conf(r, ngx_http_echo_module); +#endif + + size = 0; + b = c->buffer; + + if (mr->request_line.data[mr->request_line.len] == CR) { + line_break_len = 2; + + } else { + line_break_len = 1; + } + + if (mr->request_line.data >= b->start + && mr->request_line.data + mr->request_line.len + line_break_len + <= b->pos) + { + first = b; + size += b->pos - mr->request_line.data; + } + + if (hc->nbusy) { + b = NULL; + +#if nginx_version >= 1011011 + if (hc->nbusy > emcf->busy_buf_ptr_count) { + if (emcf->busy_buf_ptrs) { + ngx_free(emcf->busy_buf_ptrs); + } + + emcf->busy_buf_ptrs = ngx_alloc(hc->nbusy * sizeof(ngx_buf_t *), + r->connection->log); + + if (emcf->busy_buf_ptrs == NULL) { + return NGX_ERROR; + } + + emcf->busy_buf_ptr_count = hc->nbusy; + } + + bb = emcf->busy_buf_ptrs; + for (cl = hc->busy; cl; cl = cl->next) { + *bb++ = cl->buf; + } + + bb = emcf->busy_buf_ptrs; + for (i = hc->nbusy; i > 0; i--) { + b = bb[i - 1]; +#else + for (i = 0; i < hc->nbusy; i++) { + b = hc->busy[i]; +#endif + + if (first == NULL) { + if (mr->request_line.data >= b->pos + || mr->request_line.data + mr->request_line.len + + line_break_len <= b->start) + { + continue; + } + + dd("found first at %d", (int) i); + first = b; + } + + size += b->pos - b->start; + } + } + + + size++; /* plus the null terminator, as required by the later + ngx_strstr() call */ + + v->data = ngx_palloc(r->pool, size); + if (v->data == NULL) { + return NGX_ERROR; + } + + last = v->data; + + b = c->buffer; + found = 0; + + if (first == b) { + found = 1; + pos = b->pos; + + last = ngx_copy(v->data, mr->request_line.data, + pos - mr->request_line.data); + + if (b != mr->header_in) { + /* skip truncated header entries (if any) */ + while (last > v->data && last[-1] != LF) { + last--; + } + } + + i = 0; + for (p = v->data; p != last; p++) { + if (*p == '\0') { + i++; + if (p + 1 != last && *(p + 1) == LF) { + *p = CR; + + } else if (i % 2 == 1) { + *p = ':'; + + } else { + *p = LF; + } + } + } + } + + if (hc->nbusy) { + +#if nginx_version >= 1011011 + bb = emcf->busy_buf_ptrs; + for (i = hc->nbusy; i > 0; i--) { + b = bb[i - 1]; +#else + for (i = 0; i < hc->nbusy; i++) { + b = hc->busy[i]; +#endif + + if (!found) { + if (b != first) { + continue; + } + + dd("found first"); + found = 1; + } + + p = last; + + pos = b->pos; + + if (b == first) { + dd("request line: %.*s", (int) mr->request_line.len, + mr->request_line.data); + + last = ngx_copy(last, + mr->request_line.data, + pos - mr->request_line.data); + + } else { + last = ngx_copy(last, b->start, pos - b->start); + } + +#if 1 + /* skip truncated header entries (if any) */ + while (last > p && last[-1] != LF) { + last--; + } +#endif + + j = 0; + for (; p != last; p++) { + if (*p == '\0') { + j++; + if (p + 1 == last) { + /* XXX this should not happen */ + dd("found string end!!"); + + } else if (*(p + 1) == LF) { + *p = CR; + + } else if (j % 2 == 1) { + *p = ':'; + + } else { + *p = LF; + } + } + } + + if (b == mr->header_in) { + break; + } + } + } + + *last++ = '\0'; + + if (last - v->data > (ssize_t) size) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "buffer error when evaluating " + "$echo_client__request_headers: \"%V\"", + (ngx_int_t) (last - v->data - size)); + + return NGX_ERROR; + } + + /* strip the leading part (if any) of the request body in our header. + * the first part of the request body could slip in because nginx core's + * ngx_http_request_body_length_filter and etc can move r->header_in->pos + * in case that some of the body data has been preread into r->header_in. + */ + + if ((p = (u_char *) ngx_strstr(v->data, CRLF CRLF)) != NULL) { + last = p + sizeof(CRLF CRLF) - 1; + + } else if ((p = (u_char *) ngx_strstr(v->data, CRLF "\n")) != NULL) { + last = p + sizeof(CRLF "\n") - 1; + + } else if ((p = (u_char *) ngx_strstr(v->data, "\n" CRLF)) != NULL) { + last = p + sizeof("\n" CRLF) - 1; + + } else { + for (p = last - 1; p - v->data >= 2; p--) { + if (p[0] == LF && p[-1] == CR) { + p[-1] = LF; + last = p + 1; + break; + } + + if (p[0] == LF && p[-1] == LF) { + last = p + 1; + break; + } + } + } + + v->len = last - v->data; + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_cacheable_request_uri_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + if (r->uri.len) { + v->len = r->uri.len; + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + v->data = r->uri.data; + + } else { + v->not_found = 1; + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_request_uri_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + if (r->uri.len) { + v->len = r->uri.len; + v->valid = 1; + v->no_cacheable = 1; + v->not_found = 0; + v->data = r->uri.data; + + } else { + v->not_found = 1; + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_response_status_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + u_char *p; + + if (r->headers_out.status) { + dd("headers out status: %d", (int) r->headers_out.status); + + p = ngx_palloc(r->pool, NGX_INT_T_LEN); + if (p == NULL) { + return NGX_ERROR; + } + + v->len = ngx_sprintf(p, "%ui", r->headers_out.status) - p; + v->data = p; + + v->valid = 1; + v->no_cacheable = 1; + v->not_found = 0; + + } else { + v->not_found = 1; + } + + return NGX_OK; +} + + +#if nginx_version >= 1011011 +void +ngx_http_echo_request_headers_cleanup(void *data) +{ + ngx_http_echo_main_conf_t *emcf; + + emcf = (ngx_http_echo_main_conf_t *) data; + + if (emcf->busy_buf_ptrs) { + ngx_free(emcf->busy_buf_ptrs); + emcf->busy_buf_ptrs = NULL; + } +} +#endif + +/* vi:set ft=c ts=4 sw=4 et fdm=marker: */ diff --git a/echo-nginx-module/src/ngx_http_echo_request_info.h b/echo-nginx-module/src/ngx_http_echo_request_info.h new file mode 100644 index 00000000..aa5730b8 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_request_info.h @@ -0,0 +1,36 @@ +#ifndef ECHO_REQUEST_INFO_H +#define ECHO_REQUEST_INFO_H + + +#include "ngx_http_echo_module.h" + + +ngx_int_t ngx_http_echo_exec_echo_read_request_body( + ngx_http_request_t *r, ngx_http_echo_ctx_t *ctx); + +ngx_int_t ngx_http_echo_request_method_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +ngx_int_t ngx_http_echo_client_request_method_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +ngx_int_t ngx_http_echo_request_body_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +ngx_int_t ngx_http_echo_client_request_headers_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +ngx_int_t ngx_http_echo_cacheable_request_uri_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +ngx_int_t ngx_http_echo_request_uri_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +ngx_int_t ngx_http_echo_response_status_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +#if nginx_version >= 1011011 +void ngx_http_echo_request_headers_cleanup(void *data); +#endif + +#endif /* ECHO_REQUEST_INFO_H */ diff --git a/echo-nginx-module/src/ngx_http_echo_sleep.c b/echo-nginx-module/src/ngx_http_echo_sleep.c new file mode 100644 index 00000000..c96fa5a8 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_sleep.c @@ -0,0 +1,208 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_echo_sleep.h" +#include "ngx_http_echo_handler.h" + +#include +#include + + +/* event handler for echo_sleep */ + +static void ngx_http_echo_post_sleep(ngx_http_request_t *r); +static void ngx_http_echo_sleep_cleanup(void *data); + + +ngx_int_t +ngx_http_echo_exec_echo_sleep(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_str_t *computed_arg; + ngx_str_t *computed_arg_elts; + ngx_int_t delay; /* in msec */ + ngx_http_cleanup_t *cln; + + computed_arg_elts = computed_args->elts; + computed_arg = &computed_arg_elts[0]; + + delay = ngx_atofp(computed_arg->data, computed_arg->len, 3); + + if (delay == NGX_ERROR) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "invalid sleep duration \"%V\"", &computed_arg_elts[0]); + + return NGX_HTTP_BAD_REQUEST; + } + + dd("adding timer with delay %lu ms, r:%.*s", (unsigned long) delay, + (int) r->uri.len, r->uri.data); + + ngx_add_timer(&ctx->sleep, (ngx_msec_t) delay); + + /* we don't check broken downstream connections + * ourselves so even if the client shuts down + * the connection prematurely, nginx will still + * go on waiting for our timers to get properly + * expired. However, we'd still register a + * cleanup handler for completeness. */ + + cln = ngx_http_cleanup_add(r, 0); + if (cln == NULL) { + return NGX_ERROR; + } + + cln->handler = ngx_http_echo_sleep_cleanup; + cln->data = r; + + return NGX_AGAIN; +} + + +static void +ngx_http_echo_post_sleep(ngx_http_request_t *r) +{ + ngx_http_echo_ctx_t *ctx; + /* ngx_int_t rc; */ + + dd("post sleep, r:%.*s", (int) r->uri.len, r->uri.data); + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + + if (ctx == NULL) { + return; + } + + ctx->waiting = 0; + ctx->done = 1; + + dd("sleep: after get module ctx"); + + dd("timed out? %d", ctx->sleep.timedout); + dd("timer set? %d", ctx->sleep.timer_set); + + if (!ctx->sleep.timedout) { + dd("HERE reached!"); + return; + } + + ctx->sleep.timedout = 0; + + if (ctx->sleep.timer_set) { + dd("deleting timer for echo_sleep"); + + ngx_del_timer(&ctx->sleep); + } + + /* r->write_event_handler = ngx_http_request_empty_handler; */ + + ngx_http_echo_wev_handler(r); +} + + +void +ngx_http_echo_sleep_event_handler(ngx_event_t *ev) +{ + ngx_connection_t *c; + ngx_http_request_t *r; + ngx_http_log_ctx_t *ctx; + + r = ev->data; + c = r->connection; + + if (c->destroyed) { + return; + } + + if (c->error) { + ngx_http_finalize_request(r, NGX_ERROR); + return; + } + + ctx = c->log->data; + ctx->current_request = r; + + /* XXX when r->done == 1 we should do cleaning immediately + * and delete our timer and then quit. */ + + ngx_log_debug2(NGX_LOG_DEBUG_HTTP, c->log, 0, + "echo sleep event handler: \"%V?%V\"", &r->uri, &r->args); + + /* + if (r->done) { + return; + } + */ + + ngx_http_echo_post_sleep(r); + +#if defined(nginx_version) + + dd("before run posted requests"); + + ngx_http_run_posted_requests(c); + + dd("after run posted requests"); + +#endif +} + + +ngx_int_t +ngx_http_echo_exec_echo_blocking_sleep(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_str_t *computed_arg; + ngx_str_t *computed_arg_elts; + ngx_int_t delay; /* in msec */ + + computed_arg_elts = computed_args->elts; + computed_arg = &computed_arg_elts[0]; + + delay = ngx_atofp(computed_arg->data, computed_arg->len, 3); + + if (delay == NGX_ERROR) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "invalid sleep duration \"%V\"", &computed_arg_elts[0]); + return NGX_HTTP_BAD_REQUEST; + } + + dd("blocking delay: %lu ms", (unsigned long) delay); + + ngx_msleep((ngx_msec_t) delay); + + return NGX_OK; +} + + +static void +ngx_http_echo_sleep_cleanup(void *data) +{ + ngx_http_request_t *r = data; + ngx_http_echo_ctx_t *ctx; + + dd("echo sleep cleanup"); + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + if (ctx == NULL) { + return; + } + + if (ctx->sleep.timer_set) { + dd("cleanup: deleting timer for echo_sleep"); + + ngx_del_timer(&ctx->sleep); + return; + } + + dd("cleanup: timer not set"); +} diff --git a/echo-nginx-module/src/ngx_http_echo_sleep.h b/echo-nginx-module/src/ngx_http_echo_sleep.h new file mode 100644 index 00000000..8bb70c39 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_sleep.h @@ -0,0 +1,16 @@ +#ifndef ECHO_SLEEP_H +#define ECHO_SLEEP_H + +#include "ngx_http_echo_module.h" + +ngx_int_t ngx_http_echo_exec_echo_sleep( + ngx_http_request_t *r, ngx_http_echo_ctx_t *ctx, + ngx_array_t *computed_args); + +ngx_int_t ngx_http_echo_exec_echo_blocking_sleep(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args); + +void ngx_http_echo_sleep_event_handler(ngx_event_t *ev); + +#endif /* ECHO_SLEEP_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_subrequest.c b/echo-nginx-module/src/ngx_http_echo_subrequest.c new file mode 100644 index 00000000..8644d7f7 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_subrequest.c @@ -0,0 +1,791 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_echo_util.h" +#include "ngx_http_echo_subrequest.h" +#include "ngx_http_echo_handler.h" +#include + + +#define ngx_http_echo_method_name(m) { sizeof(m) - 1, (u_char *) m " " } + + +ngx_str_t ngx_http_echo_content_length_header_key = + ngx_string("Content-Length"); + +ngx_str_t ngx_http_echo_get_method = ngx_http_echo_method_name("GET"); +ngx_str_t ngx_http_echo_put_method = ngx_http_echo_method_name("PUT"); +ngx_str_t ngx_http_echo_post_method = ngx_http_echo_method_name("POST"); +ngx_str_t ngx_http_echo_head_method = ngx_http_echo_method_name("HEAD"); +ngx_str_t ngx_http_echo_copy_method = ngx_http_echo_method_name("COPY"); +ngx_str_t ngx_http_echo_move_method = ngx_http_echo_method_name("MOVE"); +ngx_str_t ngx_http_echo_lock_method = ngx_http_echo_method_name("LOCK"); +ngx_str_t ngx_http_echo_mkcol_method = ngx_http_echo_method_name("MKCOL"); +ngx_str_t ngx_http_echo_trace_method = ngx_http_echo_method_name("TRACE"); +ngx_str_t ngx_http_echo_delete_method = ngx_http_echo_method_name("DELETE"); +ngx_str_t ngx_http_echo_unlock_method = ngx_http_echo_method_name("UNLOCK"); +ngx_str_t ngx_http_echo_options_method = ngx_http_echo_method_name("OPTIONS"); +ngx_str_t ngx_http_echo_propfind_method = + ngx_http_echo_method_name("PROPFIND"); +ngx_str_t ngx_http_echo_proppatch_method = + ngx_http_echo_method_name("PROPPATCH"); + + +typedef struct ngx_http_echo_subrequest_s { + ngx_uint_t method; + ngx_str_t *method_name; + ngx_str_t *location; + ngx_str_t *query_string; + ssize_t content_length_n; + ngx_http_request_body_t *request_body; +} ngx_http_echo_subrequest_t; + + +static ngx_int_t ngx_http_echo_parse_method_name(ngx_str_t **method_name_ptr); +static ngx_int_t ngx_http_echo_adjust_subrequest(ngx_http_request_t *sr, + ngx_http_echo_subrequest_t *parsed_sr); +static ngx_int_t ngx_http_echo_parse_subrequest_spec(ngx_http_request_t *r, + ngx_array_t *computed_args, ngx_http_echo_subrequest_t **parsed_sr_ptr); +static ngx_int_t ngx_http_echo_set_content_length_header(ngx_http_request_t *r, + off_t len); + + +ngx_int_t +ngx_http_echo_exec_echo_subrequest_async(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_int_t rc; + ngx_http_echo_subrequest_t *parsed_sr; + ngx_http_request_t *sr; /* subrequest object */ + ngx_str_t args; + ngx_uint_t flags = 0; + + dd_enter(); + + rc = ngx_http_echo_parse_subrequest_spec(r, computed_args, &parsed_sr); + if (rc != NGX_OK) { + return rc; + } + + dd("location: %.*s", + (int) parsed_sr->location->len, + parsed_sr->location->data); + + args.data = NULL; + args.len = 0; + + if (ngx_http_parse_unsafe_uri(r, parsed_sr->location, &args, &flags) + != NGX_OK) + { + ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "echo_subrequest_async sees unsafe uri: \"%V\"", + parsed_sr->location); + return NGX_ERROR; + } + + if (args.len > 0 && parsed_sr->query_string == NULL) { + parsed_sr->query_string = &args; + } + + rc = ngx_http_echo_send_header_if_needed(r, ctx); + if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { + return rc; + } + + rc = ngx_http_subrequest(r, parsed_sr->location, parsed_sr->query_string, + &sr, NULL, 0); + + if (rc != NGX_OK) { + return NGX_ERROR; + } + + rc = ngx_http_echo_adjust_subrequest(sr, parsed_sr); + + if (rc != NGX_OK) { + return rc; + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_exec_echo_subrequest(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_int_t rc; + ngx_http_request_t *sr; /* subrequest object */ + ngx_http_post_subrequest_t *psr; + ngx_http_echo_subrequest_t *parsed_sr; + ngx_str_t args; + ngx_uint_t flags = 0; + ngx_http_echo_ctx_t *sr_ctx; + + dd_enter(); + + rc = ngx_http_echo_parse_subrequest_spec(r, computed_args, &parsed_sr); + if (rc != NGX_OK) { + return rc; + } + + args.data = NULL; + args.len = 0; + + if (ngx_http_parse_unsafe_uri(r, parsed_sr->location, &args, &flags) + != NGX_OK) + { + ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "echo_subrequest sees unsafe uri: \"%V\"", + parsed_sr->location); + return NGX_ERROR; + } + + if (args.len > 0 && parsed_sr->query_string == NULL) { + parsed_sr->query_string = &args; + } + + rc = ngx_http_echo_send_header_if_needed(r, ctx); + if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { + return rc; + } + + sr_ctx = ngx_http_echo_create_ctx(r); + + /* set by ngx_http_echo_create_ctx + * sr_ctx->run_post_subrequest = 0 + */ + + dd("creating sr ctx for %.*s: %p", (int) parsed_sr->location->len, + parsed_sr->location->data, sr_ctx); + + psr = ngx_palloc(r->pool, sizeof(ngx_http_post_subrequest_t)); + + if (psr == NULL) { + return NGX_ERROR; + } + + psr->handler = ngx_http_echo_post_subrequest; + psr->data = sr_ctx; + + rc = ngx_http_subrequest(r, parsed_sr->location, parsed_sr->query_string, + &sr, psr, 0); + + if (rc != NGX_OK) { + return NGX_ERROR; + } + + sr_ctx->sleep.data = sr; + + ngx_http_set_ctx(sr, sr_ctx, ngx_http_echo_module); + + rc = ngx_http_echo_adjust_subrequest(sr, parsed_sr); + + if (rc != NGX_OK) { + return NGX_ERROR; + } + + return NGX_AGAIN; +} + + +static ngx_int_t +ngx_http_echo_parse_subrequest_spec(ngx_http_request_t *r, + ngx_array_t *computed_args, ngx_http_echo_subrequest_t **parsed_sr_ptr) +{ + ngx_str_t *computed_arg_elts, *arg; + ngx_str_t **to_write = NULL; + ngx_str_t *method_name; + ngx_str_t *body_str = NULL; + ngx_str_t *body_file = NULL; + ngx_uint_t i; + ngx_flag_t expecting_opt; + ngx_http_request_body_t *rb = NULL; + ngx_buf_t *b; + ngx_http_echo_subrequest_t *parsed_sr; + ngx_open_file_info_t of; + ngx_http_core_loc_conf_t *clcf; + size_t len; + + *parsed_sr_ptr = ngx_pcalloc(r->pool, sizeof(ngx_http_echo_subrequest_t)); + if (*parsed_sr_ptr == NULL) { + return NGX_ERROR; + } + + parsed_sr = *parsed_sr_ptr; + computed_arg_elts = computed_args->elts; + method_name = &computed_arg_elts[0]; + parsed_sr->location = &computed_arg_elts[1]; + + if (parsed_sr->location->len == 0) { + return NGX_ERROR; + } + + expecting_opt = 1; + + for (i = 2; i < computed_args->nelts; i++) { + arg = &computed_arg_elts[i]; + + if (!expecting_opt) { + if (to_write == NULL) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "echo_subrequest_async: to_write should NOT be NULL"); + return NGX_ERROR; + } + + *to_write = arg; + to_write = NULL; + + expecting_opt = 1; + + continue; + } + + if (arg->len == 2) { + if (ngx_strncmp("-q", arg->data, arg->len) == 0) { + to_write = &parsed_sr->query_string; + expecting_opt = 0; + continue; + } + + if (ngx_strncmp("-b", arg->data, arg->len) == 0) { + to_write = &body_str; + expecting_opt = 0; + continue; + } + + if (ngx_strncmp("-f", arg->data, arg->len) == 0) { + dd("found option -f"); + to_write = &body_file; + expecting_opt = 0; + continue; + } + } + + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "unknown option for echo_subrequest*: %V", arg); + + return NGX_ERROR; + } + + if (body_str != NULL && body_str->len) { + rb = ngx_pcalloc(r->pool, sizeof(ngx_http_request_body_t)); + + if (rb == NULL) { + return NGX_ERROR; + } + + parsed_sr->content_length_n = body_str->len; + + b = ngx_calloc_buf(r->pool); + if (b == NULL) { + return NGX_ERROR; + } + + b->temporary = 1; + /* b->memory = 1; */ + b->start = b->pos = body_str->data; + b->end = b->last = body_str->data + body_str->len; + + rb->bufs = ngx_alloc_chain_link(r->pool); + if (rb->bufs == NULL) { + return NGX_ERROR; + } + + rb->bufs->buf = b; + rb->bufs->next = NULL; + + rb->buf = b; + + } else if (body_file != NULL && body_file->len) { + + dd("body_file defined %.*s", (int) body_file->len, body_file->data); + + body_file->data = ngx_http_echo_rebase_path(r->pool, body_file->data, + body_file->len, &len); + + if (body_file->data == NULL) { + return NGX_ERROR; + } + + body_file->len = len; + + dd("after rebase, the path becomes %.*s", (int) body_file->len, + body_file->data); + + rb = ngx_pcalloc(r->pool, sizeof(ngx_http_request_body_t)); + if (rb == NULL) { + return NGX_ERROR; + } + + clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); + ngx_memzero(&of, sizeof(ngx_open_file_info_t)); + +#if defined(nginx_version) && nginx_version >= 8018 + of.read_ahead = clcf->read_ahead; +#endif + + of.directio = clcf->directio; + of.valid = clcf->open_file_cache_valid; + of.min_uses = clcf->open_file_cache_min_uses; + of.errors = clcf->open_file_cache_errors; + of.events = clcf->open_file_cache_events; + + if (ngx_open_cached_file(clcf->open_file_cache, body_file, &of, r->pool) + != NGX_OK) + { + ngx_log_error(NGX_LOG_ERR, r->connection->log, of.err, + "%s \"%V\" failed", + of.failed, body_file); + + return NGX_ERROR; + } + + dd("file content size: %d", (int) of.size); + + parsed_sr->content_length_n = (ssize_t) of.size; + + b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); + if (b == NULL) { + return NGX_ERROR; + } + + b->file = ngx_pcalloc(r->pool, sizeof(ngx_file_t)); + if (b->file == NULL) { + return NGX_ERROR; + } + + b->file_pos = 0; + b->file_last = of.size; + + b->in_file = b->file_last ? 1: 0; + +#if 0 + b->last_buf = (r == r->main) ? 1: 0; + b->last_in_chain = 1; +#endif + + b->file->fd = of.fd; + b->file->name = *body_file; + b->file->log = r->connection->log; + b->file->directio = of.is_directio; + + rb->bufs = ngx_alloc_chain_link(r->pool); + if (rb->bufs == NULL) { + return NGX_ERROR; + } + + rb->bufs->buf = b; + rb->bufs->next = NULL; + rb->buf = b; + } + + parsed_sr->request_body = rb; + + parsed_sr->method = ngx_http_echo_parse_method_name(&method_name); + parsed_sr->method_name = method_name; + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_echo_adjust_subrequest(ngx_http_request_t *sr, + ngx_http_echo_subrequest_t *parsed_sr) +{ + ngx_http_core_main_conf_t *cmcf; + ngx_http_request_t *r; + ngx_http_request_body_t *body; + ngx_int_t rc; + + sr->method = parsed_sr->method; + sr->method_name = *(parsed_sr->method_name); + + if (sr->method == NGX_HTTP_HEAD) { + sr->header_only = 1; + } + + r = sr->parent; + + sr->header_in = r->header_in; + + /* XXX work-around a bug in ngx_http_subrequest */ + if (r->headers_in.headers.last == &r->headers_in.headers.part) { + sr->headers_in.headers.last = &sr->headers_in.headers.part; + } + + /* we do not inherit the parent request's variables */ + cmcf = ngx_http_get_module_main_conf(sr, ngx_http_core_module); + sr->variables = ngx_pcalloc(sr->pool, cmcf->variables.nelts + * sizeof(ngx_http_variable_value_t)); + + if (sr->variables == NULL) { + return NGX_ERROR; + } + + body = parsed_sr->request_body; + if (body) { + sr->request_body = body; + + rc = ngx_http_echo_set_content_length_header(sr, body->buf ? + ngx_buf_size(body->buf) + : 0); + + if (rc != NGX_OK) { + return NGX_ERROR; + } + } + + dd("subrequest body: %p", sr->request_body); + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_echo_parse_method_name(ngx_str_t **method_name_ptr) +{ + const ngx_str_t *method_name = *method_name_ptr; + + switch (method_name->len) { + case 3: + if (ngx_http_echo_strcmp_const(method_name->data, "GET") == 0) { + *method_name_ptr = &ngx_http_echo_get_method; + return NGX_HTTP_GET; + } + + if (ngx_http_echo_strcmp_const(method_name->data, "PUT") == 0) { + *method_name_ptr = &ngx_http_echo_put_method; + return NGX_HTTP_PUT; + } + + return NGX_HTTP_UNKNOWN; + + case 4: + if (ngx_http_echo_strcmp_const(method_name->data, "POST") == 0) { + *method_name_ptr = &ngx_http_echo_post_method; + return NGX_HTTP_POST; + } + + if (ngx_http_echo_strcmp_const(method_name->data, "HEAD") == 0) { + *method_name_ptr = &ngx_http_echo_head_method; + return NGX_HTTP_HEAD; + } + + if (ngx_http_echo_strcmp_const(method_name->data, "COPY") == 0) { + *method_name_ptr = &ngx_http_echo_copy_method; + return NGX_HTTP_COPY; + } + + if (ngx_http_echo_strcmp_const(method_name->data, "MOVE") == 0) { + *method_name_ptr = &ngx_http_echo_move_method; + return NGX_HTTP_MOVE; + } + + if (ngx_http_echo_strcmp_const(method_name->data, "LOCK") == 0) { + *method_name_ptr = &ngx_http_echo_lock_method; + return NGX_HTTP_LOCK; + } + + return NGX_HTTP_UNKNOWN; + + case 5: + if (ngx_http_echo_strcmp_const(method_name->data, "MKCOL") == 0) { + *method_name_ptr = &ngx_http_echo_mkcol_method; + return NGX_HTTP_MKCOL; + } + + if (ngx_http_echo_strcmp_const(method_name->data, "TRACE") == 0) { + *method_name_ptr = &ngx_http_echo_trace_method; + return NGX_HTTP_TRACE; + } + + return NGX_HTTP_UNKNOWN; + + case 6: + if (ngx_http_echo_strcmp_const(method_name->data, "DELETE") == 0) { + *method_name_ptr = &ngx_http_echo_delete_method; + return NGX_HTTP_DELETE; + } + + if (ngx_http_echo_strcmp_const(method_name->data, "UNLOCK") == 0) { + *method_name_ptr = &ngx_http_echo_unlock_method; + return NGX_HTTP_UNLOCK; + } + + return NGX_HTTP_UNKNOWN; + + case 7: + if (ngx_http_echo_strcmp_const(method_name->data, "OPTIONS") == 0) { + *method_name_ptr = &ngx_http_echo_options_method; + return NGX_HTTP_OPTIONS; + } + + return NGX_HTTP_UNKNOWN; + + case 8: + if (ngx_http_echo_strcmp_const(method_name->data, "PROPFIND") == 0) { + *method_name_ptr = &ngx_http_echo_propfind_method; + return NGX_HTTP_PROPFIND; + } + + return NGX_HTTP_UNKNOWN; + + case 9: + if (ngx_http_echo_strcmp_const(method_name->data, "PROPPATCH") == 0) { + *method_name_ptr = &ngx_http_echo_proppatch_method; + return NGX_HTTP_PROPPATCH; + } + + return NGX_HTTP_UNKNOWN; + + default: + return NGX_HTTP_UNKNOWN; + } +} + + +/* XXX extermely evil and not working yet */ +ngx_int_t +ngx_http_echo_exec_abort_parent(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx) +{ +#if 0 + ngx_http_postponed_request_t *pr, *ppr; + ngx_http_request_t *saved_data = NULL; + ngx_chain_t *out = NULL; + /* ngx_int_t rc; */ + + dd("aborting parent..."); + + if (r == r->main || r->parent == NULL) { + return NGX_OK; + } + + if (r->parent->postponed) { + dd("Found parent->postponed..."); + + saved_data = r->connection->data; + ppr = NULL; + for (pr = r->parent->postponed; pr->next; pr = pr->next) { + if (pr->request == NULL) { + continue; + } + + if (pr->request == r) { + /* r->parent->postponed->next = pr; */ + dd("found the current subrequest"); + out = pr->out; + continue; + } + + /* r->connection->data = pr->request; */ + dd("finalizing the subrequest..."); + ngx_http_upstream_create(pr->request); + pr->request->upstream = NULL; + + if (ppr == NULL) { + r->parent->postponed = pr->next; + ppr = pr->next; + } else { + ppr->next = pr->next; + ppr = pr->next; + } + } + } + + r->parent->postponed->next = NULL; + + /* + r->connection->data = r->parent; + r->connection->buffered = 0; + + if (out != NULL) { + dd("trying to send more stuffs for the parent"); + ngx_http_output_filter(r->parent, out); + } + */ + + /* ngx_http_send_special(r->parent, NGX_HTTP_LAST); */ + + if (saved_data) { + r->connection->data = saved_data; + } + + dd("terminating the parent request"); + + return ngx_http_echo_send_chain_link(r, ctx, NULL /* indicate LAST */); + + /* ngx_http_upstream_create(r); */ + + /* ngx_http_finalize_request(r->parent, NGX_ERROR); */ +#endif + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_exec_exec(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args) +{ + ngx_str_t *uri; + ngx_str_t *user_args; + ngx_str_t args; + ngx_uint_t flags; + ngx_str_t *computed_arg; + + computed_arg = computed_args->elts; + + uri = &computed_arg[0]; + + if (uri->len == 0) { + return NGX_HTTP_BAD_REQUEST; + } + + if (computed_args->nelts > 1) { + user_args = &computed_arg[1]; + + } else { + user_args = NULL; + } + + args.data = NULL; + args.len = 0; + + if (ngx_http_parse_unsafe_uri(r, uri, &args, &flags) != NGX_OK) { + ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "echo_exec sees unsafe uri: \"%V\"", + uri); + return NGX_ERROR; + } + + if (args.len > 0 && user_args == NULL) { + user_args = &args; + } + + r->write_event_handler = ngx_http_request_empty_handler; + + if (uri->data[0] == '@') { + + if (user_args && user_args->len > 0) { + ngx_log_error(NGX_LOG_WARN, r->connection->log, 0, + "querystring %V ignored when exec'ing named " + "location %V", user_args, uri); + } + +#if 1 + /* clear the modules contexts */ + ngx_memzero(r->ctx, sizeof(void *) * ngx_http_max_module); +#endif + + dd("named location: %.*s, c:%d", (int) uri->len, uri->data, + (int) r->main->count); + + return ngx_http_named_location(r, uri); + } + + return ngx_http_internal_redirect(r, uri, user_args); +} + + +static ngx_int_t +ngx_http_echo_set_content_length_header(ngx_http_request_t *r, off_t len) +{ + ngx_table_elt_t *h, *header; + u_char *p; + ngx_list_part_t *part; + ngx_http_request_t *pr; + ngx_uint_t i; + + r->headers_in.content_length_n = len; + + if (ngx_list_init(&r->headers_in.headers, r->pool, 20, + sizeof(ngx_table_elt_t)) + != NGX_OK) + { + return NGX_ERROR; + } + + h = ngx_list_push(&r->headers_in.headers); + if (h == NULL) { + return NGX_ERROR; + } + + h->key = ngx_http_echo_content_length_header_key; + h->lowcase_key = ngx_pnalloc(r->pool, h->key.len); + if (h->lowcase_key == NULL) { + return NGX_ERROR; + } + + ngx_strlow(h->lowcase_key, h->key.data, h->key.len); + + r->headers_in.content_length = h; + + p = ngx_palloc(r->pool, NGX_OFF_T_LEN); + if (p == NULL) { + return NGX_ERROR; + } + + h->value.data = p; + + h->value.len = ngx_sprintf(h->value.data, "%O", len) - h->value.data; + + h->hash = ngx_http_echo_content_length_hash; + + dd("r content length: %.*s", + (int) r->headers_in.content_length->value.len, + r->headers_in.content_length->value.data); + + pr = r->parent; + + if (pr == NULL) { + return NGX_OK; + } + + /* forward the parent request's all other request headers */ + + part = &pr->headers_in.headers.part; + header = part->elts; + + for (i = 0; /* void */; i++) { + + if (i >= part->nelts) { + if (part->next == NULL) { + break; + } + + part = part->next; + header = part->elts; + i = 0; + } + + if (header[i].key.len == sizeof("Content-Length") - 1 + && ngx_strncasecmp(header[i].key.data, (u_char *) "Content-Length", + sizeof("Content-Length") - 1) + == 0) + { + continue; + } + + h = ngx_list_push(&r->headers_in.headers); + if (h == NULL) { + return NGX_ERROR; + } + + *h = header[i]; + } + + /* XXX maybe we should set those built-in header slot in + * ngx_http_headers_in_t too? */ + + return NGX_OK; +} diff --git a/echo-nginx-module/src/ngx_http_echo_subrequest.h b/echo-nginx-module/src/ngx_http_echo_subrequest.h new file mode 100644 index 00000000..61c0a041 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_subrequest.h @@ -0,0 +1,19 @@ +#ifndef ECHO_SUBREQUEST_H +#define ECHO_SUBREQUEST_H + +#include "ngx_http_echo_module.h" + +ngx_int_t ngx_http_echo_exec_echo_subrequest(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args); + +ngx_int_t ngx_http_echo_exec_echo_subrequest_async(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args); + +ngx_int_t ngx_http_echo_exec_abort_parent(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx); + +ngx_int_t ngx_http_echo_exec_exec(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_array_t *computed_args); + +#endif /* ECHO_SUBREQUEST_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_timer.c b/echo-nginx-module/src/ngx_http_echo_timer.c new file mode 100644 index 00000000..e2777ee5 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_timer.c @@ -0,0 +1,95 @@ +#ifndef DDEBUG +#define DDEBUG 0 +#endif + +#include "ddebug.h" + +#include "ngx_http_echo_timer.h" +#include "ngx_http_echo_util.h" + +#include +#include +#include + + +ngx_int_t +ngx_http_echo_timer_elapsed_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + ngx_http_echo_ctx_t *ctx; + ngx_msec_int_t ms; + u_char *p; + ngx_time_t *tp; + size_t size; + + ctx = ngx_http_get_module_ctx(r, ngx_http_echo_module); + if (ctx == NULL) { + ctx = ngx_http_echo_create_ctx(r); + if (ctx == NULL) { + return NGX_ERROR; + } + + ngx_http_set_ctx(r, ctx, ngx_http_echo_module); + } + + if (ctx->timer_begin.sec == 0) { + ctx->timer_begin.sec = r->start_sec; + ctx->timer_begin.msec = (ngx_msec_t) r->start_msec; + } + + /* force the ngx timer to update */ + +#if (nginx_version >= 8035) || (nginx_version < 8000 && nginx_version >= 7066) + ngx_time_update(); +#else + ngx_time_update(0, 0); +#endif + + tp = ngx_timeofday(); + + dd("old sec msec: %ld %d\n", (long) ctx->timer_begin.sec, + (int) ctx->timer_begin.msec); + + dd("new sec msec: %ld %d\n", (long) tp->sec, (int) tp->msec); + + ms = (ngx_msec_int_t) + ((tp->sec - ctx->timer_begin.sec) * 1000 + + (tp->msec - ctx->timer_begin.msec)); + ms = (ms >= 0) ? ms : 0; + + size = sizeof("-9223372036854775808.000") - 1; + + p = ngx_palloc(r->pool, size); + if (p == NULL) { + return NGX_ERROR; + } + + v->len = ngx_snprintf(p, size, "%T.%03M", ms / 1000, ms % 1000) - p; + v->data = p; + + v->valid = 1; + v->no_cacheable = 1; + v->not_found = 0; + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_exec_echo_reset_timer(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx) +{ + dd("Exec timer..."); + + /* force the ngx timer to update */ + +#if (nginx_version >= 8035) || (nginx_version < 8000 && nginx_version >= 7066) + ngx_time_update(); +#else + ngx_time_update(0, 0); +#endif + + ctx->timer_begin = *ngx_timeofday(); + return NGX_OK; +} + diff --git a/echo-nginx-module/src/ngx_http_echo_timer.h b/echo-nginx-module/src/ngx_http_echo_timer.h new file mode 100644 index 00000000..b6e7ff36 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_timer.h @@ -0,0 +1,13 @@ +#ifndef ECHO_TIMER_H +#define ECHO_TIMER_H + +#include "ngx_http_echo_module.h" + +ngx_int_t ngx_http_echo_timer_elapsed_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + +ngx_int_t ngx_http_echo_exec_echo_reset_timer(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx); + +#endif /* ECHO_TIMER_H */ + diff --git a/echo-nginx-module/src/ngx_http_echo_util.c b/echo-nginx-module/src/ngx_http_echo_util.c new file mode 100644 index 00000000..fed0587f --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_util.c @@ -0,0 +1,302 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_echo_util.h" +#include "ngx_http_echo_sleep.h" + + +ngx_uint_t ngx_http_echo_content_length_hash = 0; + + +ngx_http_echo_ctx_t * +ngx_http_echo_create_ctx(ngx_http_request_t *r) +{ + ngx_http_echo_ctx_t *ctx; + + ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_echo_ctx_t)); + if (ctx == NULL) { + return NULL; + } + + ctx->sleep.handler = ngx_http_echo_sleep_event_handler; + ctx->sleep.data = r; + ctx->sleep.log = r->connection->log; + + return ctx; +} + + +ngx_int_t +ngx_http_echo_eval_cmd_args(ngx_http_request_t *r, + ngx_http_echo_cmd_t *cmd, ngx_array_t *computed_args, + ngx_array_t *opts) +{ + unsigned expecting_opts = 1; + ngx_uint_t i; + ngx_array_t *args = cmd->args; + ngx_str_t *arg, *raw, *opt; + ngx_http_echo_arg_template_t *value; + + value = args->elts; + + for (i = 0; i < args->nelts; i++) { + raw = &value[i].raw_value; + + if (value[i].lengths == NULL && raw->len > 0) { + if (expecting_opts) { + if (raw->len == 1 || raw->data[0] != '-') { + expecting_opts = 0; + + } else if (raw->data[1] == '-') { + expecting_opts = 0; + continue; + + } else { + opt = ngx_array_push(opts); + if (opt == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + opt->len = raw->len - 1; + opt->data = raw->data + 1; + + dd("pushing opt: %.*s", (int) opt->len, opt->data); + + continue; + } + } + + } else { + expecting_opts = 0; + } + + arg = ngx_array_push(computed_args); + if (arg == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + if (value[i].lengths == NULL) { /* does not contain vars */ + dd("Using raw value \"%.*s\"", (int) raw->len, raw->data); + *arg = *raw; + + } else { + if (ngx_http_script_run(r, arg, value[i].lengths->elts, + 0, value[i].values->elts) + == NULL) + { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + } + + dd("pushed arg: %.*s", (int) arg->len, arg->data); + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_echo_send_chain_link(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_chain_t *in) +{ + ngx_int_t rc; + + rc = ngx_http_echo_send_header_if_needed(r, ctx); + + if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { + return rc; + } + + if (in == NULL) { + +#if defined(nginx_version) && nginx_version <= 8004 + + /* earlier versions of nginx does not allow subrequests + to send last_buf themselves */ + if (r != r->main) { + return NGX_OK; + } + +#endif + + rc = ngx_http_send_special(r, NGX_HTTP_LAST); + if (rc >= NGX_HTTP_SPECIAL_RESPONSE) { + return rc; + } + + return NGX_OK; + } + + /* FIXME we should udpate chains to recycle chain links and bufs */ + return ngx_http_output_filter(r, in); +} + + +ngx_int_t +ngx_http_echo_send_header_if_needed(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx) +{ + ngx_int_t rc; + ngx_http_echo_loc_conf_t *elcf; + + if (!r->header_sent && !ctx->header_sent) { + elcf = ngx_http_get_module_loc_conf(r, ngx_http_echo_module); + + r->headers_out.status = (ngx_uint_t) elcf->status; + + if (ngx_http_set_content_type(r) != NGX_OK) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + ngx_http_clear_content_length(r); + ngx_http_clear_accept_ranges(r); + + rc = ngx_http_send_header(r); + ctx->header_sent = 1; + return rc; + } + + return NGX_OK; +} + + +ssize_t +ngx_http_echo_atosz(u_char *line, size_t n) +{ + ssize_t value; + + if (n == 0) { + return NGX_ERROR; + } + + for (value = 0; n--; line++) { + if (*line == '_') { /* we ignore undercores */ + continue; + } + + if (*line < '0' || *line > '9') { + return NGX_ERROR; + } + + value = value * 10 + (*line - '0'); + } + + if (value < 0) { + return NGX_ERROR; + } + + return value; +} + + +/* Modified from the ngx_strlcasestrn function in ngx_string.h + * Copyright (C) by Igor Sysoev */ +u_char * +ngx_http_echo_strlstrn(u_char *s1, u_char *last, u_char *s2, size_t n) +{ + ngx_uint_t c1, c2; + + c2 = (ngx_uint_t) *s2++; + last -= n; + + do { + do { + if (s1 >= last) { + return NULL; + } + + c1 = (ngx_uint_t) *s1++; + + } while (c1 != c2); + + } while (ngx_strncmp(s1, s2, n) != 0); + + return --s1; +} + + +ngx_int_t +ngx_http_echo_post_request_at_head(ngx_http_request_t *r, + ngx_http_posted_request_t *pr) +{ + dd_enter(); + + if (pr == NULL) { + pr = ngx_palloc(r->pool, sizeof(ngx_http_posted_request_t)); + if (pr == NULL) { + return NGX_ERROR; + } + } + + pr->request = r; + pr->next = r->main->posted_requests; + r->main->posted_requests = pr; + + return NGX_OK; +} + + +u_char * +ngx_http_echo_rebase_path(ngx_pool_t *pool, u_char *src, size_t osize, + size_t *nsize) +{ + u_char *p, *dst; + + if (osize == 0) { + return NULL; + } + + if (src[0] == '/') { + /* being an absolute path already, just add a trailing '\0' */ + *nsize = osize; + + dst = ngx_palloc(pool, *nsize + 1); + if (dst == NULL) { + *nsize = 0; + return NULL; + } + + p = ngx_copy(dst, src, osize); + *p = '\0'; + + return dst; + } + + *nsize = ngx_cycle->prefix.len + osize; + + dst = ngx_palloc(pool, *nsize + 1); + if (dst == NULL) { + *nsize = 0; + return NULL; + } + + p = ngx_copy(dst, ngx_cycle->prefix.data, ngx_cycle->prefix.len); + p = ngx_copy(p, src, osize); + + *p = '\0'; + + return dst; +} + + +ngx_int_t +ngx_http_echo_flush_postponed_outputs(ngx_http_request_t *r) +{ + if (r == r->connection->data && r->postponed) { + /* notify the downstream postpone filter to flush the postponed + * outputs of the current request */ + return ngx_http_output_filter(r, NULL); + } + + /* do nothing */ + return NGX_OK; +} diff --git a/echo-nginx-module/src/ngx_http_echo_util.h b/echo-nginx-module/src/ngx_http_echo_util.h new file mode 100644 index 00000000..24b3e151 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_util.h @@ -0,0 +1,58 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef NGX_HTTP_ECHO_UTIL_H +#define NGX_HTTP_ECHO_UTIL_H + + +#include "ngx_http_echo_module.h" + + +#define ngx_http_echo_strcmp_const(a, b) \ + ngx_strncmp(a, b, sizeof(b) - 1) + + +#define ngx_http_echo_hash_literal(s) \ + ngx_http_echo_hash_str((u_char *) s, sizeof(s) - 1) + + +static ngx_inline ngx_uint_t +ngx_http_echo_hash_str(u_char *src, size_t n) +{ + ngx_uint_t key; + + key = 0; + + while (n--) { + key = ngx_hash(key, *src); + src++; + } + + return key; +} + + +extern ngx_uint_t ngx_http_echo_content_length_hash; + + +ngx_http_echo_ctx_t *ngx_http_echo_create_ctx(ngx_http_request_t *r); +ngx_int_t ngx_http_echo_eval_cmd_args(ngx_http_request_t *r, + ngx_http_echo_cmd_t *cmd, ngx_array_t *computed_args, + ngx_array_t *opts); +ngx_int_t ngx_http_echo_send_header_if_needed(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx); +ngx_int_t ngx_http_echo_send_chain_link(ngx_http_request_t *r, + ngx_http_echo_ctx_t *ctx, ngx_chain_t *cl); +ssize_t ngx_http_echo_atosz(u_char *line, size_t n); +u_char *ngx_http_echo_strlstrn(u_char *s1, u_char *last, u_char *s2, size_t n); +ngx_int_t ngx_http_echo_post_request_at_head(ngx_http_request_t *r, + ngx_http_posted_request_t *pr); +u_char *ngx_http_echo_rebase_path(ngx_pool_t *pool, u_char *src, size_t osize, + size_t *nsize); +ngx_int_t ngx_http_echo_flush_postponed_outputs(ngx_http_request_t *r); + + +#endif /* NGX_HTTP_ECHO_UTIL_H */ diff --git a/echo-nginx-module/src/ngx_http_echo_var.c b/echo-nginx-module/src/ngx_http_echo_var.c new file mode 100644 index 00000000..138a5102 --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_var.c @@ -0,0 +1,110 @@ +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + +#include "ngx_http_echo_var.h" +#include "ngx_http_echo_timer.h" +#include "ngx_http_echo_request_info.h" +#include "ngx_http_echo_foreach.h" + + +static ngx_int_t ngx_http_echo_incr_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); + + +static ngx_http_variable_t ngx_http_echo_variables[] = { + + { ngx_string("echo_timer_elapsed"), NULL, + ngx_http_echo_timer_elapsed_variable, 0, + NGX_HTTP_VAR_NOCACHEABLE, 0 }, + + { ngx_string("echo_request_method"), NULL, + ngx_http_echo_request_method_variable, 0, + NGX_HTTP_VAR_NOCACHEABLE, 0 }, + + { ngx_string("echo_cacheable_request_uri"), NULL, + ngx_http_echo_cacheable_request_uri_variable, 0, + 0, 0 }, + + { ngx_string("echo_request_uri"), NULL, + ngx_http_echo_request_uri_variable, 0, + 0, 0 }, + + { ngx_string("echo_client_request_method"), NULL, + ngx_http_echo_client_request_method_variable, 0, + NGX_HTTP_VAR_NOCACHEABLE, 0 }, + + { ngx_string("echo_request_body"), NULL, + ngx_http_echo_request_body_variable, 0, + NGX_HTTP_VAR_NOCACHEABLE, 0 }, + + { ngx_string("echo_client_request_headers"), NULL, + ngx_http_echo_client_request_headers_variable, 0, + NGX_HTTP_VAR_NOCACHEABLE, 0 }, + + { ngx_string("echo_it"), NULL, + ngx_http_echo_it_variable, 0, + NGX_HTTP_VAR_NOCACHEABLE, 0 }, + + { ngx_string("echo_incr"), NULL, + ngx_http_echo_incr_variable, 0, + NGX_HTTP_VAR_NOCACHEABLE, 0 }, + + { ngx_string("echo_response_status"), NULL, + ngx_http_echo_response_status_variable, 0, + NGX_HTTP_VAR_NOCACHEABLE, 0 }, + + { ngx_null_string, NULL, NULL, 0, 0, 0 } +}; + + +ngx_int_t +ngx_http_echo_add_variables(ngx_conf_t *cf) +{ + ngx_http_variable_t *var, *v; + + for (v = ngx_http_echo_variables; v->name.len; v++) { + var = ngx_http_add_variable(cf, &v->name, v->flags); + if (var == NULL) { + return NGX_ERROR; + } + + var->get_handler = v->get_handler; + var->data = v->data; + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_echo_incr_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data) +{ + ngx_http_echo_ctx_t *ctx; + u_char *p; + + ctx = ngx_http_get_module_ctx(r->main, ngx_http_echo_module); + + if (ctx == NULL) { + return NGX_ERROR; + } + + ctx->counter++; + + p = ngx_palloc(r->pool, NGX_INT_T_LEN); + if (p == NULL) { + return NGX_ERROR; + } + + v->len = ngx_sprintf(p, "%ui", ctx->counter) - p; + v->data = p; + + v->valid = 1; + v->not_found = 0; + v->no_cacheable = 1; + + return NGX_OK; +} + diff --git a/echo-nginx-module/src/ngx_http_echo_var.h b/echo-nginx-module/src/ngx_http_echo_var.h new file mode 100644 index 00000000..8b24e02b --- /dev/null +++ b/echo-nginx-module/src/ngx_http_echo_var.h @@ -0,0 +1,9 @@ +#ifndef ECHO_VAR_H +#define ECHO_VAR_H + +#include "ngx_http_echo_module.h" + +ngx_int_t ngx_http_echo_add_variables(ngx_conf_t *cf); + +#endif /* ECHO_VAR_H */ + diff --git a/echo-nginx-module/t/abort-parent.t b/echo-nginx-module/t/abort-parent.t new file mode 100644 index 00000000..6137607e --- /dev/null +++ b/echo-nginx-module/t/abort-parent.t @@ -0,0 +1,63 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::LWP skip_all => + 'not working at all'; + +plan tests => 2 * blocks(); + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /abort { + echo hello; + echo_flush; + echo_location_async '/foo'; + echo_location_async '/bar'; + echo_location_async '/baz'; + echo world; + echo_flush; + } + + location /proxy { + proxy_pass "http://127.0.0.1:$server_port/sleep?$query_string"; + } + + location /sleep { + echo_sleep $arg_sleep; + echo $arg_echo; + echo_flush; + } + + location /foo { + echo_location '/proxy?sleep=1&echo=foo'; + #echo_flush; + echo_abort_parent; + } + + location /bar { + proxy_pass 'http://127.0.0.1:$server_port/sleep_bar'; + } + + location /baz { + proxy_pass 'http://127.0.0.1:$server_port/sleep_baz'; + } + + location /sleep_bar { + echo_sleep 2; + echo bar; + } + + location /sleep_baz { + echo_sleep 3; + echo baz; + } +--- request + GET /abort +--- response_body +hello +bar + diff --git a/echo-nginx-module/t/blocking-sleep.t b/echo-nginx-module/t/blocking-sleep.t new file mode 100644 index 00000000..0bdc6cc1 --- /dev/null +++ b/echo-nginx-module/t/blocking-sleep.t @@ -0,0 +1,156 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 2 * blocks(); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /echo { + echo_blocking_sleep 1; + } +--- request + GET /echo +--- response_body + + + +=== TEST 2: fractional delay +--- config + location /echo { + echo_blocking_sleep 0.01; + } +--- request + GET /echo +--- response_body + + + +=== TEST 3: leading echo +--- config + location /echo { + echo before...; + echo_blocking_sleep 0.01; + } +--- request + GET /echo +--- response_body +before... + + + +=== TEST 4: trailing echo +--- config + location /echo { + echo_blocking_sleep 0.01; + echo after...; + } +--- request + GET /echo +--- response_body +after... + + + +=== TEST 5: two echos around sleep +--- config + location /echo { + echo before...; + echo_blocking_sleep 0.01; + echo after...; + } +--- request + GET /echo +--- response_body +before... +after... + + + +=== TEST 6: interleaving sleep and echo +--- config + location /echo { + echo 1; + echo_blocking_sleep 0.01; + echo 2; + echo_blocking_sleep 0.01; + } +--- request + GET /echo +--- response_body +1 +2 + + + +=== TEST 7: interleaving sleep and echo with echo at the end... +--- config + location /echo { + echo 1; + echo_blocking_sleep 0.01; + echo 2; + echo_blocking_sleep 0.01; + echo 3; + } +--- request + GET /echo +--- response_body +1 +2 +3 + + + +=== TEST 8: flush before sleep +we didn't really test the actual effect of "echo_flush" here... +merely checks if it croaks if appears. +--- config + location /flush { + echo hi; + echo_flush; + echo_blocking_sleep 0.01; + echo trees; + } +--- request + GET /flush +--- response_body +hi +trees + + + +=== TEST 9: flush does not increment opcode pointer itself +--- config + location /flush { + echo hi; + echo_flush; + echo trees; + } +--- request + GET /flush +--- response_body +hi +trees + + + +=== TEST 10: blocking sleep by variable +--- config + location ~ ^/sleep/(.+) { + echo before...; + echo_blocking_sleep $1; + echo after...; + } +--- request + GET /sleep/0.01 +--- response_body +before... +after... + diff --git a/echo-nginx-module/t/echo-after-body.t b/echo-nginx-module/t/echo-after-body.t new file mode 100644 index 00000000..44c4c725 --- /dev/null +++ b/echo-nginx-module/t/echo-after-body.t @@ -0,0 +1,261 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (2 * blocks() + 1); + +no_long_string(); +log_level('warn'); + +#master_on(); +#workers(1); + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- http_config + postpone_output 1; +--- config + location /echo { + echo_after_body hello; + echo world; + } +--- request + GET /echo +--- response_body +world +hello + + + +=== TEST 2: echo after proxy +--- config + location /echo { + echo_after_body hello; + proxy_pass http://127.0.0.1:$server_port$request_uri/more; + } + location /echo/more { + echo world; + } +--- request + GET /echo +--- response_body +world +hello + + + +=== TEST 3: with variables +--- config + location /echo { + echo_after_body $request_method; + echo world; + } +--- request + GET /echo +--- response_body +world +GET + + + +=== TEST 4: w/o args +--- config + location /echo { + echo_after_body; + echo world; + } +--- request + GET /echo +--- response_body eval +"world\n\n" + + + +=== TEST 5: order is not important +--- config + location /reversed { + echo world; + echo_after_body hello; + } +--- request + GET /reversed +--- response_body +world +hello + + + +=== TEST 6: multiple echo_after_body instances +--- config + location /echo { + echo_after_body hello; + echo_after_body world; + echo !; + } +--- request + GET /echo +--- response_body +! +hello +world + + + +=== TEST 7: multiple echo_after_body instances with multiple echo cmds +--- config + location /echo { + echo_after_body hello; + echo_after_body world; + echo i; + echo say; + } +--- request + GET /echo +--- response_body +i +say +hello +world + + + +=== TEST 8: echo-after-body & echo-before-body +--- config + location /mixed { + echo_before_body hello; + echo_after_body world; + echo_before_body hiya; + echo_after_body igor; + echo ////////; + } +--- request + GET /mixed +--- response_body +hello +hiya +//////// +world +igor + + + +=== TEST 9: echo around proxy +--- config + location /echo { + echo_before_body hello; + echo_before_body world; + #echo $scheme://$host:$server_port$request_uri/more; + proxy_pass $scheme://127.0.0.1:$server_port$request_uri/more; + echo_after_body hiya; + echo_after_body igor; + } + location /echo/more { + echo blah; + } +--- request + GET /echo +--- response_body +hello +world +blah +hiya +igor + + + +=== TEST 10: with $echo_response_status +--- config + location /status { + echo_after_body "status: $echo_response_status"; + return 404; + } +--- request + GET /status +--- response_body_like +.*404 Not Found.* +status: 404$ +--- error_code: 404 + + + +=== TEST 11: in subrequests +--- config + location /main { + echo_location_async /hello; + } + location /hello { + echo_after_body 'world!'; + echo 'hello'; + } +--- request + GET /main +--- response_body +hello +world! + + + +=== TEST 12: echo_after_body + gzip +--- config + gzip on; + gzip_min_length 1; + location /main { + echo_after_body 'world!'; + echo_duplicate 1024 'hello'; + } +--- request + GET /main +--- response_body_like +hello +--- SKIP + + + +=== TEST 13: echo_after_body + proxy output +--- config + #gzip on; + #gzip_min_length 1; + location /main { + echo_after_body 'world'; + proxy_pass http://127.0.0.1:$server_port/foo; + } + location /foo { + echo_duplicate 10 hello; + } +--- request + GET /main +--- response_body_like +^(?:hello){10}world$ + + + +=== TEST 14: in subrequests (we get last_in_chain set properly) +--- config + location /main { + echo_location_async /hello; + } + location /hello { + echo 'hello'; + echo_after_body 'world!'; + body_filter_by_lua ' + local eof = ngx.arg[2] + if eof then + print("lua: eof found in body") + end + '; + } +--- request + GET /main +--- response_body +hello +world! +--- log_level: notice +--- error_log +lua: eof found in body + diff --git a/echo-nginx-module/t/echo-before-body.t b/echo-nginx-module/t/echo-before-body.t new file mode 100644 index 00000000..15131843 --- /dev/null +++ b/echo-nginx-module/t/echo-before-body.t @@ -0,0 +1,278 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 2 * blocks(); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /echo { + echo_before_body hello; + echo world; + } +--- request + GET /echo +--- response_body +hello +world + + + +=== TEST 2: echo before proxy +--- config + location /echo { + echo_before_body hello; + proxy_pass $scheme://127.0.0.1:$server_port$request_uri/more; + } + location /echo/more { + echo world; + } +--- request + GET /echo +--- response_body +hello +world + + + +=== TEST 3: with variables +--- config + location /echo { + echo_before_body $request_method; + echo world; + } +--- request + GET /echo +--- response_body +GET +world + + + +=== TEST 4: w/o args +--- config + location /echo { + echo_before_body; + echo world; + } +--- request + GET /echo +--- response_body eval +"\nworld\n" + + + +=== TEST 5: order is not important +--- config + location /reversed { + echo world; + echo_before_body hello; + } +--- request + GET /reversed +--- response_body +hello +world + + + +=== TEST 6: multiple echo_before_body instances +--- config + location /echo { + echo_before_body hello; + echo_before_body world; + echo !; + } +--- request + GET /echo +--- response_body +hello +world +! + + + +=== TEST 7: multiple echo_before_body instances with multiple echo cmds +--- config + location /echo { + echo_before_body hello; + echo_before_body world; + echo i; + echo say; + } +--- request + GET /echo +--- response_body +hello +world +i +say + + + +=== TEST 8: with $echo_response_status +--- config + location /status { + echo_before_body "status: $echo_response_status"; + return 404; + } +--- request + GET /status +--- response_body_like +status: 404 +.*404 Not Found.*$ +--- error_code: 404 + + + +=== TEST 9: $echo_response_status in echo_before_body in subrequests +--- config + location /main { + echo_location '/status?val=403'; + echo_location '/status?val=500'; + } + location /status { + if ($arg_val = 500) { + echo_before_body "status: $echo_response_status"; + return 500; + break; + } + if ($arg_val = 403) { + echo_before_body "status: $echo_response_status"; + return 403; + break; + } + return 200; + } +--- request + GET /main +--- response_body_like +^status: 403.*?status: 500.*$ + + + +=== TEST 10: echo -n +--- config + location /echo { + echo_before_body -n hello; + echo_before_body -n world; + echo ==; + } +--- request + GET /echo +--- response_body +helloworld== + + + +=== TEST 11: echo a -n +--- config + location /echo { + echo_before_body a -n hello; + echo_before_body b -n world; + echo ==; + } +--- request + GET /echo +--- response_body +a -n hello +b -n world +== + + + +=== TEST 12: -n in a var +--- config + location /echo { + set $opt -n; + echo_before_body $opt hello; + echo_before_body $opt world; + echo ==; + } +--- request + GET /echo +--- response_body +-n hello +-n world +== + + + +=== TEST 13: -n only +--- config + location /echo { + echo_before_body -n; + echo_before_body -n; + echo ==; + } +--- request + GET /echo +--- response_body +== + + + +=== TEST 14: -n with an empty string +--- config + location /echo { + echo_before_body -n ""; + set $empty ""; + echo_before_body -n $empty; + echo ==; + } +--- request + GET /echo +--- response_body +== + + + +=== TEST 15: -- -n +--- config + location /echo { + echo_before_body -- -n hello; + echo_before_body -- -n world; + echo ==; + } +--- request + GET /echo +--- response_body +-n hello +-n world +== + + + +=== TEST 16: -n -n +--- config + location /echo { + echo_before_body -n -n hello; + echo_before_body -n -n world; + echo ==; + } +--- request + GET /echo +--- response_body +helloworld== + + + +=== TEST 17: -n -- -n +--- config + location /echo { + echo_before_body -n -- -n hello; + echo_before_body -n -- -n world; + echo ==; + } +--- request + GET /echo +--- response_body +-n hello-n world== + diff --git a/echo-nginx-module/t/echo-duplicate.t b/echo-nginx-module/t/echo-duplicate.t new file mode 100644 index 00000000..82b67257 --- /dev/null +++ b/echo-nginx-module/t/echo-duplicate.t @@ -0,0 +1,89 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 2 * blocks(); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /dup { + echo_duplicate 3 a; + } +--- request + GET /dup +--- response_body: aaa + + + +=== TEST 2: abc abc +--- config + location /dup { + echo_duplicate 2 abc; + } +--- request + GET /dup +--- response_body: abcabc + + + +=== TEST 3: big size with underscores +--- config + location /dup { + echo_duplicate 10_000 A; + } +--- request + GET /dup +--- response_body eval +'A' x 10_000 + + + +=== TEST 4: 0 duplicate 0 empty strings +--- config + location /dup { + echo_duplicate 0 ""; + } +--- request + GET /dup +--- response_body + + + +=== TEST 5: 0 duplicate non-empty strings +--- config + location /dup { + echo_duplicate 0 "abc"; + } +--- request + GET /dup +--- response_body + + + +=== TEST 6: duplication of empty strings +--- config + location /dup { + echo_duplicate 2 ""; + } +--- request + GET /dup +--- response_body + + + +=== TEST 7: sanity (HEAD) +--- config + location /dup { + echo_duplicate 3 a; + } +--- request + HEAD /dup +--- response_body + diff --git a/echo-nginx-module/t/echo-timer.t b/echo-nginx-module/t/echo-timer.t new file mode 100644 index 00000000..712524d7 --- /dev/null +++ b/echo-nginx-module/t/echo-timer.t @@ -0,0 +1,107 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 2 * blocks(); + +run_tests(); + +__DATA__ + +=== TEST 1: timer without explicit reset +--- config + location /timer { + echo_sleep 0.03; + echo "elapsed $echo_timer_elapsed sec."; + } +--- request + GET /timer +--- response_body_like +^elapsed 0\.0(2[6-9]|3[0-6]) sec\.$ + + + +=== TEST 2: timer without explicit reset and sleep +--- config + location /timer { + echo "elapsed $echo_timer_elapsed sec."; + } +--- request + GET /timer +--- response_body_like +^elapsed 0\.00[0-5] sec\.$ + + + +=== TEST 3: timing accumulated sleeps +--- config + location /timer { + echo_sleep 0.03; + echo_sleep 0.02; + echo "elapsed $echo_timer_elapsed sec."; + } +--- request + GET /timer +--- response_body_like +^elapsed 0\.0(4[6-9]|5[0-6]) sec\.$ + + + +=== TEST 4: timer with explicit reset but without sleep +--- config + location /timer { + echo_reset_timer; + echo "elapsed $echo_timer_elapsed sec."; + } +--- request + GET /timer +--- response_body_like +^elapsed 0\.00[0-5] sec\.$ + + + +=== TEST 5: reset timer between sleeps +--- config + location /timer { + echo_sleep 0.02; + echo "elapsed $echo_timer_elapsed sec."; + echo_reset_timer; + echo_sleep 0.03; + echo "elapsed $echo_timer_elapsed sec."; + } +--- request + GET /timer +--- response_body_like +^elapsed 0\.0(1[6-9]|2[0-6]) sec\. +elapsed 0\.0(2[6-9]|3[0-6]) sec\.$ + + + +=== TEST 6: reset timer between blocking sleeps +--- config + location /timer { + echo_blocking_sleep 0.02; + echo "elapsed $echo_timer_elapsed sec."; + echo_reset_timer; + echo_blocking_sleep 0.03; + echo "elapsed $echo_timer_elapsed sec."; + } +--- request + GET /timer +--- response_body_like +^elapsed 0\.0(1[6-9]|2[0-9]) sec\. +elapsed 0\.0(2[6-9]|3[0-6]) sec\.$ + + + +=== TEST 7: timer without explicit reset +--- config + location = /timer { + return 200 "$echo_timer_elapsed"; + } +--- request + GET /timer +--- response_body_like chop +^0(\.0\d*)$ + diff --git a/echo-nginx-module/t/echo.t b/echo-nginx-module/t/echo.t new file mode 100644 index 00000000..b1812592 --- /dev/null +++ b/echo-nginx-module/t/echo.t @@ -0,0 +1,416 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (2 * blocks() + 6); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /echo { + echo hello; + } +--- request + GET /echo +--- response_body +hello + + + +=== TEST 2: multiple args +--- config + location /echo { + echo say hello world; + } +--- request + GET /echo +--- response_body +say hello world + + + +=== TEST 3: multiple directive instances +--- config + location /echo { + echo say that; + echo hello; + echo world !; + } +--- request + GET /echo +--- response_body +say that +hello +world ! + + + +=== TEST 4: echo without arguments +--- config + location /echo { + echo; + echo; + } +--- request + GET /echo +--- response_body eval +"\n\n" + + + +=== TEST 5: escaped newline +--- config + location /echo { + echo "hello\nworld"; + } +--- request + GET /echo +--- response_body +hello +world + + + +=== TEST 6: escaped tabs and \r and " wihtin "..." +--- config + location /echo { + echo "i say \"hello\tworld\"\r"; + } +--- request + GET /echo +--- response_body eval: "i say \"hello\tworld\"\r\n" + + + +=== TEST 7: escaped tabs and \r and " in single quotes +--- config + location /echo { + echo 'i say \"hello\tworld\"\r'; + } +--- request + GET /echo +--- response_body eval: "i say \"hello\tworld\"\r\n" + + + +=== TEST 8: escaped tabs and \r and " w/o any quotes +--- config + location /echo { + echo i say \"hello\tworld\"\r; + } +--- request + GET /echo +--- response_body eval: "i say \"hello\tworld\"\r\n" + + + +=== TEST 9: escaping $ +As of Nginx 0.8.20, there's still no way to escape the '$' character. +--- config + location /echo { + echo \$; + } +--- request + GET /echo +--- response_body +$ +--- SKIP + + + +=== TEST 10: XSS +--- config + location /blah { + echo_duplicate 1 "$arg_callback("; + echo_location_async "/data?$uri"; + echo_duplicate 1 ")"; + } + location /data { + echo_duplicate 1 '{"dog":"$query_string"}'; + } +--- request + GET /blah/9999999.json?callback=ding1111111 +--- response_body chomp +ding1111111({"dog":"/blah/9999999.json"}) + + + +=== TEST 11: XSS - filter version +--- config + location /blah { + echo_before_body "$arg_callback("; + + echo_duplicate 1 '{"dog":"$uri"}'; + + echo_after_body ")"; + } +--- request + GET /blah/9999999.json?callback=ding1111111 +--- response_body +ding1111111( +{"dog":"/blah/9999999.json"}) + + + +=== TEST 12: if +--- config +location /first { + echo "before"; + echo_location_async /second $request_uri; + echo "after"; +} + +location = /second { + if ($query_string ~ '([^?]+)') { + set $memcached_key $1; # needing this to be keyed on the request_path, not the entire uri + echo $memcached_key; + } +} +--- request + GET /first/9999999.json?callback=ding1111111 +--- response_body +before +/first/9999999.json +after + + + +=== TEST 13: echo -n +--- config + location /echo { + echo -n hello; + echo -n world; + } +--- request + GET /echo +--- response_body chop +helloworld + + + +=== TEST 14: echo a -n +--- config + location /echo { + echo a -n hello; + echo b -n world; + } +--- request + GET /echo +--- response_body +a -n hello +b -n world + + + +=== TEST 15: -n in a var +--- config + location /echo { + set $opt -n; + echo $opt hello; + echo $opt world; + } +--- request + GET /echo +--- response_body +-n hello +-n world + + + +=== TEST 16: -n only +--- config + location /echo { + echo -n; + echo -n; + } +--- request + GET /echo +--- response_body chop + + + +=== TEST 17: -n with an empty string +--- config + location /echo { + echo -n ""; + set $empty ""; + echo -n $empty; + } +--- request + GET /echo +--- response_body chop + + + +=== TEST 18: -- -n +--- config + location /echo { + echo -- -n hello; + echo -- -n world; + } +--- request + GET /echo +--- response_body +-n hello +-n world + + + +=== TEST 19: -n -n +--- config + location /echo { + echo -n -n hello; + echo -n -n world; + } +--- request + GET /echo +--- response_body chop +helloworld + + + +=== TEST 20: -n -- -n +--- config + location /echo { + echo -n -- -n hello; + echo -n -- -n world; + } +--- request + GET /echo +--- response_body chop +-n hello-n world + + + +=== TEST 21: proxy +--- config + location /main { + proxy_pass http://127.0.0.1:$server_port/echo; + } + location /echo { + echo hello; + echo world; + } +--- request + GET /main +--- response_headers +!Content-Length +--- response_body +hello +world + + + +=== TEST 22: if is evil +--- config + location /test { + set $a 3; + set_by_lua $a ' + if ngx.var.a == "3" then + return 4 + end + '; + echo $a; + } +--- request + GET /test +--- response_body +4 +--- SKIP + + + +=== TEST 23: HEAD +--- config + location /echo { + echo hello; + echo world; + } +--- request + HEAD /echo +--- response_body + + + +=== TEST 24: POST +--- config + location /echo { + echo hello; + echo world; + } +--- pipelined_requests eval +["POST /echo +blah blah", "POST /echo +foo bar baz"] +--- response_body eval +["hello\nworld\n","hello\nworld\n"] + + + +=== TEST 25: POST +--- config + location /echo { + echo_sleep 0.001; + echo hello; + echo world; + } +--- pipelined_requests eval +["POST /echo +blah blah", "POST /echo +foo bar baz"] +--- response_body eval +["hello\nworld\n","hello\nworld\n"] + + + +=== TEST 26: empty arg after -n (github issue #33) +--- config + location = /t { + set $empty ""; + echo -n $empty hello world; + } +--- request + GET /t +--- response_body chop + hello world + + + +=== TEST 27: image filter +--- config + location = /gif { + empty_gif; + } + + location = /t { + default_type image/gif; + image_filter resize 10 10; + set $gif1 ''; + set $gif2 ''; + rewrite_by_lua ' + local res = ngx.location.capture("/gif") + local data = res.body + ngx.var.gif1 = string.sub(data, 1, #data - 1) + ngx.var.gif2 = string.sub(data, #data) + '; + echo -n $gif1; + echo -n $gif2; + } +--- request + GET /t +--- stap +F(ngx_http_image_header_filter) { + println("image header filter") +} +--- stap_out +image header filter +--- response_body_like: . + diff --git a/echo-nginx-module/t/exec.t b/echo-nginx-module/t/exec.t new file mode 100644 index 00000000..b7c1308c --- /dev/null +++ b/echo-nginx-module/t/exec.t @@ -0,0 +1,228 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (2 * blocks() + 1); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: exec normal location +--- config + location /main { + echo_exec /bar; + echo end; + } + location = /bar { + echo "$echo_request_uri:"; + echo bar; + } +--- request + GET /main +--- response_body +/bar: +bar + + + +=== TEST 2: location with args (inlined in uri) +--- config + location /main { + echo_exec /bar?a=32; + echo end; + } + location /bar { + echo "a: [$arg_a]"; + } +--- request + GET /main +--- response_body +a: [32] + + + +=== TEST 3: location with args (in separate arg) +--- config + location /main { + echo_exec /bar a=56; + echo end; + } + location /bar { + echo "a: [$arg_a]"; + } +--- request + GET /main +--- response_body +a: [56] + + + +=== TEST 4: exec named location +--- config + location /main { + echo_exec @bar; + echo end; + } + location @bar { + echo bar; + } +--- request + GET /main +--- response_body +bar + + + +=== TEST 5: query string ignored for named locations +--- config + location /main { + echo_exec @bar?a=32; + echo end; + } + location @bar { + echo "a: [$arg_a]"; + } +--- request + GET /main +--- response_body +a: [] +--- error_log +querystring a=32 ignored when exec'ing named location @bar + + + +=== TEST 6: query string ignored for named locations +--- config + location /foo { + echo_exec @bar; + } + location @bar { + echo "uri: [$echo_request_uri]"; + } +--- request + GET /foo +--- response_body +uri: [/foo] + + + +=== TEST 7: exec(named location) in subrequests +--- config + location /entry { + echo_location /foo; + echo_sleep 0.001; + echo_location /foo2; + } + location /foo { + echo_exec @bar; + } + location /foo2 { + echo_exec @bar; + } + + location @bar { + proxy_pass http://127.0.0.1:$server_port/bar; + } + location /bar { + echo_sleep 0.01; + echo hello; + } +--- request + GET /entry +--- response_body +hello +hello + + + +=== TEST 8: exec(normal loctions) in subrequests +--- config + location /entry { + echo_location /foo; + echo_sleep 0.001; + echo_location /foo2; + } + location /foo { + echo_exec /baz; + } + location /foo2 { + echo_exec /baz; + } + + location /baz { + proxy_pass http://127.0.0.1:$server_port/bar; + } + location /bar { + echo_sleep 0.01; + echo hello; + } +--- request + GET /entry +--- response_body +hello +hello + + + +=== TEST 9: exec should clear ctx +--- config + location @bar { + echo hello; + echo world; + echo heh; + } + location /foo { + #echo_sleep 0.001; + echo_reset_timer; + echo_exec @bar; + } +--- request + GET /foo +--- response_body +hello +world +heh + + + +=== TEST 10: reset ctx +--- config + location @proxy { + rewrite_by_lua return; + echo hello; + } + location /main { + rewrite_by_lua return; + echo_exec @proxy; + } +--- request + GET /main +--- response_body +hello + + + +=== TEST 11: yield before exec +--- config + location @bar { + echo hello; + echo world; + echo heh; + } + location /foo { + echo_sleep 0.001; + echo_exec @bar; + } +--- request + GET /foo +--- response_body +hello +world +heh + diff --git a/echo-nginx-module/t/filter-used.t b/echo-nginx-module/t/filter-used.t new file mode 100644 index 00000000..28352701 --- /dev/null +++ b/echo-nginx-module/t/filter-used.t @@ -0,0 +1,59 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (3 * blocks()); + +no_long_string(); +log_level('warn'); + +#master_on(); +#workers(1); + +run_tests(); + +__DATA__ + +=== TEST 1: filter indeed used +--- http_config + postpone_output 1; +--- config + location /echo { + echo_after_body hello; + echo world; + } +--- request + GET /echo +--- stap +F(ngx_http_echo_header_filter) { + println("echo header filter called") +} +--- stap_out +echo header filter called +--- response_body +world +hello + + + +=== TEST 2: filter not used +--- http_config + postpone_output 1; +--- config + location /echo { + #echo_after_body hello; + echo world; + } +--- request + GET /echo +--- stap +F(ngx_http_echo_header_filter) { + println("echo header filter called") +} +--- stap_out +--- response_body +world + diff --git a/echo-nginx-module/t/foreach-split.t b/echo-nginx-module/t/foreach-split.t new file mode 100644 index 00000000..266a7014 --- /dev/null +++ b/echo-nginx-module/t/foreach-split.t @@ -0,0 +1,283 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * 2 * blocks(); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /main { + echo_foreach_split '&' $query_string; + echo_location_async $echo_it; + echo '/* end */'; + echo_end; + } + location /sub/1.css { + echo "body { font-size: 12pt; }"; + } + location /sub/2.css { + echo "table { color: 'red'; }"; + } +--- request + GET /main?/sub/1.css&/sub/2.css +--- response_body +body { font-size: 12pt; } +/* end */ +table { color: 'red'; } +/* end */ + + + +=== TEST 2: split in a url argument (echo_location_async) +--- config + location /main_async { + echo_foreach_split ',' $arg_cssfiles; + echo_location_async $echo_it; + echo_end; + } + location /foo.css { + echo foo; + } + location /bar.css { + echo bar; + } + location /baz.css { + echo baz; + } +--- request + GET /main_async?cssfiles=/foo.css,/bar.css,/baz.css +--- response_body +foo +bar +baz + + + +=== TEST 3: split in a url argument (echo_location) +--- config + location /main_sync { + echo_foreach_split ',' $arg_cssfiles; + echo_location $echo_it; + echo_end; + } + location /foo.css { + echo foo; + } + location /bar.css { + echo bar; + } + location /baz.css { + echo baz; + } +--- request + GET /main_sync?cssfiles=/foo.css,/bar.css,/baz.css +--- response_body +foo +bar +baz +--- SKIP + + + +=== TEST 4: empty loop +--- config + location /main { + echo "start"; + echo_foreach_split ',' $arg_cssfiles; + echo_end; + echo "end"; + } +--- request + GET /main?cssfiles=/foo.css,/bar.css,/baz.css +--- response_body +start +end + + + +=== TEST 5: trailing delimiter +--- config + location /main_t { + echo_foreach_split ',' $arg_cssfiles; + echo_location_async $echo_it; + echo_end; + } + location /foo.css { + echo foo; + } +--- request + GET /main_t?cssfiles=/foo.css, +--- response_body +foo + + + +=== TEST 6: multi-char delimiter +--- config + location /main_sleep { + echo_foreach_split '-a-' $arg_list; + echo $echo_it; + echo_end; + } +--- request + GET /main_sleep?list=foo-a-bar-a-baz +--- error_code: 500 +--- response_body_like: 500 Internal Server Error + + + +=== TEST 7: multi-char delimiter (the right way) +--- config + location /main_sleep { + echo_foreach_split -- '-a-' $arg_list; + echo $echo_it; + echo_end; + } +--- request + GET /main_sleep?list=foo-a-bar-a-baz +--- response_body +foo +bar +baz + + + +=== TEST 8: loop with sleep +--- config + location /main_sleep { + echo_foreach_split '-' $arg_list; + echo_sleep 0.001; + echo $echo_it; + echo_end; + } +--- request + GET /main_sleep?list=foo-a-bar-A-baz +--- response_body +foo +a +bar +A +baz + + + +=== TEST 9: empty +--- config + location /merge { + default_type 'text/javascript'; + echo_foreach_split '&' $query_string; + echo "/* JS File $echo_it */"; + echo_location_async $echo_it; + echo; + echo_end; + } +--- request + GET /merge +--- response_body + + + +=== TEST 10: single & +--- config + location /merge { + default_type 'text/javascript'; + echo_foreach_split '&' $query_string; + echo "/* JS File $echo_it */"; + echo_location_async $echo_it; + echo; + echo_end; + } +--- request + GET /merge?& +--- response_body + + + +=== TEST 11: pure &'s +--- config + location /merge { + default_type 'text/javascript'; + echo_foreach_split '&' $query_string; + echo "/* JS File $echo_it */"; + echo_location_async $echo_it; + echo; + echo_end; + } +--- request + GET /merge?&&& +--- response_body + + + +=== TEST 12: pure & and spaces +TODO: needs to uri_decode $echo_it... +--- config + location /merge { + default_type 'text/javascript'; + echo_foreach_split '&' $query_string; + echo "/* JS File $echo_it */"; + echo_location_async $echo_it; + echo; + echo_end; + } +--- request + GET /merge?&%20&%20& +--- response_body +--- SKIP + + + +=== TEST 13: multiple foreach_split +--- config + location /multi { + echo_foreach_split '&' $query_string; + echo [$echo_it]; + echo_end; + + echo '...'; + + echo_foreach_split '-' $query_string; + echo [$echo_it]; + echo_end; + } +--- request + GET /multi?a-b&c-d +--- response_body +[a-b] +[c-d] +... +[a] +[b&c] +[d] + + + +=== TEST 14: github issue #2: setting a variable from $echo_it results to crashing +--- config +location = /getFile { + set $filelist "a,b,c"; + echo_foreach_split ',' $filelist; + set $file $echo_it; + echo_subrequest GET '/getFile2' -q 'sha256=$file'; + echo_end; +} + +location = /getFile2 { + echo "sha256: $arg_sha256"; +} +--- request + GET /getFile +--- response_body +sha256: +sha256: +sha256: + diff --git a/echo-nginx-module/t/gzip.t b/echo-nginx-module/t/gzip.t new file mode 100644 index 00000000..61eb4f60 --- /dev/null +++ b/echo-nginx-module/t/gzip.t @@ -0,0 +1,31 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(1); + +plan tests => repeat_each() * 2 * blocks(); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /gzip { + gzip on; + gzip_min_length 10; + gzip_types text/plain; + + echo_duplicate 1000 hello; + } +--- request + GET /gzip +--- more_headers +Accept-Encoding: gzip +--- response_headers +Content-Encoding: gzip +--- timeout: 20 diff --git a/echo-nginx-module/t/if.t b/echo-nginx-module/t/if.t new file mode 100644 index 00000000..054ec437 --- /dev/null +++ b/echo-nginx-module/t/if.t @@ -0,0 +1,150 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 2 * blocks(); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity (hit) +--- config + location ^~ /if { + set $res miss; + if ($arg_val ~* '^a') { + set $res hit; + echo $res; + } + echo $res; + } +--- request + GET /if?val=abc +--- response_body +hit + + + +=== TEST 2: sanity (miss) +--- config + location ^~ /if { + set $res miss; + if ($arg_val ~* '^a') { + set $res hit; + echo $res; + } + echo $res; + } +--- request + GET /if?val=bcd +--- response_body +miss + + + +=== TEST 3: proxy in if (hit) +--- config + location ^~ /if { + set $res miss; + if ($arg_val ~* '^a') { + set $res hit; + proxy_pass $scheme://127.0.0.1:$server_port/foo?res=$res; + } + proxy_pass $scheme://127.0.0.1:$server_port/foo?res=$res; + } + location /foo { + echo "res = $arg_res"; + } +--- request + GET /if?val=abc +--- response_body +res = hit + + + +=== TEST 4: proxy in if (miss) +--- config + location ^~ /if { + set $res miss; + if ($arg_val ~* '^a') { + set $res hit; + proxy_pass $scheme://127.0.0.1:$server_port/foo?res=$res; + } + proxy_pass $scheme://127.0.0.1:$server_port/foo?res=$res; + } + location /foo { + echo "res = $arg_res"; + } +--- request + GET /if?val=bcd +--- response_body +res = miss + + + +=== TEST 5: if too long url (hit) +--- config + location /foo { + if ($request_uri ~ '.{20,}') { + echo too long; + } + echo ok; + } +--- request + GET /foo?a=12345678901234567890 +--- response_body +too long + + + +=== TEST 6: if too long url (miss) +--- config + location /foo { + if ($request_uri ~ '.{20,}') { + echo too long; + } + echo ok; + } +--- request + GET /foo?a=1234567890 +--- response_body +ok + + + +=== TEST 7: echo should be inherited by if blocks +--- config + location /foo { + if ($uri ~ 'foo') { + } + echo ok; + } +--- request + GET /foo +--- response_body +ok + + + +=== TEST 8: echo_after_body and echo_before_body should be inherited by if blocks +--- config + location /foo { + if ($uri ~ 'foo') { + } + echo_before_body -n 'hello'; + echo_location /comma; + echo_after_body 'world'; + } + + location = /comma { + internal; + echo -n ', '; + } +--- request + GET /foo +--- response_body +hello, world + diff --git a/echo-nginx-module/t/incr.t b/echo-nginx-module/t/incr.t new file mode 100644 index 00000000..8ad6d98d --- /dev/null +++ b/echo-nginx-module/t/incr.t @@ -0,0 +1,32 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 2 * blocks(); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /main { + echo "main pre: $echo_incr"; + echo_location_async /sub; + echo_location_async /sub; + echo "main post: $echo_incr"; + } + location /sub { + echo "sub: $echo_incr"; + } +--- request + GET /main +--- response_body +main pre: 1 +sub: 3 +sub: 4 +main post: 2 + diff --git a/echo-nginx-module/t/location-async.t b/echo-nginx-module/t/location-async.t new file mode 100644 index 00000000..3494516c --- /dev/null +++ b/echo-nginx-module/t/location-async.t @@ -0,0 +1,439 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (2 * blocks() + 1); + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /main { + echo_location_async /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +hello + + + +=== TEST 2: trailing echo +--- config + location /main { + echo_location_async /sub; + echo after subrequest; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +hello +after subrequest + + + +=== TEST 3: leading echo +--- config + location /main { + echo before subrequest; + echo_location_async /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before subrequest +hello + + + +=== TEST 4: leading & trailing echo +--- config + location /main { + echo before subrequest; + echo_location_async /sub; + echo after subrequest; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before subrequest +hello +after subrequest + + + +=== TEST 5: multiple subrequests +--- config + location /main { + echo before sr 1; + echo_location_async /sub; + echo after sr 1; + echo before sr 2; + echo_location_async /sub; + echo after sr 2; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before sr 1 +hello +after sr 1 +before sr 2 +hello +after sr 2 + + + +=== TEST 6: timed multiple subrequests (blocking sleep) +--- config + location /main { + echo_reset_timer; + echo_location_async /sub1; + echo_location_async /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_blocking_sleep 0.02; + echo hello; + } + location /sub2 { + echo_blocking_sleep 0.01; + echo world; + } + +--- request + GET /main +--- response_body_like +^hello +world +took 0\.00[0-5] sec for total\.$ + + + +=== TEST 7: timed multiple subrequests (non-blocking sleep) +--- config + location /main { + echo_reset_timer; + echo_location_async /sub1; + echo_location_async /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_sleep 0.02; + echo hello; + } + location /sub2 { + echo_sleep 0.01; + echo world; + } + +--- request + GET /main +--- response_body_like +^hello +world +took 0\.00[0-5] sec for total\.$ + + + +=== TEST 8: location with args +--- config + location /main { + echo_location_async /sub 'foo=Foo&bar=Bar'; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +Foo Bar + + + +=== TEST 9: encoded chars in query strings +--- config + location /main { + echo_location_async /sub 'foo=a%20b&bar=Bar'; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +a%20b Bar + + + +=== TEST 10: UTF-8 chars in query strings +--- config + location /main { + echo_location_async /sub 'foo=你好'; + } + location /sub { + echo $arg_foo; + } +--- request + GET /main +--- response_body +你好 + + + +=== TEST 11: encoded chars in location url +--- config + location /main { + echo_location_async /sub%31 'foo=Foo&bar=Bar'; + } + location /sub%31 { + echo 'sub%31'; + } + location /sub1 { + echo 'sub1'; + } +--- request + GET /main +--- response_body +sub1 + + + +=== TEST 12: querystring in url +--- config + location /main { + echo_location_async /sub?foo=Foo&bar=Bar; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +Foo Bar + + + +=== TEST 13: querystring in url *AND* an explicit querystring +--- config + location /main { + echo_location_async /sub?foo=Foo&bar=Bar blah=Blah; + } + location /sub { + echo $arg_foo $arg_bar $arg_blah; + } +--- request + GET /main +--- response_body + Blah + + + +=== TEST 14: explicit flush in main request +flush won't really flush the buffer... +--- config + location /main_flush { + echo 'pre main'; + echo_location_async /sub; + echo 'post main'; + echo_flush; + } + + location /sub { + echo_sleep 0.02; + echo 'sub'; + } +--- request + GET /main_flush +--- response_body +pre main +sub +post main + + + +=== TEST 15: no varaiable inheritance +--- config + location /main { + echo $echo_cacheable_request_uri; + echo_location_async /sub; + echo_location_async /sub2; + } + location /sub { + echo $echo_cacheable_request_uri; + } + location /sub2 { + echo $echo_cacheable_request_uri; + } + +--- request + GET /main +--- response_body +/main +/sub +/sub2 + + + +=== TEST 16: unsafe uri +--- config + location /unsafe { + echo_location_async '/../foo'; + } +--- request + GET /unsafe +--- stap2 +F(ngx_http_send_header) { + printf("send header on req %p (header sent: %d)\n", $r, $r->header_sent) + print_ubacktrace() +} +--- ignore_response +--- error_log +echo_location_async sees unsafe uri: "/../foo" +--- no_error_log +[error] +[alert] + + + +=== TEST 17: access/deny (access phase handlers skipped in subrequests) +--- config + location /main { + echo_location_async /denied; + } + location /denied { + deny all; + echo No no no; + } +--- request + GET /main +--- error_code: 200 +--- response_body +No no no + + + +=== TEST 18: rewrite is honored. +--- config + location /main { + echo_location_async /rewrite; + } + location /rewrite { + rewrite ^ /foo break; + echo $uri; + } +--- request + GET /main +--- response_body +/foo + + + +=== TEST 19: let subrequest to read the main request's request body +--- SKIP +--- config + location /main { + echo_location_async /sub; + } + location /sub { + echo_read_request_body; + echo_request_body; + } +--- request +POST /main +hello, body! +--- response_body chomp +hello, body! + + + +=== TEST 20: leading subrequest & echo_before_body +--- config + location /main { + echo_before_body hello; + echo_location_async /foo; + } + location /foo { + echo world; + } +--- request + GET /main +--- response_body +hello +world + + + +=== TEST 21: leading subrequest & xss +--- config + location /main { + default_type 'application/json'; + xss_get on; + xss_callback_arg c; + echo_location_async /foo; + } + location /foo { + echo -n world; + } +--- request + GET /main?c=hi +--- response_body chop +hi(world); + + + +=== TEST 22: multiple leading subrequest & xss +--- config + location /main { + default_type 'application/json'; + xss_get on; + xss_callback_arg c; + echo_location_async /foo; + echo_location_async /bar; + } + location /foo { + echo -n world; + } + location /bar { + echo -n ' people'; + } +--- request + GET /main?c=hi +--- response_body chop +hi(world people); + + + +=== TEST 23: sanity (HEAD) +--- config + location /main { + echo_location_async /sub; + echo_location_async /sub; + } + location /sub { + echo hello; + } +--- request + HEAD /main +--- response_body + diff --git a/echo-nginx-module/t/location.t b/echo-nginx-module/t/location.t new file mode 100644 index 00000000..48c851ea --- /dev/null +++ b/echo-nginx-module/t/location.t @@ -0,0 +1,567 @@ +# vi:filetype= + +use lib 'lib'; + +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (2 * blocks() + 2); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +#no_diff(); + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /main { + echo_location /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +hello + + + +=== TEST 2: sanity with proxy in the middle +--- config + location /main { + echo_location /proxy; + } + location /proxy { + proxy_pass $scheme://127.0.0.1:$server_port/sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +hello + + + +=== TEST 3: trailing echo +--- config + location /main { + echo_location /sub; + echo after subrequest; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +hello +after subrequest + + + +=== TEST 4: leading echo +--- config + location /main { + echo before subrequest; + echo_location /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before subrequest +hello + + + +=== TEST 5: leading & trailing echo +--- config + location /main { + echo before subrequest; + echo_location /sub; + echo after subrequest; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before subrequest +hello +after subrequest + + + +=== TEST 6: multiple subrequests +--- config + location /main { + echo before sr 1; + echo_location /sub; + echo after sr 1; + echo before sr 2; + echo_location /sub; + echo after sr 2; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before sr 1 +hello +after sr 1 +before sr 2 +hello +after sr 2 + + + +=== TEST 7: timed multiple subrequests (blocking sleep) +--- config + location /main { + echo_reset_timer; + echo_location /sub1; + echo_location /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_blocking_sleep 0.02; + echo hello; + } + location /sub2 { + echo_blocking_sleep 0.01; + echo world; + } + +--- request + GET /main +--- response_body_like +^hello +world +took 0\.0(?:2[5-9]|3[0-6]) sec for total\.$ + + + +=== TEST 8: timed multiple subrequests (non-blocking sleep) +--- config + location /main { + echo_reset_timer; + echo_location /sub1; + echo_location /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_sleep 0.02; + echo hello; + } + location /sub2 { + echo_sleep 0.01; + echo world; + } + +--- request + GET /main +--- response_body_like +^hello +world +took 0\.0(?:2[5-9]|3[0-6]) sec for total\.$ + + + +=== TEST 9: location with args +--- config + location /main { + echo_location /sub 'foo=Foo&bar=Bar'; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +Foo Bar + + + +=== TEST 10: chained subrequests +--- config + location /main { + echo 'pre main'; + echo_location /sub; + echo 'post main'; + } + + location /sub { + echo 'pre sub'; + echo_location /subsub; + echo 'post sub'; + } + + location /subsub { + echo 'subsub'; + } +--- request + GET /main +--- response_body +pre main +pre sub +subsub +post sub +post main + + + +=== TEST 11: chained subrequests using named locations +as of 0.8.20, ngx_http_subrequest still does not support +named location. sigh. this case is a TODO. +--- config + location /main { + echo 'pre main'; + echo_location @sub; + echo 'post main'; + } + + location @sub { + echo 'pre sub'; + echo_location @subsub; + echo 'post sub'; + } + + location @subsub { + echo 'subsub'; + } +--- request + GET /main +--- response_body +pre main +pre sub +subsub +post sub +post main +--- SKIP + + + +=== TEST 12: explicit flush in main request +--- config + location /main { + echo 'pre main'; + echo_location /sub; + echo 'post main'; + echo_flush; + } + + location /sub { + echo_sleep 0.02; + echo 'sub'; + } +--- request + GET /main +--- response_body +pre main +sub +post main + + + +=== TEST 13: no varaiable inheritance +--- config + location /main { + echo $echo_cacheable_request_uri; + echo_location /sub; + echo_location /sub2; + } + location /sub { + echo $echo_cacheable_request_uri; + } + location /sub2 { + echo $echo_cacheable_request_uri; + } + +--- request + GET /main +--- response_body +/main +/sub +/sub2 + + + +=== TEST 14: unsafe uri +--- config + location /unsafe { + echo_location '/../foo'; + } +--- request + GET /unsafe +--- ignore_response +--- error_log +echo_location sees unsafe uri: "/../foo" +--- no_error_log +[error] +[alert] + + + +=== TEST 15: querystring in url +--- config + location /main { + echo_location /sub?foo=Foo&bar=Bar; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +Foo Bar + + + +=== TEST 16: querystring in url *AND* an explicit querystring +--- config + location /main { + echo_location /sub?foo=Foo&bar=Bar blah=Blah; + } + location /sub { + echo $arg_foo $arg_bar $arg_blah; + } +--- request + GET /main +--- response_body + Blah + + + +=== TEST 17: let subrequest to read the main request's request body +--- SKIP +--- config + location /main { + echo_location /sub; + } + location /sub { + echo_read_request_body; + echo_request_body; + } +--- request +POST /main +hello, body! +--- response_body chomp +hello, body! + + + +=== TEST 18: sleep after location +--- config + location /main { + echo_location /sub; + echo_sleep 0.001; + echo_location /sub; + } + location /sub { + echo_sleep 0.001; + echo sub; + } +--- request + GET /main +--- response_body +sub +sub +--- skip_nginx: 2: < 0.8.11 + + + +=== TEST 19: deep nested echo_location/echo_location_async +--- config + location /main { + echo_location /bar; + echo_location_async /bar; + echo_location_async /bar; + echo_location /group; + echo_location_async /group; + } + + location /group { + echo_location /bar; + echo_location_async /bar; + } + + location /bar { + #echo_sleep 0.001; + echo $echo_incr; + } +--- request +GET /main +--- response_body +1 +2 +3 +4 +5 +6 +7 +--- timeout: 2 + + + +=== TEST 20: deep nested echo_location/echo_location_async (with sleep) +--- config + location /main { + echo_location /bar; + echo_location_async /bar; + echo_location_async /bar; + echo_location /group; + echo_location_async /group; + } + + location /group { + echo_location /baz; + echo_location_async /bah; + } + + location ~ '^/ba[rzh]' { + echo_sleep 0.001; + echo $echo_incr; + } +--- request +GET /main +--- response_body +1 +2 +3 +4 +5 +6 +7 +--- timeout: 2 + + + +=== TEST 21: deep nested echo_location (with sleep) +--- config + location /main { + echo_location /bar; + echo_location /bar; + echo_location /bar; + echo_location /group; + echo_location /group; + } + + location /group { + echo_location /bar; + echo_location /bar; + } + + location /incr { + echo_sleep 0.001; + echo $echo_incr; + } + + location /bar { + proxy_pass $scheme://127.0.0.1:$server_port/incr; + } +--- request +GET /main +--- response_body +1 +1 +1 +1 +1 +1 +1 +--- timeout: 5 +--- no_error_log +[error] + + + +=== TEST 22: leading subrequest & echo_before_body +--- config + location /main { + echo_before_body hello; + echo_location /foo; + } + location /foo { + echo world; + } +--- request + GET /main +--- response_body +hello +world + + + +=== TEST 23: leading subrequest & xss +--- config + location /main { + default_type 'application/json'; + xss_get on; + xss_callback_arg c; + echo_location /foo; + } + location /foo { + echo -n world; + } +--- request + GET /main?c=hi +--- response_body chop +hi(world); + + + +=== TEST 24: multiple leading subrequest & xss +--- config + location /main { + default_type 'application/json'; + xss_get on; + xss_callback_arg c; + echo_location /foo; + echo_location /bar; + } + location /main2 { + content_by_lua ' + local res = ngx.location.capture("/foo") + local res2 = ngx.location.capture("/bar") + ngx.say(res.body) + ngx.say(res2.body) + '; + } + location /foo { + echo -n world; + } + location /bar { + echo -n ' people'; + } +--- request + GET /main?c=hi +--- response_body chop +hi(world people); + + + +=== TEST 25: sanity (HEAD) +--- config + location /main { + echo_location /sub; + echo_location /sub; + } + location /sub { + echo hello; + } +--- request + HEAD /main +--- response_body + diff --git a/echo-nginx-module/t/mixed.t b/echo-nginx-module/t/mixed.t new file mode 100644 index 00000000..abf25997 --- /dev/null +++ b/echo-nginx-module/t/mixed.t @@ -0,0 +1,82 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 2 * blocks(); + +run_tests(); + +__DATA__ + +=== TEST 1: echo before echo_client_request_headers +--- config + location /echo { + echo "headers:"; + echo -n $echo_client_request_headers; + } +--- request + GET /echo +--- response_body eval +"headers: +GET /echo HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +" + + + +=== TEST 2: echo_client_request_headers before echo +--- config + location /echo { + echo -n $echo_client_request_headers; + echo "...these are the headers"; + } +--- request + GET /echo +--- response_body eval +"GET /echo HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +...these are the headers +" + + + +=== TEST 3: echo & headers & echo +--- config + location /echo { + echo "headers are"; + echo -n $echo_client_request_headers; + echo "...these are the headers"; + } +--- request + GET /echo +--- response_body eval +"headers are +GET /echo HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +...these are the headers +" + + + +=== TEST 4: mixed with echo_duplicate +--- config + location /mixed { + echo hello; + echo_duplicate 2 ---; + echo_duplicate 1 ' END '; + echo_duplicate 2 ---; + echo; + } +--- request + GET /mixed +--- response_body +hello +------ END ------ + diff --git a/echo-nginx-module/t/request-body.t b/echo-nginx-module/t/request-body.t new file mode 100644 index 00000000..d467b2ed --- /dev/null +++ b/echo-nginx-module/t/request-body.t @@ -0,0 +1,58 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * 2 * blocks(); + +run_tests(); + +__DATA__ + +=== TEST 1: big client body buffered into temp files +--- config + location /echo { + client_body_buffer_size 1k; + echo_read_request_body; + echo_request_body; + } +--- request eval +"POST /echo +" . 'a' x 4096 . 'end'; +--- response_body eval +'a' x 4096 . 'end' + + + +=== TEST 2: in memory request body (trailing echo) +--- config + location /echo { + client_body_buffer_size 1k; + echo_read_request_body; + echo_request_body; + echo done; + } +--- request +POST /echo +hello world +--- response_body +hello worlddone + + + +=== TEST 3: big client body buffered into temp files (trailing echo) +--- config + location /echo { + client_body_buffer_size 1k; + echo_read_request_body; + echo_request_body; + echo done; + } +--- request eval +"POST /echo +" . 'a' x 4096 . "end\n"; +--- response_body eval +'a' x 4096 . "enddone\n" + diff --git a/echo-nginx-module/t/request-info.t b/echo-nginx-module/t/request-info.t new file mode 100644 index 00000000..8fd015ed --- /dev/null +++ b/echo-nginx-module/t/request-info.t @@ -0,0 +1,841 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (3 * blocks() + 15); + +run_tests(); + +__DATA__ + +=== TEST 1: standalone directive +--- config + location /echo { + echo -n $echo_client_request_headers; + } +--- request + GET /echo +--- response_body eval +"GET /echo HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +" +--- no_error_log +[error] + + + +=== TEST 2: multiple instances +--- config + location /echo { + echo -n $echo_client_request_headers; + echo -n $echo_client_request_headers; + } +--- request + GET /echo +--- response_body eval +"GET /echo HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +GET /echo HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +" +--- no_error_log +[error] + + + +=== TEST 3: does not explicitly request_body +--- config + location /echo { + echo [$echo_request_body]; + } +--- request +POST /echo +body here +heh +--- response_body +[] +--- no_error_log +[error] + + + +=== TEST 4: let proxy read request_body +--- config + location /echo { + echo_before_body [$echo_request_body]; + proxy_pass $scheme://127.0.0.1:$server_port/blah; + } + location /blah { echo_duplicate 0 ''; } +--- request +POST /echo +body here +heh +--- response_body +[body here +heh] +--- no_error_log +[error] + + + +=== TEST 5: use echo_read_request_body to read it! +--- config + location /echo { + echo_read_request_body; + echo [$echo_request_body]; + } +--- request +POST /echo +body here +heh +--- response_body +[body here +heh] +--- no_error_log +[error] + + + +=== TEST 6: how about sleep after that? +--- config + location /echo { + echo_read_request_body; + echo_sleep 0.002; + echo [$echo_request_body]; + } +--- request +POST /echo +body here +heh +--- response_body +[body here +heh] +--- no_error_log +[error] + + + +=== TEST 7: echo back the whole client request +--- config + # echo back the client request + location /echoback { + echo -n $echo_client_request_headers; + echo_read_request_body; + echo $echo_request_body; + } +--- request +POST /echoback +body here +haha +--- response_body eval +"POST /echoback HTTP/1.1\r +Host: localhost\r +Connection: close\r +Content-Length: 14\r +\r +body here +haha +" +--- no_error_log +[error] + + + +=== TEST 8: echo_request_body +--- config + location /body { + client_body_buffer_size 5; + echo_read_request_body; + echo "[$echo_request_body]"; + echo_request_body; + } +--- request eval +"POST /body +" . ('a' x 2048) . "b" +--- response_body eval +"[]\n" . +('a' x 2048) . "b" +--- no_error_log +[error] + + + +=== TEST 9: $echo_response_status in content handler +--- config + location /status { + echo "status: $echo_response_status"; + } +--- request + GET /status +--- response_body +status: +--- no_error_log +[error] + + + +=== TEST 10: echo_request_body (empty body) +--- config + location /body { + echo_read_request_body; + echo_request_body; + } + location /main { + proxy_pass http://127.0.0.1:$server_port/body; + } +--- request eval +"POST /main" +--- response_body eval +"" +--- no_error_log +[error] + + + +=== TEST 11: small header +--- config + location /t { + echo -n $echo_client_request_headers; + } +--- request +GET /t +--- response_body eval +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +} +--- no_error_log +[error] +--- no_error_log +[error] + + + +=== TEST 12: large header +--- config + client_header_buffer_size 10; + large_client_header_buffers 30 561; + location /t { + echo -n $echo_client_request_headers; + } +--- request +GET /t +--- more_headers eval +CORE::join "\n", map { "Header$_: value-$_" } 1..512 + +--- response_body eval +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_" } 1..512) . "\r\n\r\n" + +--- no_error_log +[error] + + + +=== TEST 13: small header, with leading CRLF +--- config + location /t { + echo -n $echo_client_request_headers; + } +--- raw_request eval +"\r\nGET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +" +--- response_body eval +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +} +--- no_error_log +[error] + + + +=== TEST 14: large header, with leading CRLF +--- config + client_header_buffer_size 10; + large_client_header_buffers 30 561; + location /t { + echo -n $echo_client_request_headers; + } + +--- raw_request eval +"\r\nGET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +". +(CORE::join "\r\n", map { "Header$_: value-$_" } 1..512) . "\r\n\r\n" + +--- response_body eval +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_" } 1..512) . "\r\n\r\n" + +--- no_error_log +[error] + + + +=== TEST 15: small header, pipelined +--- config + location /t { + echo -n $echo_client_request_headers; + } +--- pipelined_requests eval +["GET /t", "GET /th"] + +--- more_headers +Foo: bar + +--- response_body eval +[qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: keep-alive\r +Foo: bar\r +\r +}, qq{GET /th HTTP/1.1\r +Host: localhost\r +Connection: close\r +Foo: bar\r +\r +}] +--- no_error_log +[error] + + + +=== TEST 16: large header, pipelined +--- config + client_header_buffer_size 10; + large_client_header_buffers 30 561; + location /t { + echo -n $echo_client_request_headers; + } +--- pipelined_requests eval +["GET /t", "GET /t"] + +--- more_headers eval +CORE::join "\n", map { "Header$_: value-$_" } 1..512 + +--- response_body eval +my $headers = (CORE::join "\r\n", map { "Header$_: value-$_" } 1..512) . "\r\n\r\n"; + +[qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: keep-alive\r +$headers}, +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +$headers}] + +--- no_error_log +[error] + + + +=== TEST 17: small header, multi-line header +--- config + location /t { + echo -n $echo_client_request_headers; + } +--- raw_request eval +"GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +Foo: bar baz\r + blah\r +\r +" +--- response_body eval +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +Foo: bar baz\r + blah\r +\r +} +--- no_error_log +[error] + + + +=== TEST 18: large header, multi-line header +--- config + client_header_buffer_size 10; + large_client_header_buffers 50 567; + location /t { + echo -n $echo_client_request_headers; + } + +--- raw_request eval +my $headers = (CORE::join "\r\n", map { "Header$_: value-$_\r\n hello $_ world blah blah" } 1..512) . "\r\n\r\n"; + +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +$headers} + +--- response_body eval +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_\r\n hello $_ world blah blah" } 1..512) . "\r\n\r\n" + +--- no_error_log +[error] + + + +=== TEST 19: small header (POST body) +--- config + location /t { + echo_read_request_body; + echo -n $echo_client_request_headers; + } +--- request +POST /t +hello +--- response_body eval +qq{POST /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +Content-Length: 5\r +\r +} +--- no_error_log +[error] + + + +=== TEST 20: small header (POST body) - in subrequests (location) +--- config + location /t { + echo -n $echo_client_request_headers; + } + location /main { + echo_location /t; + } + +--- request +POST /main +hello +--- response_body eval +qq{POST /main HTTP/1.1\r +Host: localhost\r +Connection: close\r +Content-Length: 5\r +\r +} +--- no_error_log +[error] + + + +=== TEST 21: large header (POST body) +--- config + client_header_buffer_size 10; + large_client_header_buffers 30 561; + location /t { + echo_read_request_body; + echo -n $echo_client_request_headers; + } +--- request +POST /t +hello + +--- more_headers eval +CORE::join"\n", map { "Header$_: value-$_" } 1..512 + +--- response_body eval +qq{POST /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_" } 1..512) . "\r\nContent-Length: 5\r\n\r\n" + +--- no_error_log +[error] +--- timeout: 5 + + + +=== TEST 22: large header (POST body) - in subrequests +--- config + client_header_buffer_size 10; + large_client_header_buffers 30 561; + location /t { + echo_read_request_body; + echo -n $echo_client_request_headers; + } + + location /main { + echo_location /t; + } +--- request +POST /main +hello +--- more_headers eval +CORE::join"\n", map { "Header$_: value-$_" } 1..512 + +--- response_body eval +qq{POST /main HTTP/1.1\r +Host: localhost\r +Connection: close\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_" } 1..512) . "\r\nContent-Length: 5\r\n\r\n" + +--- no_error_log +[error] +--- timeout: 5 + + + +=== TEST 23: raw headers - the default header buffer can hold the request line, but not the header entries +--- config + location /t { + echo_read_request_body; + echo -n $echo_client_request_headers; + } +--- request +GET /t +--- more_headers eval +my $s = "User-Agent: curl\nBah: bah\n"; +$s .= "Accept: */*\n"; +$s .= "Cookie: " . "C" x 1200 . "\n"; +$s +--- response_body eval +"GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +User-Agent: curl\r +Bah: bah\r +Accept: */*\r +Cookie: " . ("C" x 1200) . "\r\n\r\n" +--- no_error_log +[error] + + + +=== TEST 24: small header (POST body) - in subrequests (location_async) +--- config + location /t { + echo -n $echo_client_request_headers; + } + location /main { + echo_location_async /t; + } + +--- request +POST /main +hello +--- response_body eval +qq{POST /main HTTP/1.1\r +Host: localhost\r +Connection: close\r +Content-Length: 5\r +\r +} +--- no_error_log +[error] + + + +=== TEST 25: small header (POST body) - in subrequests (subrequest) +--- config + location /t { + echo -n $echo_client_request_headers; + } + location /main { + echo_subrequest GET /t; + } + +--- request +POST /main +hello +--- response_body eval +qq{POST /main HTTP/1.1\r +Host: localhost\r +Connection: close\r +Content-Length: 5\r +\r +} +--- no_error_log +[error] + + + +=== TEST 26: small header (POST body) - in subrequests (subrequest_async) +--- config + location /t { + echo -n $echo_client_request_headers; + } + location /main { + echo_subrequest_async GET /t; + } + +--- request +POST /main +hello +--- response_body eval +qq{POST /main HTTP/1.1\r +Host: localhost\r +Connection: close\r +Content-Length: 5\r +\r +} +--- no_error_log +[error] + + + +=== TEST 27: ngx_proxy/ngx_fastcgi/etc change r->header_end to point to their own buffers +--- config + location = /t { + proxy_buffering off; + proxy_pass http://127.0.0.1:$server_port/bad; + proxy_intercept_errors on; + error_page 500 = /500; + } + + location = /bad { + return 500; + } + + location = /500 { + echo -n $echo_client_request_headers; + } +--- request +GET /t +--- response_body eval +"GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +\r +" +--- no_error_log +[error] + + + +=== TEST 28: ngx_proxy/ngx_fastcgi/etc change r->header_end to point to their own buffers (exclusive LF in the request data) +--- config + location = /t { + proxy_buffering off; + proxy_pass http://127.0.0.1:$server_port/bad; + proxy_intercept_errors on; + error_page 500 = /500; + } + + location = /bad { + return 500; + } + + location = /500 { + internal; + echo -n $echo_client_request_headers; + } +--- raw_request eval +"GET /t HTTP/1.1 +Host: localhost +Connection: close +Content-Length: 5 + +hello" +--- response_body eval +"GET /t HTTP/1.1 +Host: localhost +Connection: close +Content-Length: 5 + +" +--- no_error_log +[error] + + + +=== TEST 29: ngx_proxy/ngx_fastcgi/etc change r->header_end to point to their own buffers (mixed LF and CRLF in the request data) +--- config + location = /t { + proxy_buffering off; + proxy_pass http://127.0.0.1:$server_port/bad; + proxy_intercept_errors on; + error_page 500 = /500; + } + + location = /bad { + return 500; + } + + location = /500 { + internal; + echo -n $echo_client_request_headers; + } +--- raw_request eval +"GET /t HTTP/1.1\r +Host: localhost +Connection: close\r +Content-Length: 5\r + +hello" +--- response_body eval +"GET /t HTTP/1.1\r +Host: localhost +Connection: close\r +Content-Length: 5\r + +" +--- no_error_log +[error] + + + +=== TEST 30: ngx_proxy/ngx_fastcgi/etc change r->header_end to point to their own buffers (another way of mixing LF and CRLF in the request data) +--- config + location = /t { + proxy_buffering off; + proxy_pass http://127.0.0.1:$server_port/bad; + proxy_intercept_errors on; + error_page 500 = /500; + } + + location = /bad { + return 500; + } + + location = /500 { + internal; + echo -n $echo_client_request_headers; + } +--- raw_request eval +"GET /t HTTP/1.1\r +Host: localhost +Connection: close\r +Content-Length: 5 +\r +hello" +--- response_body eval +"GET /t HTTP/1.1\r +Host: localhost +Connection: close\r +Content-Length: 5 +\r +" +--- no_error_log +[error] + + + +=== TEST 31: two pipelined requests with large headers +--- config + client_header_buffer_size 10; + large_client_header_buffers 3 5610; + location /t { + echo -n $echo_client_request_headers; + } +--- pipelined_requests eval +["GET /t", "GET /t"] +--- more_headers eval +CORE::join "\n", map { "Header$_: value-$_" } 1..585 + +--- response_body eval +[qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: keep-alive\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_" } 1..585) . "\r\n\r\n", +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_" } 1..585) . "\r\n\r\n", +, +] + +--- no_error_log +[error] +--- timeout: 5 + + + +=== TEST 32: a request with large header and a smaller pipelined request following +--- config + client_header_buffer_size 10; + large_client_header_buffers 2 1921; + location /t { + echo -n $echo_client_request_headers; + } +--- pipelined_requests eval +["GET /t", "GET /t"] +--- more_headers eval +[CORE::join("\n", map { "Header$_: value-$_" } 1..170), "Foo: bar\n"] + +--- response_body eval +[qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: keep-alive\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_" } 1..170) . "\r\n\r\n", +qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +Foo: bar\r +\r +}, +] + +--- no_error_log +[error] +--- timeout: 5 + + + +=== TEST 33: a request with large header and a smaller pipelined request following +--- config + client_header_buffer_size 10; + large_client_header_buffers 2 1921; + location /t { + echo -n $echo_client_request_headers; + } +--- pipelined_requests eval +["GET /t", "GET /t" . ("a" x 512)] +--- more_headers eval +[CORE::join("\n", map { "Header$_: value-$_" } 1..170), "Foo: bar\n"] + +--- response_body eval +[qq{GET /t HTTP/1.1\r +Host: localhost\r +Connection: keep-alive\r +} +.(CORE::join "\r\n", map { "Header$_: value-$_" } 1..170) . "\r\n\r\n", +qq{GET /t} . ("a" x 512) . qq{ HTTP/1.1\r +Host: localhost\r +Connection: close\r +Foo: bar\r +\r +}, +] + +--- no_error_log +[error] +--- timeout: 5 + diff --git a/echo-nginx-module/t/sleep.t b/echo-nginx-module/t/sleep.t new file mode 100644 index 00000000..f8e741ed --- /dev/null +++ b/echo-nginx-module/t/sleep.t @@ -0,0 +1,200 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 2 * blocks(); + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /echo { + echo_sleep 1; + } +--- request + GET /echo +--- response_body + + + +=== TEST 2: fractional delay +--- config + location /echo { + echo_sleep 0.01; + } +--- request + GET /echo +--- response_body + + + +=== TEST 3: leading echo +--- config + location /echo { + echo before...; + echo_sleep 0.01; + } +--- request + GET /echo +--- response_body +before... + + + +=== TEST 4: trailing echo +--- config + location /echo { + echo_sleep 0.01; + echo after...; + } +--- request + GET /echo +--- response_body +after... + + + +=== TEST 5: two echos around sleep +--- config + location /echo { + echo before...; + echo_sleep 0.01; + echo after...; + } +--- request + GET /echo +--- response_body +before... +after... + + + +=== TEST 6: interleaving sleep and echo +--- config + location /echo { + echo 1; + echo_sleep 0.01; + echo 2; + echo_sleep 0.01; + } +--- request + GET /echo +--- response_body +1 +2 + + + +=== TEST 7: interleaving sleep and echo with echo at the end... +--- config + location /echo { + echo 1; + echo_sleep 0.01; + echo 2; + echo_sleep 0.01; + echo 3; + } +--- request + GET /echo +--- response_body +1 +2 +3 + + + +=== TEST 8: flush before sleep +we didn't really test the actual effect of "echo_flush" here... +merely checks if it croaks if appears. +--- config + location /flush { + echo hi; + echo_flush; + echo_sleep 0.01; + echo trees; + } +--- request + GET /flush +--- response_body +hi +trees + + + +=== TEST 9: flush does not increment opcode pointer itself +--- config + location /flush { + echo hi; + echo_flush; + echo trees; + } +--- request + GET /flush +--- response_body +hi +trees + + + +=== TEST 10: sleep through a proxy +this reveals a bug in v0.19 and the bug is fixed in v0.20. +--- config + location /proxy { + proxy_pass $scheme://127.0.0.1:$server_port/entry'; + } + location /entry { + echo_sleep 0.001; + echo done; + } +--- request + GET /proxy +--- response_body_like +done + + + +=== TEST 11: abnormally quit +--- config + location /quit { + echo before; + echo_flush; + echo_sleep 1; + echo after; + } +--- request + GET /quit +--- response_body +before +after + + + +=== TEST 12: two echos around sleep (HEAD) +--- config + location /echo { + echo before...; + echo_sleep 0.01; + echo after...; + } +--- request + HEAD /echo +--- response_body + + + +=== TEST 13: sleep by variable +--- config + location ~ ^/sleep/(.+) { + echo before...; + echo_sleep $1; + echo after...; + } +--- request + GET /sleep/0.01 +--- response_body +before... +after... + diff --git a/echo-nginx-module/t/status.t b/echo-nginx-module/t/status.t new file mode 100644 index 00000000..d97b0841 --- /dev/null +++ b/echo-nginx-module/t/status.t @@ -0,0 +1,142 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(1); + +plan tests => repeat_each() * (2 * blocks()); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +run_tests(); + +__DATA__ + +=== TEST 1: 200 +--- config + location /echo { + echo_status 200; + echo hello; + } +--- request + GET /echo +--- response_body +hello +--- error_code: 200 + + + +=== TEST 2: if location (200) +--- config + location /echo { + set $true 1; + if ($true) { + } + echo_status 200; + echo hello; + } +--- request + GET /echo +--- response_body +hello +--- error_code: 200 + + + +=== TEST 3: 404 +--- config + location /echo { + echo_status 404; + echo hello; + } +--- request + GET /echo +--- response_body +hello +--- error_code: 404 + + + +=== TEST 4: if location (404) +--- config + location /echo { + set $true 1; + if ($true) { + } + echo_status 404; + echo hello; + } +--- request + GET /echo +--- response_body +hello +--- error_code: 404 + + + +=== TEST 5: 500 +--- config + location /echo { + echo_status 500; + echo hello; + } +--- request + GET /echo +--- response_body +hello +--- error_code: 500 + + + +=== TEST 6: if location (500) +--- config + location /echo { + set $true 1; + if ($true) { + } + echo_status 500; + echo hello; + } +--- request + GET /echo +--- response_body +hello +--- error_code: 500 + + + +=== TEST 7: if location (500) no inherit +--- config + location /echo { + set $true 1; + if ($true) { + echo_status 503; + } + echo_status 500; + echo hello; + } +--- request + GET /echo +--- response_body +hello +--- error_code: 503 + + + +=== TEST 8: subrequest +--- config + location /echo { + echo_location /sub; + echo_status 503; + } + + location /sub { + echo blah blah; + } +--- request + GET /echo +--- response_body +blah blah +--- error_code: 503 + diff --git a/echo-nginx-module/t/subrequest-async.t b/echo-nginx-module/t/subrequest-async.t new file mode 100644 index 00000000..882b3684 --- /dev/null +++ b/echo-nginx-module/t/subrequest-async.t @@ -0,0 +1,604 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (blocks() * 2 + 1); + +#$Test::Nginx::LWP::LogLevel = 'debug'; + +$ENV{TEST_NGINX_HTML_DIR} = html_dir; + +run_tests(); + +__DATA__ + +=== TEST 1: sanity - GET +--- config + location /main { + echo_subrequest_async GET /sub; + } + location /sub { + echo "sub method: $echo_request_method"; + echo "main method: $echo_client_request_method"; + } +--- request + GET /main +--- response_body +sub method: GET +main method: GET + + + +=== TEST 2: sanity - DELETE +--- config + location /main { + echo_subrequest_async DELETE /sub; + } + location /sub { + echo "sub method: $echo_request_method"; + echo "main method: $echo_client_request_method"; + } +--- request + GET /main +--- response_body +sub method: DELETE +main method: GET + + + +=== TEST 3: trailing echo +--- config + location /main { + echo_subrequest_async GET /sub; + echo after subrequest; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +hello +after subrequest + + + +=== TEST 4: leading echo +--- config + location /main { + echo before subrequest; + echo_subrequest_async GET /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before subrequest +hello + + + +=== TEST 5: leading & trailing echo +--- config + location /main { + echo before subrequest; + echo_subrequest_async GET /sub; + echo after subrequest; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before subrequest +hello +after subrequest + + + +=== TEST 6: multiple subrequests +--- config + location /main { + echo before sr 1; + echo_subrequest_async GET /sub; + echo after sr 1; + echo before sr 2; + echo_subrequest_async GET /sub; + echo after sr 2; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before sr 1 +hello +after sr 1 +before sr 2 +hello +after sr 2 + + + +=== TEST 7: timed multiple subrequests (blocking sleep) +--- config + location /main { + echo_reset_timer; + echo_subrequest_async GET /sub1; + echo_subrequest_async GET /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_blocking_sleep 0.02; + echo hello; + } + location /sub2 { + echo_blocking_sleep 0.01; + echo world; + } + +--- request + GET /main +--- response_body_like +^hello +world +took 0\.00[0-5] sec for total\.$ + + + +=== TEST 8: timed multiple subrequests (non-blocking sleep) +--- config + location /main { + echo_reset_timer; + echo_subrequest_async GET /sub1; + echo_subrequest_async GET /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_sleep 0.02; + echo hello; + } + location /sub2 { + echo_sleep 0.01; + echo world; + } + +--- request + GET /main +--- response_body_like +^hello +world +took 0\.00[0-5] sec for total\.$ + + + +=== TEST 9: location with args +--- config + location /main { + echo_subrequest_async GET /sub -q 'foo=Foo&bar=Bar'; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +Foo Bar + + + +=== TEST 10: encoded chars in query strings +--- config + location /main { + echo_subrequest_async GET /sub -q 'foo=a%20b&bar=Bar'; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +a%20b Bar + + + +=== TEST 11: UTF-8 chars in query strings +--- config + location /main { + echo_subrequest_async GET /sub -q 'foo=你好'; + } + location /sub { + echo $arg_foo; + } +--- request + GET /main +--- response_body +你好 + + + +=== TEST 12: encoded chars in location url +--- config + location /main { + echo_subrequest_async GET /sub%31 -q 'foo=Foo&bar=Bar'; + } + location /sub%31 { + echo 'sub%31'; + } + location /sub1 { + echo 'sub1'; + } +--- request + GET /main +--- response_body +sub1 + + + +=== TEST 13: querystring in url +--- config + location /main { + echo_subrequest_async GET /sub?foo=Foo&bar=Bar; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +Foo Bar + + + +=== TEST 14: querystring in url *AND* an explicit querystring +--- config + location /main { + echo_subrequest_async GET /sub?foo=Foo&bar=Bar -q blah=Blah; + } + location /sub { + echo $arg_foo $arg_bar $arg_blah; + } +--- request + GET /main +--- response_body + Blah + + + +=== TEST 15: explicit flush in main request +flush won't really flush the buffer... +--- config + location /main_flush { + echo 'pre main'; + echo_subrequest_async GET /sub; + echo 'post main'; + echo_flush; + } + + location /sub { + echo_sleep 0.02; + echo 'sub'; + } +--- request + GET /main_flush +--- response_body +pre main +sub +post main + + + +=== TEST 16: POST subrequest with body (with proxy in the middle) and without read body explicitly +--- config + location /main { + echo_subrequest_async POST /proxy -b 'hello, world'; + } + location /proxy { + proxy_pass $scheme://127.0.0.1:$server_port/sub; + } + location /sub { + echo "sub method: $echo_request_method."; + # we need to read body explicitly here...or $echo_request_body + # will evaluate to empty ("") + echo "sub body: $echo_request_body."; + } +--- request + GET /main +--- response_body +sub method: POST. +sub body: . + + + +=== TEST 17: POST subrequest with body (with proxy in the middle) and read body explicitly +--- config + location /main { + echo_subrequest_async POST /proxy -b 'hello, world'; + } + location /proxy { + proxy_pass $scheme://127.0.0.1:$server_port/sub; + } + location /sub { + echo "sub method: $echo_request_method."; + # we need to read body explicitly here...or $echo_request_body + # will evaluate to empty ("") + echo_read_request_body; + echo "sub body: $echo_request_body."; + } +--- request + GET /main +--- response_body +sub method: POST. +sub body: hello, world. + + + +=== TEST 18: multiple subrequests +--- config + location /multi { + echo_subrequest_async POST '/sub' -q 'foo=Foo' -b 'hi'; + echo_subrequest_async PUT '/sub' -q 'bar=Bar' -b 'hello'; + } + location /sub { + echo "querystring: $query_string"; + echo "method: $echo_request_method"; + echo "body: $echo_request_body"; + echo "content length: $http_content_length"; + echo '///'; + } +--- request + GET /multi +--- response_body +querystring: foo=Foo +method: POST +body: hi +content length: 2 +/// +querystring: bar=Bar +method: PUT +body: hello +content length: 5 +/// + + + +=== TEST 19: no varaiable inheritance +--- config + location /main { + echo $echo_cacheable_request_uri; + echo_subrequest_async GET /sub; + echo_subrequest_async GET /sub2; + } + location /sub { + echo $echo_cacheable_request_uri; + } + location /sub2 { + echo $echo_cacheable_request_uri; + } + +--- request + GET /main +--- response_body +/main +/sub +/sub2 + + + +=== TEST 20: unsafe uri +--- config + location /unsafe { + echo_subrequest_async GET '/../foo'; + } +--- request + GET /unsafe +--- ignore_response +--- error_log +echo_subrequest_async sees unsafe uri: "/../foo" +--- no_error_log +[error] +[alert] + + + +=== TEST 21: let subrequest to read the main request's request body +--- SKIP +--- config + location /main { + echo_subrequest_async POST /sub; + } + location /sub { + echo_read_request_body; + echo_request_body; + } +--- request +POST /main +hello, body! +--- response_body chomp +hello, body! + + + +=== TEST 22: POST subrequest with file body (relative paths) +--- config + location /main { + echo_subrequest_async POST /sub -f html/blah.txt; + } + location /sub { + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo_request_body; + } +--- user_files +>>> blah.txt +Hello, world +--- request + GET /main +--- response_body +sub method: POST +Hello, world + + + +=== TEST 23: POST subrequest with file body (absolute paths) +--- config + location /main { + echo_subrequest_async POST /sub -f $TEST_NGINX_HTML_DIR/blah.txt; + } + location /sub { + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo_request_body; + } +--- user_files +>>> blah.txt +Hello, world! +Haha +--- request + GET /main +--- response_body +sub method: POST +Hello, world! +Haha + + + +=== TEST 24: POST subrequest with file body (file not found) +--- config + location /main { + echo_subrequest_async POST /sub -f html/blah/blah.txt; + } + location /sub { + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo_request_body; + } +--- user_files +>>> blah.txt +Hello, world +--- request + GET /main +--- ignore_response +--- error_log eval +qr/open\(\) ".*?" failed/ +--- no_error_log +[alert] + + + +=== TEST 25: POST subrequest with file body (absolute paths in vars) +--- config + location /main { + set $path $TEST_NGINX_HTML_DIR/blah.txt; + echo_subrequest_async POST /sub -f $path; + } + location /sub { + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo_request_body; + } +--- user_files +>>> blah.txt +Hello, world! +Haha +--- request + GET /main +--- response_body +sub method: POST +Hello, world! +Haha + + + +=== TEST 26: leading subrequest & echo_before_body +--- config + location /main { + echo_before_body hello; + echo_subrequest_async GET /foo; + } + location /foo { + echo world; + } +--- request + GET /main +--- response_body +hello +world + + + +=== TEST 27: leading subrequest & xss +--- config + location /main { + default_type 'application/json'; + xss_get on; + xss_callback_arg c; + echo_subrequest_async GET /foo; + } + location /foo { + echo -n world; + } +--- request + GET /main?c=hi +--- response_body chop +hi(world); + + + +=== TEST 28: multiple leading subrequest & xss +--- config + location /main { + default_type 'application/json'; + xss_get on; + xss_callback_arg c; + echo_subrequest_async GET /foo; + echo_subrequest_async GET /bar; + } + location /foo { + echo -n world; + } + location /bar { + echo -n ' people'; + } +--- request + GET /main?c=hi +--- response_body chop +hi(world people); + + + +=== TEST 29: sanity (HEAD) +--- config + location /main { + echo_subrequest_async GET /sub; + echo_subrequest_async GET /sub; + } + location /sub { + echo hello; + } +--- request + HEAD /main +--- response_body + + + +=== TEST 30: HEAD subrequest +--- config + location /main { + echo_subrequest_async HEAD /sub; + echo_subrequest_async HEAD /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body + diff --git a/echo-nginx-module/t/subrequest.t b/echo-nginx-module/t/subrequest.t new file mode 100644 index 00000000..6d965d01 --- /dev/null +++ b/echo-nginx-module/t/subrequest.t @@ -0,0 +1,725 @@ +# vi:filetype= + +use lib 'lib'; + +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (2 * blocks() + 1); + +$ENV{TEST_NGINX_HTML_DIR} = html_dir; +$ENV{TEST_NGINX_CLIENT_PORT} ||= server_port(); + +run_tests(); + +__DATA__ + +=== TEST 1: sanity +--- config + location /main { + echo_subrequest GET /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +hello + + + +=== TEST 2: trailing echo +--- config + location /main { + echo_subrequest GET /sub; + echo after subrequest; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +hello +after subrequest + + + +=== TEST 3: leading echo +--- config + location /main { + echo before subrequest; + echo_subrequest GET /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before subrequest +hello + + + +=== TEST 4: leading & trailing echo +--- config + location /main { + echo before subrequest; + echo_subrequest GET /sub; + echo after subrequest; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before subrequest +hello +after subrequest + + + +=== TEST 5: multiple subrequests +--- config + location /main { + echo before sr 1; + echo_subrequest GET /sub; + echo after sr 1; + echo before sr 2; + echo_subrequest GET /sub; + echo after sr 2; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body +before sr 1 +hello +after sr 1 +before sr 2 +hello +after sr 2 + + + +=== TEST 6: timed multiple subrequests (blocking sleep) +--- config + location /main { + echo_reset_timer; + echo_subrequest GET /sub1; + echo_subrequest GET /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_blocking_sleep 0.02; + echo hello; + } + location /sub2 { + echo_blocking_sleep 0.01; + echo world; + } + +--- request + GET /main +--- response_body_like +^hello +world +took 0\.0(?:2[5-9]|3[0-6]) sec for total\.$ + + + +=== TEST 7: timed multiple subrequests (non-blocking sleep) +--- config + location /main { + echo_reset_timer; + echo_subrequest GET /sub1; + echo_subrequest GET /sub2; + echo "took $echo_timer_elapsed sec for total."; + } + location /sub1 { + echo_sleep 0.02; + echo hello; + } + location /sub2 { + echo_sleep 0.01; + echo world; + } + +--- request + GET /main +--- response_body_like +^hello +world +took 0\.0(?:2[5-9]|3[0-6]) sec for total\.$ + + + +=== TEST 8: location with args +--- config + location /main { + echo_subrequest GET /sub -q 'foo=Foo&bar=Bar'; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +Foo Bar + + + +=== TEST 9: chained subrequests +--- config + location /main { + echo 'pre main'; + echo_subrequest GET /sub; + echo 'post main'; + } + + location /sub { + echo 'pre sub'; + echo_subrequest GET /subsub; + echo 'post sub'; + } + + location /subsub { + echo 'subsub'; + } +--- request + GET /main +--- response_body +pre main +pre sub +subsub +post sub +post main + + + +=== TEST 10: chained subrequests using named locations +as of 0.8.20, ngx_http_subrequest still does not support +named location. sigh. this case is a TODO. +--- config + location /main { + echo 'pre main'; + echo_subrequest GET @sub; + echo 'post main'; + } + + location @sub { + echo 'pre sub'; + echo_subrequest GET @subsub; + echo 'post sub'; + } + + location @subsub { + echo 'subsub'; + } +--- request + GET /main +--- response_body +pre main +pre sub +subsub +post sub +post main +--- SKIP + + + +=== TEST 11: explicit flush in main request +--- config + location /main { + echo 'pre main'; + echo_subrequest GET /sub; + echo 'post main'; + echo_flush; + } + + location /sub { + echo_sleep 0.02; + echo 'sub'; + } +--- request + GET /main +--- response_body +pre main +sub +post main + + + +=== TEST 12: DELETE subrequest +--- config + location /main { + echo_subrequest DELETE /sub; + } + location /sub { + echo "sub method: $echo_request_method"; + echo "main method: $echo_client_request_method"; + } +--- request + GET /main +--- response_body +sub method: DELETE +main method: GET + + + +=== TEST 13: DELETE subrequest +--- config + location /main { + echo "main method: $echo_client_request_method"; + echo_subrequest GET /proxy; + echo_subrequest DELETE /proxy; + } + location /proxy { + proxy_pass $scheme://127.0.0.1:$server_port/sub; + } + location /sub { + echo "sub method: $echo_request_method"; + } +--- request + GET /main +--- response_body +main method: GET +sub method: GET +sub method: DELETE + + + +=== TEST 14: POST subrequest with body +--- config + location /main { + echo_subrequest POST /sub -b 'hello, world'; + } + location /sub { + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo "sub body: $echo_request_body"; + } +--- request + GET /main +--- response_body +sub method: POST +sub body: hello, world + + + +=== TEST 15: POST subrequest with body (explicitly read the body) +--- config + location /main { + echo_subrequest POST /sub -b 'hello, world'; + } + location /sub { + echo "sub method: $echo_request_method"; + # we call echo_read_client_body explicitly here even + # though it's not necessary. + echo_read_request_body; + echo "sub body: $echo_request_body"; + } +--- request + GET /main +--- response_body +sub method: POST +sub body: hello, world + + + +=== TEST 16: POST subrequest with body (with proxy in the middle) and without read body explicitly +--- config + location /main { + echo_subrequest POST /proxy -b 'hello, world'; + } + location /proxy { + proxy_pass $scheme://127.0.0.1:$server_port/sub; + } + location /sub { + echo "sub method: $echo_request_method."; + # we need to read body explicitly here...or $echo_request_body + # will evaluate to empty ("") + echo "sub body: $echo_request_body."; + } +--- request + GET /main +--- response_body +sub method: POST. +sub body: . + + + +=== TEST 17: POST subrequest with body (with proxy in the middle) and read body explicitly +--- config + location /main { + echo_subrequest POST /proxy -b 'hello, world'; + } + location /proxy { + proxy_pass $scheme://127.0.0.1:$server_port/sub; + } + location /sub { + echo "sub method: $echo_request_method."; + # we need to read body explicitly here...or $echo_request_body + # will evaluate to empty ("") + echo_read_request_body; + echo "sub body: $echo_request_body."; + } +--- request + GET /main +--- response_body +sub method: POST. +sub body: hello, world. + + + +=== TEST 18: multiple subrequests +--- config + location /multi { + echo_subrequest POST '/sub' -q 'foo=Foo' -b 'hi'; + echo_subrequest PUT '/sub' -q 'bar=Bar' -b 'hello'; + } + location /sub { + echo "querystring: $query_string"; + echo "method: $echo_request_method"; + echo "body: $echo_request_body"; + echo "content length: $http_content_length"; + echo '///'; + } +--- request + GET /multi +--- response_body +querystring: foo=Foo +method: POST +body: hi +content length: 2 +/// +querystring: bar=Bar +method: PUT +body: hello +content length: 5 +/// + + + +=== TEST 19: unsafe uri +--- config + location /unsafe { + echo_subrequest GET '/../foo'; + } +--- request + GET /unsafe +--- ignore_response +--- error_log +echo_subrequest sees unsafe uri: "/../foo" +--- no_error_log +[error] + + + +=== TEST 20: querystring in url +--- config + location /main { + echo_subrequest GET /sub?foo=Foo&bar=Bar; + } + location /sub { + echo $arg_foo $arg_bar; + } +--- request + GET /main +--- response_body +Foo Bar + + + +=== TEST 21: querystring in url *AND* an explicit querystring +--- config + location /main { + echo_subrequest GET /sub?foo=Foo&bar=Bar -q blah=Blah; + } + location /sub { + echo $arg_foo $arg_bar $arg_blah; + } +--- request + GET /main +--- response_body + Blah + + + +=== TEST 22: let subrequest to read the main request's request body +--- SKIP +--- config + location /main { + echo_subrequest POST /sub; + } + location /sub { + echo_read_request_body; + echo_request_body; + } +--- request +POST /main +hello, body! +--- response_body chomp +hello, body! + + + +=== TEST 23: deep nested echo_subrequest/echo_subrequest_async +--- config + location /main { + echo_subrequest GET /bar; + echo_subrequest_async GET /bar; + echo_subrequest_async GET /bar; + echo_subrequest GET /group; + echo_subrequest_async GET /group; + } + + location /group { + echo_subrequest GET /bar; + echo_subrequest_async GET /bar; + } + + location /bar { + echo $echo_incr; + } +--- request +GET /main +--- response_body +1 +2 +3 +4 +5 +6 +7 + + + +=== TEST 24: deep nested echo_subrequest/echo_subrequest_async +--- config + location /main { + echo_subrequest GET /bar?a; + echo_subrequest_async GET /bar?b; + echo_subrequest_async GET /bar?c; + echo_subrequest GET /group?a=d&b=e; + echo_subrequest_async GET /group?a=f&b=g; + } + + location /group { + echo_subrequest GET /bar?$arg_a; + echo_subrequest_async GET /bar?$arg_b; + } + + location /bar { + echo -n $query_string; + } +--- request +GET /main +--- response_body: abcdefg +--- timeout: 2 + + + +=== TEST 25: POST subrequest with file body (relative paths) +--- config + location /main { + echo_subrequest POST /sub -f html/blah.txt; + } + location /sub { + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo_request_body; + } +--- user_files +>>> blah.txt +Hello, world +--- request + GET /main +--- response_body +sub method: POST +Hello, world + + + +=== TEST 26: POST subrequest with file body (absolute paths) +--- config + location /main { + echo_subrequest POST /sub -f $TEST_NGINX_HTML_DIR/blah.txt; + } + location /sub { + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo_request_body; + } +--- user_files +>>> blah.txt +Hello, world! +Haha +--- request + GET /main +--- response_body +sub method: POST +Hello, world! +Haha + + + +=== TEST 27: POST subrequest with file body (file not found) +--- config + location /main { + echo_subrequest POST /sub -f html/blah/blah.txt; + } + location /sub { + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo_request_body; + } +--- user_files +>>> blah.txt +Hello, world +--- request + GET /main +--- ignore_response +--- error_log eval +qr/open\(\) ".*?" failed/ +--- no_error_log +[alert] + + + +=== TEST 28: leading subrequest & echo_before_body +--- config + location /main { + echo_before_body hello; + echo_subrequest GET /foo; + } + location /foo { + echo world; + } +--- request + GET /main +--- response_body +hello +world + + + +=== TEST 29: leading subrequest & xss +--- config + location /main { + default_type 'application/json'; + xss_get on; + xss_callback_arg c; + echo_subrequest GET /foo; + } + location /foo { + echo -n world; + } +--- request + GET /main?c=hi +--- response_body chop +hi(world); + + + +=== TEST 30: multiple leading subrequest & xss +--- config + location /main { + default_type 'application/json'; + xss_get on; + xss_callback_arg c; + echo_subrequest GET /foo; + echo_subrequest GET /bar; + } + location /foo { + echo -n world; + } + location /bar { + echo -n ' people'; + } +--- request + GET /main?c=hi +--- response_body chop +hi(world people); + + + +=== TEST 31: sanity (HEAD) +--- config + location /main { + echo_subrequest GET /sub; + echo_subrequest GET /sub; + } + location /sub { + echo hello; + } +--- request + HEAD /main +--- response_body + + + +=== TEST 32: POST subrequest to ngx_proxy +--- config + location /hello { + default_type text/plain; + echo_subrequest POST '/proxy' -q 'foo=Foo&bar=baz' -b 'request_body=test&test=3'; + } + + location /proxy { + proxy_pass http://127.0.0.1:$TEST_NGINX_CLIENT_PORT/sub; + #proxy_pass http://127.0.0.1:1113/sub; + } + + location /sub { + echo_read_request_body; + echo "sub method: $echo_request_method"; + # we don't need to call echo_read_client_body explicitly here + echo "sub body: $echo_request_body"; + } +--- request + GET /hello +--- response_body +sub method: POST +sub body: request_body=test&test=3 + + + +=== TEST 33: HEAD subrequest +--- config + location /main { + echo_subrequest HEAD /sub; + echo_subrequest HEAD /sub; + } + location /sub { + echo hello; + } +--- request + GET /main +--- response_body + + + +=== TEST 34: method name as an nginx variable (github issue #34) +--- config + location ~ ^/delay/(?[0-9.]+)/(?.*)$ { + # echo_blocking_sleep $delay; + echo_subrequest '$echo_request_method' '/$originalURL' -q '$args'; + } + + location /api { + echo "args: $args"; + } +--- request + GET /delay/0.343/api/?a=b +--- response_body +args: a=b +--- no_error_log +[error] + diff --git a/echo-nginx-module/t/unused.t b/echo-nginx-module/t/unused.t new file mode 100644 index 00000000..f3c6e9e2 --- /dev/null +++ b/echo-nginx-module/t/unused.t @@ -0,0 +1,119 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (5 * blocks()); + +no_long_string(); +log_level('warn'); + +#master_on(); +#workers(1); + +run_tests(); + +__DATA__ + +=== TEST 1: filters used +--- http_config + postpone_output 1; +--- config + location /echo { + echo world; + echo_after_body hello; + } +--- request + GET /echo?blah +--- response_body +world +hello +--- error_log +echo header filter, uri "/echo?blah" +echo body filter, uri "/echo?blah" +--- no_error_log +[error] +--- log_level: debug + + + +=== TEST 2: filters not used +--- http_config + postpone_output 1; +--- config + location /echo { + echo world; + #echo_after_body hello; + } +--- request + GET /echo?blah +--- response_body +world +--- no_error_log +echo header filter, uri "/echo?blah" +echo body filter, uri "/echo?blah" +[error] +--- log_level: debug + + + +=== TEST 3: (after) filters used (multiple http {} blocks) +This test case won't run with nginx 1.9.3+ since duplicate http {} blocks +have been prohibited since then. +--- SKIP +--- http_config + postpone_output 1; +--- config + location /echo { + echo world; + echo_after_body hello; + } + +--- post_main_config + http { + } + +--- request + GET /echo?blah +--- response_body +world +hello +--- error_log +echo header filter, uri "/echo?blah" +echo body filter, uri "/echo?blah" +--- no_error_log +[error] +--- log_level: debug + + + +=== TEST 4: (before) filters used (multiple http {} blocks) +This test case won't run with nginx 1.9.3+ since duplicate http {} blocks +have been prohibited since then. +--- SKIP +--- http_config + postpone_output 1; +--- config + location /echo { + echo world; + echo_before_body hello; + } + +--- post_main_config + http { + } + +--- request + GET /echo?blah +--- response_body +hello +world +--- error_log +echo header filter, uri "/echo?blah" +echo body filter, uri "/echo?blah" +--- no_error_log +[error] +--- log_level: debug + diff --git a/echo-nginx-module/util/build.sh b/echo-nginx-module/util/build.sh new file mode 100755 index 00000000..45949bb9 --- /dev/null +++ b/echo-nginx-module/util/build.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +# this file is mostly meant to be used by the author himself. + +root=`pwd` +version=$1 +force=$2 +home=~ + + #--with-cc=gcc46 \ + +ngx-build $force $version \ + --with-ld-opt="-L$PCRE_LIB -Wl,-rpath,$PCRE_LIB:$LIBDRIZZLE_LIB:/usr/local/lib" \ + --with-cc-opt="-DDEBUG_MALLOC" \ + --with-http_stub_status_module \ + --with-http_image_filter_module \ + --without-mail_pop3_module \ + --without-mail_imap_module \ + --without-mail_smtp_module \ + --without-http_upstream_ip_hash_module \ + --without-http_memcached_module \ + --without-http_referer_module \ + --without-http_autoindex_module \ + --without-http_auth_basic_module \ + --without-http_userid_module \ + --add-module=$root/../ndk-nginx-module \ + --add-module=$root/../set-misc-nginx-module \ + --add-module=$root/../eval-nginx-module \ + --add-module=$root/../xss-nginx-module \ + --add-module=$root/../rds-json-nginx-module \ + --add-module=$root/../headers-more-nginx-module \ + --add-module=$root/../lua-nginx-module \ + --add-module=$root $opts \ + --with-http_v2_module \ + --with-select_module \ + --with-poll_module \ + --without-http_ssi_module \ + --with-debug || exit 1 + #--add-module=$root/../lz-session-nginx-module \ + #--add-module=$home/work/ndk \ + #--add-module=$home/work/ndk/examples/http/set_var \ + #--add-module=$root/../eval-nginx-module \ + #--add-module=/home/agentz/work/nginx_eval_module-1.0.1 \ + diff --git a/echo-nginx-module/util/wiki2pod.pl b/echo-nginx-module/util/wiki2pod.pl new file mode 100644 index 00000000..cdd33a25 --- /dev/null +++ b/echo-nginx-module/util/wiki2pod.pl @@ -0,0 +1,131 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use bytes; + +my @nl_counts; +my $last_nl_count_level; + +my @bl_counts; +my $last_bl_count_level; + +sub fmt_pos ($) { + (my $s = $_[0]) =~ s{\#(.*)}{/"$1"}; + $s; +} + +sub fmt_mark ($$) { + my ($tag, $s) = @_; + my $max_level = 0; + while ($s =~ /([<>])\1*/g) { + my $level = length $&; + if ($level > $max_level) { + $max_level = $level; + } + } + + my $times = $max_level + 1; + if ($times > 1) { + $s = " $s "; + } + return $tag . ('<' x $times) . $s . ('>' x $times); +} + +print "=encoding utf-8\n\n"; + +while (<>) { + if ($. == 1) { + # strip the leading U+FEFF byte in MS-DOS text files + my $first = ord(substr($_, 0, 1)); + #printf STDERR "0x%x", $first; + #my $second = ord(substr($_, 2, 1)); + #printf STDERR "0x%x", $second; + if ($first == 0xEF) { + substr($_, 0, 1, ''); + #warn "Hit!"; + } + } + s{\[(http[^ \]]+) ([^\]]*)\]}{$2 (L<$1>)}gi; + s{ \[\[ ( [^\]\|]+ ) \| ([^\]]*) \]\] }{"L<$2|" . fmt_pos($1) . ">"}gixe; + s{(.*?)}{fmt_mark('C', $1)}gie; + s{'''(.*?)'''}{fmt_mark('B', $1)}ge; + s{''(.*?)''}{fmt_mark('I', $1)}ge; + if (s{^\s*<[^>]+>\s*$}{}) { + next; + } + + if (/^\s*$/) { + print "\n"; + next; + } + +=begin cmt + + if ($. == 1) { + warn $_; + for my $i (0..length($_) - 1) { + my $chr = substr($_, $i, 1); + warn "chr ord($i): ".ord($chr)." \"$chr\"\n"; + } + } + +=end cmt +=cut + + if (/(=+) (.*) \1$/) { + #warn "HERE! $_" if $. == 1; + my ($level, $title) = (length $1, $2); + collapse_lists(); + + print "\n=head$level $title\n\n"; + } elsif (/^(\#+) (.*)/) { + my ($level, $txt) = (length($1) - 1, $2); + if (defined $last_nl_count_level && $level != $last_nl_count_level) { + print "\n=back\n\n"; + } + $last_nl_count_level = $level; + $nl_counts[$level] ||= 0; + if ($nl_counts[$level] == 0) { + print "\n=over\n\n"; + } + $nl_counts[$level]++; + print "\n=item $nl_counts[$level].\n\n"; + print "$txt\n"; + } elsif (/^(\*+) (.*)/) { + my ($level, $txt) = (length($1) - 1, $2); + if (defined $last_bl_count_level && $level != $last_bl_count_level) { + print "\n=back\n\n"; + } + $last_bl_count_level = $level; + $bl_counts[$level] ||= 0; + if ($bl_counts[$level] == 0) { + print "\n=over\n\n"; + } + $bl_counts[$level]++; + print "\n=item *\n\n"; + print "$txt\n"; + } else { + collapse_lists(); + print; + } +} + +collapse_lists(); + +sub collapse_lists { + while (defined $last_nl_count_level && $last_nl_count_level >= 0) { + print "\n=back\n\n"; + $last_nl_count_level--; + } + undef $last_nl_count_level; + undef @nl_counts; + + while (defined $last_bl_count_level && $last_bl_count_level >= 0) { + print "\n=back\n\n"; + $last_bl_count_level--; + } + undef $last_bl_count_level; + undef @bl_counts; +} + diff --git a/echo-nginx-module/valgrind.suppress b/echo-nginx-module/valgrind.suppress new file mode 100644 index 00000000..d4bfe63e --- /dev/null +++ b/echo-nginx-module/valgrind.suppress @@ -0,0 +1,48 @@ +{ + + Memcheck:Addr4 + fun:lj_str_new + fun:lua_setfield + fun:ngx_http_lua_cache_store_code +} +{ + + Memcheck:Addr4 + fun:lj_str_new + fun:lua_getfield + fun:ngx_http_lua_cache_load_code +} +{ + + Memcheck:Param + epoll_ctl(event) + fun:epoll_ctl +} +{ + + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_event_process_init +} +{ + + Memcheck:Cond + fun:index + fun:expand_dynamic_string_token + fun:_dl_map_object + fun:map_doit + fun:_dl_catch_error + fun:do_preload + fun:dl_main +} +{ + + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:ngx_alloc + fun:ngx_set_environment + fun:ngx_single_process_cycle + fun:main +} diff --git a/headers-more-nginx-module/.gitattributes b/headers-more-nginx-module/.gitattributes new file mode 100644 index 00000000..6fe6f35c --- /dev/null +++ b/headers-more-nginx-module/.gitattributes @@ -0,0 +1 @@ +*.t linguist-language=Text diff --git a/headers-more-nginx-module/.gitignore b/headers-more-nginx-module/.gitignore new file mode 100644 index 00000000..39c82faa --- /dev/null +++ b/headers-more-nginx-module/.gitignore @@ -0,0 +1,54 @@ +reindex +.libs +*.swp +*.slo +*.la +*.swo +*.lo +*~ +*.o +print.txt +.rsync +*.tar.gz +dist +build[78] +build +tags +update-readme +*.tmp +test/Makefile +test/blib +test.sh +t.sh +t/t.sh +test/t/servroot/ +releng +reset +*.t_ +genmobi.sh +*.mobi +misc/chunked +src/headers.c +src/headers.h +src/module.c +src/module.h +src/util.c +src/util.h +go +ctags +src/in.c +src/in.h +src/out.c +src/out.h +build[89] +build1[0-9] +buildroot/ +work/ +all +t/servroot +analyze +cov +nginx +*.plist +a.patch +Makefile diff --git a/headers-more-nginx-module/.travis.yml b/headers-more-nginx-module/.travis.yml new file mode 100644 index 00000000..d8c39b00 --- /dev/null +++ b/headers-more-nginx-module/.travis.yml @@ -0,0 +1,42 @@ +sudo: required +dist: trusty + +os: linux + +language: c + +compiler: + - gcc + - clang + +addons: + apt: + packages: + - axel + - cpanminus + - libluajit-5.1-dev + +env: + global: + - LUAJIT_LIB=/usr/lib64/libluajit-5.1.so + - LUAJIT_INC=/usr/include/luajit-2.0 + matrix: + - NGINX_VERSION=1.9.15 + - NGINX_VERSION=1.11.2 + +before_install: + - sudo cpanm -v --notest Test::Nginx > build.log 2>&1 || (cat build.log && exit 1) + +install: + - git clone https://github.com/openresty/echo-nginx-module.git ../echo-nginx-module + - git clone https://github.com/openresty/lua-nginx-module.git ../lua-nginx-module + - git clone https://github.com/openresty/nginx-eval-module.git ../eval-nginx-module + - git clone https://github.com/openresty/openresty.git ../openresty + - git clone https://github.com/openresty/no-pool-nginx.git ../no-pool-nginx + - git clone https://github.com/openresty/nginx-devel-utils.git + +script: + - export PATH=$PWD/work/nginx/sbin:$PWD/nginx-devel-utils:$PATH + - export NGX_BUILD_CC=$CC + - sh util/build.sh $NGINX_VERSION > build.log 2>&1 || (cat build.log && exit 1) + - prove -r t diff --git a/headers-more-nginx-module/README.markdown b/headers-more-nginx-module/README.markdown new file mode 100644 index 00000000..030c03f2 --- /dev/null +++ b/headers-more-nginx-module/README.markdown @@ -0,0 +1,547 @@ +Name +==== + +**ngx_headers_more** - Set and clear input and output headers...more than "add"! + +*This module is not distributed with the Nginx source.* See [the installation instructions](#installation). + +Table of Contents +================= + +* [Name](#name) +* [Version](#version) +* [Synopsis](#synopsis) +* [Description](#description) +* [Directives](#directives) + * [more_set_headers](#more_set_headers) + * [more_clear_headers](#more_clear_headers) + * [more_set_input_headers](#more_set_input_headers) + * [more_clear_input_headers](#more_clear_input_headers) +* [Limitations](#limitations) +* [Installation](#installation) +* [Compatibility](#compatibility) +* [Community](#community) + * [English Mailing List](#english-mailing-list) + * [Chinese Mailing List](#chinese-mailing-list) +* [Bugs and Patches](#bugs-and-patches) +* [Source Repository](#source-repository) +* [Changes](#changes) +* [Test Suite](#test-suite) +* [TODO](#todo) +* [Getting involved](#getting-involved) +* [Authors](#authors) +* [Copyright & License](#copyright--license) +* [See Also](#see-also) + +Version +======= + +This document describes headers-more-nginx-module [v0.32](https://github.com/openresty/headers-more-nginx-module/tags) released on 4 November 2016. + +Synopsis +======== + +```nginx + + # set the Server output header + more_set_headers 'Server: my-server'; + + # set and clear output headers + location /bar { + more_set_headers 'X-MyHeader: blah' 'X-MyHeader2: foo'; + more_set_headers -t 'text/plain text/css' 'Content-Type: text/foo'; + more_set_headers -s '400 404 500 503' -s 413 'Foo: Bar'; + more_clear_headers 'Content-Type'; + + # your proxy_pass/memcached_pass/or any other config goes here... + } + + # set output headers + location /type { + more_set_headers 'Content-Type: text/plain'; + # ... + } + + # set input headers + location /foo { + set $my_host 'my dog'; + more_set_input_headers 'Host: $my_host'; + more_set_input_headers -t 'text/plain' 'X-Foo: bah'; + + # now $host and $http_host have their new values... + # ... + } + + # replace input header X-Foo *only* if it already exists + more_set_input_headers -r 'X-Foo: howdy'; +``` + +Description +=========== + +This module allows you to add, set, or clear any output +or input header that you specify. + +This is an enhanced version of the standard +[headers](http://nginx.org/en/docs/http/ngx_http_headers_module.html) module because it provides more utilities like +resetting or clearing "builtin headers" like `Content-Type`, +`Content-Length`, and `Server`. + +It also allows you to specify an optional HTTP status code +criteria using the `-s` option and an optional content +type criteria using the `-t` option while modifying the +output headers with the [more_set_headers](#more_set_headers) and +[more_clear_headers](#more_clear_headers) directives. For example, + +```nginx + more_set_headers -s 404 -t 'text/html' 'X-Foo: Bar'; +``` + +You can also specify multiple MIME types to filter out in a single `-t` option. +For example, + +```nginx +more_set_headers -t 'text/html text/plain' 'X-Foo: Bar'; +``` + +Never use other paramemters like `charset=utf-8` in the `-t` option values; they will not +work as you would expect. + +Input headers can be modified as well. For example + +```nginx + location /foo { + more_set_input_headers 'Host: foo' 'User-Agent: faked'; + # now $host, $http_host, $user_agent, and + # $http_user_agent all have their new values. + } +``` + +The option `-t` is also available in the +[more_set_input_headers](#more_set_input_headers) and +[more_clear_input_headers](#more_clear_input_headers) directives (for request header filtering) while the `-s` option +is not allowed. + +Unlike the standard [headers](http://nginx.org/en/docs/http/ngx_http_headers_module.html) module, this module's directives will by +default apply to all the status codes, including `4xx` and `5xx`. + +[Back to TOC](#table-of-contents) + +Directives +========== + +[Back to TOC](#table-of-contents) + +more_set_headers +---------------- +**syntax:** *more_set_headers [-t <content-type list>]... [-s <status-code list>]... <new-header>...* + +**default:** *no* + +**context:** *http, server, location, location if* + +**phase:** *output-header-filter* + +Replaces (if any) or adds (if not any) the specified output headers when the response status code matches the codes specified by the `-s` option *AND* the response content type matches the types specified by the `-t` option. + +If either `-s` or `-t` is not specified or has an empty list value, then no match is required. Therefore, the following directive set the `Server` output header to the custom value for *any* status code and *any* content type: + +```nginx + + more_set_headers "Server: my_server"; +``` + +Existing response headers with the same name are always overridden. If you want to add headers incrementally, use the standard [add_header](http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header) directive instead. + +A single directive can set/add multiple output headers. For example + +```nginx + + more_set_headers 'Foo: bar' 'Baz: bah'; +``` + +Multiple occurrences of the options are allowed in a single directive. Their values will be merged together. For instance + +```nginx + + more_set_headers -s 404 -s '500 503' 'Foo: bar'; +``` + +is equivalent to + +```nginx + + more_set_headers -s '404 500 503' 'Foo: bar'; +``` + +The new header should be the one of the forms: + +1. `Name: Value` +1. `Name: ` +1. `Name` + +The last two effectively clear the value of the header `Name`. + +Nginx variables are allowed in header values. For example: + +```nginx + + set $my_var "dog"; + more_set_headers "Server: $my_var"; +``` + +But variables won't work in header keys due to performance considerations. + +Multiple set/clear header directives are allowed in a single location, and they're executed sequentially. + +Directives inherited from an upper level scope (say, http block or server blocks) are executed before the directives in the location block. + +Note that although `more_set_headers` is allowed in *location* if blocks, it is *not* allowed in the *server* if blocks, as in + +```nginx + + ? # This is NOT allowed! + ? server { + ? if ($args ~ 'download') { + ? more_set_headers 'Foo: Bar'; + ? } + ? ... + ? } +``` + +Behind the scene, use of this directive and its friend [more_clear_headers](#more_clear_headers) will (lazily) register an ouput header filter that modifies `r->headers_out` the way you specify. + +[Back to TOC](#table-of-contents) + +more_clear_headers +------------------ +**syntax:** *more_clear_headers [-t <content-type list>]... [-s <status-code list>]... <new-header>...* + +**default:** *no* + +**context:** *http, server, location, location if* + +**phase:** *output-header-filter* + +Clears the specified output headers. + +In fact, + +```nginx + + more_clear_headers -s 404 -t 'text/plain' Foo Baz; +``` + +is exactly equivalent to + +```nginx + + more_set_headers -s 404 -t 'text/plain' "Foo: " "Baz: "; +``` + +or + +```nginx + + more_set_headers -s 404 -t 'text/plain' Foo Baz +``` + +See [more_set_headers](#more_set_headers) for more details. + +The wildcard character, `*`, can also be used at the end of the header name to specify a pattern. For example, the following directive +effectively clears *any* output headers starting by "`X-Hidden-`": + +```nginx + + more_clear_headers 'X-Hidden-*'; +``` + +The `*` wildcard support was first introduced in [v0.09](#v009). + +[Back to TOC](#table-of-contents) + +more_set_input_headers +---------------------- +**syntax:** *more_set_input_headers [-r] [-t <content-type list>]... <new-header>...* + +**default:** *no* + +**context:** *http, server, location, location if* + +**phase:** *rewrite tail* + +Very much like [more_set_headers](#more_set_headers) except that it operates on input headers (or request headers) and it only supports the `-t` option. + +Note that using the `-t` option in this directive means filtering by the `Content-Type` *request* header, rather than the response header. + +Behind the scene, use of this directive and its friend [more_clear_input_headers](#more_clear_input_headers) will (lazily) +register a `rewrite phase` handler that modifies `r->headers_in` the way you specify. Note that it always run at the *end* of +the `rewrite` phase so that it runs *after* the standard [rewrite module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html) +and works in subrequests as well. + +If the `-r` option is specified, then the headers will be replaced to the new values *only if* they already exist. + +[Back to TOC](#table-of-contents) + +more_clear_input_headers +------------------------ +**syntax:** *more_clear_input_headers [-t <content-type list>]... <new-header>...* + +**default:** *no* + +**context:** *http, server, location, location if* + +**phase:** *rewrite tail* + +Clears the specified input headers. + +In fact, + +```nginx + + more_clear_input_headers -t 'text/plain' Foo Baz; +``` + +is exactly equivalent to + +```nginx + + more_set_input_headers -t 'text/plain' "Foo: " "Baz: "; +``` + +or + +```nginx + + more_set_input_headers -t 'text/plain' Foo Baz +``` + +To remove request headers "Foo" and "Baz" for all incoming requests regardless of the content type, we can write + +```nginx + + more_clear_input_headers "Foo" "Baz"; +``` + +See [more_set_input_headers](#more_set_input_headers) for more details. + +The wildcard character, `*`, can also be used at the end of the header name to specify a pattern. For example, the following directive +effectively clears *any* input headers starting by "`X-Hidden-`": + +```nginx + + more_clear_input_headers 'X-Hidden-*'; +``` + +[Back to TOC](#table-of-contents) + +Limitations +=========== + +* Unlike the standard [headers](http://nginx.org/en/docs/http/ngx_http_headers_module.html) module, this module does not automatically take care of the constraint among the `Expires`, `Cache-Control`, and `Last-Modified` headers. You have to get them right yourself or use the [headers](http://nginx.org/en/docs/http/ngx_http_headers_module.html) module together with this module. +* You cannot remove the `Connection` response header using this module because the `Connection` response header is generated by the standard `ngx_http_header_filter_module` in the Nginx core, whose output header filter runs always *after* the filter of this module. The only way to actually remove the `Connection` header is to patch the Nginx core, that is, editing the C function `ngx_http_header_filter` in the `src/http/ngx_http_header_filter_module.c` file. + +[Back to TOC](#table-of-contents) + +Installation +============ + +Grab the nginx source code from [nginx.org](http://nginx.org/), for example, +the version 1.11.2 (see [nginx compatibility](#compatibility)), and then build the source with this module: + +```bash + + wget 'http://nginx.org/download/nginx-1.11.2.tar.gz' + tar -xzvf nginx-1.11.2.tar.gz + cd nginx-1.11.2/ + + # Here we assume you would install you nginx under /opt/nginx/. + ./configure --prefix=/opt/nginx \ + --add-module=/path/to/headers-more-nginx-module + + make + make install +``` + +Download the latest version of the release tarball of this module from [headers-more-nginx-module file list](https://github.com/openresty/headers-more-nginx-module/tags). + +Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the `--add-dynamic-module=PATH` option instead of `--add-module=PATH` on the +`./configure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load_module](http://nginx.org/en/docs/ngx_core_module.html#load_module) +directive, for example, + +```nginx +load_module /path/to/modules/ngx_http_headers_more_filter_module.so; +``` + +Also, this module is included and enabled by default in the [OpenResty bundle](http://openresty.org). + +[Back to TOC](#table-of-contents) + +Compatibility +============= + +The following versions of Nginx should work with this module: + +* **1.11.x** (last tested: 1.11.2) +* **1.10.x** +* **1.9.x** (last tested: 1.9.15) +* **1.8.x** +* **1.7.x** (last tested: 1.7.10) +* **1.6.x** (last tested: 1.6.2) +* **1.5.x** (last tested: 1.5.8) +* **1.4.x** (last tested: 1.4.4) +* **1.3.x** (last tested: 1.3.7) +* **1.2.x** (last tested: 1.2.9) +* **1.1.x** (last tested: 1.1.5) +* **1.0.x** (last tested: 1.0.11) +* **0.9.x** (last tested: 0.9.4) +* **0.8.x** (last tested: 0.8.54) +* **0.7.x >= 0.7.44** (last tested: 0.7.68) + +Earlier versions of Nginx like 0.6.x and 0.5.x will *not* work. + +If you find that any particular version of Nginx above 0.7.44 does not work with this module, please consider [reporting a bug](#report-bugs). + +[Back to TOC](#table-of-contents) + +Community +========= + +[Back to TOC](#table-of-contents) + +English Mailing List +-------------------- + +The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers. + +[Back to TOC](#table-of-contents) + +Chinese Mailing List +-------------------- + +The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers. + +[Back to TOC](#table-of-contents) + +Bugs and Patches +================ + +Please submit bug reports, wishlists, or patches by + +1. creating a ticket on the [GitHub Issue Tracker](https://github.com/chaoslawful/lua-nginx-module/issues), +1. or posting to the [OpenResty community](#community). + +[Back to TOC](#table-of-contents) + +Source Repository +================= + +Available on github at [openresty/headers-more-nginx-module](https://github.com/openresty/headers-more-nginx-module). + +[Back to TOC](#table-of-contents) + +Changes +======= + +The changes of every release of this module can be obtained from the OpenResty bundle's change logs: + + + +[Back to TOC](#table-of-contents) + +Test Suite +========== + +This module comes with a Perl-driven test suite. The [test cases](https://github.com/openresty/headers-more-nginx-module/tree/master/t/) are +[declarative](https://github.com/openresty/headers-more-nginx-module/blob/master/t/sanity.t) too. Thanks to the [Test::Nginx](http://search.cpan.org/perldoc?Test::Nginx) module in the Perl world. + +To run it on your side: + +```bash + + $ PATH=/path/to/your/nginx-with-headers-more-module:$PATH prove -r t +``` + +To run the test suite with valgrind's memcheck, use the following commands: + +```bash + + $ export PATH=/path/to/your/nginx-with-headers-more-module:$PATH + $ TEST_NGINX_USE_VALGRIND=1 prove -r t +``` + +You need to terminate any Nginx processes before running the test suite if you have changed the Nginx server binary. + +Because a single nginx server (by default, `localhost:1984`) is used across all the test scripts (`.t` files), it's meaningless to run the test suite in parallel by specifying `-jN` when invoking the `prove` utility. + +Some parts of the test suite requires modules [proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html), [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), and [echo](https://github.com/openresty/echo-nginx-module) to be enabled as well when building Nginx. + +[Back to TOC](#table-of-contents) + +TODO +==== + +* Support variables in new headers' keys. + +[Back to TOC](#table-of-contents) + +Getting involved +================ + +You'll be very welcomed to submit patches to the [author](#author) or just ask for a commit bit to the [source repository](#source-repository) on GitHub. + +[Back to TOC](#table-of-contents) + +Authors +======= + +* Yichun "agentzh" Zhang (章亦春) *<agentzh@gmail.com>*, OpenResty Inc. +* Bernd Dorn ( ) + +This wiki page is also maintained by the author himself, and everybody is encouraged to improve this page as well. + +[Back to TOC](#table-of-contents) + +Copyright & License +=================== + +The code base is borrowed directly from the standard [headers](http://nginx.org/en/docs/http/ngx_http_headers_module.html) module in Nginx 0.8.24. This part of code is copyrighted by Igor Sysoev. + +Copyright (c) 2009-2017, Yichun "agentzh" Zhang (章亦春) , OpenResty Inc. + +Copyright (c) 2010-2013, Bernd Dorn. + +This module is licensed under the terms of the BSD license. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +[Back to TOC](#table-of-contents) + +See Also +======== + +* The original thread on the Nginx mailing list that inspires this module's development: ["A question about add_header replication"](http://forum.nginx.org/read.php?2,11206,11738). +* The orginal announcement thread on the Nginx mailing list: ["The "headers_more" module: Set and clear output headers...more than 'add'!"](http://forum.nginx.org/read.php?2,23460). +* The original [blog post](http://agentzh.blogspot.com/2009/11/headers-more-module-scripting-input-and.html) about this module's initial development. +* The [echo module](https://github.com/openresty/echo-nginx-module) for Nginx module's automated testing. +* The standard [headers](http://nginx.org/en/docs/http/ngx_http_headers_module.html) module. + +[Back to TOC](#table-of-contents) + diff --git a/headers-more-nginx-module/config b/headers-more-nginx-module/config new file mode 100644 index 00000000..5707cc4a --- /dev/null +++ b/headers-more-nginx-module/config @@ -0,0 +1,32 @@ +ngx_addon_name=ngx_http_headers_more_filter_module + +HEADERS_MORE_SRCS=" \ + $ngx_addon_dir/src/ngx_http_headers_more_filter_module.c \ + $ngx_addon_dir/src/ngx_http_headers_more_headers_out.c \ + $ngx_addon_dir/src/ngx_http_headers_more_headers_in.c \ + $ngx_addon_dir/src/ngx_http_headers_more_util.c \ + " + +HEADERS_MORE_DEPS=" \ + $ngx_addon_dir/src/ddebug.h \ + $ngx_addon_dir/src/ngx_http_headers_more_filter_module.h \ + $ngx_addon_dir/src/ngx_http_headers_more_headers_in.h \ + $ngx_addon_dir/src/ngx_http_headers_more_headers_out.h \ + $ngx_addon_dir/src/ngx_http_headers_more_headers_in.h \ + $ngx_addon_dir/src/ngx_http_headers_more_util.h \ + " + +if test -n "$ngx_module_link"; then + ngx_module_type=HTTP_AUX_FILTER + ngx_module_name=$ngx_addon_name + ngx_module_incs= + ngx_module_deps="$HEADERS_MORE_DEPS" + ngx_module_srcs="$HEADERS_MORE_SRCS" + ngx_module_libs= + + . auto/module +else + HTTP_AUX_FILTER_MODULES="$HTTP_AUX_FILTER_MODULES $ngx_addon_name" + NGX_ADDON_SRCS="$NGX_ADDON_SRCS $HEADERS_MORE_SRCS" + NGX_ADDON_DEPS="$NGX_ADDON_DEPS $HEADERS_MORE_DEPS" +fi diff --git a/headers-more-nginx-module/src/ddebug.h b/headers-more-nginx-module/src/ddebug.h new file mode 100644 index 00000000..13879af9 --- /dev/null +++ b/headers-more-nginx-module/src/ddebug.h @@ -0,0 +1,124 @@ +#ifndef DDEBUG_H +#define DDEBUG_H + + +#include +#include +#include +#include + + +#if defined(DDEBUG) && (DDEBUG) + +# if (NGX_HAVE_VARIADIC_MACROS) + +# define dd(...) fprintf(stderr, "headers-more *** %s: ", __func__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, " at %s line %d.\n", __FILE__, __LINE__) + +# else + +#include +#include + +#include + +static ngx_inline void +dd(const char * fmt, ...) { +} + +# endif + +# if DDEBUG > 1 + +# define dd_enter() dd_enter_helper(r, __func__) + +# if defined(nginx_version) && nginx_version >= 8011 +# define dd_main_req_count r->main->count +# else +# define dd_main_req_count 0 +# endif + +static ngx_inline void +dd_enter_helper(ngx_http_request_t *r, const char *func) +{ + ngx_http_posted_request_t *pr; + + fprintf(stderr, "headers-more *** enter %s %.*s %.*s?%.*s c:%d m:%p r:%p ar:%p pr:%p", + func, + (int) r->method_name.len, r->method_name.data, + (int) r->uri.len, r->uri.data, + (int) r->args.len, r->args.data, + (int) dd_main_req_count, r->main, + r, r->connection->data, r->parent); + + if (r->posted_requests) { + fprintf(stderr, " posted:"); + + for (pr = r->posted_requests; pr; pr = pr->next) { + fprintf(stderr, "%p,", pr); + } + } + + fprintf(stderr, "\n"); +} + +# else + +# define dd_enter() + +# endif + +#else + +# if (NGX_HAVE_VARIADIC_MACROS) + +# define dd(...) + +# define dd_enter() + +# else + +#include + +static ngx_inline void +dd(const char * fmt, ...) { +} + +static ngx_inline void +dd_enter() { +} + +# endif + +#endif + +#if defined(DDEBUG) && (DDEBUG) + +#define dd_check_read_event_handler(r) \ + dd("r->read_event_handler = %s", \ + r->read_event_handler == ngx_http_block_reading ? \ + "ngx_http_block_reading" : \ + r->read_event_handler == ngx_http_test_reading ? \ + "ngx_http_test_reading" : \ + r->read_event_handler == ngx_http_request_empty_handler ? \ + "ngx_http_request_empty_handler" : "UNKNOWN") + +#define dd_check_write_event_handler(r) \ + dd("r->write_event_handler = %s", \ + r->write_event_handler == ngx_http_handler ? \ + "ngx_http_handler" : \ + r->write_event_handler == ngx_http_core_run_phases ? \ + "ngx_http_core_run_phases" : \ + r->write_event_handler == ngx_http_request_empty_handler ? \ + "ngx_http_request_empty_handler" : "UNKNOWN") + +#else + +#define dd_check_read_event_handler(r) +#define dd_check_write_event_handler(r) + +#endif + +#endif /* DDEBUG_H */ + diff --git a/headers-more-nginx-module/src/ngx_http_headers_more_filter_module.c b/headers-more-nginx-module/src/ngx_http_headers_more_filter_module.c new file mode 100644 index 00000000..0bb6fec2 --- /dev/null +++ b/headers-more-nginx-module/src/ngx_http_headers_more_filter_module.c @@ -0,0 +1,348 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_headers_more_filter_module.h" +#include "ngx_http_headers_more_headers_out.h" +#include "ngx_http_headers_more_headers_in.h" +#include "ngx_http_headers_more_util.h" +#include + + +/* config handlers */ + +static void *ngx_http_headers_more_create_loc_conf(ngx_conf_t *cf); +static char *ngx_http_headers_more_merge_loc_conf(ngx_conf_t *cf, + void *parent, void *child); +static void *ngx_http_headers_more_create_main_conf(ngx_conf_t *cf); +static ngx_int_t ngx_http_headers_more_post_config(ngx_conf_t *cf); + +/* post-read-phase handler */ + +static ngx_int_t ngx_http_headers_more_handler(ngx_http_request_t *r); + +/* filter handlers */ + +static ngx_int_t ngx_http_headers_more_filter_init(ngx_conf_t *cf); + +ngx_uint_t ngx_http_headers_more_location_hash = 0; + + +static ngx_command_t ngx_http_headers_more_filter_commands[] = { + + { ngx_string("more_set_headers"), + NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF + |NGX_CONF_1MORE, + ngx_http_headers_more_set_headers, + NGX_HTTP_LOC_CONF_OFFSET, + 0, + NULL}, + + { ngx_string("more_clear_headers"), + NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF + |NGX_CONF_1MORE, + ngx_http_headers_more_clear_headers, + NGX_HTTP_LOC_CONF_OFFSET, + 0, + NULL}, + + { ngx_string("more_set_input_headers"), + NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF + |NGX_CONF_1MORE, + ngx_http_headers_more_set_input_headers, + NGX_HTTP_LOC_CONF_OFFSET, + 0, + NULL}, + + { ngx_string("more_clear_input_headers"), + NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF + |NGX_CONF_1MORE, + ngx_http_headers_more_clear_input_headers, + NGX_HTTP_LOC_CONF_OFFSET, + 0, + NULL}, + + ngx_null_command +}; + + +static ngx_http_module_t ngx_http_headers_more_filter_module_ctx = { + NULL, /* preconfiguration */ + ngx_http_headers_more_post_config, /* postconfiguration */ + + ngx_http_headers_more_create_main_conf, /* create main configuration */ + NULL, /* init main configuration */ + + NULL, /* create server configuration */ + NULL, /* merge server configuration */ + + ngx_http_headers_more_create_loc_conf, /* create location configuration */ + ngx_http_headers_more_merge_loc_conf /* merge location configuration */ +}; + + +ngx_module_t ngx_http_headers_more_filter_module = { + NGX_MODULE_V1, + &ngx_http_headers_more_filter_module_ctx, /* module context */ + ngx_http_headers_more_filter_commands, /* module directives */ + NGX_HTTP_MODULE, /* module type */ + NULL, /* init master */ + NULL, /* init module */ + NULL, /* init process */ + NULL, /* init thread */ + NULL, /* exit thread */ + NULL, /* exit process */ + NULL, /* exit master */ + NGX_MODULE_V1_PADDING +}; + + +static ngx_http_output_header_filter_pt ngx_http_next_header_filter; + + +static volatile ngx_cycle_t *ngx_http_headers_more_prev_cycle = NULL; + + +static ngx_int_t +ngx_http_headers_more_filter(ngx_http_request_t *r) +{ + ngx_int_t rc; + ngx_uint_t i; + ngx_http_headers_more_loc_conf_t *conf; + ngx_http_headers_more_cmd_t *cmd; + + ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "headers more header filter, uri \"%V\"", &r->uri); + + conf = ngx_http_get_module_loc_conf(r, ngx_http_headers_more_filter_module); + + if (conf->cmds) { + cmd = conf->cmds->elts; + for (i = 0; i < conf->cmds->nelts; i++) { + if (cmd[i].is_input) { + continue; + } + + rc = ngx_http_headers_more_exec_cmd(r, &cmd[i]); + + if (rc != NGX_OK) { + return rc; + } + } + } + + return ngx_http_next_header_filter(r); +} + + +static ngx_int_t +ngx_http_headers_more_filter_init(ngx_conf_t *cf) +{ + ngx_http_next_header_filter = ngx_http_top_header_filter; + ngx_http_top_header_filter = ngx_http_headers_more_filter; + + return NGX_OK; +} + + +static void * +ngx_http_headers_more_create_loc_conf(ngx_conf_t *cf) +{ + ngx_http_headers_more_loc_conf_t *conf; + + conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_headers_more_loc_conf_t)); + if (conf == NULL) { + return NULL; + } + + /* + * set by ngx_pcalloc(): + * + * conf->cmds = NULL; + */ + + return conf; +} + + +static char * +ngx_http_headers_more_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child) +{ + ngx_uint_t i; + ngx_uint_t orig_len; + ngx_http_headers_more_cmd_t *prev_cmd, *cmd; + ngx_http_headers_more_loc_conf_t *prev = parent; + ngx_http_headers_more_loc_conf_t *conf = child; + + if (conf->cmds == NULL || conf->cmds->nelts == 0) { + conf->cmds = prev->cmds; + + } else if (prev->cmds && prev->cmds->nelts) { + orig_len = conf->cmds->nelts; + + (void) ngx_array_push_n(conf->cmds, prev->cmds->nelts); + + cmd = conf->cmds->elts; + + for (i = 0; i < orig_len; i++) { + cmd[conf->cmds->nelts - 1 - i] = cmd[orig_len - 1 - i]; + } + + prev_cmd = prev->cmds->elts; + + for (i = 0; i < prev->cmds->nelts; i++) { + cmd[i] = prev_cmd[i]; + } + } + + return NGX_CONF_OK; +} + + +static ngx_int_t +ngx_http_headers_more_post_config(ngx_conf_t *cf) +{ + int multi_http_blocks; + ngx_int_t rc; + ngx_http_handler_pt *h; + ngx_http_core_main_conf_t *cmcf; + + ngx_http_headers_more_main_conf_t *hmcf; + + ngx_http_headers_more_location_hash = + ngx_http_headers_more_hash_literal("location"); + + hmcf = ngx_http_conf_get_module_main_conf(cf, + ngx_http_headers_more_filter_module); + + if (ngx_http_headers_more_prev_cycle != ngx_cycle) { + ngx_http_headers_more_prev_cycle = ngx_cycle; + multi_http_blocks = 0; + + } else { + multi_http_blocks = 1; + } + + if (multi_http_blocks || hmcf->requires_filter) { + rc = ngx_http_headers_more_filter_init(cf); + if (rc != NGX_OK) { + return rc; + } + } + + if (!hmcf->requires_handler) { + return NGX_OK; + } + + cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module); + + h = ngx_array_push(&cmcf->phases[NGX_HTTP_REWRITE_PHASE].handlers); + if (h == NULL) { + return NGX_ERROR; + } + + *h = ngx_http_headers_more_handler; + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_headers_more_handler(ngx_http_request_t *r) +{ + ngx_int_t rc; + ngx_uint_t i; + ngx_http_headers_more_loc_conf_t *conf; + ngx_http_headers_more_main_conf_t *hmcf; + ngx_http_headers_more_cmd_t *cmd; + + ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "headers more rewrite handler, uri \"%V\"", &r->uri); + + hmcf = ngx_http_get_module_main_conf(r, + ngx_http_headers_more_filter_module); + + if (!hmcf->postponed_to_phase_end) { + ngx_http_core_main_conf_t *cmcf; + ngx_http_phase_handler_t tmp; + ngx_http_phase_handler_t *ph; + ngx_http_phase_handler_t *cur_ph; + ngx_http_phase_handler_t *last_ph; + + hmcf->postponed_to_phase_end = 1; + + cmcf = ngx_http_get_module_main_conf(r, ngx_http_core_module); + + ph = cmcf->phase_engine.handlers; + cur_ph = &ph[r->phase_handler]; + last_ph = &ph[cur_ph->next - 1]; + + if (cur_ph < last_ph) { + dd("swaping the contents of cur_ph and last_ph..."); + + tmp = *cur_ph; + + memmove(cur_ph, cur_ph + 1, + (last_ph - cur_ph) * sizeof (ngx_http_phase_handler_t)); + + *last_ph = tmp; + + r->phase_handler--; /* redo the current ph */ + + return NGX_DECLINED; + } + } + + dd("running phase handler..."); + + conf = ngx_http_get_module_loc_conf(r, ngx_http_headers_more_filter_module); + + if (conf->cmds) { + if (r->http_version < NGX_HTTP_VERSION_10) { + return NGX_DECLINED; + } + + cmd = conf->cmds->elts; + for (i = 0; i < conf->cmds->nelts; i++) { + if (!cmd[i].is_input) { + continue; + } + + rc = ngx_http_headers_more_exec_input_cmd(r, &cmd[i]); + + if (rc != NGX_OK) { + return rc; + } + } + } + + return NGX_DECLINED; +} + + +static void * +ngx_http_headers_more_create_main_conf(ngx_conf_t *cf) +{ + ngx_http_headers_more_main_conf_t *hmcf; + + hmcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_headers_more_main_conf_t)); + if (hmcf == NULL) { + return NULL; + } + + /* set by ngx_pcalloc: + * hmcf->postponed_to_phase_end = 0; + * hmcf->requires_filter = 0; + * hmcf->requires_handler = 0; + */ + + return hmcf; +} diff --git a/headers-more-nginx-module/src/ngx_http_headers_more_filter_module.h b/headers-more-nginx-module/src/ngx_http_headers_more_filter_module.h new file mode 100644 index 00000000..72a5317c --- /dev/null +++ b/headers-more-nginx-module/src/ngx_http_headers_more_filter_module.h @@ -0,0 +1,80 @@ + +/* + * Copyright (c) Yichun Zhang (agentzh) + */ + + +#ifndef NGX_HTTP_HEADERS_MORE_FILTER_MODULE_H +#define NGX_HTTP_HEADERS_MORE_FILTER_MODULE_H + + +#include +#include +#include + + +typedef enum { + ngx_http_headers_more_opcode_set, + ngx_http_headers_more_opcode_clear +} ngx_http_headers_more_opcode_t; + + +typedef struct { + ngx_array_t *types; /* of ngx_str_t */ + ngx_array_t *statuses; /* of ngx_uint_t */ + ngx_array_t *headers; /* of ngx_http_header_val_t */ + ngx_flag_t is_input; +} ngx_http_headers_more_cmd_t; + + +typedef struct { + ngx_array_t *cmds; /* of ngx_http_headers_more_cmd_t */ +} ngx_http_headers_more_loc_conf_t; + + +typedef struct { + ngx_int_t postponed_to_phase_end; + ngx_int_t requires_filter; + ngx_int_t requires_handler; +} ngx_http_headers_more_main_conf_t; + + +typedef struct ngx_http_headers_more_header_val_s + ngx_http_headers_more_header_val_t; + + +typedef ngx_int_t (*ngx_http_headers_more_set_header_pt)(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); + + +typedef struct { + ngx_str_t name; + ngx_uint_t offset; + ngx_http_headers_more_set_header_pt handler; +} ngx_http_headers_more_set_header_t; + + +struct ngx_http_headers_more_header_val_s { + ngx_http_complex_value_t value; + ngx_uint_t hash; + ngx_str_t key; + ngx_http_headers_more_set_header_pt handler; + ngx_uint_t offset; + ngx_flag_t replace; + ngx_flag_t wildcard; +}; + + +extern ngx_module_t ngx_http_headers_more_filter_module; + + +#ifndef ngx_str_set +#define ngx_str_set(str, text) \ + (str)->len = sizeof(text) - 1; (str)->data = (u_char *) text +#endif + + +#define ngx_http_headers_more_assert(a) assert(a) + + +#endif /* NGX_HTTP_HEADERS_MORE_FILTER_MODULE_H */ diff --git a/headers-more-nginx-module/src/ngx_http_headers_more_headers_in.c b/headers-more-nginx-module/src/ngx_http_headers_more_headers_in.c new file mode 100644 index 00000000..c3eb8f7d --- /dev/null +++ b/headers-more-nginx-module/src/ngx_http_headers_more_headers_in.c @@ -0,0 +1,899 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_headers_more_headers_in.h" +#include "ngx_http_headers_more_util.h" +#include + + +static char *ngx_http_headers_more_parse_directive(ngx_conf_t *cf, + ngx_command_t *ngx_cmd, void *conf, + ngx_http_headers_more_opcode_t opcode); +static int ngx_http_headers_more_check_type(ngx_http_request_t *r, + ngx_array_t *types); +static ngx_int_t ngx_http_set_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_header_helper(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value, + ngx_table_elt_t **output_header); +static ngx_int_t ngx_http_set_builtin_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_user_agent_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_content_length_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_clear_builtin_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_clear_content_length_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_host_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_connection_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_builtin_multi_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_headers_more_validate_host(ngx_str_t *host, + ngx_pool_t *pool, ngx_uint_t alloc); + + +static ngx_http_headers_more_set_header_t ngx_http_headers_more_set_handlers[] + = { + + { ngx_string("Host"), + offsetof(ngx_http_headers_in_t, host), + ngx_http_set_host_header }, + + { ngx_string("Connection"), + offsetof(ngx_http_headers_in_t, connection), + ngx_http_set_connection_header }, + + { ngx_string("If-Modified-Since"), + offsetof(ngx_http_headers_in_t, if_modified_since), + ngx_http_set_builtin_header }, + +#if defined(nginx_version) && nginx_version >= 9002 + { ngx_string("If-Unmodified-Since"), + offsetof(ngx_http_headers_in_t, if_unmodified_since), + ngx_http_set_builtin_header }, +#endif + +#if defined(nginx_version) && nginx_version >= 1003003 + { ngx_string("If-Match"), + offsetof(ngx_http_headers_in_t, if_match), + ngx_http_set_builtin_header }, + + { ngx_string("If-None-Match"), + offsetof(ngx_http_headers_in_t, if_none_match), + ngx_http_set_builtin_header }, +#endif + + { ngx_string("User-Agent"), + offsetof(ngx_http_headers_in_t, user_agent), + ngx_http_set_user_agent_header }, + + { ngx_string("Referer"), + offsetof(ngx_http_headers_in_t, referer), + ngx_http_set_builtin_header }, + + { ngx_string("Content-Length"), + offsetof(ngx_http_headers_in_t, content_length), + ngx_http_set_content_length_header }, + + { ngx_string("Content-Type"), + offsetof(ngx_http_headers_in_t, content_type), + ngx_http_set_builtin_header }, + + { ngx_string("Range"), + offsetof(ngx_http_headers_in_t, range), + ngx_http_set_builtin_header }, + + { ngx_string("If-Range"), + offsetof(ngx_http_headers_in_t, if_range), + ngx_http_set_builtin_header }, + + { ngx_string("Transfer-Encoding"), + offsetof(ngx_http_headers_in_t, transfer_encoding), + ngx_http_set_builtin_header }, + + { ngx_string("Expect"), + offsetof(ngx_http_headers_in_t, expect), + ngx_http_set_builtin_header }, + +#if defined(nginx_version) && nginx_version >= 1003013 + { ngx_string("Upgrade"), + offsetof(ngx_http_headers_in_t, upgrade), + ngx_http_set_builtin_header }, +#endif + +#if (NGX_HTTP_GZIP) + { ngx_string("Accept-Encoding"), + offsetof(ngx_http_headers_in_t, accept_encoding), + ngx_http_set_builtin_header }, + + { ngx_string("Via"), offsetof(ngx_http_headers_in_t, via), + ngx_http_set_builtin_header }, +#endif + + { ngx_string("Authorization"), + offsetof(ngx_http_headers_in_t, authorization), + ngx_http_set_builtin_header }, + + { ngx_string("Keep-Alive"), + offsetof(ngx_http_headers_in_t, keep_alive), + ngx_http_set_builtin_header }, + +#if (NGX_HTTP_X_FORWARDED_FOR) + { ngx_string("X-Forwarded-For"), + offsetof(ngx_http_headers_in_t, x_forwarded_for), + ngx_http_set_builtin_multi_header }, + +#endif + +#if (NGX_HTTP_REALIP) + { ngx_string("X-Real-IP"), + offsetof(ngx_http_headers_in_t, x_real_ip), + ngx_http_set_builtin_header }, +#endif + +#if (NGX_HTTP_DAV) + { ngx_string("Depth"), offsetof(ngx_http_headers_in_t, depth), + ngx_http_set_builtin_header }, + + { ngx_string("Destination"), offsetof(ngx_http_headers_in_t, destination), + ngx_http_set_builtin_header }, + + { ngx_string("Overwrite"), offsetof(ngx_http_headers_in_t, overwrite), + ngx_http_set_builtin_header }, + + { ngx_string("Date"), offsetof(ngx_http_headers_in_t, date), + ngx_http_set_builtin_header }, +#endif + + { ngx_string("Cookie"), + offsetof(ngx_http_headers_in_t, cookies), + ngx_http_set_builtin_multi_header }, + + { ngx_null_string, 0, ngx_http_set_header } +}; + + +ngx_int_t +ngx_http_headers_more_exec_input_cmd(ngx_http_request_t *r, + ngx_http_headers_more_cmd_t *cmd) +{ + ngx_str_t value; + ngx_http_headers_more_header_val_t *h; + ngx_uint_t i; + + if (!cmd->headers) { + return NGX_OK; + } + + if (cmd->types && !ngx_http_headers_more_check_type(r, cmd->types)) { + return NGX_OK; + } + + h = cmd->headers->elts; + for (i = 0; i < cmd->headers->nelts; i++) { + + if (ngx_http_complex_value(r, &h[i].value, &value) != NGX_OK) { + return NGX_ERROR; + } + + if (value.len) { + value.len--; /* remove the trailing '\0' added by + ngx_http_headers_more_parse_header */ + } + + if (h[i].handler(r, &h[i], &value) != NGX_OK) { + return NGX_ERROR; + } + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_set_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + return ngx_http_set_header_helper(r, hv, value, NULL); +} + + +static ngx_int_t +ngx_http_set_header_helper(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value, + ngx_table_elt_t **output_header) +{ + ngx_table_elt_t *h, *matched; + ngx_list_part_t *part; + ngx_uint_t i; + ngx_uint_t rc; + + dd_enter(); + + matched = NULL; + +retry: + + part = &r->headers_in.headers.part; + h = part->elts; + + for (i = 0; /* void */; i++) { + dd("i: %d, part: %p", (int) i, part); + + if (i >= part->nelts) { + if (part->next == NULL) { + break; + } + + part = part->next; + h = part->elts; + i = 0; + } + + if (!hv->wildcard + && h[i].key.len == hv->key.len + && ngx_strncasecmp(h[i].key.data, hv->key.data, + h[i].key.len) == 0) + { + goto matched; + } + + if (hv->wildcard + && value->len == 0 + && h[i].key.len >= hv->key.len - 1 + && ngx_strncasecmp(h[i].key.data, hv->key.data, + hv->key.len - 1) == 0) + { + goto matched; + } + + /* not matched */ + continue; + +matched: + + if (value->len == 0 || (matched && matched != &h[i])) { + h[i].hash = 0; + + rc = ngx_http_headers_more_rm_header_helper( + &r->headers_in.headers, part, i); + + ngx_http_headers_more_assert( + !(r->headers_in.headers.part.next == NULL + && r->headers_in.headers.last + != &r->headers_in.headers.part)); + + if (rc == NGX_OK) { + if (output_header) { + *output_header = NULL; + } + + goto retry; + } + + return NGX_ERROR; + } + + h[i].value = *value; + + if (output_header) { + *output_header = &h[i]; + dd("setting existing builtin input header"); + } + + if (matched == NULL) { + matched = &h[i]; + } + } + + if (matched) { + return NGX_OK; + } + + if (value->len == 0 || hv->replace) { + return NGX_OK; + } + + if (r->headers_in.headers.last == NULL) { + /* must be 400 bad request */ + return NGX_OK; + } + + h = ngx_list_push(&r->headers_in.headers); + + if (h == NULL) { + return NGX_ERROR; + } + + dd("created new header for %.*s", (int) hv->key.len, hv->key.data); + + if (value->len == 0) { + h->hash = 0; + + } else { + h->hash = hv->hash; + } + + h->key = hv->key; + h->value = *value; + + h->lowcase_key = ngx_pnalloc(r->pool, h->key.len); + if (h->lowcase_key == NULL) { + return NGX_ERROR; + } + + ngx_strlow(h->lowcase_key, h->key.data, h->key.len); + + if (output_header) { + *output_header = h; + + while (r != r->main) { + r->parent->headers_in = r->headers_in; + r = r->parent; + } + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_set_builtin_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + ngx_table_elt_t *h, **old; + + dd("entered set_builtin_header (input)"); + + if (hv->offset) { + old = (ngx_table_elt_t **) ((char *) &r->headers_in + hv->offset); + + } else { + old = NULL; + } + + dd("old builtin ptr ptr: %p", old); + if (old) { + dd("old builtin ptr: %p", *old); + } + + if (old == NULL || *old == NULL) { + dd("set normal header"); + return ngx_http_set_header_helper(r, hv, value, old); + } + + h = *old; + + if (value->len == 0) { + h->hash = 0; + h->value = *value; + + return ngx_http_set_header_helper(r, hv, value, old); + } + + h->hash = hv->hash; + h->value = *value; + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_set_host_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + ngx_str_t host; + + if (value->len) { + host= *value; + + if (ngx_http_headers_more_validate_host(&host, r->pool, 0) != NGX_OK) { + return NGX_ERROR; + } + + r->headers_in.server = host; + + } else { + r->headers_in.server = *value; + } + + return ngx_http_set_builtin_header(r, hv, value); +} + + +static ngx_int_t +ngx_http_set_content_length_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + off_t len; + + if (value->len == 0) { + return ngx_http_clear_content_length_header(r, hv, value); + } + + len = ngx_atosz(value->data, value->len); + if (len == NGX_ERROR) { + return NGX_ERROR; + } + + dd("reset headers_in.content_length_n to %d", (int) len); + + r->headers_in.content_length_n = len; + + return ngx_http_set_builtin_header(r, hv, value); +} + + +static ngx_int_t +ngx_http_clear_content_length_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + r->headers_in.content_length_n = -1; + + return ngx_http_clear_builtin_header(r, hv, value); +} + + +static ngx_int_t +ngx_http_clear_builtin_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + value->len = 0; + return ngx_http_set_builtin_header(r, hv, value); +} + + +char * +ngx_http_headers_more_set_input_headers(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf) +{ + return ngx_http_headers_more_parse_directive(cf, cmd, conf, + ngx_http_headers_more_opcode_set); +} + + +char * +ngx_http_headers_more_clear_input_headers(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf) +{ + return ngx_http_headers_more_parse_directive(cf, cmd, conf, + ngx_http_headers_more_opcode_clear); +} + + +static int +ngx_http_headers_more_check_type(ngx_http_request_t *r, ngx_array_t *types) +{ + ngx_uint_t i; + ngx_str_t *t; + ngx_str_t actual_type; + + if (r->headers_in.content_type == NULL) { + return 0; + } + + actual_type = r->headers_in.content_type->value; + if (actual_type.len == 0) { + return 0; + } + + dd("headers_in->content_type: %.*s", + (int) actual_type.len, + actual_type.data); + + t = types->elts; + for (i = 0; i < types->nelts; i++) { + dd("...comparing with type [%.*s]", (int) t[i].len, t[i].data); + + if (actual_type.len == t[i].len + && ngx_strncmp(actual_type.data, t[i].data, t[i].len) == 0) + { + return 1; + } + } + + return 0; +} + + +static char * +ngx_http_headers_more_parse_directive(ngx_conf_t *cf, ngx_command_t *ngx_cmd, + void *conf, ngx_http_headers_more_opcode_t opcode) +{ + ngx_http_headers_more_loc_conf_t *hlcf = conf; + + ngx_uint_t i; + ngx_http_headers_more_cmd_t *cmd; + ngx_str_t *arg; + ngx_flag_t ignore_next_arg; + ngx_str_t *cmd_name; + ngx_int_t rc; + ngx_flag_t replace = 0; + ngx_http_headers_more_header_val_t *h; + + ngx_http_headers_more_main_conf_t *hmcf; + + if (hlcf->cmds == NULL) { + hlcf->cmds = ngx_array_create(cf->pool, 1, + sizeof(ngx_http_headers_more_cmd_t)); + + if (hlcf->cmds == NULL) { + return NGX_CONF_ERROR; + } + } + + cmd = ngx_array_push(hlcf->cmds); + + if (cmd == NULL) { + return NGX_CONF_ERROR; + } + + cmd->headers = ngx_array_create(cf->pool, 1, + sizeof(ngx_http_headers_more_header_val_t)); + + if (cmd->headers == NULL) { + return NGX_CONF_ERROR; + } + + cmd->types = ngx_array_create(cf->pool, 1, sizeof(ngx_str_t)); + if (cmd->types == NULL) { + return NGX_CONF_ERROR; + } + + cmd->statuses = NULL; + + arg = cf->args->elts; + + cmd_name = &arg[0]; + + ignore_next_arg = 0; + + for (i = 1; i < cf->args->nelts; i++) { + if (ignore_next_arg) { + ignore_next_arg = 0; + continue; + } + + if (arg[i].len == 0) { + continue; + } + + if (arg[i].data[0] != '-') { + rc = ngx_http_headers_more_parse_header(cf, cmd_name, + &arg[i], cmd->headers, + opcode, + ngx_http_headers_more_set_handlers); + + if (rc != NGX_OK) { + return NGX_CONF_ERROR; + } + + continue; + } + + if (arg[i].len == 2) { + if (arg[i].data[1] == 't') { + if (i == cf->args->nelts - 1) { + ngx_log_error(NGX_LOG_ERR, cf->log, 0, + "%V: option -t takes an argument.", + cmd_name); + + return NGX_CONF_ERROR; + } + + rc = ngx_http_headers_more_parse_types(cf->log, cmd_name, + &arg[i + 1], + cmd->types); + + if (rc != NGX_OK) { + return NGX_CONF_ERROR; + } + + ignore_next_arg = 1; + + continue; + } + + if (arg[i].data[1] == 'r') { + dd("Found replace flag"); + replace = 1; + continue; + } + } + + ngx_log_error(NGX_LOG_ERR, cf->log, 0, + "%V: invalid option name: \"%V\"", cmd_name, &arg[i]); + + return NGX_CONF_ERROR; + } + + dd("Found %d types, and %d headers", + (int) cmd->types->nelts, + (int) cmd->headers->nelts); + + if (cmd->headers->nelts == 0) { + ngx_pfree(cf->pool, cmd->headers); + cmd->headers = NULL; + + } else { + h = cmd->headers->elts; + for (i = 0; i < cmd->headers->nelts; i++) { + h[i].replace = replace; + } + } + + if (cmd->types->nelts == 0) { + ngx_pfree(cf->pool, cmd->types); + cmd->types = NULL; + } + + cmd->is_input = 1; + + hmcf = ngx_http_conf_get_module_main_conf(cf, + ngx_http_headers_more_filter_module); + + hmcf->requires_handler = 1; + + return NGX_CONF_OK; +} + + +/* borrowed the code from ngx_http_request.c:ngx_http_process_user_agent */ +static ngx_int_t +ngx_http_set_user_agent_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + u_char *user_agent, *msie; + + /* clear existing settings */ + + r->headers_in.msie = 0; + r->headers_in.msie6 = 0; + r->headers_in.opera = 0; + r->headers_in.gecko = 0; + r->headers_in.chrome = 0; + r->headers_in.safari = 0; + r->headers_in.konqueror = 0; + + if (value->len == 0) { + return ngx_http_set_builtin_header(r, hv, value); + } + + /* check some widespread browsers */ + + user_agent = value->data; + + msie = ngx_strstrn(user_agent, "MSIE ", 5 - 1); + + if (msie && msie + 7 < user_agent + value->len) { + + r->headers_in.msie = 1; + + if (msie[6] == '.') { + + switch (msie[5]) { + case '4': + case '5': + r->headers_in.msie6 = 1; + break; + case '6': + if (ngx_strstrn(msie + 8, "SV1", 3 - 1) == NULL) { + r->headers_in.msie6 = 1; + } + break; + } + } + } + + if (ngx_strstrn(user_agent, "Opera", 5 - 1)) { + r->headers_in.opera = 1; + r->headers_in.msie = 0; + r->headers_in.msie6 = 0; + } + + if (!r->headers_in.msie && !r->headers_in.opera) { + + if (ngx_strstrn(user_agent, "Gecko/", 6 - 1)) { + r->headers_in.gecko = 1; + + } else if (ngx_strstrn(user_agent, "Chrome/", 7 - 1)) { + r->headers_in.chrome = 1; + + } else if (ngx_strstrn(user_agent, "Safari/", 7 - 1) + && ngx_strstrn(user_agent, "Mac OS X", 8 - 1)) + { + r->headers_in.safari = 1; + + } else if (ngx_strstrn(user_agent, "Konqueror", 9 - 1)) { + r->headers_in.konqueror = 1; + } + } + + return ngx_http_set_builtin_header(r, hv, value); +} + + +static ngx_int_t +ngx_http_set_connection_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + r->headers_in.connection_type = 0; + + if (value->len == 0) { + return ngx_http_set_builtin_header(r, hv, value); + } + + if (ngx_strcasestrn(value->data, "close", 5 - 1)) { + r->headers_in.connection_type = NGX_HTTP_CONNECTION_CLOSE; + r->headers_in.keep_alive_n = -1; + + } else if (ngx_strcasestrn(value->data, "keep-alive", 10 - 1)) { + r->headers_in.connection_type = NGX_HTTP_CONNECTION_KEEP_ALIVE; + } + + return ngx_http_set_builtin_header(r, hv, value); +} + + +static ngx_int_t +ngx_http_set_builtin_multi_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + ngx_array_t *headers; + ngx_table_elt_t **v, *h; + + if (r->headers_out.status == 400 || r->headers_in.headers.last == NULL) { + /* must be a 400 Bad Request */ + return NGX_OK; + } + + headers = (ngx_array_t *) ((char *) &r->headers_in + hv->offset); + + if (headers->nelts > 0) { + ngx_array_destroy(headers); + + if (ngx_array_init(headers, r->pool, 2, + sizeof(ngx_table_elt_t *)) + != NGX_OK) + { + return NGX_ERROR; + } + + dd("clear multi-value headers: %d", (int) headers->nelts); + } + +#if 1 + if (headers->nalloc == 0) { + if (ngx_array_init(headers, r->pool, 2, + sizeof(ngx_table_elt_t *)) + != NGX_OK) + { + return NGX_ERROR; + } + } +#endif + + h = NULL; + if (ngx_http_set_header_helper(r, hv, value, &h) == NGX_ERROR) { + return NGX_ERROR; + } + + if (value->len == 0) { + return NGX_OK; + } + + dd("new cookie header: %p", h); + + v = ngx_array_push(headers); + if (v == NULL) { + return NGX_ERROR; + } + + *v = h; + return NGX_OK; +} + + +static ngx_int_t +ngx_http_headers_more_validate_host(ngx_str_t *host, ngx_pool_t *pool, + ngx_uint_t alloc) +{ + u_char *h, ch; + size_t i, dot_pos, host_len; + + enum { + sw_usual = 0, + sw_literal, + sw_rest + } state; + + dot_pos = host->len; + host_len = host->len; + + h = host->data; + + state = sw_usual; + + for (i = 0; i < host->len; i++) { + ch = h[i]; + + switch (ch) { + + case '.': + if (dot_pos == i - 1) { + return NGX_DECLINED; + } + dot_pos = i; + break; + + case ':': + if (state == sw_usual) { + host_len = i; + state = sw_rest; + } + break; + + case '[': + if (i == 0) { + state = sw_literal; + } + break; + + case ']': + if (state == sw_literal) { + host_len = i + 1; + state = sw_rest; + } + break; + + case '\0': + return NGX_DECLINED; + + default: + + if (ngx_path_separator(ch)) { + return NGX_DECLINED; + } + + if (ch >= 'A' && ch <= 'Z') { + alloc = 1; + } + + break; + } + } + + if (dot_pos == host_len - 1) { + host_len--; + } + + if (host_len == 0) { + return NGX_DECLINED; + } + + if (alloc) { + host->data = ngx_pnalloc(pool, host_len); + if (host->data == NULL) { + return NGX_ERROR; + } + + ngx_strlow(host->data, h, host_len); + } + + host->len = host_len; + + return NGX_OK; +} diff --git a/headers-more-nginx-module/src/ngx_http_headers_more_headers_in.h b/headers-more-nginx-module/src/ngx_http_headers_more_headers_in.h new file mode 100644 index 00000000..d2251da1 --- /dev/null +++ b/headers-more-nginx-module/src/ngx_http_headers_more_headers_in.h @@ -0,0 +1,26 @@ + +/* + * Copyright (c) Yichun Zhang (agentzh) + */ + + +#ifndef NGX_HTTP_HEADERS_MORE_INPUT_HEADERS_H +#define NGX_HTTP_HEADERS_MORE_INPUT_HEADERS_H + + +#include "ngx_http_headers_more_filter_module.h" + + +/* output header setters and clearers */ + +ngx_int_t ngx_http_headers_more_exec_input_cmd(ngx_http_request_t *r, + ngx_http_headers_more_cmd_t *cmd); + +char *ngx_http_headers_more_set_input_headers(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); + +char *ngx_http_headers_more_clear_input_headers(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); + + +#endif /* NGX_HTTP_HEADERS_MORE_INPUT_HEADERS_H */ diff --git a/headers-more-nginx-module/src/ngx_http_headers_more_headers_out.c b/headers-more-nginx-module/src/ngx_http_headers_more_headers_out.c new file mode 100644 index 00000000..0f9bc877 --- /dev/null +++ b/headers-more-nginx-module/src/ngx_http_headers_more_headers_out.c @@ -0,0 +1,716 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_headers_more_headers_out.h" +#include "ngx_http_headers_more_util.h" +#include + + +static char * +ngx_http_headers_more_parse_directive(ngx_conf_t *cf, ngx_command_t *ngx_cmd, + void *conf, ngx_http_headers_more_opcode_t opcode); +static ngx_flag_t ngx_http_headers_more_check_type(ngx_http_request_t *r, + ngx_array_t *types); +static ngx_flag_t ngx_http_headers_more_check_status(ngx_http_request_t *r, + ngx_array_t *statuses); +static ngx_int_t ngx_http_set_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_header_helper(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value, + ngx_table_elt_t **output_header, ngx_flag_t no_create); +static ngx_int_t ngx_http_set_builtin_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_accept_ranges_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_content_length_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_content_type_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_clear_builtin_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_clear_content_length_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); +static ngx_int_t ngx_http_set_builtin_multi_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); + + +static ngx_http_headers_more_set_header_t ngx_http_headers_more_set_handlers[] + = { + + { ngx_string("Server"), + offsetof(ngx_http_headers_out_t, server), + ngx_http_set_builtin_header }, + + { ngx_string("Date"), + offsetof(ngx_http_headers_out_t, date), + ngx_http_set_builtin_header }, + + { ngx_string("Content-Encoding"), + offsetof(ngx_http_headers_out_t, content_encoding), + ngx_http_set_builtin_header }, + + { ngx_string("Location"), + offsetof(ngx_http_headers_out_t, location), + ngx_http_set_builtin_header }, + + { ngx_string("Refresh"), + offsetof(ngx_http_headers_out_t, refresh), + ngx_http_set_builtin_header }, + + { ngx_string("Last-Modified"), + offsetof(ngx_http_headers_out_t, last_modified), + ngx_http_set_builtin_header }, + + { ngx_string("Content-Range"), + offsetof(ngx_http_headers_out_t, content_range), + ngx_http_set_builtin_header }, + + { ngx_string("Accept-Ranges"), + offsetof(ngx_http_headers_out_t, accept_ranges), + ngx_http_set_accept_ranges_header }, + + { ngx_string("WWW-Authenticate"), + offsetof(ngx_http_headers_out_t, www_authenticate), + ngx_http_set_builtin_header }, + + { ngx_string("Expires"), + offsetof(ngx_http_headers_out_t, expires), + ngx_http_set_builtin_header }, + + { ngx_string("E-Tag"), + offsetof(ngx_http_headers_out_t, etag), + ngx_http_set_builtin_header }, + + { ngx_string("Content-Length"), + offsetof(ngx_http_headers_out_t, content_length), + ngx_http_set_content_length_header }, + + { ngx_string("Content-Type"), + 0, + ngx_http_set_content_type_header }, + + { ngx_string("Cache-Control"), + offsetof(ngx_http_headers_out_t, cache_control), + ngx_http_set_builtin_multi_header }, + + { ngx_null_string, 0, ngx_http_set_header } +}; + + +ngx_int_t +ngx_http_headers_more_exec_cmd(ngx_http_request_t *r, + ngx_http_headers_more_cmd_t *cmd) +{ + ngx_str_t value; + ngx_http_headers_more_header_val_t *h; + ngx_uint_t i; + + if (!cmd->headers) { + return NGX_OK; + } + + if (cmd->types && !ngx_http_headers_more_check_type(r, cmd->types)) { + return NGX_OK; + } + + if (cmd->statuses + && !ngx_http_headers_more_check_status(r, cmd->statuses)) + { + return NGX_OK; + } + + h = cmd->headers->elts; + for (i = 0; i < cmd->headers->nelts; i++) { + + if (ngx_http_complex_value(r, &h[i].value, &value) != NGX_OK) { + return NGX_ERROR; + } + + if (value.len) { + value.len--; /* remove the trailing '\0' added by + ngx_http_headers_more_parse_header */ + } + + if (h[i].handler(r, &h[i], &value) != NGX_OK) { + return NGX_ERROR; + } + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_set_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + return ngx_http_set_header_helper(r, hv, value, NULL, 0); +} + + +static ngx_int_t +ngx_http_set_header_helper(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value, + ngx_table_elt_t **output_header, ngx_flag_t no_create) +{ + ngx_table_elt_t *h; + ngx_list_part_t *part; + ngx_uint_t i; + ngx_flag_t matched = 0; + + dd_enter(); + +#if 1 + if (r->headers_out.location + && r->headers_out.location->value.len + && r->headers_out.location->value.data[0] == '/') + { + /* XXX ngx_http_core_find_config_phase, for example, + * may not initialize the "key" and "hash" fields + * for a nasty optimization purpose, and + * we have to work-around it here */ + + r->headers_out.location->hash = ngx_http_headers_more_location_hash; + ngx_str_set(&r->headers_out.location->key, "Location"); + } +#endif + + part = &r->headers_out.headers.part; + h = part->elts; + + for (i = 0; /* void */; i++) { + + if (i >= part->nelts) { + if (part->next == NULL) { + break; + } + + part = part->next; + h = part->elts; + i = 0; + } + + if (h[i].hash == 0) { + continue; + } + + if (!hv->wildcard + && h[i].key.len == hv->key.len + && ngx_strncasecmp(h[i].key.data, hv->key.data, + h[i].key.len) == 0) + { + goto matched; + } + + if (hv->wildcard + && h[i].key.len >= hv->key.len - 1 + && ngx_strncasecmp(h[i].key.data, hv->key.data, + hv->key.len - 1) == 0) + { + goto matched; + } + + /* not matched */ + continue; + +matched: + + if (value->len == 0 || matched) { + dd("clearing normal header for %.*s", (int) hv->key.len, + hv->key.data); + + h[i].value.len = 0; + h[i].hash = 0; + + } else { + h[i].value = *value; + h[i].hash = hv->hash; + } + + if (output_header) { + *output_header = &h[i]; + } + + matched = 1; + } + + if (matched){ + return NGX_OK; + } + + if ((hv->wildcard || no_create) && value->len == 0) { + return NGX_OK; + } + + /* XXX we still need to create header slot even if the value + * is empty because some builtin headers like Last-Modified + * relies on this to get cleared */ + + h = ngx_list_push(&r->headers_out.headers); + if (h == NULL) { + return NGX_ERROR; + } + + if (value->len == 0) { + h->hash = 0; + + } else { + h->hash = hv->hash; + } + + h->key = hv->key; + h->value = *value; + + h->lowcase_key = ngx_pnalloc(r->pool, h->key.len); + if (h->lowcase_key == NULL) { + return NGX_ERROR; + } + + ngx_strlow(h->lowcase_key, h->key.data, h->key.len); + + if (output_header) { + *output_header = h; + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_set_builtin_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + ngx_table_elt_t *h, **old; + + dd_enter(); + + if (hv->offset) { + old = (ngx_table_elt_t **) ((char *) &r->headers_out + hv->offset); + + } else { + old = NULL; + } + + if (old == NULL || *old == NULL) { + return ngx_http_set_header_helper(r, hv, value, old, 0); + } + + h = *old; + + if (value->len == 0) { + dd("clearing the builtin header"); + + h->hash = 0; + h->value = *value; + + return NGX_OK; + } + + h->hash = hv->hash; + h->key = hv->key; + h->value = *value; + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_set_builtin_multi_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + ngx_array_t *pa; + ngx_table_elt_t *ho, **ph; + ngx_uint_t i; + + pa = (ngx_array_t *) ((char *) &r->headers_out + hv->offset); + + if (pa->elts == NULL) { + if (ngx_array_init(pa, r->pool, 2, sizeof(ngx_table_elt_t *)) + != NGX_OK) + { + return NGX_ERROR; + } + } + + /* override old values (if any) */ + + if (pa->nelts > 0) { + ph = pa->elts; + for (i = 1; i < pa->nelts; i++) { + ph[i]->hash = 0; + ph[i]->value.len = 0; + } + + ph[0]->value = *value; + + if (value->len == 0) { + ph[0]->hash = 0; + + } else { + ph[0]->hash = hv->hash; + } + + return NGX_OK; + } + + ph = ngx_array_push(pa); + if (ph == NULL) { + return NGX_ERROR; + } + + ho = ngx_list_push(&r->headers_out.headers); + if (ho == NULL) { + return NGX_ERROR; + } + + ho->value = *value; + ho->hash = hv->hash; + ngx_str_set(&ho->key, "Cache-Control"); + *ph = ho; + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_set_content_type_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + u_char *p, *last, *end; + + r->headers_out.content_type_len = value->len; + r->headers_out.content_type = *value; + r->headers_out.content_type_hash = hv->hash; + r->headers_out.content_type_lowcase = NULL; + + p = value->data; + end = p + value->len; + + for (; p != end; p++) { + + if (*p != ';') { + continue; + } + + last = p; + + while (*++p == ' ') { /* void */ } + + if (p == end) { + break; + } + + if (ngx_strncasecmp(p, (u_char *) "charset=", 8) != 0) { + continue; + } + + p += 8; + + r->headers_out.content_type_len = last - value->data; + + if (*p == '"') { + p++; + } + + last = end; + + if (*(last - 1) == '"') { + last--; + } + + r->headers_out.charset.len = last - p; + r->headers_out.charset.data = p; + + break; + } + + value->len = 0; + + return ngx_http_set_header_helper(r, hv, value, NULL, 1); +} + + +static ngx_int_t +ngx_http_set_content_length_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + off_t len; + + if (value->len == 0) { + return ngx_http_clear_content_length_header(r, hv, value); + } + + len = ngx_atosz(value->data, value->len); + if (len == NGX_ERROR) { + return NGX_ERROR; + } + + r->headers_out.content_length_n = len; + + return ngx_http_set_builtin_header(r, hv, value); +} + + +static ngx_int_t +ngx_http_set_accept_ranges_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + if (value->len == 0) { + r->allow_ranges = 0; + } + + return ngx_http_set_builtin_header(r, hv, value); +} + + +static ngx_int_t +ngx_http_clear_content_length_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + r->headers_out.content_length_n = -1; + + return ngx_http_clear_builtin_header(r, hv, value); +} + + +static ngx_int_t +ngx_http_clear_builtin_header(ngx_http_request_t *r, + ngx_http_headers_more_header_val_t *hv, ngx_str_t *value) +{ + dd_enter(); + + value->len = 0; + + return ngx_http_set_builtin_header(r, hv, value); +} + + +char * +ngx_http_headers_more_set_headers(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf) +{ + return ngx_http_headers_more_parse_directive(cf, cmd, conf, + ngx_http_headers_more_opcode_set); +} + + +char * +ngx_http_headers_more_clear_headers(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf) +{ + return ngx_http_headers_more_parse_directive(cf, cmd, conf, + ngx_http_headers_more_opcode_clear); +} + + +static ngx_flag_t +ngx_http_headers_more_check_type(ngx_http_request_t *r, ngx_array_t *types) +{ + ngx_uint_t i; + ngx_str_t *t; + + dd("headers_out->content_type: %.*s (len %d)", + (int) r->headers_out.content_type.len, + r->headers_out.content_type.data, + (int) r->headers_out.content_type.len); + + t = types->elts; + + for (i = 0; i < types->nelts; i++) { + dd("...comparing with type [%.*s]", (int) t[i].len, t[i].data); + + if (r->headers_out.content_type_len == t[i].len + && ngx_strncmp(r->headers_out.content_type.data, + t[i].data, t[i].len) == 0) + { + return 1; + } + } + + return 0; +} + + +static ngx_flag_t +ngx_http_headers_more_check_status(ngx_http_request_t *r, ngx_array_t *statuses) +{ + ngx_uint_t i; + ngx_uint_t *status; + + dd("headers_out.status = %d", (int) r->headers_out.status); + + status = statuses->elts; + for (i = 0; i < statuses->nelts; i++) { + dd("...comparing with specified status %d", (int) status[i]); + + if (r->headers_out.status == status[i]) { + return 1; + } + } + + return 0; +} + + +static char * +ngx_http_headers_more_parse_directive(ngx_conf_t *cf, ngx_command_t *ngx_cmd, + void *conf, ngx_http_headers_more_opcode_t opcode) +{ + ngx_http_headers_more_loc_conf_t *hlcf = conf; + + ngx_uint_t i; + ngx_http_headers_more_cmd_t *cmd; + ngx_str_t *arg; + ngx_flag_t ignore_next_arg; + ngx_str_t *cmd_name; + ngx_int_t rc; + + ngx_http_headers_more_main_conf_t *hmcf; + + if (hlcf->cmds == NULL) { + hlcf->cmds = ngx_array_create(cf->pool, 1, + sizeof(ngx_http_headers_more_cmd_t)); + + if (hlcf->cmds == NULL) { + return NGX_CONF_ERROR; + } + } + + cmd = ngx_array_push(hlcf->cmds); + if (cmd == NULL) { + return NGX_CONF_ERROR; + } + + cmd->headers = + ngx_array_create(cf->pool, 1, + sizeof(ngx_http_headers_more_header_val_t)); + if (cmd->headers == NULL) { + return NGX_CONF_ERROR; + } + + cmd->types = ngx_array_create(cf->pool, 1, sizeof(ngx_str_t)); + if (cmd->types == NULL) { + return NGX_CONF_ERROR; + } + + cmd->statuses = ngx_array_create(cf->pool, 1, sizeof(ngx_uint_t)); + if (cmd->statuses == NULL) { + return NGX_CONF_ERROR; + } + + arg = cf->args->elts; + + cmd_name = &arg[0]; + + ignore_next_arg = 0; + + for (i = 1; i < cf->args->nelts; i++) { + + if (ignore_next_arg) { + ignore_next_arg = 0; + continue; + } + + if (arg[i].len == 0) { + continue; + } + + if (arg[i].data[0] != '-') { + rc = ngx_http_headers_more_parse_header(cf, cmd_name, + &arg[i], cmd->headers, + opcode, + ngx_http_headers_more_set_handlers); + + if (rc != NGX_OK) { + return NGX_CONF_ERROR; + } + + continue; + } + + if (arg[i].len == 2) { + if (arg[i].data[1] == 't') { + if (i == cf->args->nelts - 1) { + ngx_log_error(NGX_LOG_ERR, cf->log, 0, + "%V: option -t takes an argument.", + cmd_name); + + return NGX_CONF_ERROR; + } + + rc = ngx_http_headers_more_parse_types(cf->log, cmd_name, + &arg[i + 1], + cmd->types); + + if (rc != NGX_OK) { + return NGX_CONF_ERROR; + } + + ignore_next_arg = 1; + + continue; + + } else if (arg[i].data[1] == 's') { + + if (i == cf->args->nelts - 1) { + ngx_log_error(NGX_LOG_ERR, cf->log, 0, + "%V: option -s takes an argument.", + cmd_name); + + return NGX_CONF_ERROR; + } + + rc = ngx_http_headers_more_parse_statuses(cf->log, cmd_name, + &arg[i + 1], + cmd->statuses); + + if (rc != NGX_OK) { + return NGX_CONF_ERROR; + } + + ignore_next_arg = 1; + + continue; + } + } + + ngx_log_error(NGX_LOG_ERR, cf->log, 0, + "%V: invalid option name: \"%V\"", cmd_name, &arg[i]); + + return NGX_CONF_ERROR; + } + + dd("Found %d statuses, %d types, and %d headers", + (int) cmd->statuses->nelts, (int) cmd->types->nelts, + (int) cmd->headers->nelts); + + if (cmd->headers->nelts == 0) { + cmd->headers = NULL; + } + + if (cmd->types->nelts == 0) { + cmd->types = NULL; + } + + if (cmd->statuses->nelts == 0) { + cmd->statuses = NULL; + } + + cmd->is_input = 0; + + hmcf = ngx_http_conf_get_module_main_conf(cf, + ngx_http_headers_more_filter_module); + + hmcf->requires_filter = 1; + + return NGX_CONF_OK; +} diff --git a/headers-more-nginx-module/src/ngx_http_headers_more_headers_out.h b/headers-more-nginx-module/src/ngx_http_headers_more_headers_out.h new file mode 100644 index 00000000..c9395073 --- /dev/null +++ b/headers-more-nginx-module/src/ngx_http_headers_more_headers_out.h @@ -0,0 +1,26 @@ + +/* + * Copyright (c) Yichun Zhang (agentzh) + */ + + +#ifndef NGX_HTTP_HEADERS_MORE_OUTPUT_HEADERS_H +#define NGX_HTTP_HEADERS_MORE_OUTPUT_HEADERS_H + + +#include "ngx_http_headers_more_filter_module.h" + + +/* output header setters and clearers */ + +ngx_int_t ngx_http_headers_more_exec_cmd(ngx_http_request_t *r, + ngx_http_headers_more_cmd_t *cmd); + +char *ngx_http_headers_more_set_headers(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); + +char *ngx_http_headers_more_clear_headers(ngx_conf_t *cf, + ngx_command_t *cmd, void *conf); + + +#endif /* NGX_HTTP_HEADERS_MORE_OUTPUT_HEADERS_H */ diff --git a/headers-more-nginx-module/src/ngx_http_headers_more_util.c b/headers-more-nginx-module/src/ngx_http_headers_more_util.c new file mode 100644 index 00000000..caf372e9 --- /dev/null +++ b/headers-more-nginx-module/src/ngx_http_headers_more_util.c @@ -0,0 +1,380 @@ + +/* + * Copyright (C) Yichun Zhang (agentzh) + */ + + +#ifndef DDEBUG +#define DDEBUG 0 +#endif +#include "ddebug.h" + + +#include "ngx_http_headers_more_util.h" +#include + + +ngx_int_t +ngx_http_headers_more_parse_header(ngx_conf_t *cf, ngx_str_t *cmd_name, + ngx_str_t *raw_header, ngx_array_t *headers, + ngx_http_headers_more_opcode_t opcode, + ngx_http_headers_more_set_header_t *handlers) +{ + ngx_http_headers_more_header_val_t *hv; + + ngx_uint_t i; + ngx_str_t key = ngx_null_string; + ngx_str_t value = ngx_null_string; + ngx_flag_t seen_end_of_key; + ngx_http_compile_complex_value_t ccv; + u_char *p; + + hv = ngx_array_push(headers); + if (hv == NULL) { + return NGX_ERROR; + } + + seen_end_of_key = 0; + for (i = 0; i < raw_header->len; i++) { + if (key.len == 0) { + if (isspace(raw_header->data[i])) { + continue; + } + + key.data = raw_header->data; + key.len = 1; + + continue; + } + + if (!seen_end_of_key) { + if (raw_header->data[i] == ':' + || isspace(raw_header->data[i])) + { + seen_end_of_key = 1; + continue; + } + + key.len++; + + continue; + } + + if (value.len == 0) { + if (raw_header->data[i] == ':' + || isspace(raw_header->data[i])) + { + continue; + } + + value.data = &raw_header->data[i]; + value.len = 1; + + continue; + } + + value.len++; + } + + if (key.len == 0) { + ngx_log_error(NGX_LOG_ERR, cf->log, 0, + "%V: no key found in the header argument: %V", + cmd_name, raw_header); + + return NGX_ERROR; + } + + hv->wildcard = (key.data[key.len - 1] == '*'); + if (hv->wildcard && key.len<2){ + ngx_log_error(NGX_LOG_ERR, cf->log, 0, + "%V: wildcard key too short: %V", + cmd_name, raw_header); + return NGX_ERROR; + } + + hv->hash = ngx_hash_key_lc(key.data, key.len); + hv->key = key; + + hv->offset = 0; + + for (i = 0; handlers[i].name.len; i++) { + if (hv->key.len != handlers[i].name.len + || ngx_strncasecmp(hv->key.data, handlers[i].name.data, + handlers[i].name.len) != 0) + { + dd("hv key comparison: %s <> %s", handlers[i].name.data, + hv->key.data); + + continue; + } + + hv->offset = handlers[i].offset; + hv->handler = handlers[i].handler; + + break; + } + + if (handlers[i].name.len == 0 && handlers[i].handler) { + hv->offset = handlers[i].offset; + hv->handler = handlers[i].handler; + } + + if (opcode == ngx_http_headers_more_opcode_clear) { + value.len = 0; + } + + if (value.len == 0) { + ngx_memzero(&hv->value, sizeof(ngx_http_complex_value_t)); + return NGX_OK; + + } + + /* Nginx request header value requires to be a null-terminated + * C string */ + + p = ngx_palloc(cf->pool, value.len + 1); + if (p == NULL) { + return NGX_ERROR; + } + + ngx_memcpy(p, value.data, value.len); + p[value.len] = '\0'; + value.data = p; + value.len++; /* we should also compile the trailing '\0' */ + + /* compile the header value as a complex value */ + + ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t)); + + ccv.cf = cf; + ccv.value = &value; + ccv.complex_value = &hv->value; + + if (ngx_http_compile_complex_value(&ccv) != NGX_OK) { + return NGX_ERROR; + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_headers_more_parse_statuses(ngx_log_t *log, ngx_str_t *cmd_name, + ngx_str_t *value, ngx_array_t *statuses) +{ + u_char *p, *last; + ngx_uint_t *s = NULL; + + p = value->data; + last = p + value->len; + + for (; p != last; p++) { + if (s == NULL) { + if (isspace(*p)) { + continue; + } + + s = ngx_array_push(statuses); + if (s == NULL) { + return NGX_ERROR; + } + + if (*p >= '0' && *p <= '9') { + *s = *p - '0'; + + } else { + ngx_log_error(NGX_LOG_ERR, log, 0, + "%V: invalid digit \"%c\" found in " + "the status code list \"%V\"", + cmd_name, *p, value); + + return NGX_ERROR; + } + + continue; + } + + if (isspace(*p)) { + dd("Parsed status %d", (int) *s); + + s = NULL; + continue; + } + + if (*p >= '0' && *p <= '9') { + *s *= 10; + *s += *p - '0'; + + } else { + ngx_log_error(NGX_LOG_ERR, log, 0, + "%V: invalid digit \"%c\" found in " + "the status code list \"%V\"", + cmd_name, *p, value); + + return NGX_ERROR; + } + } + + if (s) { + dd("Parsed status %d", (int) *s); + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_headers_more_parse_types(ngx_log_t *log, ngx_str_t *cmd_name, + ngx_str_t *value, ngx_array_t *types) +{ + u_char *p, *last; + ngx_str_t *t = NULL; + + p = value->data; + last = p + value->len; + + for (; p != last; p++) { + if (t == NULL) { + if (isspace(*p) || *p == ';') { + continue; + } + + t = ngx_array_push(types); + if (t == NULL) { + return NGX_ERROR; + } + + t->len = 1; + t->data = p; + + continue; + } + + if (isspace(*p) || *p == ';') { + t = NULL; + continue; + } + + t->len++; + } + + return NGX_OK; +} + + +ngx_int_t +ngx_http_headers_more_rm_header_helper(ngx_list_t *l, ngx_list_part_t *cur, + ngx_uint_t i) +{ + ngx_table_elt_t *data; + ngx_list_part_t *new, *part; + + dd("list rm item: part %p, i %d, nalloc %d", cur, (int) i, + (int) l->nalloc); + + data = cur->elts; + + dd("cur: nelts %d, nalloc %d", (int) cur->nelts, + (int) l->nalloc); + + if (i == 0) { + cur->elts = (char *) cur->elts + l->size; + cur->nelts--; + + if (cur == l->last) { + if (cur->nelts == 0) { +#if 1 + part = &l->part; + + if (part == cur) { + cur->elts = (char *) cur->elts - l->size; + /* do nothing */ + + } else { + while (part->next != cur) { + if (part->next == NULL) { + return NGX_ERROR; + } + part = part->next; + } + + l->last = part; + part->next = NULL; + dd("part nelts: %d", (int) part->nelts); + l->nalloc = part->nelts; + } +#endif + + } else { + l->nalloc--; + } + + return NGX_OK; + } + + if (cur->nelts == 0) { + part = &l->part; + + if (part == cur) { + ngx_http_headers_more_assert(cur->next != NULL); + + dd("remove 'cur' from the list by rewriting 'cur': " + "l->last: %p, cur: %p, cur->next: %p, part: %p", + l->last, cur, cur->next, part); + + if (l->last == cur->next) { + dd("last is cur->next"); + l->part = *(cur->next); + l->last = part; + l->nalloc = part->nelts; + + } else { + l->part = *(cur->next); + } + + } else { + dd("remove 'cur' from the list"); + while (part->next != cur) { + if (part->next == NULL) { + return NGX_ERROR; + } + part = part->next; + } + + part->next = cur->next; + } + + return NGX_OK; + } + + return NGX_OK; + } + + if (i == cur->nelts - 1) { + cur->nelts--; + + if (cur == l->last) { + l->nalloc = cur->nelts; + } + + return NGX_OK; + } + + new = ngx_palloc(l->pool, sizeof(ngx_list_part_t)); + if (new == NULL) { + return NGX_ERROR; + } + + new->elts = &data[i + 1]; + new->nelts = cur->nelts - i - 1; + new->next = cur->next; + + cur->nelts = i; + cur->next = new; + if (cur == l->last) { + l->last = new; + l->nalloc = new->nelts; + } + + return NGX_OK; +} diff --git a/headers-more-nginx-module/src/ngx_http_headers_more_util.h b/headers-more-nginx-module/src/ngx_http_headers_more_util.h new file mode 100644 index 00000000..6c4614ba --- /dev/null +++ b/headers-more-nginx-module/src/ngx_http_headers_more_util.h @@ -0,0 +1,52 @@ + +/* + * Copyright (c) Yichun Zhang (agentzh) + */ + + +#ifndef NGX_HTTP_HEADERS_MORE_UTIL_H +#define NGX_HTTP_HEADERS_MORE_UTIL_H + + +#include "ngx_http_headers_more_filter_module.h" + + +#define ngx_http_headers_more_hash_literal(s) \ + ngx_http_headers_more_hash_str((u_char *) s, sizeof(s) - 1) + + +static ngx_inline ngx_uint_t +ngx_http_headers_more_hash_str(u_char *src, size_t n) +{ + ngx_uint_t key; + + key = 0; + + while (n--) { + key = ngx_hash(key, *src); + src++; + } + + return key; +} + + +extern ngx_uint_t ngx_http_headers_more_location_hash; + + +ngx_int_t ngx_http_headers_more_parse_header(ngx_conf_t *cf, + ngx_str_t *cmd_name, ngx_str_t *raw_header, ngx_array_t *headers, + ngx_http_headers_more_opcode_t opcode, + ngx_http_headers_more_set_header_t *handlers); + +ngx_int_t ngx_http_headers_more_parse_statuses(ngx_log_t *log, + ngx_str_t *cmd_name, ngx_str_t *value, ngx_array_t *statuses); + +ngx_int_t ngx_http_headers_more_parse_types(ngx_log_t *log, + ngx_str_t *cmd_name, ngx_str_t *value, ngx_array_t *types); + +ngx_int_t ngx_http_headers_more_rm_header_helper(ngx_list_t *l, + ngx_list_part_t *cur, ngx_uint_t i); + + +#endif /* NGX_HTTP_HEADERS_MORE_UTIL_H */ diff --git a/headers-more-nginx-module/t/bug.t b/headers-more-nginx-module/t/bug.t new file mode 100644 index 00000000..88cfa095 --- /dev/null +++ b/headers-more-nginx-module/t/bug.t @@ -0,0 +1,393 @@ +# vi:filetype= + +use Test::Nginx::Socket; # 'no_plan'; + +repeat_each(2); + +plan tests => 53 * repeat_each(); + +no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: set Server +--- config + #more_set_headers 'Last-Modified: x'; + more_clear_headers 'Last-Modified'; +--- request + GET /index.html +--- response_headers +! Last-Modified +--- response_body_like: It works! + + + +=== TEST 2: variables in the Ranges header +--- config + location /index.html { + set $rfrom 1; + set $rto 3; + more_set_input_headers 'Range: bytes=$rfrom - $rto'; + #more_set_input_headers 'Range: bytes=1 - 3'; + #echo $http_range; + } +--- request +GET /index.html +--- error_code: 206 +--- response_body chomp +htm + + + +=== TEST 3: mime type overriding (inlined types) +--- config + more_clear_headers 'X-Powered-By' 'X-Runtime' 'ETag'; + + types { + text/html html htm shtml; + text/css css; + } +--- user_files +>>> a.css +hello +--- request +GET /a.css +--- error_code: 200 +--- response_headers +Content-Type: text/css +--- response_body +hello + + + +=== TEST 4: mime type overriding (included types file) +--- config + more_clear_headers 'X-Powered-By' 'X-Runtime' 'ETag'; + include mime.types; +--- user_files +>>> a.css +hello +>>> ../conf/mime.types +types { + text/html html htm shtml; + text/css css; +} +--- request +GET /a.css +--- error_code: 200 +--- response_headers +Content-Type: text/css +--- response_body +hello + + + +=== TEST 5: empty variable as the header value +--- config + location /foo { + more_set_headers 'X-Foo: $arg_foo'; + echo hi; + } +--- request + GET /foo +--- response_headers +! X-Foo +--- response_body +hi + + + +=== TEST 6: range bug +--- config + location /index.html { + more_clear_input_headers "Range*" ; + more_clear_input_headers "Content-Range*" ; + + more_set_input_headers 'Range: bytes=1-5'; + more_set_headers 'Content-Range: bytes 1-5/1000'; + } +--- request + GET /index.html +--- more_headers +Range: bytes=1-3 +--- raw_response_headers_like: Content-Range: bytes 1-5/1000$ +--- response_body chop +html> +--- error_code: 206 +--- SKIP + + + +=== TEST 7: Allow-Ranges +--- config + location /index.html { + more_clear_headers 'Accept-Ranges'; + } +--- request + GET /index.html +--- response_headers +! Accept-Ranges +--- response_body_like: It works + + + +=== TEST 8: clear hand-written Allow-Ranges headers +--- config + location /index.html { + more_set_headers 'Accept-Ranges: bytes'; + more_clear_headers 'Accept-Ranges'; + } +--- request + GET /index.html +--- response_headers +! Accept-Ranges +--- response_body_like: It works + + + +=== TEST 9: clear first, then add +--- config + location /bug { + more_clear_headers 'Foo'; + more_set_headers 'Foo: a'; + echo hello; + } +--- request + GET /bug +--- raw_response_headers_like eval +".*Foo: a.*" +--- response_body +hello + + + +=== TEST 10: first add, then clear, then add again +--- config + location /bug { + more_set_headers 'Foo: a'; + more_clear_headers 'Foo'; + more_set_headers 'Foo: b'; + echo hello; + } +--- request + GET /bug +--- raw_response_headers_like eval +".*Foo: b.*" +--- response_body +hello + + + +=== TEST 11: override charset +--- config + location /foo { + charset iso-8859-1; + default_type "text/html"; + echo hiya; + } + + location /bug { + more_set_headers "Content-Type: text/html; charset=UTF-8"; + proxy_pass http://127.0.0.1:$server_port/foo; + } +--- request + GET /bug +--- response_body +hiya +--- response_headers +Content-Type: text/html; charset=UTF-8 + + + +=== TEST 12: set multi-value header to a single value +--- config + location /main { + set $footer ''; + proxy_pass http://127.0.0.1:$server_port/foo; + more_set_headers 'Foo: b'; + header_filter_by_lua ' + ngx.var.footer = ngx.header.Foo + '; + echo_after_body $footer; + } + location /foo { + echo foo; + add_header Foo a; + add_header Foo c; + } +--- request + GET /main +--- response_headers +Foo: b +--- response_body +foo +b + + + +=== TEST 13: set multi values to cache-control and override it with multiple values (to reproduce a bug) +--- config + location /lua { + content_by_lua ' + ngx.header.cache_control = { "private", "no-store", "foo", "bar", "baz" } + ngx.send_headers() + ngx.say("Cache-Control: ", ngx.var.sent_http_cache_control) + '; + more_clear_headers Cache-Control; + add_header Cache-Control "blah"; + } +--- request + GET /lua +--- response_headers +Cache-Control: blah +--- response_body +Cache-Control: blah + + + +=== TEST 14: set 20+ headers +--- config + location /test { + more_clear_input_headers "Authorization"; + echo $http_a1; + echo $http_authorization; + echo $http_a2; + echo $http_a3; + echo $http_a23; + echo $http_a24; + echo $http_a25; + } +--- request + GET /test +--- more_headers eval +my $i = 1; +my $s; +while ($i <= 25) { + $s .= "A$i: $i\n"; + if ($i == 22) { + $s .= "Authorization: blah\n"; + } + $i++; +} +#warn $s; +$s +--- response_body +1 + +2 +3 +23 +24 +25 + + + +=== TEST 15: github #20: segfault caused by the nasty optimization in the nginx core (set) +--- config + location = /t/ { + more_set_headers "Foo: 1"; + proxy_pass http://127.0.0.1:$server_port; + } +--- request +GET /t +--- more_headers +Foo: bar +Bah: baz +--- response_body_like: 301 Moved Permanently +--- error_code: 301 +--- no_error_log +[error] + + + +=== TEST 16: github #20: segfault caused by the nasty optimization in the nginx core (clear) +--- config + location = /t/ { + more_clear_headers Foo; + proxy_pass http://127.0.0.1:$server_port; + } +--- request +GET /t +--- more_headers +Foo: bar +Bah: baz +--- response_body_like: 301 Moved Permanently +--- error_code: 301 +--- no_error_log +[error] + + + +=== TEST 17: Content-Type response headers with a charset param (correct -t values) +--- config + location = /t { + more_set_headers -t 'text/html' 'X-Foo: Bar'; + proxy_pass http://127.0.0.1:$server_port/fake; + } + + location = /fake { + default_type text/html; + charset utf-8; + echo ok; + } +--- request +GET /t +--- response_headers +X-Foo: Bar +--- response_body +ok + + + +=== TEST 18: Content-Type response headers with a charset param (WRONG -t values) +--- config + location = /t { + more_set_headers -t 'text/html; charset=utf-8' 'X-Foo: Bar'; + proxy_pass http://127.0.0.1:$server_port/fake; + } + + location = /fake { + default_type text/html; + charset utf-8; + echo ok; + } +--- request +GET /t +--- response_headers +X-Foo: Bar +--- response_body +ok + + + +=== TEST 19: for bad requests (bad request method letter case) +--- config + error_page 400 = /err; + + location = /err { + more_set_input_headers "Foo: bar"; + echo ok; + } +--- raw_request +GeT / HTTP/1.1 +--- response_body +ok +--- no_check_leak + + + +=== TEST 20: for bad requests (bad request method names) +--- config + error_page 400 = /err; + + location = /err { + more_set_input_headers "Foo: bar"; + echo ok; + } +--- raw_request +GET x HTTP/1.1 +--- response_body +ok +--- no_check_leak diff --git a/headers-more-nginx-module/t/builtin.t b/headers-more-nginx-module/t/builtin.t new file mode 100644 index 00000000..27b20afa --- /dev/null +++ b/headers-more-nginx-module/t/builtin.t @@ -0,0 +1,338 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; # 'no_plan'; + +plan tests => 60; + +no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: set Server +--- config + location /foo { + echo hi; + more_set_headers 'Server: Foo'; + } +--- request + GET /foo +--- response_headers +Server: Foo +--- response_body +hi + + + +=== TEST 2: clear Server +--- config + location /foo { + echo hi; + more_clear_headers 'Server: '; + } +--- request + GET /foo +--- response_headers +! Server +--- response_body +hi + + + +=== TEST 3: set Content-Type +--- config + location /foo { + default_type 'text/plan'; + more_set_headers 'Content-Type: text/css'; + echo hi; + } +--- request + GET /foo +--- response_headers +Content-Type: text/css +--- response_body +hi + + + +=== TEST 4: set Content-Type +--- config + location /foo { + default_type 'text/plan'; + more_set_headers 'Content-Type: text/css'; + return 404; + } +--- request + GET /foo +--- response_headers +Content-Type: text/css +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 5: clear Content-Type +--- config + location /foo { + default_type 'text/plain'; + more_clear_headers 'Content-Type: '; + return 404; + } +--- request + GET /foo +--- response_headers +! Content-Type +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 6: clear Content-Type (colon not required) +--- config + location /foo { + default_type 'text/plain'; + more_set_headers 'Content-Type: Hello'; + more_clear_headers 'Content-Type'; + return 404; + } +--- request + GET /foo +--- response_headers +! Content-Type +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 7: clear Content-Type (value ignored) +--- config + location /foo { + default_type 'text/plain'; + more_set_headers 'Content-Type: Hello'; + more_clear_headers 'Content-Type: blah'; + return 404; + } +--- request + GET /foo +--- response_headers +! Content-Type +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 8: clear Content-Type (case insensitive) +--- config + location /foo { + default_type 'text/plain'; + more_set_headers 'Content-Type: Hello'; + more_clear_headers 'content-type: blah'; + return 404; + } +--- request + GET /foo +--- response_headers +! Content-Type +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 9: clear Content-Type using set empty +--- config + location /foo { + default_type 'text/plain'; + more_set_headers 'Content-Type: Hello'; + more_set_headers 'content-type:'; + return 404; + } +--- request + GET /foo +--- response_headers +! Content-Type +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 10: clear Content-Type using setting key only +--- config + location /foo { + default_type 'text/plain'; + more_set_headers 'Content-Type: Hello'; + more_set_headers 'content-type'; + return 404; + } +--- request + GET /foo +--- response_headers +! Content-Type +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 11: set content-length +--- config + location /len { + more_set_headers 'Content-Length: 2'; + echo hello; + } +--- request + GET /len +--- response_headers +Content-Length: 2 +--- response_body chop +he + + + +=== TEST 12: set content-length multiple times +--- config + location /len { + more_set_headers 'Content-Length: 2'; + more_set_headers 'Content-Length: 4'; + echo hello; + } +--- request + GET /len +--- response_headers +Content-Length: 4 +--- response_body chop +hell + + + +=== TEST 13: clear content-length +--- config + location /len { + more_set_headers 'Content-Length: 4'; + more_set_headers 'Content-Length:'; + echo hello; + } +--- request + GET /len +--- response_headers +! Content-Length +--- response_body +hello + + + +=== TEST 14: clear content-length (another way) +--- config + location /len { + more_set_headers 'Content-Length: 4'; + more_clear_headers 'Content-Length'; + echo hello; + } +--- request + GET /len +--- response_headers +! Content-Length +--- response_body +hello + + + +=== TEST 15: clear content-type +--- config + location /len { + default_type 'text/plain'; + more_set_headers 'Content-Type:'; + echo hello; + } +--- request + GET /len +--- response_headers +! Content-Type +--- response_body +hello + + + +=== TEST 16: clear content-type (the other way) +--- config + location /len { + default_type 'text/plain'; + more_clear_headers 'Content-Type:'; + echo hello; + } +--- request + GET /len +--- response_headers +! Content-Type +--- response_body +hello + + + +=== TEST 17: set Charset +--- config + location /len { + default_type 'text/plain'; + more_set_headers 'Charset: gbk'; + echo hello; + } +--- request + GET /len +--- response_headers +Charset: gbk +--- response_body +hello + + + +=== TEST 18: clear Charset +--- config + location /len { + default_type 'text/plain'; + more_set_headers 'Charset: gbk'; + more_clear_headers 'Charset'; + echo hello; + } +--- request + GET /len +--- response_headers +! Charset +--- response_body +hello + + + +=== TEST 19: clear Charset (the other way: using set) +--- config + location /len { + default_type 'text/plain'; + more_set_headers 'Charset: gbk'; + more_set_headers 'Charset: '; + echo hello; + } +--- request + GET /len +--- response_headers +! Charset +--- response_body +hello + + + +=== TEST 20: set Vary +--- config + location /foo { + more_set_headers 'Vary: gbk'; + echo hello; + } + location /len { + default_type 'text/plain'; + more_set_headers 'Vary: hello'; + proxy_pass http://127.0.0.1:$server_port/foo; + } +--- request + GET /len +--- response_headers +Vary: hello +--- response_body +hello diff --git a/headers-more-nginx-module/t/eval.t b/headers-more-nginx-module/t/eval.t new file mode 100644 index 00000000..febd306d --- /dev/null +++ b/headers-more-nginx-module/t/eval.t @@ -0,0 +1,36 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; # 'no_plan'; + +repeat_each(3); + +plan tests => repeat_each() * 2 * blocks(); + +#no_long_string(); +#no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: set request header at client side +--- config + location /foo { + eval_subrequest_in_memory off; + eval_override_content_type text/plain; + eval $res { + echo -n 1; + } + #echo "[$res]"; + if ($res = '1') { + more_set_input_headers 'Foo: Bar'; + echo "OK"; + break; + } + echo "NOT OK"; + } +--- request + GET /foo +--- response_body +OK diff --git a/headers-more-nginx-module/t/input-conn.t b/headers-more-nginx-module/t/input-conn.t new file mode 100644 index 00000000..f53e80f1 --- /dev/null +++ b/headers-more-nginx-module/t/input-conn.t @@ -0,0 +1,137 @@ +# vim:set ft= ts=4 sw=4 et fdm=marker: + +use lib 'lib'; +use Test::Nginx::Socket; + +#worker_connections(1014); +#master_process_enabled(1); +#log_level('warn'); + +repeat_each(2); + +plan tests => repeat_each() * (4 * blocks()); + +#no_diff(); +no_long_string(); + +run_tests(); + +__DATA__ + +=== TEST 1: clear the Connection req header +--- config + location /req-header { + more_clear_input_headers Connection; + echo "connection: $http_connection"; + } +--- request +GET /req-header + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: conn type: %d\n", $r->headers_in->connection_type) +} + + +F(ngx_http_core_content_phase) { + printf("content: conn type: %d\n", $r->headers_in->connection_type) +} + +--- stap_out +rewrite: conn type: 1 +content: conn type: 0 + +--- response_body +connection: +--- no_error_log +[error] + + + +=== TEST 2: set custom Connection req header (close) +--- config + location /req-header { + more_set_input_headers "Connection: CLOSE"; + echo "connection: $http_connection"; + } +--- request +GET /req-header + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: conn type: %d\n", $r->headers_in->connection_type) +} + + +F(ngx_http_core_content_phase) { + printf("content: conn type: %d\n", $r->headers_in->connection_type) +} + +--- stap_out +rewrite: conn type: 1 +content: conn type: 1 + +--- response_body +connection: CLOSE +--- no_error_log +[error] + + + +=== TEST 3: set custom Connection req header (keep-alive) +--- config + location /req-header { + more_set_input_headers "Connection: keep-alive"; + echo "connection: $http_connection"; + } +--- request +GET /req-header + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: conn type: %d\n", $r->headers_in->connection_type) +} + + +F(ngx_http_core_content_phase) { + printf("content: conn type: %d\n", $r->headers_in->connection_type) +} + +--- stap_out +rewrite: conn type: 1 +content: conn type: 2 + +--- response_body +connection: keep-alive +--- no_error_log +[error] + + + +=== TEST 4: set custom Connection req header (bad) +--- config + location /req-header { + more_set_input_headers "Connection: bad"; + echo "connection: $http_connection"; + } +--- request +GET /req-header + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: conn type: %d\n", $r->headers_in->connection_type) +} + + +F(ngx_http_core_content_phase) { + printf("content: conn type: %d\n", $r->headers_in->connection_type) +} + +--- stap_out +rewrite: conn type: 1 +content: conn type: 0 + +--- response_body +connection: bad +--- no_error_log +[error] diff --git a/headers-more-nginx-module/t/input-cookie.t b/headers-more-nginx-module/t/input-cookie.t new file mode 100644 index 00000000..68db4d0a --- /dev/null +++ b/headers-more-nginx-module/t/input-cookie.t @@ -0,0 +1,183 @@ +# vim:set ft= ts=4 sw=4 et fdm=marker: + +use lib 'lib'; +use Test::Nginx::Socket; + +#worker_connections(1014); +#master_process_enabled(1); +#log_level('warn'); + +repeat_each(2); + +plan tests => repeat_each() * (4 * blocks()); + +#no_diff(); +no_long_string(); + +run_tests(); + +__DATA__ + +=== TEST 1: clear cookie (with existing cookies) +--- config + location /t { + more_clear_input_headers Cookie; + echo "Cookie foo: $cookie_foo"; + echo "Cookie baz: $cookie_baz"; + echo "Cookie: $http_cookie"; + } +--- request +GET /t +--- more_headers +Cookie: foo=bar +Cookie: baz=blah + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: cookies: %d\n", $r->headers_in->cookies->nelts) +} + +F(ngx_http_core_content_phase) { + printf("content: cookies: %d\n", $r->headers_in->cookies->nelts) +} + +--- stap_out +rewrite: cookies: 2 +content: cookies: 0 + +--- response_body +Cookie foo: +Cookie baz: +Cookie: + +--- no_error_log +[error] + + + +=== TEST 2: clear cookie (without existing cookies) +--- config + location /t { + more_clear_input_headers Cookie; + echo "Cookie foo: $cookie_foo"; + echo "Cookie baz: $cookie_baz"; + echo "Cookie: $http_cookie"; + } +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: cookies: %d\n", $r->headers_in->cookies->nelts) +} + +F(ngx_http_core_content_phase) { + printf("content: cookies: %d\n", $r->headers_in->cookies->nelts) +} + +--- stap_out +rewrite: cookies: 0 +content: cookies: 0 + +--- response_body +Cookie foo: +Cookie baz: +Cookie: + +--- no_error_log +[error] + + + +=== TEST 3: set one custom cookie (with existing cookies) +--- config + location /t { + more_set_input_headers "Cookie: boo=123"; + echo "Cookie foo: $cookie_foo"; + echo "Cookie baz: $cookie_baz"; + echo "Cookie boo: $cookie_boo"; + echo "Cookie: $http_cookie"; + } +--- request +GET /t +--- more_headers +Cookie: foo=bar +Cookie: baz=blah + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: cookies: %d\n", $r->headers_in->cookies->nelts) +} + +F(ngx_http_core_content_phase) { + printf("content: cookies: %d\n", $r->headers_in->cookies->nelts) +} + +--- stap_out +rewrite: cookies: 2 +content: cookies: 1 + +--- response_body +Cookie foo: +Cookie baz: +Cookie boo: 123 +Cookie: boo=123 + +--- no_error_log +[error] + + + +=== TEST 4: set one custom cookie (without existing cookies) +--- config + location /t { + more_set_input_headers "Cookie: boo=123"; + echo "Cookie foo: $cookie_foo"; + echo "Cookie baz: $cookie_baz"; + echo "Cookie boo: $cookie_boo"; + echo "Cookie: $http_cookie"; + } +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: cookies: %d\n", $r->headers_in->cookies->nelts) +} + +F(ngx_http_core_content_phase) { + printf("content: cookies: %d\n", $r->headers_in->cookies->nelts) +} + +--- stap_out +rewrite: cookies: 0 +content: cookies: 1 + +--- response_body +Cookie foo: +Cookie baz: +Cookie boo: 123 +Cookie: boo=123 + +--- no_error_log +[error] + + + +=== TEST 5: for bad requests causing segfaults when setting & getting multi-value headers +--- config + error_page 400 = /err; + + location = /err { + more_set_input_headers "Cookie: foo=bar"; + echo -n $cookie_foo; + echo ok; + } +--- raw_request +GeT / HTTP/1.1 +--- response_body +ok +--- no_error_log +[error] +[alert] +--- no_check_leak diff --git a/headers-more-nginx-module/t/input-ua.t b/headers-more-nginx-module/t/input-ua.t new file mode 100644 index 00000000..da9a60dd --- /dev/null +++ b/headers-more-nginx-module/t/input-ua.t @@ -0,0 +1,628 @@ +# vim:set ft= ts=4 sw=4 et fdm=marker: + +use lib 'lib'; +use Test::Nginx::Socket; + +#worker_connections(1014); +#master_process_enabled(1); +#log_level('warn'); + +repeat_each(2); + +plan tests => repeat_each() * (4 * blocks()); + +#no_diff(); +no_long_string(); + +run_tests(); + +__DATA__ + +=== TEST 1: clear Opera user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Opera/9.80 (Macintosh; Intel Mac OS X 10.7.4; U; en) Presto/2.10.229 Version/11.62 + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: opera: %d\n", $r->headers_in->opera) +} + +F(ngx_http_core_content_phase) { + printf("content: opera: %d\n", $r->headers_in->opera) +} + +--- stap_out +rewrite: opera: 1 +content: opera: 0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 2: clear MSIE 4 user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows NT 5.0) + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=1 msie6=1 +content: msie=0 msie6=0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 3: set custom MSIE 4 user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows NT 5.0)"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=0 msie6=0 +content: msie=1 msie6=1 + +--- response_body +User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows NT 5.0) +--- no_error_log +[error] + + + +=== TEST 4: clear MSIE 5 user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows 95; MSIECrawler) + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=1 msie6=1 +content: msie=0 msie6=0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 5: set custom MSIE 5 user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows 95; MSIECrawler)"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=0 msie6=0 +content: msie=1 msie6=1 + +--- response_body +User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows 95; MSIECrawler) +--- no_error_log +[error] + + + +=== TEST 6: clear MSIE 6 (without SV1) user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Google Wireless Transcoder;) + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=1 msie6=1 +content: msie=0 msie6=0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 7: set custom MSIE 6 (without SV1) user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Google Wireless Transcoder;)"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=0 msie6=0 +content: msie=1 msie6=1 + +--- response_body +User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Google Wireless Transcoder;) +--- no_error_log +[error] + + + +=== TEST 8: clear MSIE 6 (with SV1) user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1) + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=1 msie6=0 +content: msie=0 msie6=0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 9: set custom MSIE 6 (with SV1) user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1)"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=0 msie6=0 +content: msie=1 msie6=0 + +--- response_body +User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1) +--- no_error_log +[error] + + + +=== TEST 10: set custom MSIE 7 user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; winfx; .NET CLR 1.1.4322; .NET CLR 2.0.50727; Zune 2.0)"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +F(ngx_http_core_content_phase) { + printf("content: msie=%d msie6=%d\n", + $r->headers_in->msie, + $r->headers_in->msie6) +} + +--- stap_out +rewrite: msie=0 msie6=0 +content: msie=1 msie6=0 + +--- response_body +User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; winfx; .NET CLR 1.1.4322; .NET CLR 2.0.50727; Zune 2.0) +--- no_error_log +[error] + + + +=== TEST 11: clear Gecko user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Mozilla/5.0 (Android; Mobile; rv:13.0) Gecko/13.0 Firefox/13.0 + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: gecko: %d\n", $r->headers_in->gecko) +} + + +F(ngx_http_core_content_phase) { + printf("content: gecko: %d\n", $r->headers_in->gecko) +} + +--- stap_out +rewrite: gecko: 1 +content: gecko: 0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 12: set custom Gecko user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/5.0 (Android; Mobile; rv:13.0) Gecko/13.0 Firefox/13.0"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: gecko: %d\n", $r->headers_in->gecko) +} + + +F(ngx_http_core_content_phase) { + printf("content: gecko: %d\n", $r->headers_in->gecko) +} + +--- stap_out +rewrite: gecko: 0 +content: gecko: 1 + +--- response_body +User-Agent: Mozilla/5.0 (Android; Mobile; rv:13.0) Gecko/13.0 Firefox/13.0 +--- no_error_log +[error] + + + +=== TEST 13: clear Chrome user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19 + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: chrome: %d\n", $r->headers_in->chrome) +} + + +F(ngx_http_core_content_phase) { + printf("content: chrome: %d\n", $r->headers_in->chrome) +} + +--- stap_out +rewrite: chrome: 1 +content: chrome: 0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 14: set custom Chrome user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: chrome: %d\n", $r->headers_in->chrome) +} + + +F(ngx_http_core_content_phase) { + printf("content: chrome: %d\n", $r->headers_in->chrome) +} + +--- stap_out +rewrite: chrome: 0 +content: chrome: 1 + +--- response_body +User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19 +--- no_error_log +[error] + + + +=== TEST 15: clear Safari (Mac OS X) user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/125.2 (KHTML, like Gecko) Safari/125.8 + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: safari: %d\n", $r->headers_in->safari) +} + + +F(ngx_http_core_content_phase) { + printf("content: safari: %d\n", $r->headers_in->safari) +} + +--- stap_out +rewrite: safari: 1 +content: safari: 0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 16: set custom Safari user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/125.2 (KHTML, like Gecko) Safari/125.8"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: safari: %d\n", $r->headers_in->safari) +} + + +F(ngx_http_core_content_phase) { + printf("content: safari: %d\n", $r->headers_in->safari) +} + +--- stap_out +rewrite: safari: 0 +content: safari: 1 + +--- response_body +User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/125.2 (KHTML, like Gecko) Safari/125.8 +--- no_error_log +[error] + + + +=== TEST 17: clear Konqueror user-agent +--- config + location /t { + more_clear_input_headers User-Agent; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- more_headers +User-Agent: Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.10 (like Gecko) (Kubuntu) + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: konqueror: %d\n", $r->headers_in->konqueror) +} + + +F(ngx_http_core_content_phase) { + printf("content: konqueror: %d\n", $r->headers_in->konqueror) +} + +--- stap_out +rewrite: konqueror: 1 +content: konqueror: 0 + +--- response_body +User-Agent: +--- no_error_log +[error] + + + +=== TEST 18: set custom Konqueror user-agent +--- config + location /t { + more_set_input_headers "User-Agent: Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.10 (like Gecko) (Kubuntu)"; + echo "User-Agent: $http_user_agent"; + } + +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + printf("rewrite: konqueror: %d\n", $r->headers_in->konqueror) +} + + +F(ngx_http_core_content_phase) { + printf("content: konqueror: %d\n", $r->headers_in->konqueror) +} + +--- stap_out +rewrite: konqueror: 0 +content: konqueror: 1 + +--- response_body +User-Agent: Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.10 (like Gecko) (Kubuntu) +--- no_error_log +[error] diff --git a/headers-more-nginx-module/t/input.t b/headers-more-nginx-module/t/input.t new file mode 100644 index 00000000..01ae73ff --- /dev/null +++ b/headers-more-nginx-module/t/input.t @@ -0,0 +1,1331 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; # 'no_plan'; + +repeat_each(2); + +plan tests => repeat_each() * 128; + +no_long_string(); +#no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: set request header at client side +--- config + location /foo { + #more_set_input_headers 'X-Foo: howdy'; + echo $http_x_foo; + } +--- request + GET /foo +--- more_headers +X-Foo: blah +--- response_headers +! X-Foo +--- response_body +blah + + + +=== TEST 2: set request header at client side and rewrite it +--- config + location /foo { + more_set_input_headers 'X-Foo: howdy'; + echo $http_x_foo; + } +--- request + GET /foo +--- more_headers +X-Foo: blah +--- response_headers +! X-Foo +--- response_body +howdy + + + +=== TEST 3: rewrite content length +--- config + location /bar { + more_set_input_headers 'Content-Length: 2048'; + echo_read_request_body; + echo_request_body; + } +--- request eval +"POST /bar\n" . +"a" x 4096 +--- response_body eval +"a" x 2048 +--- timeout: 15 + + + +=== TEST 4: try to rewrite content length using the rewrite module +Thisshould not take effect ;) +--- config + location /bar { + set $http_content_length 2048; + echo_read_request_body; + echo_request_body; + } +--- request eval +"POST /bar\n" . +"a" x 4096 +--- response_body eval +"a" x 4096 + + + +=== TEST 5: rewrite host and user-agent +--- config + location /bar { + more_set_input_headers 'Host: foo' 'User-Agent: blah'; + echo "Host: $host"; + echo "User-Agent: $http_user_agent"; + } +--- request +GET /bar +--- response_body +Host: foo +User-Agent: blah + + + +=== TEST 6: clear host and user-agent +$host always has a default value and cannot be really cleared. +--- config + location /bar { + more_clear_input_headers 'Host: foo' 'User-Agent: blah'; + echo "Host: $host"; + echo "Host (2): $http_host"; + echo "User-Agent: $http_user_agent"; + } +--- request +GET /bar +--- response_body +Host: localhost +Host (2): +User-Agent: + + + +=== TEST 7: clear host and user-agent (the other way) +--- config + location /bar { + more_set_input_headers 'Host:' 'User-Agent:' 'X-Foo:'; + echo "Host: $host"; + echo "User-Agent: $http_user_agent"; + echo "X-Foo: $http_x_foo"; + } +--- request +GET /bar +--- more_headers +X-Foo: bar +--- response_body +Host: localhost +User-Agent: +X-Foo: + + + +=== TEST 8: clear content-length +--- config + location /bar { + more_set_input_headers 'Content-Length: '; + echo "Content-Length: $http_content_length"; + } +--- request +POST /bar +hello +--- more_headers +--- response_body +Content-Length: + + + +=== TEST 9: clear content-length (the other way) +--- config + location /bar { + more_clear_input_headers 'Content-Length: '; + echo "Content-Length: $http_content_length"; + } +--- request +POST /bar +hello +--- more_headers +--- response_body +Content-Length: + + + +=== TEST 10: rewrite type +--- config + location /bar { + more_set_input_headers 'Content-Type: text/css'; + echo "Content-Type: $content_type"; + } +--- request +POST /bar +hello +--- more_headers +Content-Type: text/plain +--- response_body +Content-Type: text/css + + + +=== TEST 11: clear type +--- config + location /bar { + more_set_input_headers 'Content-Type:'; + echo "Content-Type: $content_type"; + } +--- request +POST /bar +hello +--- more_headers +Content-Type: text/plain +--- response_body +Content-Type: + + + +=== TEST 12: clear type (the other way) +--- config + location /bar { + more_clear_input_headers 'Content-Type:foo'; + echo "Content-Type: $content_type"; + } +--- request +POST /bar +hello +--- more_headers +Content-Type: text/plain +--- response_body +Content-Type: + + + +=== TEST 13: add type constraints +--- config + location /bar { + more_set_input_headers -t 'text/plain' 'X-Blah:yay'; + echo $http_x_blah; + } +--- request +POST /bar +hello +--- more_headers +Content-Type: text/plain +--- response_body +yay + + + +=== TEST 14: add type constraints (not matched) +--- config + location /bar { + more_set_input_headers -t 'text/plain' 'X-Blah:yay'; + echo $http_x_blah; + } +--- request +POST /bar +hello +--- more_headers +Content-Type: text/css +--- response_body eval: "\n" + + + +=== TEST 15: add type constraints (OR'd) +--- config + location /bar { + more_set_input_headers -t 'text/plain text/css' 'X-Blah:yay'; + echo $http_x_blah; + } +--- request +POST /bar +hello +--- more_headers +Content-Type: text/css +--- response_body +yay + + + +=== TEST 16: add type constraints (OR'd) +--- config + location /bar { + more_set_input_headers -t 'text/plain text/css' 'X-Blah:yay'; + echo $http_x_blah; + } +--- request +POST /bar +hello +--- more_headers +Content-Type: text/plain +--- response_body +yay + + + +=== TEST 17: add type constraints (OR'd) (not matched) +--- config + location /bar { + more_set_input_headers -t 'text/plain text/css' 'X-Blah:yay'; + echo $http_x_blah; + } +--- request +POST /bar +hello +--- more_headers +Content-Type: text/html +--- response_body eval: "\n" + + + +=== TEST 18: mix input and output cmds +--- config + location /bar { + more_set_input_headers 'X-Blah:yay'; + more_set_headers 'X-Blah:hiya'; + echo $http_x_blah; + } +--- request +GET /bar +--- response_headers +X-Blah: hiya +--- response +yay + + + +=== TEST 19: set request header at client side and replace +--- config + location /foo { + more_set_input_headers -r 'X-Foo: howdy'; + echo $http_x_foo; + } +--- request + GET /foo +--- more_headers +X-Foo: blah +--- response_headers +! X-Foo +--- response_body +howdy + + + +=== TEST 20: do no set request header at client, so no replace with -r option +--- config + location /foo { + more_set_input_headers -r 'X-Foo: howdy'; + echo "empty_header:" $http_x_foo; + } +--- request + GET /foo +--- response_headers +! X-Foo +--- response_body +empty_header: + + + +=== TEST 21: clear input headers +--- config + location /foo { + set $val 'dog'; + + more_clear_input_headers 'User-Agent'; + + proxy_pass http://127.0.0.1:$server_port/proxy; + } + location /proxy { + echo -n $echo_client_request_headers; + } +--- request + GET /foo +--- more_headers +User-Agent: my-sock +--- response_body eval +"GET /proxy HTTP/1.0\r +Host: 127.0.0.1:\$ServerPort\r +Connection: close\r +\r +" +--- skip_nginx: 3: < 0.7.46 + + + +=== TEST 22: clear input headers +--- config + location /foo { + more_clear_input_headers 'User-Agent'; + + proxy_pass http://127.0.0.1:$server_port/proxy; + } + location /proxy { + echo -n $echo_client_request_headers; + } +--- request + GET /foo +--- response_body eval +"GET /proxy HTTP/1.0\r +Host: 127.0.0.1:\$ServerPort\r +Connection: close\r +\r +" +--- skip_nginx: 3: < 0.7.46 + + + +=== TEST 23: clear input headers +--- config + location /foo { + more_clear_input_headers 'X-Foo19'; + more_clear_input_headers 'X-Foo20'; + more_clear_input_headers 'X-Foo21'; + + proxy_pass http://127.0.0.1:$server_port/proxy; + } + location /proxy { + echo -n $echo_client_request_headers; + } +--- request + GET /foo +--- more_headers eval +my $s; +for my $i (3..21) { + $s .= "X-Foo$i: $i\n"; +} +$s; +--- response_body eval +"GET /proxy HTTP/1.0\r +Host: 127.0.0.1:\$ServerPort\r +Connection: close\r +X-Foo3: 3\r +X-Foo4: 4\r +X-Foo5: 5\r +X-Foo6: 6\r +X-Foo7: 7\r +X-Foo8: 8\r +X-Foo9: 9\r +X-Foo10: 10\r +X-Foo11: 11\r +X-Foo12: 12\r +X-Foo13: 13\r +X-Foo14: 14\r +X-Foo15: 15\r +X-Foo16: 16\r +X-Foo17: 17\r +X-Foo18: 18\r +\r +" +--- skip_nginx: 3: < 0.7.46 + + + +=== TEST 24: Accept-Encoding +--- config + location /bar { + default_type 'text/plain'; + more_set_input_headers 'Accept-Encoding: gzip'; + gzip on; + gzip_min_length 1; + gzip_buffers 4 8k; + gzip_types text/plain; + } +--- user_files +">>> bar +" . ("hello" x 512) +--- request +GET /bar +--- response_headers +Content-Encoding: gzip +--- response_body_like: . + + + +=== TEST 25: rewrite + set request header +--- config + location /t { + rewrite ^ /foo last; + } + + location /foo { + more_set_input_headers 'X-Foo: howdy'; + proxy_pass http://127.0.0.1:$server_port/echo; + } + + location /echo { + echo "X-Foo: $http_x_foo"; + } +--- request + GET /foo +--- response_headers +! X-Foo +--- response_body +X-Foo: howdy + + + +=== TEST 26: clear_header should clear all the instances of the user custom header +--- config + location = /t { + more_clear_input_headers Foo; + + proxy_pass http://127.0.0.1:$server_port/echo; + } + + location = /echo { + echo "Foo: [$http_foo]"; + echo "Test-Header: [$http_test_header]"; + } +--- request +GET /t +--- more_headers +Foo: foo +Foo: bah +Test-Header: 1 +--- response_body +Foo: [] +Test-Header: [1] + + + +=== TEST 27: clear_header should clear all the instances of the builtin header +--- config + location = /t { + more_clear_input_headers Content-Type; + + proxy_pass http://127.0.0.1:$server_port/echo; + } + + location = /echo { + echo "Content-Type: [$http_content_type]"; + echo "Test-Header: [$http_test_header]"; + #echo $echo_client_request_headers; + } +--- request +GET /t +--- more_headers +Content-Type: foo +Content-Type: bah +Test-Header: 1 +--- response_body +Content-Type: [] +Test-Header: [1] + + + +=== TEST 28: Converting POST to GET - clearing headers (bug found by Matthieu Tourne, 411 error page) +--- config + location /t { + more_clear_input_headers Content-Type; + more_clear_input_headers Content-Length; + + #proxy_pass http://127.0.0.1:8888; + proxy_pass http://127.0.0.1:$server_port/back; + } + + location /back { + echo $echo_client_request_headers; + } +--- request +POST /t +hello world +--- more_headers +Content-Type: application/ocsp-request +Test-Header: 1 +--- response_body_like eval +qr/Connection: close\r +Test-Header: 1\r +\r +$/ +--- no_error_log +[error] + + + +=== TEST 29: clear_header() does not duplicate subsequent headers (old bug) +--- config + location = /t { + more_clear_input_headers Foo; + + proxy_pass http://127.0.0.1:$server_port/echo; + } + + location = /echo { + echo $echo_client_request_headers; + } +--- request +GET /t +--- more_headers +Bah: bah +Foo: foo +Test-Header: 1 +Foo1: foo1 +Foo2: foo2 +Foo3: foo3 +Foo4: foo4 +Foo5: foo5 +Foo6: foo6 +Foo7: foo7 +Foo8: foo8 +Foo9: foo9 +Foo10: foo10 +Foo11: foo11 +Foo12: foo12 +Foo13: foo13 +Foo14: foo14 +Foo15: foo15 +Foo16: foo16 +Foo17: foo17 +Foo18: foo18 +Foo19: foo19 +Foo20: foo20 +Foo21: foo21 +Foo22: foo22 +--- response_body_like eval +qr/Bah: bah\r +Test-Header: 1\r +Foo1: foo1\r +Foo2: foo2\r +Foo3: foo3\r +Foo4: foo4\r +Foo5: foo5\r +Foo6: foo6\r +Foo7: foo7\r +Foo8: foo8\r +Foo9: foo9\r +Foo10: foo10\r +Foo11: foo11\r +Foo12: foo12\r +Foo13: foo13\r +Foo14: foo14\r +Foo15: foo15\r +Foo16: foo16\r +Foo17: foo17\r +Foo18: foo18\r +Foo19: foo19\r +Foo20: foo20\r +Foo21: foo21\r +Foo22: foo22\r +/ + + + +=== TEST 30: clear input header (just more than 20 headers) +--- config + location = /t { + more_clear_input_headers "R"; + proxy_pass http://127.0.0.1:$server_port/back; + proxy_set_header Host foo; + #proxy_pass http://127.0.0.1:1234/back; + } + + location = /back { + echo -n $echo_client_request_headers; + } +--- request +GET /t +--- more_headers eval +my $s = "User-Agent: curl\n"; + +for my $i ('a' .. 'r') { + $s .= uc($i) . ": " . "$i\n" +} +$s +--- response_body eval +"GET /back HTTP/1.0\r +Host: foo\r +Connection: close\r +User-Agent: curl\r +A: a\r +B: b\r +C: c\r +D: d\r +E: e\r +F: f\r +G: g\r +H: h\r +I: i\r +J: j\r +K: k\r +L: l\r +M: m\r +N: n\r +O: o\r +P: p\r +Q: q\r +\r +" + + + +=== TEST 31: clear input header (just more than 20 headers, and add more) +--- config + location = /t { + more_clear_input_headers R; + more_set_input_headers "foo-1: 1" "foo-2: 2" "foo-3: 3" "foo-4: 4" + "foo-5: 5" "foo-6: 6" "foo-7: 7" "foo-8: 8" "foo-9: 9" + "foo-10: 10" "foo-11: 11" "foo-12: 12" "foo-13: 13" + "foo-14: 14" "foo-15: 15" "foo-16: 16" "foo-17: 17" "foo-18: 18" + "foo-19: 19" "foo-20: 20" "foo-21: 21"; + + proxy_pass http://127.0.0.1:$server_port/back; + proxy_set_header Host foo; + #proxy_pass http://127.0.0.1:1234/back; + } + + location = /back { + echo -n $echo_client_request_headers; + } +--- request +GET /t +--- more_headers eval +my $s = "User-Agent: curl\n"; + +for my $i ('a' .. 'r') { + $s .= uc($i) . ": " . "$i\n" +} +$s +--- response_body eval +"GET /back HTTP/1.0\r +Host: foo\r +Connection: close\r +User-Agent: curl\r +A: a\r +B: b\r +C: c\r +D: d\r +E: e\r +F: f\r +G: g\r +H: h\r +I: i\r +J: j\r +K: k\r +L: l\r +M: m\r +N: n\r +O: o\r +P: p\r +Q: q\r +foo-1: 1\r +foo-2: 2\r +foo-3: 3\r +foo-4: 4\r +foo-5: 5\r +foo-6: 6\r +foo-7: 7\r +foo-8: 8\r +foo-9: 9\r +foo-10: 10\r +foo-11: 11\r +foo-12: 12\r +foo-13: 13\r +foo-14: 14\r +foo-15: 15\r +foo-16: 16\r +foo-17: 17\r +foo-18: 18\r +foo-19: 19\r +foo-20: 20\r +foo-21: 21\r +\r +" + + + +=== TEST 32: clear input header (just more than 21 headers) +--- config + location = /t { + more_clear_input_headers R Q; + proxy_pass http://127.0.0.1:$server_port/back; + proxy_set_header Host foo; + #proxy_pass http://127.0.0.1:1234/back; + } + + location = /back { + echo -n $echo_client_request_headers; + } +--- request +GET /t +--- more_headers eval +my $s = "User-Agent: curl\nBah: bah\n"; + +for my $i ('a' .. 'r') { + $s .= uc($i) . ": " . "$i\n" +} +$s +--- response_body eval +"GET /back HTTP/1.0\r +Host: foo\r +Connection: close\r +User-Agent: curl\r +Bah: bah\r +A: a\r +B: b\r +C: c\r +D: d\r +E: e\r +F: f\r +G: g\r +H: h\r +I: i\r +J: j\r +K: k\r +L: l\r +M: m\r +N: n\r +O: o\r +P: p\r +\r +" + + + +=== TEST 33: clear input header (just more than 21 headers) +--- config + location = /t { + more_clear_input_headers R Q; + more_set_input_headers "foo-1: 1" "foo-2: 2" "foo-3: 3" "foo-4: 4" + "foo-5: 5" "foo-6: 6" "foo-7: 7" "foo-8: 8" "foo-9: 9" + "foo-10: 10" "foo-11: 11" "foo-12: 12" "foo-13: 13" + "foo-14: 14" "foo-15: 15" "foo-16: 16" "foo-17: 17" "foo-18: 18" + "foo-19: 19" "foo-20: 20" "foo-21: 21"; + + proxy_pass http://127.0.0.1:$server_port/back; + proxy_set_header Host foo; + #proxy_pass http://127.0.0.1:1234/back; + } + + location = /back { + echo -n $echo_client_request_headers; + } +--- request +GET /t +--- more_headers eval +my $s = "User-Agent: curl\nBah: bah\n"; + +for my $i ('a' .. 'r') { + $s .= uc($i) . ": " . "$i\n" +} +$s +--- response_body eval +"GET /back HTTP/1.0\r +Host: foo\r +Connection: close\r +User-Agent: curl\r +Bah: bah\r +A: a\r +B: b\r +C: c\r +D: d\r +E: e\r +F: f\r +G: g\r +H: h\r +I: i\r +J: j\r +K: k\r +L: l\r +M: m\r +N: n\r +O: o\r +P: p\r +foo-1: 1\r +foo-2: 2\r +foo-3: 3\r +foo-4: 4\r +foo-5: 5\r +foo-6: 6\r +foo-7: 7\r +foo-8: 8\r +foo-9: 9\r +foo-10: 10\r +foo-11: 11\r +foo-12: 12\r +foo-13: 13\r +foo-14: 14\r +foo-15: 15\r +foo-16: 16\r +foo-17: 17\r +foo-18: 18\r +foo-19: 19\r +foo-20: 20\r +foo-21: 21\r +\r +" + + + +=== TEST 34: clear X-Real-IP +--- config + location /t { + more_clear_input_headers X-Real-IP; + echo "X-Real-IP: $http_x_real_ip"; + } +--- request +GET /t +--- more_headers +X-Real-IP: 8.8.8.8 + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + if (@defined($r->headers_in->x_real_ip) && $r->headers_in->x_real_ip) { + printf("rewrite: x-real-ip: %s\n", + user_string_n($r->headers_in->x_real_ip->value->data, + $r->headers_in->x_real_ip->value->len)) + } else { + println("rewrite: no x-real-ip") + } +} + +F(ngx_http_core_content_phase) { + if (@defined($r->headers_in->x_real_ip) && $r->headers_in->x_real_ip) { + printf("content: x-real-ip: %s\n", + user_string_n($r->headers_in->x_real_ip->value->data, + $r->headers_in->x_real_ip->value->len)) + } else { + println("content: no x-real-ip") + } +} + +--- stap_out +rewrite: x-real-ip: 8.8.8.8 +content: no x-real-ip + +--- response_body +X-Real-IP: + +--- no_error_log +[error] + + + +=== TEST 35: set custom X-Real-IP +--- config + location /t { + more_set_input_headers "X-Real-IP: 8.8.4.4"; + echo "X-Real-IP: $http_x_real_ip"; + } +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + if (@defined($r->headers_in->x_real_ip) && $r->headers_in->x_real_ip) { + printf("rewrite: x-real-ip: %s\n", + user_string_n($r->headers_in->x_real_ip->value->data, + $r->headers_in->x_real_ip->value->len)) + } else { + println("rewrite: no x-real-ip") + } + +} + +F(ngx_http_core_content_phase) { + if (@defined($r->headers_in->x_real_ip) && $r->headers_in->x_real_ip) { + printf("content: x-real-ip: %s\n", + user_string_n($r->headers_in->x_real_ip->value->data, + $r->headers_in->x_real_ip->value->len)) + } else { + println("content: no x-real-ip") + } +} + +--- stap_out +rewrite: no x-real-ip +content: x-real-ip: 8.8.4.4 + +--- response_body +X-Real-IP: 8.8.4.4 + +--- no_error_log +[error] + + + +=== TEST 36: clear Via +--- config + location /t { + more_clear_input_headers Via; + echo "Via: $http_via"; + } +--- request +GET /t +--- more_headers +Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + if (@defined($r->headers_in->via) && $r->headers_in->via) { + printf("rewrite: via: %s\n", + user_string_n($r->headers_in->via->value->data, + $r->headers_in->via->value->len)) + } else { + println("rewrite: no via") + } +} + +F(ngx_http_core_content_phase) { + if (@defined($r->headers_in->via) && $r->headers_in->via) { + printf("content: via: %s\n", + user_string_n($r->headers_in->via->value->data, + $r->headers_in->via->value->len)) + } else { + println("content: no via") + } +} + +--- stap_out +rewrite: via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) +content: no via + +--- response_body +Via: + +--- no_error_log +[error] + + + +=== TEST 37: set custom Via +--- config + location /t { + more_set_input_headers "Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)"; + echo "Via: $http_via"; + } +--- request +GET /t + +--- stap +F(ngx_http_headers_more_exec_input_cmd) { + if (@defined($r->headers_in->via) && $r->headers_in->via) { + printf("rewrite: via: %s\n", + user_string_n($r->headers_in->via->value->data, + $r->headers_in->via->value->len)) + } else { + println("rewrite: no via") + } + +} + +F(ngx_http_core_content_phase) { + if (@defined($r->headers_in->via) && $r->headers_in->via) { + printf("content: via: %s\n", + user_string_n($r->headers_in->via->value->data, + $r->headers_in->via->value->len)) + } else { + println("content: no via") + } +} + +--- stap_out +rewrite: no via +content: via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) + +--- response_body +Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) + +--- no_error_log +[error] + + + +=== TEST 38: HTTP 0.9 (set) +--- config + location /foo { + more_set_input_headers 'X-Foo: howdy'; + echo "x-foo: $http_x_foo"; + } +--- raw_request eval +"GET /foo\r\n" +--- response_headers +! X-Foo +--- response_body +x-foo: +--- http09 + + + +=== TEST 39: HTTP 0.9 (clear) +--- config + location /foo { + more_clear_input_headers 'X-Foo'; + echo "x-foo: $http_x_foo"; + } +--- raw_request eval +"GET /foo\r\n" +--- response_headers +! X-Foo +--- response_body +x-foo: +--- http09 + + + +=== TEST 40: Host header with port and $host +--- config + location /bar { + more_set_input_headers 'Host: agentzh.org:1984'; + echo "host var: $host"; + echo "http_host var: $http_host"; + } +--- request +GET /bar +--- response_body +host var: agentzh.org +http_host var: agentzh.org:1984 + + + +=== TEST 41: Host header with upper case letters and $host +--- config + location /bar { + more_set_input_headers 'Host: agentZH.org:1984'; + echo "host var: $host"; + echo "http_host var: $http_host"; + } +--- request +GET /bar +--- response_body +host var: agentzh.org +http_host var: agentZH.org:1984 + + + +=== TEST 42: clear all and re-insert +--- config + location = /t { + more_clear_input_headers Host Connection Cache-Control Accept + User-Agent Accept-Encoding Accept-Language + Cookie; + + more_set_input_headers "Host: a" "Connection: b" "Cache-Control: c" + "Accept: d" "User-Agent: e" "Accept-Encoding: f" + "Accept-Language: g" "Cookie: h"; + + more_clear_input_headers Host Connection Cache-Control Accept + User-Agent Accept-Encoding Accept-Language + Cookie; + + more_set_input_headers "Host: a" "Connection: b" "Cache-Control: c" + "Accept: d" "User-Agent: e" "Accept-Encoding: f" + "Accept-Language: g" "Cookie: h"; + + echo ok; + } + +--- raw_request eval +"GET /t HTTP/1.1\r +Host: localhost\r +Connection: close\r +Cache-Control: max-age=0\r +Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r +User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36\r +Accept-Encoding: gzip,deflate,sdch\r +Accept-Language: en-US,en;q=0.8\r +Cookie: test=cookie;\r +\r +" +--- response_body +ok +--- no_error_log +[error] + + + +=== TEST 43: more_set_input_header does not override request headers with multiple values +--- config + #lua_code_cache off; + location = /t { + more_set_input_headers "AAA: 111"; + + content_by_lua ' + local headers = ngx.req.get_headers() + ngx.say(headers["AAA"]) + '; + } +--- request +GET /t +--- more_headers +AAA: 123 +AAA: 456 +AAA: 678 + +--- response_body +111 +--- no_error_log +[error] + + + +=== TEST 44: clear If-Unmodified-Since req header +--- config + location = /t { + more_clear_input_headers 'If-Unmodified-Since'; + content_by_lua ' + ngx.header["Last-Modified"] = "Tue, 30 Jun 2011 12:16:36 GMT" + ngx.say("If-Unmodified-Since: ", ngx.var.http_if_unmodified_since) + '; + } +--- request +GET /t +--- more_headers +If-Unmodified-Since: Tue, 28 Jun 2011 12:16:36 GMT +--- response_body +If-Unmodified-Since: nil +--- no_error_log +[error] + + + +=== TEST 45: clear If-Match req header +--- config + location = /t { + more_clear_input_headers 'If-Match'; + echo "If-Match: $http_if_match"; + } +--- request +GET /t +--- more_headers +If-Match: abc +--- response_body +If-Match: +--- no_error_log +[error] + + + +=== TEST 46: clear If-None-Match req header +--- config + location = /t { + more_clear_input_headers 'If-None-Match'; + echo "If-None-Match: $http_if_none_match"; + } +--- request +GET /t +--- more_headers +If-None-Match: * +--- response_body +If-None-Match: +--- no_error_log +[error] + + + +=== TEST 47: set the Destination request header for WebDav +--- config + location = /a.txt { + more_set_input_headers "Destination: /b.txt"; + dav_methods MOVE; + dav_access all:rw; + root html; + } + +--- user_files +>>> a.txt +hello, world! + +--- request +MOVE /a.txt + +--- response_body +--- no_error_log +client sent no "Destination" header +[error] +--- error_code: 204 + + + +=== TEST 48: more_set_input_headers + X-Forwarded-For +--- config + location = /t { + more_set_input_headers "X-Forwarded-For: 8.8.8.8"; + proxy_pass http://127.0.0.1:$server_port/back; + proxy_set_header Foo $proxy_add_x_forwarded_for; + } + + location = /back { + echo "Foo: $http_foo"; + } + +--- request +GET /t + +--- response_body +Foo: 8.8.8.8, 127.0.0.1 +--- no_error_log +[error] + + + +=== TEST 49: more_clear_input_headers + X-Forwarded-For +--- config + location = /t { + more_clear_input_headers "X-Forwarded-For"; + proxy_pass http://127.0.0.1:$server_port/back; + proxy_set_header Foo $proxy_add_x_forwarded_for; + } + + location = /back { + echo "Foo: $http_foo"; + } + +--- request +GET /t + +--- more_headers +X-Forwarded-For: 8.8.8.8 +--- response_body +Foo: 127.0.0.1 +--- no_error_log +[error] + + + +=== TEST 50: clear input headers with wildcard +--- config + location /hello { + more_clear_input_headers 'X-Hidden-*'; + content_by_lua ' + ngx.say("X-Hidden-One: ", ngx.var.http_x_hidden_one) + ngx.say("X-Hidden-Two: ", ngx.var.http_x_hidden_two) + '; + } +--- request + GET /hello +--- more_headers +X-Hidden-One: i am hidden +X-Hidden-Two: me 2 +--- response_body +X-Hidden-One: nil +X-Hidden-Two: nil + + + +=== TEST 51: make sure wildcard doesn't affect more_set_input_headers +--- config + location /hello { + more_set_input_headers 'X-Hidden-*: lol'; + content_by_lua ' + ngx.say("X-Hidden-One: ", ngx.var.http_x_hidden_one) + ngx.say("X-Hidden-Two: ", ngx.var.http_x_hidden_two) + '; + } +--- request + GET /hello +--- more_headers +X-Hidden-One: i am hidden +X-Hidden-Two: me 2 +--- response_body +X-Hidden-One: i am hidden +X-Hidden-Two: me 2 diff --git a/headers-more-nginx-module/t/phase.t b/headers-more-nginx-module/t/phase.t new file mode 100644 index 00000000..11183db7 --- /dev/null +++ b/headers-more-nginx-module/t/phase.t @@ -0,0 +1,25 @@ +# vi:filetype=perl + +use lib 'lib'; +use Test::Nginx::Socket; + +plan tests => 3; + +no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: simple set (1 arg) +--- config + location /foo { + deny all; + more_set_headers 'X-Foo: Blah'; + } +--- request + GET /foo +--- response_headers +X-Foo: Blah +--- response_body_like: 403 Forbidden +--- error_code: 403 diff --git a/headers-more-nginx-module/t/sanity.t b/headers-more-nginx-module/t/sanity.t new file mode 100644 index 00000000..d06f5dcd --- /dev/null +++ b/headers-more-nginx-module/t/sanity.t @@ -0,0 +1,567 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * 113; + +#master_on(); +#workers(2); +log_level("warn"); +no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: simple set (1 arg) +--- config + location /foo { + echo hi; + more_set_headers 'X-Foo: Blah'; + } +--- request + GET /foo +--- response_headers +X-Foo: Blah +--- response_body +hi + + + +=== TEST 2: simple set (2 args) +--- config + location /foo { + echo hi; + more_set_headers 'X-Foo: Blah' 'X-Bar: hi'; + } +--- request + GET /foo +--- response_headers +X-Foo: Blah +X-Bar: hi +--- response_body +hi + + + +=== TEST 3: two sets in a single location +--- config + location /two { + echo hi; + more_set_headers 'X-Foo: Blah' + more_set_headers 'X-Bar: hi'; + } +--- request + GET /two +--- response_headers +X-Foo: Blah +X-Bar: hi +--- response_body +hi + + + +=== TEST 4: two sets in a single location (for 404 too) +--- config + location /two { + more_set_headers 'X-Foo: Blah' + more_set_headers 'X-Bar: hi'; + return 404; + } +--- request + GET /two +--- response_headers +X-Foo: Blah +X-Bar: hi +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 5: set a header then clears it (500) +--- config + location /two { + more_set_headers 'X-Foo: Blah'; + more_set_headers 'X-Foo:'; + return 500; + } +--- request + GET /two +--- response_headers +! X-Foo +! X-Bar +--- response_body_like: 500 Internal Server Error +--- error_code: 500 + + + +=== TEST 6: set a header only when 500 (matched) +--- config + location /bad { + more_set_headers -s 500 'X-Mine: Hiya'; + more_set_headers -s 404 'X-Yours: Blah'; + return 500; + } +--- request + GET /bad +--- response_headers +X-Mine: Hiya +! X-Yours +--- response_body_like: 500 Internal Server Error +--- error_code: 500 + + + +=== TEST 7: set a header only when 500 (not matched with 200) +--- config + location /bad { + more_set_headers -s 500 'X-Mine: Hiya'; + more_set_headers -s 404 'X-Yours: Blah'; + echo hello; + } +--- request + GET /bad +--- response_headers +! X-Mine +! X-Yours +--- response_body +hello +--- error_code: 200 + + + +=== TEST 8: set a header only when 500 (not matched with 404) +--- config + location /bad { + more_set_headers -s 500 'X-Mine: Hiya'; + more_set_headers -s 404 'X-Yours: Blah'; + return 404; + } +--- request + GET /bad +--- response_headers +! X-Mine +X-Yours: Blah +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 9: more conditions +--- config + location /bad { + more_set_headers -s '503 404' 'X-Mine: Hiya'; + more_set_headers -s ' 404 413 ' 'X-Yours: Blah'; + return 503; + } +--- request + GET /bad +--- response_headers +X-Mine: Hiya +! X-Yours +--- response_body_like: 503 Service +--- error_code: 503 + + + +=== TEST 10: more conditions +--- config + location /bad { + more_set_headers -s '503 404' 'X-Mine: Hiya'; + more_set_headers -s ' 404 413 ' 'X-Yours: Blah'; + return 404; + } +--- request + GET /bad +--- response_headers +X-Mine: Hiya +X-Yours: Blah +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 11: more conditions +--- config + location /bad { + more_set_headers -s '503 404' 'X-Mine: Hiya'; + more_set_headers -s ' 404 413 ' 'X-Yours: Blah'; + return 413; + } +--- request + GET /bad +--- response_headers +! X-Mine +X-Yours: Blah +--- response_body_like: 413 Request Entity Too Large +--- error_code: 413 + + + +=== TEST 12: simple -t +--- config + location /bad { + default_type 'text/css'; + more_set_headers -t 'text/css' 'X-CSS: yes'; + echo hi; + } +--- request + GET /bad +--- response_headers +X-CSS: yes +--- response_body +hi + + + +=== TEST 13: simple -t (not matched) +--- config + location /bad { + default_type 'text/plain'; + more_set_headers -t 'text/css' 'X-CSS: yes'; + echo hi; + } +--- request + GET /bad +--- response_headers +! X-CSS +--- response_body +hi + + + +=== TEST 14: multiple -t (not matched) +--- config + location /bad { + default_type 'text/plain'; + more_set_headers -t 'text/javascript' -t 'text/css' 'X-CSS: yes'; + echo hi; + } +--- request + GET /bad +--- response_headers +! X-CSS +--- response_body +hi + + + +=== TEST 15: multiple -t (matched) +--- config + location /bad { + default_type 'text/plain'; + more_set_headers -t 'text/javascript' -t 'text/plain' 'X-CSS: yes'; + echo hi; + } +--- request + GET /bad +--- response_headers +X-CSS: yes +--- response_body +hi + + + +=== TEST 16: multiple -t (matched) +--- config + location /bad { + default_type 'text/javascript'; + more_set_headers -t 'text/javascript' -t 'text/plain' 'X-CSS: yes'; + echo hi; + } +--- request + GET /bad +--- response_headers +X-CSS: yes +--- response_body +hi + + + +=== TEST 17: multiple -t (matched) with extra spaces +--- config + location /bad { + default_type 'text/javascript'; + more_set_headers -t ' text/javascript ' -t 'text/plain' 'X-CSS: yes'; + echo hi; + } +--- request + GET /bad +--- response_headers +X-CSS: yes +--- response_body +hi + + + +=== TEST 18: multiple -t merged +--- config + location /bad { + default_type 'text/javascript'; + more_set_headers -t ' text/javascript text/plain' 'X-CSS: yes'; + echo hi; + } +--- request + GET /bad +--- response_headers +X-CSS: yes +--- response_body +hi + + + +=== TEST 19: multiple -t merged (2) +--- config + location /bad { + default_type 'text/plain'; + more_set_headers -t ' text/javascript text/plain' 'X-CSS: yes'; + echo hi; + } +--- request + GET /bad +--- response_headers +X-CSS: yes +--- response_body +hi + + + +=== TEST 20: multiple -s option in a directive (not matched) +--- config + location /bad { + more_set_headers -s 404 -s 500 'X-status: howdy'; + echo hi; + } +--- request + GET /bad +--- response_headers +! X-status +--- response_body +hi + + + +=== TEST 21: multiple -s option in a directive (matched 404) +--- config + location /bad { + more_set_headers -s 404 -s 500 'X-status: howdy'; + return 404; + } +--- request + GET /bad +--- response_headers +X-status: howdy +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 22: multiple -s option in a directive (matched 500) +--- config + location /bad { + more_set_headers -s 404 -s 500 'X-status: howdy'; + return 500; + } +--- request + GET /bad +--- response_headers +X-status: howdy +--- response_body_like: 500 Internal Server Error +--- error_code: 500 + + + +=== TEST 23: -s mixed with -t +--- config + location /bad { + default_type 'text/html'; + more_set_headers -s 404 -s 200 -t 'text/html' 'X-status: howdy2'; + return 404; + } +--- request + GET /bad +--- response_headers +X-status: howdy2 +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 24: -s mixed with -t +--- config + location /bad { + default_type 'text/html'; + more_set_headers -s 404 -s 200 -t 'text/plain' 'X-status: howdy2'; + return 404; + } +--- request + GET /bad +--- response_headers +! X-status +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 25: -s mixed with -t +--- config + location /bad { + default_type 'text/html'; + more_set_headers -s 404 -s 200 -t 'text/html' 'X-status: howdy2'; + echo hi; + } +--- request + GET /bad +--- response_headers +X-status: howdy2 +--- response_body +hi +--- error_code: 200 + + + +=== TEST 26: -s mixed with -t +--- config + location /bad { + default_type 'text/html'; + more_set_headers -s 500 -s 200 -t 'text/html' 'X-status: howdy2'; + return 404; + } +--- request + GET /bad +--- response_headers +! X-status +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 27: merge from the upper level +--- config + more_set_headers -s 404 -t 'text/html' 'X-status2: howdy3'; + location /bad { + default_type 'text/html'; + more_set_headers -s 500 -s 200 -t 'text/html' 'X-status: howdy2'; + return 404; + } +--- request + GET /bad +--- response_headers +X-status2: howdy3 +! X-status +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 28: merge from the upper level +--- config + more_set_headers -s 404 -t 'text/html' 'X-status2: howdy3'; + location /bad { + default_type 'text/html'; + more_set_headers -s 500 -s 200 -t 'text/html' 'X-status: howdy2'; + echo yeah; + } +--- request + GET /bad +--- response_headers +! X-status2 +X-status: howdy2 +--- response_body +yeah +--- error_code: 200 + + + +=== TEST 29: override settings by inheritance +--- config + more_set_headers -s 404 -t 'text/html' 'X-status: yeah'; + location /bad { + default_type 'text/html'; + more_set_headers -s 404 -t 'text/html' 'X-status: nope'; + return 404; + } +--- request + GET /bad +--- response_headers +X-status: nope +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 30: append settings by inheritance +--- config + more_set_headers -s 404 -t 'text/html' 'X-status: yeah'; + location /bad { + default_type 'text/html'; + more_set_headers -s 404 -t 'text/html' 'X-status2: nope'; + return 404; + } +--- request + GET /bad +--- response_headers +X-status: yeah +X-status2: nope +--- response_body_like: 404 Not Found +--- error_code: 404 + + + +=== TEST 31: clear headers with wildcard +--- config + location = /backend { + add_header X-Hidden-One "i am hidden"; + add_header X-Hidden-Two "me 2"; + echo hi; + } + location /hello { + more_clear_headers 'X-Hidden-*'; + proxy_pass http://127.0.0.1:$server_port/backend; + } +--- request + GET /hello +--- response_headers +! X-Hidden-One +! X-Hidden-Two +--- response_body +hi + + + +=== TEST 32: clear duplicate headers +--- config + location = /backend { + add_header pragma no-cache; + add_header pragma no-cache; + echo hi; + } + location /hello { + more_clear_headers 'pragma'; + proxy_pass http://127.0.0.1:$server_port/backend; + } +--- request + GET /hello +--- response_headers +!pragma +--- response_body +hi + + + +=== TEST 33: HTTP 0.9 (set) +--- config + location /foo { + more_set_headers 'X-Foo: howdy'; + echo ok; + } +--- raw_request eval +"GET /foo\r\n" +--- response_headers +! X-Foo +--- response_body +ok +--- http09 diff --git a/headers-more-nginx-module/t/subrequest.t b/headers-more-nginx-module/t/subrequest.t new file mode 100644 index 00000000..9443eca0 --- /dev/null +++ b/headers-more-nginx-module/t/subrequest.t @@ -0,0 +1,68 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; # 'no_plan'; + +plan tests => blocks() * 3; + +no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: vars in input header directives +--- config + location /main { + echo_location /foo; + echo "main: $http_user_agent"; + } + location /foo { + set $val 'dog'; + + more_set_input_headers 'User-Agent: $val'; + + proxy_pass http://127.0.0.1:$server_port/proxy; + } + location /proxy { + echo "sub: $http_user_agent"; + } +--- request + GET /main +--- more_headers +User-Agent: my-sock +--- response_body +sub: dog +main: dog +--- response_headers +! Host +--- skip_nginx: 3: < 0.7.46 + + + +=== TEST 2: vars in input header directives +--- config + location /main { + #more_set_input_headers 'User-Agent: cat'; + echo_location /foo; + echo "main: $http_user_agent"; + } + location /foo { + set $val 'dog'; + + more_set_input_headers 'User-Agent: $val'; + + proxy_pass http://127.0.0.1:$server_port/proxy; + #echo $http_user_agent; + } + location /proxy { + echo "sub: $http_user_agent"; + } +--- request + GET /main +--- response_body +sub: dog +main: dog +--- response_headers +! Host +--- skip_nginx: 3: < 0.7.46 diff --git a/headers-more-nginx-module/t/unused.t b/headers-more-nginx-module/t/unused.t new file mode 100644 index 00000000..c51f91c6 --- /dev/null +++ b/headers-more-nginx-module/t/unused.t @@ -0,0 +1,174 @@ +# vi:filetype= + +use lib 'lib'; +use Test::Nginx::Socket; + +repeat_each(2); + +plan tests => repeat_each() * (blocks() * 4 + 2); + +#master_on(); +#workers(2); +log_level("warn"); +no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: used output filter +--- config + location /foo { + echo hi; + more_set_headers "Foo: bar"; + } +--- request + GET /foo +--- response_headers +Foo: bar +--- response_body +hi +--- error_log +headers more header filter +--- no_error_log +[error] +--- log_level: debug + + + +=== TEST 2: unused output filter (none) +--- config + location /foo { + echo hi; + } +--- request + GET /foo +--- response_body +hi +--- no_error_log +headers more header filter +[error] +--- log_level: debug + + + +=== TEST 3: unused output filter (with more_set_input_headers only) +--- config + location /foo { + more_set_input_headers "Foo: bar"; + echo hi; + } +--- request + GET /foo +--- response_body +hi +--- no_error_log +headers more header filter +[error] +--- log_level: debug + + + +=== TEST 4: used rewrite handler +--- config + location /foo { + more_set_input_headers "Foo: bar"; + echo hi; + } +--- request + GET /foo +--- response_body +hi +--- error_log +headers more rewrite handler +--- no_error_log +[error] +--- log_level: debug + + + +=== TEST 5: unused rewrite handler (none) +--- config + location /foo { + #more_set_input_headers "Foo: bar"; + echo hi; + } +--- request + GET /foo +--- response_body +hi +--- no_error_log +headers more rewrite handler +[error] +--- log_level: debug + + + +=== TEST 6: unused rewrite handler (with output header filters) +--- config + location /foo { + #more_set_input_headers "Foo: bar"; + echo hi; + more_set_headers "Foo: bar"; + } +--- request + GET /foo +--- response_headers +Foo: bar +--- response_body +hi +--- no_error_log +headers more rewrite handler +[error] +--- log_level: debug + + + +=== TEST 7: multiple http {} blocks (filter) +This test case won't run with nginx 1.9.3+ since duplicate http {} blocks +have been prohibited since then. +--- SKIP +--- config + location /foo { + echo hi; + more_set_headers 'Foo: bar'; + } +--- post_main_config + http { + } + +--- request + GET /foo +--- response_body +hi +--- response_headers +Foo: bar +--- no_error_log +[error] +--- error_log +headers more header filter +--- log_level: debug + + + +=== TEST 8: multiple http {} blocks (handler) +This test case won't run with nginx 1.9.3+ since duplicate http {} blocks +have been prohibited since then. +--- SKIP +--- config + location /foo { + more_set_input_headers 'Foo: bar'; + echo $http_foo; + } +--- post_main_config + http { + } + +--- request + GET /foo +--- response_body +bar +--- no_error_log +headers more header handler +[error] +--- log_level: debug diff --git a/headers-more-nginx-module/t/vars.t b/headers-more-nginx-module/t/vars.t new file mode 100644 index 00000000..04c75c38 --- /dev/null +++ b/headers-more-nginx-module/t/vars.t @@ -0,0 +1,58 @@ +# vi:ft= + +use lib 'lib'; +use Test::Nginx::Socket; # 'no_plan'; + +plan tests => 9; + +no_diff; + +run_tests(); + +__DATA__ + +=== TEST 1: vars +--- config + location /foo { + echo hi; + set $val 'hello, world'; + more_set_headers 'X-Foo: $val'; + } +--- request + GET /foo +--- response_headers +X-Foo: hello, world +--- response_body +hi + + + +=== TEST 2: vars in both key and val +--- config + location /foo { + echo hi; + set $val 'hello, world'; + more_set_headers '$val: $val'; + } +--- request + GET /foo +--- response_headers +$val: hello, world +--- response_body +hi + + + +=== TEST 3: vars in input header directives +--- config + location /foo { + set $val 'dog'; + more_set_input_headers 'Host: $val'; + echo $host; + } +--- request + GET /foo +--- response_body +dog +--- response_headers +Host: diff --git a/headers-more-nginx-module/util/build.sh b/headers-more-nginx-module/util/build.sh new file mode 100755 index 00000000..007194d7 --- /dev/null +++ b/headers-more-nginx-module/util/build.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +# this file is mostly meant to be used by the author himself. + +root=`pwd` +version=$1 +home=~ +force=$2 + + #--with-cc=gcc46 \ + +ngx-build $force $version \ + --with-ld-opt="-L$PCRE_LIB -Wl,-rpath,$PCRE_LIB:$LIBDRIZZLE_LIB" \ + --without-mail_pop3_module \ + --without-mail_imap_module \ + --without-mail_smtp_module \ + --without-http_upstream_ip_hash_module \ + --without-http_empty_gif_module \ + --without-http_memcached_module \ + --without-http_referer_module \ + --without-http_autoindex_module \ + --without-http_auth_basic_module \ + --without-http_userid_module \ + --with-http_realip_module \ + --with-http_dav_module \ + --add-module=$root/../eval-nginx-module \ + --add-module=$root/../lua-nginx-module \ + --add-module=$root/../echo-nginx-module \ + --add-module=$root $opts \ + --with-debug + #--add-module=$root/../ndk-nginx-module \ + #--without-http_ssi_module # we cannot disable ssi because echo_location_async depends on it (i dunno why?!) + diff --git a/headers-more-nginx-module/valgrind.suppress b/headers-more-nginx-module/valgrind.suppress new file mode 100644 index 00000000..bba7217a --- /dev/null +++ b/headers-more-nginx-module/valgrind.suppress @@ -0,0 +1,215 @@ +{ + +Memcheck:Cond +fun:lj_str_new +} +{ + + Memcheck:Cond + fun:lj_str_new + fun:lua_pushlstring +} +{ + + Memcheck:Addr4 + fun:lj_str_new + fun:lua_pushlstring +} +{ + +Memcheck:Leak +fun:malloc +fun:ngx_alloc +obj:* +} +{ + +Memcheck:Leak +fun:malloc +fun:ngx_alloc +} +{ + +Memcheck:Leak +fun:malloc +fun:ngx_alloc +fun:ngx_palloc_large +fun:ngx_palloc +} +{ + + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_calloc + fun:ngx_event_process_init +} +{ + +Memcheck:Addr4 +fun:lj_str_new +fun:lua_pushlstring +fun:ngx_http_lua_get_output_header +} +{ + + Memcheck:Addr4 + fun:lj_str_new + fun:lua_getfield + fun:ngx_http_lua_cache_load_code +} +{ + + Memcheck:Addr4 + fun:lj_str_new + fun:lua_setfield + fun:ngx_http_lua_cache_store_code +} +{ + + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_event_process_init +} +{ + + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:(below main) +} +{ + + Memcheck:Param + epoll_ctl(event) + fun:epoll_ctl +} +{ + + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_create_pool +} +{ + + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_malloc + fun:ngx_palloc_large +} +{ + + Memcheck:Cond + fun:memcpy + fun:ngx_vslprintf + fun:ngx_log_error_core + fun:ngx_http_charset_header_filter +} +{ + + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_malloc + fun:ngx_pnalloc +} +{ + + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_malloc + fun:ngx_palloc +} +{ + nginx-core-process-init + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_event_process_init +} +{ + nginx-core-crc32-init + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_crc32_table_init + fun:main +} +{ + palloc_large_for_init_request + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_palloc_large + fun:ngx_palloc + fun:ngx_pcalloc + fun:ngx_http_init_request + fun:ngx_epoll_process_events + fun:ngx_process_events_and_timers +} +{ + palloc_large_for_create_temp_buf + Memcheck:Leak + fun:malloc + fun:ngx_alloc + fun:ngx_palloc_large + fun:ngx_palloc + fun:ngx_create_temp_buf + fun:ngx_http_init_request + fun:ngx_epoll_process_events + fun:ngx_process_events_and_timers +} +{ + accept_create_pool + Memcheck:Leak + fun:memalign + fun:posix_memalign + fun:ngx_memalign + fun:ngx_create_pool + fun:ngx_event_accept + fun:ngx_epoll_process_events + fun:ngx_process_events_and_timers +} +{ + create_pool_for_init_req + Memcheck:Leak + fun:memalign + fun:posix_memalign + fun:ngx_memalign + fun:ngx_create_pool + fun:ngx_http_init_request + fun:ngx_epoll_process_events + fun:ngx_process_events_and_timers +} +{ + + Memcheck:Leak + fun:memalign + fun:posix_memalign + fun:ngx_memalign + fun:ngx_palloc_block + fun:ngx_palloc +} +{ + + Memcheck:Addr8 + fun:getenv + fun:gcov_exit + fun:exit + fun:ngx_master_process_exit +} +{ + + Memcheck:Cond + fun:index + fun:expand_dynamic_string_token + fun:_dl_map_object + fun:map_doit + fun:_dl_catch_error + fun:do_preload + fun:dl_main +} diff --git a/lua-nginx-module/.gitattributes b/lua-nginx-module/.gitattributes new file mode 100644 index 00000000..6fe6f35c --- /dev/null +++ b/lua-nginx-module/.gitattributes @@ -0,0 +1 @@ +*.t linguist-language=Text diff --git a/lua-nginx-module/.github/ISSUE_TEMPLATE.md b/lua-nginx-module/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..e6359b0a --- /dev/null +++ b/lua-nginx-module/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,23 @@ +This place is for bug reports and development discussions only. For general questions and +discussions, please join the openresty-en mailing list instead: https://openresty.org/en/community.html + +Ensure you have provided the following details while reporting a problem: + +* The exact version of the related software, including but not limited to the OpenResty version +(if any), the NGINX core version, the `ngx_lua` module version, +and your operating system version. +* A minimal and standalone test case that others can easily run on their side and +reproduce the issue you are seeing. +* Do not simply say "something is broken" or "something does not work". Always provide +as much details as possible. Always describe the symptoms and your expected results. +* You can (temporarily) enable the nginx debugging logs to see the internal workings +of NGINX in your nginx''s `error.log` file. See http://nginx.org/en/docs/debugging_log.html +The same instructions apply equally well to OpenResty. +* If you are seeing crashes, please provide the full backtrace for the crash. See +https://www.nginx.com/resources/wiki/start/topics/tutorials/debugging/#core-dump +for more details. + +Please, do not use Chinese here. This place is considered English only. If you +really want to use Chinese, please join and post to the openresty (Chinese) +mailing list instead. Please see https://openresty.org/en/community.html Thanks for +your cooperation. diff --git a/lua-nginx-module/.github/PULL_REQUEST_TEMPLATE.md b/lua-nginx-module/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..5e833bab --- /dev/null +++ b/lua-nginx-module/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,2 @@ +I hereby granted the copyright of the changes in this pull request +to the authors of this lua-nginx-module project. diff --git a/lua-nginx-module/.gitignore b/lua-nginx-module/.gitignore new file mode 100644 index 00000000..eff33724 --- /dev/null +++ b/lua-nginx-module/.gitignore @@ -0,0 +1,172 @@ +build/ +work/ +tags +cscope.* +*.mobi +genmobi.sh +.libs +*.swp +*.slo +*.la +*.swo +*.lo +*~ +*.o +print.txt +.rsync +*.tar.gz +dist +build[789] +build +tags +update-readme +*.tmp +test/Makefile +test/blib +test.sh +t.sh +t/t.sh +test/t/servroot/ +releng +reset +*.t_ +src/handler.h +src/util.c +src/module.h +src/module.c +src/drizzle.c +src/processor.h +src/handler.c +src/util.h +src/drizzle.h +src/processor.c +src/output.c +src/output.h +libdrizzle +ctags +src/stream.h +nginx +keepalive +reindex +src/keepalive.c +src/keepalive.h +src/checker.h +src/checker.c +src/quoting.h +src/quoting.c +src/module.h +src/module.c +src/util.h +src/util.c +src/processor.h +src/processor.c +src/rds.h +src/utils.h +src/handler.c +src/handler.h +util/bench +*.html +trace.out* +try.sh +src/cache.c +src/cache.h +src/common.h +src/directive.c +src/directive.h +src/consts.[ch] +src/contentby.[ch] +src/pcrefix.[ch] +src/util.c +src/clfactory.c +src/directive.c +src/conf.h +src/setby.h +src/cache.h +src/hook.c +src/util.h +src/hook.h +src/common.h +src/directive.h +src/conf.c +src/setby.c +src/cache.c +src/module.c +src/clfactory.h +src/capturefilter.[ch] +src/contentby.c +pack +b.sh +src/in.[ch] +src/out.[ch] +go +all.sh +src/accessby.[ch] +src/rewriteby.[ch] +src/patch.[ch] +src/ndk.[ch] +src/control.[ch] +src/output.[ch] +src/variable.[ch] +src/string.[ch] +src/misc.[ch] +src/log.[ch] +src/exception.[ch] +src/subrequest.[ch] +src/time.[ch] +src/regex.[ch] +src/ctx.[ch] +src/args.[ch] +src/headers.[ch] +src/script.[ch] +src/filter.[ch] +src/shdict.[ch] +src/body.[ch] +src/uri.[ch] +src/api.[ch] +src/coroutine.[ch] +src/logby.[ch] +src/sleep.[ch] +a.patch +all +build1[0-9] +g +buildroot/ +src/headerfilterby.[ch] +*.patch +analyze +tsock +a.c +test.lua +build12 +ERRORS +src/bodyfilterby.[ch] +src/tcp.[ch] +src/initby.[ch] +src/initworkerby.[ch] +src/socket.[ch] +src/udp.[ch] +src/method.[ch] +tre +src/phase.[ch] +src/probe.h +src/uthread.[ch] +src/timer.[ch] +src/config.[ch] +src/worker.[ch] +src/certby.[ch] +src/storeby.[ch] +src/fetchby.[ch] +src/ssl.[ch] +src/ocsp.c +src/lex.[ch] +src/balancer.[ch] +src/semaphore.[ch] +*.plist +lua +ttimer +Makefile +tsubreq +tthread +addr2line +hup +theaders diff --git a/lua-nginx-module/.travis.yml b/lua-nginx-module/.travis.yml new file mode 100644 index 00000000..7448f65a --- /dev/null +++ b/lua-nginx-module/.travis.yml @@ -0,0 +1,131 @@ +sudo: required +dist: trusty + +os: linux + +language: c + +compiler: + - gcc + - clang + +addons: + apt: + packages: + - axel + - cpanminus + - libtest-base-perl + - libtext-diff-perl + - liburi-perl + - libwww-perl + - libtest-longstring-perl + - liblist-moreutils-perl + - libgd-dev + +cache: + directories: + - download-cache + +env: + global: + - JOBS=3 + - NGX_BUILD_JOBS=$JOBS + - LUAJIT_PREFIX=/opt/luajit21 + - LUAJIT_LIB=$LUAJIT_PREFIX/lib + - LUAJIT_INC=$LUAJIT_PREFIX/include/luajit-2.1 + - LUA_INCLUDE_DIR=$LUAJIT_INC + - PCRE_VER=8.40 + - PCRE_PREFIX=/opt/pcre + - PCRE_LIB=$PCRE_PREFIX/lib + - PCRE_INC=$PCRE_PREFIX/include + - OPENSSL_PREFIX=/opt/ssl + - OPENSSL_LIB=$OPENSSL_PREFIX/lib + - OPENSSL_INC=$OPENSSL_PREFIX/include + - OPENSSL_VER=1.0.2k + - LIBDRIZZLE_PREFIX=/opt/drizzle + - LIBDRIZZLE_INC=$LIBDRIZZLE_PREFIX/include/libdrizzle-1.0 + - LIBDRIZZLE_LIB=$LIBDRIZZLE_PREFIX/lib + - LD_LIBRARY_PATH=$LUAJIT_LIB:$LD_LIBRARY_PATH + - DRIZZLE_VER=2011.07.21 + - TEST_NGINX_SLEEP=0.006 + matrix: + - NGINX_VERSION=1.11.2 + - NGINX_VERSION=1.13.5 + +services: + - memcache + - redis-server + - mysql + +before_install: + - '! grep -n -P ''(?<=.{80}).+'' --color `find src -name ''*.c''` `find . -name ''*.h''` || (echo "ERROR: Found C source lines exceeding 80 columns." > /dev/stderr; exit 1)' + - '! grep -n -P ''\t+'' --color `find src -name ''*.c''` `find . -name ''*.h''` || (echo "ERROR: Cannot use tabs." > /dev/stderr; exit 1)' + - sudo cpanm --notest Test::Nginx IPC::Run > build.log 2>&1 || (cat build.log && exit 1) + +install: + - if [ ! -f download-cache/drizzle7-$DRIZZLE_VER.tar.gz ]; then wget -P download-cache http://openresty.org/download/drizzle7-$DRIZZLE_VER.tar.gz; fi + - if [ ! -f download-cache/pcre-$PCRE_VER.tar.gz ]; then wget -P download-cache http://ftp.cs.stanford.edu/pub/exim/pcre/pcre-$PCRE_VER.tar.gz; fi + - if [ ! -f download-cache/openssl-$OPENSSL_VER.tar.gz ]; then wget -P download-cache https://www.openssl.org/source/openssl-$OPENSSL_VER.tar.gz; fi + - git clone https://github.com/openresty/test-nginx.git + - git clone https://github.com/openresty/openresty.git ../openresty + - git clone https://github.com/openresty/no-pool-nginx.git ../no-pool-nginx + - git clone https://github.com/openresty/openresty-devel-utils.git + - git clone https://github.com/openresty/mockeagain.git + - git clone https://github.com/openresty/lua-cjson.git + - git clone https://github.com/openresty/lua-upstream-nginx-module.git ../lua-upstream-nginx-module + - git clone https://github.com/openresty/echo-nginx-module.git ../echo-nginx-module + - git clone https://github.com/openresty/nginx-eval-module.git ../nginx-eval-module + - git clone https://github.com/simpl/ngx_devel_kit.git ../ndk-nginx-module + - git clone https://github.com/FRiCKLE/ngx_coolkit.git ../coolkit-nginx-module + - git clone https://github.com/openresty/headers-more-nginx-module.git ../headers-more-nginx-module + - git clone https://github.com/openresty/drizzle-nginx-module.git ../drizzle-nginx-module + - git clone https://github.com/openresty/set-misc-nginx-module.git ../set-misc-nginx-module + - git clone https://github.com/openresty/memc-nginx-module.git ../memc-nginx-module + - git clone https://github.com/openresty/rds-json-nginx-module.git ../rds-json-nginx-module + - git clone https://github.com/openresty/srcache-nginx-module.git ../srcache-nginx-module + - git clone https://github.com/openresty/redis2-nginx-module.git ../redis2-nginx-module + - git clone https://github.com/openresty/lua-resty-core.git ../lua-resty-core + - git clone https://github.com/openresty/lua-resty-lrucache.git ../lua-resty-lrucache + - git clone https://github.com/openresty/lua-resty-mysql.git ../lua-resty-mysql + - git clone -b v2.1-agentzh https://github.com/openresty/luajit2.git + +before_script: + - mysql -uroot -e 'create database ngx_test; grant all on ngx_test.* to "ngx_test"@"%" identified by "ngx_test"; flush privileges;' + +script: + - sudo iptables -I OUTPUT 1 -p udp --dport 10086 -j REJECT + - cd luajit2/ + - make -j$JOBS CCDEBUG=-g Q= PREFIX=$LUAJIT_PREFIX CC=$CC XCFLAGS='-DLUA_USE_APICHECK -DLUA_USE_ASSERT -msse4.2' > build.log 2>&1 || (cat build.log && exit 1) + - sudo make install PREFIX=$LUAJIT_PREFIX > build.log 2>&1 || (cat build.log && exit 1) + - cd .. + - tar xzf download-cache/drizzle7-$DRIZZLE_VER.tar.gz && cd drizzle7-$DRIZZLE_VER + - ./configure --prefix=$LIBDRIZZLE_PREFIX --without-server > build.log 2>&1 || (cat build.log && exit 1) + - make libdrizzle-1.0 -j$JOBS > build.log 2>&1 || (cat build.log && exit 1) + - sudo make install-libdrizzle-1.0 > build.log 2>&1 || (cat build.log && exit 1) + - cd ../mockeagain/ && make CC=$CC -j$JOBS && cd .. + - cd lua-cjson/ && make -j$JOBS && sudo make install && cd .. + - tar zxf download-cache/pcre-$PCRE_VER.tar.gz + - cd pcre-$PCRE_VER/ + - ./configure --prefix=$PCRE_PREFIX --enable-jit --enable-utf --enable-unicode-properties > build.log 2>&1 || (cat build.log && exit 1) + - make -j$JOBS > build.log 2>&1 || (cat build.log && exit 1) + - sudo PATH=$PATH make install > build.log 2>&1 || (cat build.log && exit 1) + - cd .. + - tar zxf download-cache/openssl-$OPENSSL_VER.tar.gz + - cd openssl-$OPENSSL_VER/ + - if [ ! -f ../download-cache/openssl-1.0.2h-sess_set_get_cb_yield.patch ]; then wget -P ../download-cache https://raw.githubusercontent.com/openresty/openresty/master/patches/openssl-1.0.2h-sess_set_get_cb_yield.patch; fi + - patch -p1 < ../download-cache/openssl-1.0.2h-sess_set_get_cb_yield.patch + - ./config shared --prefix=$OPENSSL_PREFIX -DPURIFY > build.log 2>&1 || (cat build.log && exit 1) + - make -j$JOBS > build.log 2>&1 || (cat build.log && exit 1) + - sudo make PATH=$PATH install_sw > build.log 2>&1 || (cat build.log && exit 1) + - cd .. + - export PATH=$PWD/work/nginx/sbin:$PWD/openresty-devel-utils:$PATH + - export NGX_BUILD_CC=$CC + - sh util/build.sh $NGINX_VERSION > build.log 2>&1 || (cat build.log && exit 1) + - nginx -V + - ldd `which nginx`|grep -E 'luajit|ssl|pcre' + - export LD_PRELOAD=$PWD/mockeagain/mockeagain.so + - export LD_LIBRARY_PATH=$PWD/mockeagain:$LD_LIBRARY_PATH + - export TEST_NGINX_RESOLVER=8.8.4.4 + - dig +short @$TEST_NGINX_RESOLVER openresty.org || exit 0 + - dig +short @$TEST_NGINX_RESOLVER agentzh.org || exit 0 + - prove -Itest-nginx/lib -r t diff --git a/lua-nginx-module/README.markdown b/lua-nginx-module/README.markdown new file mode 100644 index 00000000..28ba6e68 --- /dev/null +++ b/lua-nginx-module/README.markdown @@ -0,0 +1,8265 @@ + + +Name +==== + +ngx_http_lua_module - Embed the power of Lua into Nginx HTTP Servers. + +*This module is not distributed with the Nginx source.* See [the installation instructions](#installation). + +Table of Contents +================= + +* [Name](#name) +* [Status](#status) +* [Version](#version) +* [Synopsis](#synopsis) +* [Description](#description) +* [Typical Uses](#typical-uses) +* [Nginx Compatibility](#nginx-compatibility) +* [Installation](#installation) + * [Building as a dynamic module](#building-as-a-dynamic-module) + * [C Macro Configurations](#c-macro-configurations) + * [Installation on Ubuntu 11.10](#installation-on-ubuntu-1110) +* [Community](#community) + * [English Mailing List](#english-mailing-list) + * [Chinese Mailing List](#chinese-mailing-list) +* [Code Repository](#code-repository) +* [Bugs and Patches](#bugs-and-patches) +* [Lua/LuaJIT bytecode support](#lualuajit-bytecode-support) +* [System Environment Variable Support](#system-environment-variable-support) +* [HTTP 1.0 support](#http-10-support) +* [Statically Linking Pure Lua Modules](#statically-linking-pure-lua-modules) +* [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker) +* [Known Issues](#known-issues) + * [TCP socket connect operation issues](#tcp-socket-connect-operation-issues) + * [Lua Coroutine Yielding/Resuming](#lua-coroutine-yieldingresuming) + * [Lua Variable Scope](#lua-variable-scope) + * [Locations Configured by Subrequest Directives of Other Modules](#locations-configured-by-subrequest-directives-of-other-modules) + * [Cosockets Not Available Everywhere](#cosockets-not-available-everywhere) + * [Special Escaping Sequences](#special-escaping-sequences) + * [Mixing with SSI Not Supported](#mixing-with-ssi-not-supported) + * [SPDY Mode Not Fully Supported](#spdy-mode-not-fully-supported) + * [Missing data on short circuited requests](#missing-data-on-short-circuited-requests) +* [TODO](#todo) +* [Changes](#changes) +* [Test Suite](#test-suite) +* [Copyright and License](#copyright-and-license) +* [See Also](#see-also) +* [Directives](#directives) +* [Nginx API for Lua](#nginx-api-for-lua) +* [Obsolete Sections](#obsolete-sections) + * [Special PCRE Sequences](#special-pcre-sequences) + +Status +====== + +Production ready. + +Version +======= + +This document describes ngx_lua [v0.10.10](https://github.com/openresty/lua-nginx-module/tags) released on 8 August 2017. + +Synopsis +======== +```nginx + + # set search paths for pure Lua external libraries (';;' is the default path): + lua_package_path '/foo/bar/?.lua;/blah/?.lua;;'; + + # set search paths for Lua external libraries written in C (can also use ';;'): + lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;'; + + server { + location /lua_content { + # MIME type determined by default_type: + default_type 'text/plain'; + + content_by_lua_block { + ngx.say('Hello,world!') + } + } + + location /nginx_var { + # MIME type determined by default_type: + default_type 'text/plain'; + + # try access /nginx_var?a=hello,world + content_by_lua_block { + ngx.say(ngx.var.arg_a) + } + } + + location = /request_body { + client_max_body_size 50k; + client_body_buffer_size 50k; + + content_by_lua_block { + ngx.req.read_body() -- explicitly read the req body + local data = ngx.req.get_body_data() + if data then + ngx.say("body data:") + ngx.print(data) + return + end + + -- body may get buffered in a temp file: + local file = ngx.req.get_body_file() + if file then + ngx.say("body is in file ", file) + else + ngx.say("no body found") + end + } + } + + # transparent non-blocking I/O in Lua via subrequests + # (well, a better way is to use cosockets) + location = /lua { + # MIME type determined by default_type: + default_type 'text/plain'; + + content_by_lua_block { + local res = ngx.location.capture("/some_other_location") + if res then + ngx.say("status: ", res.status) + ngx.say("body:") + ngx.print(res.body) + end + } + } + + location = /foo { + rewrite_by_lua_block { + res = ngx.location.capture("/memc", + { args = { cmd = "incr", key = ngx.var.uri } } + ) + } + + proxy_pass http://blah.blah.com; + } + + location = /mixed { + rewrite_by_lua_file /path/to/rewrite.lua; + access_by_lua_file /path/to/access.lua; + content_by_lua_file /path/to/content.lua; + } + + # use nginx var in code path + # CAUTION: contents in nginx var must be carefully filtered, + # otherwise there'll be great security risk! + location ~ ^/app/([-_a-zA-Z0-9/]+) { + set $path $1; + content_by_lua_file /path/to/lua/app/root/$path.lua; + } + + location / { + client_max_body_size 100k; + client_body_buffer_size 100k; + + access_by_lua_block { + -- check the client IP address is in our black list + if ngx.var.remote_addr == "132.5.72.3" then + ngx.exit(ngx.HTTP_FORBIDDEN) + end + + -- check if the URI contains bad words + if ngx.var.uri and + string.match(ngx.var.request_body, "evil") + then + return ngx.redirect("/terms_of_use.html") + end + + -- tests passed + } + + # proxy_pass/fastcgi_pass/etc settings + } + } +``` + +[Back to TOC](#table-of-contents) + +Description +=========== + +This module embeds Lua, via the standard Lua 5.1 interpreter or [LuaJIT 2.0/2.1](http://luajit.org/luajit.html), into Nginx and by leveraging Nginx's subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the Nginx event model. + +Unlike [Apache's mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html) and [Lighttpd's mod_magnet](http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet), Lua code executed using this module can be *100% non-blocking* on network traffic as long as the [Nginx API for Lua](#nginx-api-for-lua) provided by this module is used to handle +requests to upstream services such as MySQL, PostgreSQL, Memcached, Redis, or upstream HTTP web services. + +At least the following Lua libraries and Nginx modules can be used with this ngx_lua module: + +* [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached) +* [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql) +* [lua-resty-redis](https://github.com/openresty/lua-resty-redis) +* [lua-resty-dns](https://github.com/openresty/lua-resty-dns) +* [lua-resty-upload](https://github.com/openresty/lua-resty-upload) +* [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket) +* [lua-resty-lock](https://github.com/openresty/lua-resty-lock) +* [lua-resty-logger-socket](https://github.com/cloudflare/lua-resty-logger-socket) +* [lua-resty-lrucache](https://github.com/openresty/lua-resty-lrucache) +* [lua-resty-string](https://github.com/openresty/lua-resty-string) +* [ngx_memc](http://github.com/openresty/memc-nginx-module) +* [ngx_postgres](https://github.com/FRiCKLE/ngx_postgres) +* [ngx_redis2](http://github.com/openresty/redis2-nginx-module) +* [ngx_redis](http://wiki.nginx.org/HttpRedisModule) +* [ngx_proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) +* [ngx_fastcgi](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html) + +Almost all the Nginx modules can be used with this ngx_lua module by means of [ngx.location.capture](#ngxlocationcapture) or [ngx.location.capture_multi](#ngxlocationcapture_multi) but it is recommended to use those `lua-resty-*` libraries instead of creating subrequests to access the Nginx upstream modules because the former is usually much more flexible and memory-efficient. + +The Lua interpreter or LuaJIT instance is shared across all the requests in a single nginx worker process but request contexts are segregated using lightweight Lua coroutines. + +Loaded Lua modules persist in the nginx worker process level resulting in a small memory footprint in Lua even when under heavy loads. + +This module is plugged into NGINX's "http" subsystem so it can only speaks downstream communication protocols in the HTTP family (HTTP 0.9/1.0/1.1/2.0, WebSockets, and etc). +If you want to do generic TCP communications with the downstream clients, then you should use the [ngx_stream_lua](https://github.com/openresty/stream-lua-nginx-module#readme) module instead +which has a compatible Lua API. + +[Back to TOC](#table-of-contents) + +Typical Uses +============ + +Just to name a few: + +* Mashup'ing and processing outputs of various nginx upstream outputs (proxy, drizzle, postgres, redis, memcached, and etc) in Lua, +* doing arbitrarily complex access control and security checks in Lua before requests actually reach the upstream backends, +* manipulating response headers in an arbitrary way (by Lua) +* fetching backend information from external storage backends (like redis, memcached, mysql, postgresql) and use that information to choose which upstream backend to access on-the-fly, +* coding up arbitrarily complex web applications in a content handler using synchronous but still non-blocking access to the database backends and other storage, +* doing very complex URL dispatch in Lua at rewrite phase, +* using Lua to implement advanced caching mechanism for Nginx's subrequests and arbitrary locations. + +The possibilities are unlimited as the module allows bringing together various elements within Nginx as well as exposing the power of the Lua language to the user. The module provides the full flexibility of scripting while offering performance levels comparable with native C language programs both in terms of CPU time as well as memory footprint. This is particularly the case when LuaJIT 2.x is enabled. + +Other scripting language implementations typically struggle to match this performance level. + +The Lua state (Lua VM instance) is shared across all the requests handled by a single nginx worker process to minimize memory use. + +[Back to TOC](#table-of-contents) + +Nginx Compatibility +=================== + +The latest version of this module is compatible with the following versions of Nginx: + +* 1.11.x (last tested: 1.11.2) +* 1.10.x +* 1.9.x (last tested: 1.9.15) +* 1.8.x +* 1.7.x (last tested: 1.7.10) +* 1.6.x + +Nginx cores older than 1.6.0 (exclusive) are *not* supported. + +[Back to TOC](#table-of-contents) + +Installation +============ + +It is *highly* recommended to use [OpenResty releases](http://openresty.org) which integrate Nginx, ngx_lua, LuaJIT 2.1, as well as other powerful companion Nginx modules and Lua libraries. It is discouraged to build this module with nginx yourself since it is tricky to set up exactly right. Also, the stock nginx cores have various limitations and long standing bugs that can make some of this modules' features become disabled, not work properly, or run slower. + +Alternatively, ngx_lua can be manually compiled into Nginx: + +1. Install LuaJIT 2.0 or 2.1 (recommended) or Lua 5.1 (Lua 5.2 is *not* supported yet). LuaJIT can be downloaded from the [LuaJIT project website](http://luajit.org/download.html) and Lua 5.1, from the [Lua project website](http://www.lua.org/). Some distribution package managers also distribute LuaJIT and/or Lua. +1. Download the latest version of the ngx_devel_kit (NDK) module [HERE](https://github.com/simpl/ngx_devel_kit/tags). +1. Download the latest version of ngx_lua [HERE](https://github.com/openresty/lua-nginx-module/tags). +1. Download the latest version of Nginx [HERE](http://nginx.org/) (See [Nginx Compatibility](#nginx-compatibility)) + +Build the source with this module: + +```bash + + wget 'http://nginx.org/download/nginx-1.11.2.tar.gz' + tar -xzvf nginx-1.11.2.tar.gz + cd nginx-1.11.2/ + + # tell nginx's build system where to find LuaJIT 2.0: + export LUAJIT_LIB=/path/to/luajit/lib + export LUAJIT_INC=/path/to/luajit/include/luajit-2.0 + + # tell nginx's build system where to find LuaJIT 2.1: + export LUAJIT_LIB=/path/to/luajit/lib + export LUAJIT_INC=/path/to/luajit/include/luajit-2.1 + + # or tell where to find Lua if using Lua instead: + #export LUA_LIB=/path/to/lua/lib + #export LUA_INC=/path/to/lua/include + + # Here we assume Nginx is to be installed under /opt/nginx/. + ./configure --prefix=/opt/nginx \ + --with-ld-opt="-Wl,-rpath,/path/to/luajit-or-lua/lib" \ + --add-module=/path/to/ngx_devel_kit \ + --add-module=/path/to/lua-nginx-module + + # Note that you may also want to add `./configure` options which are used in your + # current nginx build. + # You can get usually those options using command nginx -V + + # you can change the parallism number 2 below to fit the number of spare CPU cores in your + # machine. + make -j2 + make install +``` + +[Back to TOC](#table-of-contents) + +Building as a dynamic module +---------------------------- + +Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the `--add-dynamic-module=PATH` option instead of `--add-module=PATH` on the +`./configure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load_module](http://nginx.org/en/docs/ngx_core_module.html#load_module) +directive, for example, + +```nginx + + load_module /path/to/modules/ndk_http_module.so; # assuming NDK is built as a dynamic module too + load_module /path/to/modules/ngx_http_lua_module.so; +``` + +[Back to TOC](#table-of-contents) + +C Macro Configurations +---------------------- + +While building this module either via OpenResty or with the NGINX core, you can define the following C macros via the C compiler options: + +* `NGX_LUA_USE_ASSERT` + When defined, will enable assertions in the ngx_lua C code base. Recommended for debugging or testing builds. It can introduce some (small) runtime overhead when enabled. This macro was first introduced in the `v0.9.10` release. +* `NGX_LUA_ABORT_AT_PANIC` + When the Lua/LuaJIT VM panics, ngx_lua will instruct the current nginx worker process to quit gracefully by default. By specifying this C macro, ngx_lua will abort the current nginx worker process (which usually result in a core dump file) immediately. This option is useful for debugging VM panics. This option was first introduced in the `v0.9.8` release. +* `NGX_LUA_NO_FFI_API` + Excludes pure C API functions for FFI-based Lua API for NGINX (as required by [lua-resty-core](https://github.com/openresty/lua-resty-core#readme), for example). Enabling this macro can make the resulting binary code size smaller. + +To enable one or more of these macros, just pass extra C compiler options to the `./configure` script of either NGINX or OpenResty. For instance, + + + ./configure --with-cc-opt="-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC" + + +[Back to TOC](#table-of-contents) + +Installation on Ubuntu 11.10 +---------------------------- + +Note that it is recommended to use LuaJIT 2.0 or LuaJIT 2.1 instead of the standard Lua 5.1 interpreter wherever possible. + +If the standard Lua 5.1 interpreter is required however, run the following command to install it from the Ubuntu repository: + +```bash + + apt-get install -y lua5.1 liblua5.1-0 liblua5.1-0-dev +``` + +Everything should be installed correctly, except for one small tweak. + +Library name `liblua.so` has been changed in liblua5.1 package, it only comes with `liblua5.1.so`, which needs to be symlinked to `/usr/lib` so it could be found during the configuration process. + +```bash + + ln -s /usr/lib/x86_64-linux-gnu/liblua5.1.so /usr/lib/liblua.so +``` + +[Back to TOC](#table-of-contents) + +Community +========= + +[Back to TOC](#table-of-contents) + +English Mailing List +-------------------- + +The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers. + +[Back to TOC](#table-of-contents) + +Chinese Mailing List +-------------------- + +The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers. + +[Back to TOC](#table-of-contents) + +Code Repository +=============== + +The code repository of this project is hosted on github at [openresty/lua-nginx-module](https://github.com/openresty/lua-nginx-module). + +[Back to TOC](#table-of-contents) + +Bugs and Patches +================ + +Please submit bug reports, wishlists, or patches by + +1. creating a ticket on the [GitHub Issue Tracker](https://github.com/openresty/lua-nginx-module/issues), +1. or posting to the [OpenResty community](#community). + +[Back to TOC](#table-of-contents) + +Lua/LuaJIT bytecode support +=========================== + +As from the `v0.5.0rc32` release, all `*_by_lua_file` configure directives (such as [content_by_lua_file](#content_by_lua_file)) support loading Lua 5.1 and LuaJIT 2.0/2.1 raw bytecode files directly. + +Please note that the bytecode format used by LuaJIT 2.0/2.1 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0/2.1 with ngx_lua, LuaJIT compatible bytecode files must be generated as shown: + +```bash + + /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.ljbc +``` + +The `-bg` option can be used to include debug information in the LuaJIT bytecode file: + +```bash + + /path/to/luajit/bin/luajit -bg /path/to/input_file.lua /path/to/output_file.ljbc +``` + +Please refer to the official LuaJIT documentation on the `-b` option for more details: + + + +Also, the bytecode files generated by LuaJIT 2.1 is *not* compatible with LuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added in ngx_lua v0.9.3. + +Similarly, if using the standard Lua 5.1 interpreter with ngx_lua, Lua compatible bytecode files must be generated using the `luac` commandline utility as shown: + +```bash + + luac -o /path/to/output_file.luac /path/to/input_file.lua +``` + +Unlike as with LuaJIT, debug information is included in standard Lua 5.1 bytecode files by default. This can be striped out by specifying the `-s` option as shown: + +```bash + + luac -s -o /path/to/output_file.luac /path/to/input_file.lua +``` + +Attempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked to LuaJIT 2.0/2.1 or vice versa, will result in an error message, such as that below, being logged into the Nginx `error.log` file: + + + [error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac + + +Loading bytecode files via the Lua primitives like `require` and `dofile` should always work as expected. + +[Back to TOC](#table-of-contents) + +System Environment Variable Support +=================================== + +If you want to access the system environment variable, say, `foo`, in Lua via the standard Lua API [os.getenv](http://www.lua.org/manual/5.1/manual.html#pdf-os.getenv), then you should also list this environment variable name in your `nginx.conf` file via the [env directive](http://nginx.org/en/docs/ngx_core_module.html#env). For example, + +```nginx + + env foo; +``` + +[Back to TOC](#table-of-contents) + +HTTP 1.0 support +================ + +The HTTP 1.0 protocol does not support chunked output and requires an explicit `Content-Length` header when the response body is not empty in order to support the HTTP 1.0 keep-alive. +So when a HTTP 1.0 request is made and the [lua_http10_buffering](#lua_http10_buffering) directive is turned `on`, ngx_lua will buffer the +output of [ngx.say](#ngxsay) and [ngx.print](#ngxprint) calls and also postpone sending response headers until all the response body output is received. +At that time ngx_lua can calculate the total length of the body and construct a proper `Content-Length` header to return to the HTTP 1.0 client. +If the `Content-Length` response header is set in the running Lua code, however, this buffering will be disabled even if the [lua_http10_buffering](#lua_http10_buffering) directive is turned `on`. + +For large streaming output responses, it is important to disable the [lua_http10_buffering](#lua_http10_buffering) directive to minimise memory usage. + +Note that common HTTP benchmark tools such as `ab` and `http_load` issue HTTP 1.0 requests by default. +To force `curl` to send HTTP 1.0 requests, use the `-0` option. + +[Back to TOC](#table-of-contents) + +Statically Linking Pure Lua Modules +=================================== + +When LuaJIT 2.x is used, it is possible to statically link the bytecode of pure Lua modules into the Nginx executable. + +Basically you use the `luajit` executable to compile `.lua` Lua module files to `.o` object files containing the exported bytecode data, and then link the `.o` files directly in your Nginx build. + +Below is a trivial example to demonstrate this. Consider that we have the following `.lua` file named `foo.lua`: + +```lua + + -- foo.lua + local _M = {} + + function _M.go() + print("Hello from foo") + end + + return _M +``` + +And then we compile this `.lua` file to `foo.o` file: + + /path/to/luajit/bin/luajit -bg foo.lua foo.o + +What matters here is the name of the `.lua` file, which determines how you use this module later on the Lua land. The file name `foo.o` does not matter at all except the `.o` file extension (which tells `luajit` what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the `-b` option above instead of `-bg`. + +Then when building Nginx or OpenResty, pass the `--with-ld-opt="foo.o"` option to the `./configure` script: + +```bash + + ./configure --with-ld-opt="/path/to/foo.o" ... +``` + +Finally, you can just do the following in any Lua code run by ngx_lua: + +```lua + + local foo = require "foo" + foo.go() +``` + +And this piece of code no longer depends on the external `foo.lua` file any more because it has already been compiled into the `nginx` executable. + +If you want to use dot in the Lua module name when calling `require`, as in + +```lua + + local foo = require "resty.foo" +``` + +then you need to rename the `foo.lua` file to `resty_foo.lua` before compiling it down to a `.o` file with the `luajit` command-line utility. + +It is important to use exactly the same version of LuaJIT when compiling `.lua` files to `.o` files as building nginx + ngx_lua. This is because the LuaJIT bytecode format may be incompatible between different LuaJIT versions. When the bytecode format is incompatible, you will see a Lua runtime error saying that the Lua module is not found. + +When you have multiple `.lua` files to compile and link, then just specify their `.o` files at the same time in the value of the `--with-ld-opt` option. For instance, + +```bash + + ./configure --with-ld-opt="/path/to/foo.o /path/to/bar.o" ... +``` + +If you have just too many `.o` files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your `.o` files, as in + +```bash + + ar rcus libmyluafiles.a *.o +``` + +then you can link the `myluafiles` archive as a whole to your nginx executable: + +```bash + + ./configure \ + --with-ld-opt="-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive" +``` + +where `/path/to/lib` is the path of the directory containing the `libmyluafiles.a` file. It should be noted that the linker option `--whole-archive` is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable. + +[Back to TOC](#table-of-contents) + +Data Sharing within an Nginx Worker +=================================== + +To globally share data among all the requests handled by the same nginx worker process, encapsulate the shared data into a Lua module, use the Lua `require` builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design. + +Here is a complete small example: + +```lua + + -- mydata.lua + local _M = {} + + local data = { + dog = 3, + cat = 4, + pig = 5, + } + + function _M.get_age(name) + return data[name] + end + + return _M +``` + +and then accessing it from `nginx.conf`: + +```nginx + + location /lua { + content_by_lua_block { + local mydata = require "mydata" + ngx.say(mydata.get_age("dog")) + } + } +``` + +The `mydata` module in this example will only be loaded and run on the first request to the location `/lua`, +and all subsequent requests to the same nginx worker process will use the reloaded instance of the +module as well as the same copy of the data in it, until a `HUP` signal is sent to the Nginx master process to force a reload. +This data sharing technique is essential for high performance Lua applications based on this module. + +Note that this data sharing is on a *per-worker* basis and not on a *per-server* basis. That is, when there are multiple nginx worker processes under an Nginx master, data sharing cannot cross the process boundary between these workers. + +It is usually recommended to share read-only data this way. You can also share changeable data among all the concurrent requests of each nginx worker process as +long as there is *no* nonblocking I/O operations (including [ngx.sleep](#ngxsleep)) +in the middle of your calculations. As long as you do not give the +control back to the nginx event loop and ngx_lua's light thread +scheduler (even implicitly), there can never be any race conditions in +between. For this reason, always be very careful when you want to share changeable data on the +worker level. Buggy optimizations can easily lead to hard-to-debug +race conditions under load. + +If server-wide data sharing is required, then use one or more of the following approaches: + +1. Use the [ngx.shared.DICT](#ngxshareddict) API provided by this module. +1. Use only a single nginx worker and a single server (this is however not recommended when there is a multi core CPU or multiple CPUs in a single machine). +1. Use data storage mechanisms such as `memcached`, `redis`, `MySQL` or `PostgreSQL`. [The OpenResty bundle](http://openresty.org) associated with this module comes with a set of companion Nginx modules and Lua libraries that provide interfaces with these data storage mechanisms. + +[Back to TOC](#table-of-contents) + +Known Issues +============ + +[Back to TOC](#table-of-contents) + +TCP socket connect operation issues +----------------------------------- +The [tcpsock:connect](#tcpsockconnect) method may indicate `success` despite connection failures such as with `Connection Refused` errors. + +However, later attempts to manipulate the cosocket object will fail and return the actual error status message generated by the failed connect operation. + +This issue is due to limitations in the Nginx event model and only appears to affect Mac OS X. + +[Back to TOC](#table-of-contents) + +Lua Coroutine Yielding/Resuming +------------------------------- +* Because Lua's `dofile` and `require` builtins are currently implemented as C functions in both Lua 5.1 and LuaJIT 2.0/2.1, if the Lua file being loaded by `dofile` or `require` invokes [ngx.location.capture*](#ngxlocationcapture), [ngx.exec](#ngxexec), [ngx.exit](#ngxexit), or other API functions requiring yielding in the *top-level* scope of the Lua file, then the Lua error "attempt to yield across C-call boundary" will be raised. To avoid this, put these calls requiring yielding into your own Lua functions in the Lua file instead of the top-level scope of the file. +* As the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture_multi](#ngxlocationcapture_multi), [ngx.redirect](#ngxredirect), [ngx.exec](#ngxexec), and [ngx.exit](#ngxexit) cannot be used within the context of a Lua [pcall()](http://www.lua.org/manual/5.1/manual.html#pdf-pcall) or [xpcall()](http://www.lua.org/manual/5.1/manual.html#pdf-xpcall) or even the first line of the `for ... in ...` statement when the standard Lua 5.1 interpreter is used and the `attempt to yield across metamethod/C-call boundary` error will be produced. Please use LuaJIT 2.x, which supports a fully resumable VM, to avoid this. + +[Back to TOC](#table-of-contents) + +Lua Variable Scope +------------------ +Care must be taken when importing modules and this form should be used: + +```lua + + local xxx = require('xxx') +``` + +instead of the old deprecated form: + +```lua + + require('xxx') +``` + +Here is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the `require()` built-in in the `package.loaded` table for later reference, and the `module()` builtin used by some Lua modules has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler, and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the `nil` value. + +The use of Lua global variables is a generally inadvisable in the ngx_lua context as: + +1. the misuse of Lua globals has detrimental side effects on concurrent requests when such variables should instead be local in scope, +1. Lua global variables require Lua table look-ups in the global environment which is computationally expensive, and +1. some Lua global variable references may include typing errors which make such difficult to debug. + +It is therefore *highly* recommended to always declare such within an appropriate local scope instead. + +```lua + + -- Avoid + foo = 123 + -- Recommended + local foo = 123 + + -- Avoid + function foo() return 123 end + -- Recommended + local function foo() return 123 end +``` + + +To find all instances of Lua global variables in your Lua code, run the [lua-releng tool](https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng) across all `.lua` source files: + + $ lua-releng + Checking use of Lua global variables in file lib/foo/bar.lua ... + 1 [1489] SETGLOBAL 7 -1 ; contains + 55 [1506] GETGLOBAL 7 -3 ; setvar + 3 [1545] GETGLOBAL 3 -4 ; varexpand + +The output says that the line 1489 of file `lib/foo/bar.lua` writes to a global variable named `contains`, the line 1506 reads from the global variable `setvar`, and line 1545 reads the global `varexpand`. + +This tool will guarantee that local variables in the Lua module functions are all declared with the `local` keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker) for the reasons behind this. + +[Back to TOC](#table-of-contents) + +Locations Configured by Subrequest Directives of Other Modules +-------------------------------------------------------------- +The [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) directives cannot capture locations that include the [add_before_body](http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_before_body), [add_after_body](http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_after_body), [auth_request](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request), [echo_location](http://github.com/openresty/echo-nginx-module#echo_location), [echo_location_async](http://github.com/openresty/echo-nginx-module#echo_location_async), [echo_subrequest](http://github.com/openresty/echo-nginx-module#echo_subrequest), or [echo_subrequest_async](http://github.com/openresty/echo-nginx-module#echo_subrequest_async) directives. + +```nginx + + location /foo { + content_by_lua_block { + res = ngx.location.capture("/bar") + } + } + location /bar { + echo_location /blah; + } + location /blah { + echo "Success!"; + } +``` + +```nginx + + $ curl -i http://example.com/foo +``` + +will not work as expected. + +[Back to TOC](#table-of-contents) + +Cosockets Not Available Everywhere +---------------------------------- + +Due to internal limitations in the nginx core, the cosocket API is disabled in the following contexts: [set_by_lua*](#set_by_lua), [log_by_lua*](#log_by_lua), [header_filter_by_lua*](#header_filter_by_lua), and [body_filter_by_lua](#body_filter_by_lua). + +The cosockets are currently also disabled in the [init_by_lua*](#init_by_lua) and [init_worker_by_lua*](#init_worker_by_lua) directive contexts but we may add support for these contexts in the future because there is no limitation in the nginx core (or the limitation might be worked around). + +There exists a work-around, however, when the original context does *not* need to wait for the cosocket results. That is, creating a zero-delay timer via the [ngx.timer.at](#ngxtimerat) API and do the cosocket results in the timer handler, which runs asynchronously as to the original context creating the timer. + +[Back to TOC](#table-of-contents) + +Special Escaping Sequences +-------------------------- + +**NOTE** Following the `v0.9.17` release, this pitfall can be avoided by using the `*_by_lua_block {}` configuration directives. + +PCRE sequences such as `\d`, `\s`, or `\w`, require special attention because in string literals, the backslash character, `\`, is stripped out by both the Lua language parser and by the nginx config file parser before processing if not within a `*_by_lua_block {}` directive. So the following snippet will not work as expected: + +```nginx + + # nginx.conf + ? location /test { + ? content_by_lua ' + ? local regex = "\d+" -- THIS IS WRONG OUTSIDE OF A *_by_lua_block DIRECTIVE + ? local m = ngx.re.match("hello, 1234", regex) + ? if m then ngx.say(m[0]) else ngx.say("not matched!") end + ? '; + ? } + # evaluates to "not matched!" +``` + +To avoid this, *double* escape the backslash: + +```nginx + + # nginx.conf + location /test { + content_by_lua ' + local regex = "\\\\d+" + local m = ngx.re.match("hello, 1234", regex) + if m then ngx.say(m[0]) else ngx.say("not matched!") end + '; + } + # evaluates to "1234" +``` + +Here, `\\\\d+` is stripped down to `\\d+` by the Nginx config file parser and this is further stripped down to `\d+` by the Lua language parser before running. + +Alternatively, the regex pattern can be presented as a long-bracketed Lua string literal by encasing it in "long brackets", `[[...]]`, in which case backslashes have to only be escaped once for the Nginx config file parser. + +```nginx + + # nginx.conf + location /test { + content_by_lua ' + local regex = [[\\d+]] + local m = ngx.re.match("hello, 1234", regex) + if m then ngx.say(m[0]) else ngx.say("not matched!") end + '; + } + # evaluates to "1234" +``` + +Here, `[[\\d+]]` is stripped down to `[[\d+]]` by the Nginx config file parser and this is processed correctly. + +Note that a longer from of the long bracket, `[=[...]=]`, may be required if the regex pattern contains `[...]` sequences. +The `[=[...]=]` form may be used as the default form if desired. + +```nginx + + # nginx.conf + location /test { + content_by_lua ' + local regex = [=[[0-9]+]=] + local m = ngx.re.match("hello, 1234", regex) + if m then ngx.say(m[0]) else ngx.say("not matched!") end + '; + } + # evaluates to "1234" +``` + +An alternative approach to escaping PCRE sequences is to ensure that Lua code is placed in external script files and executed using the various `*_by_lua_file` directives. +With this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each. + +```lua + + -- test.lua + local regex = "\\d+" + local m = ngx.re.match("hello, 1234", regex) + if m then ngx.say(m[0]) else ngx.say("not matched!") end + -- evaluates to "1234" +``` + +Within external script files, PCRE sequences presented as long-bracketed Lua string literals do not require modification. + +```lua + + -- test.lua + local regex = [[\d+]] + local m = ngx.re.match("hello, 1234", regex) + if m then ngx.say(m[0]) else ngx.say("not matched!") end + -- evaluates to "1234" +``` + +As noted earlier, PCRE sequences presented within `*_by_lua_block {}` directives (available following the `v0.9.17` release) do not require modification. + +```nginx + + # nginx.conf + location /test { + content_by_lua_block { + local regex = "\d+" + local m = ngx.re.match("hello, 1234", regex) + if m then ngx.say(m[0]) else ngx.say("not matched!") end + } + } + # evaluates to "1234" +``` + + +[Back to TOC](#table-of-contents) + +Mixing with SSI Not Supported +----------------------------- + +Mixing SSI with ngx_lua in the same Nginx request is not supported at all. Just use ngx_lua exclusively. Everything you can do with SSI can be done atop ngx_lua anyway and it can be more efficient when using ngx_lua. + +[Back to TOC](#table-of-contents) + +SPDY Mode Not Fully Supported +----------------------------- + +Certain Lua APIs provided by ngx_lua do not work in Nginx's SPDY mode yet: [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture_multi](#ngxlocationcapture_multi), and [ngx.req.socket](#ngxreqsocket). + +[Back to TOC](#table-of-contents) + +Missing data on short circuited requests +---------------------------------------- + +Nginx may terminate a request early with (at least): + +* 400 (Bad Request) +* 405 (Not Allowed) +* 408 (Request Timeout) +* 414 (Request URI Too Large) +* 494 (Request Headers Too Large) +* 499 (Client Closed Request) +* 500 (Internal Server Error) +* 501 (Not Implemented) + +This means that phases that normally run are skipped, such as the rewrite or +access phase. This also means that later phases that are run regardless, e.g. +[log_by_lua](#log_by_lua), will not have access to information that is normally set in those +phases. + +[Back to TOC](#table-of-contents) + +TODO +==== + +* cosocket: implement LuaSocket's unconnected UDP API. +* port this module to the "datagram" subsystem of NGINX for implementing general UDP servers instead of HTTP +servers in Lua. For example, +```lua + + datagram { + server { + listen 1953; + handler_by_lua_block { + -- custom Lua code implementing the special UDP server... + } + } + } +``` +* shm: implement a "shared queue API" to complement the existing [shared dict](#lua_shared_dict) API. +* cosocket: add support in the context of [init_by_lua*](#init_by_lua). +* cosocket: implement the `bind()` method for stream-typed cosockets. +* cosocket: pool-based backend concurrency level control: implement automatic `connect` queueing when the backend concurrency exceeds its connection pool limit. +* cosocket: review and merge aviramc's [patch](https://github.com/openresty/lua-nginx-module/pull/290) for adding the `bsdrecv` method. +* add new API function `ngx.resp.add_header` to emulate the standard `add_header` config directive. +* review and apply vadim-pavlov's patch for [ngx.location.capture](#ngxlocationcapture)'s `extra_headers` option +* use `ngx_hash_t` to optimize the built-in header look-up process for [ngx.req.set_header](#ngxreqset_header), [ngx.header.HEADER](#ngxheaderheader), and etc. +* add configure options for different strategies of handling the cosocket connection exceeding in the pools. +* add directives to run Lua codes when nginx stops. +* add `ignore_resp_headers`, `ignore_resp_body`, and `ignore_resp` options to [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) methods, to allow micro performance tuning on the user side. +* add automatic Lua code time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks. +* add `stat` mode similar to [mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html). +* cosocket: add client SSL certificate support. + +[Back to TOC](#table-of-contents) + +Changes +======= + +The changes made in every release of this module are listed in the change logs of the OpenResty bundle: + + + +[Back to TOC](#table-of-contents) + +Test Suite +========== + +The following dependencies are required to run the test suite: + +* Nginx version >= 1.4.2 + +* Perl modules: + * Test::Nginx: + +* Nginx modules: + * [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) + * [ngx_set_misc](https://github.com/openresty/set-misc-nginx-module) + * [ngx_auth_request](http://mdounin.ru/files/ngx_http_auth_request_module-0.2.tar.gz) (this is not needed if you're using Nginx 1.5.4+. + * [ngx_echo](https://github.com/openresty/echo-nginx-module) + * [ngx_memc](https://github.com/openresty/memc-nginx-module) + * [ngx_srcache](https://github.com/openresty/srcache-nginx-module) + * ngx_lua (i.e., this module) + * [ngx_lua_upstream](https://github.com/openresty/lua-upstream-nginx-module) + * [ngx_headers_more](https://github.com/openresty/headers-more-nginx-module) + * [ngx_drizzle](https://github.com/openresty/drizzle-nginx-module) + * [ngx_rds_json](https://github.com/openresty/rds-json-nginx-module) + * [ngx_coolkit](https://github.com/FRiCKLE/ngx_coolkit) + * [ngx_redis2](https://github.com/openresty/redis2-nginx-module) + +The order in which these modules are added during configuration is important because the position of any filter module in the +filtering chain determines the final output, for example. The correct adding order is shown above. + +* 3rd-party Lua libraries: + * [lua-cjson](http://www.kyne.com.au/~mark/software/lua-cjson.php) + +* Applications: + * mysql: create database 'ngx_test', grant all privileges to user 'ngx_test', password is 'ngx_test' + * memcached: listening on the default port, 11211. + * redis: listening on the default port, 6379. + +See also the [developer build script](https://github.com/openresty/lua-nginx-module/blob/master/util/build.sh) for more details on setting up the testing environment. + +To run the whole test suite in the default testing mode: + + cd /path/to/lua-nginx-module + export PATH=/path/to/your/nginx/sbin:$PATH + prove -I/path/to/test-nginx/lib -r t + + +To run specific test files: + + cd /path/to/lua-nginx-module + export PATH=/path/to/your/nginx/sbin:$PATH + prove -I/path/to/test-nginx/lib t/002-content.t t/003-errors.t + + +To run a specific test block in a particular test file, add the line `--- ONLY` to the test block you want to run, and then use the `prove` utility to run that `.t` file. + +There are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [Test::Nginx documentation](http://search.cpan.org/perldoc?Test::Nginx) for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: . + +[Back to TOC](#table-of-contents) + +Copyright and License +===================== + +This module is licensed under the BSD license. + +Copyright (C) 2009-2017, by Xiaozhe Wang (chaoslawful) . + +Copyright (C) 2009-2017, by Yichun "agentzh" Zhang (章亦春) , OpenResty Inc. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +[Back to TOC](#table-of-contents) + +See Also +======== + +* [ngx_stream_lua_module](https://github.com/openresty/stream-lua-nginx-module#readme) for an official port of this module for the NGINX "stream" subsystem (doing generic downstream TCP communications). +* [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached) library based on ngx_lua cosocket. +* [lua-resty-redis](https://github.com/openresty/lua-resty-redis) library based on ngx_lua cosocket. +* [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql) library based on ngx_lua cosocket. +* [lua-resty-upload](https://github.com/openresty/lua-resty-upload) library based on ngx_lua cosocket. +* [lua-resty-dns](https://github.com/openresty/lua-resty-dns) library based on ngx_lua cosocket. +* [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket) library for both WebSocket server and client, based on ngx_lua cosocket. +* [lua-resty-string](https://github.com/openresty/lua-resty-string) library based on [LuaJIT FFI](http://luajit.org/ext_ffi.html). +* [lua-resty-lock](https://github.com/openresty/lua-resty-lock) library for a nonblocking simple lock API. +* [lua-resty-cookie](https://github.com/cloudflare/lua-resty-cookie) library for HTTP cookie manipulation. +* [Routing requests to different MySQL queries based on URI arguments](http://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs) +* [Dynamic Routing Based on Redis and Lua](http://openresty.org/#DynamicRoutingBasedOnRedis) +* [Using LuaRocks with ngx_lua](http://openresty.org/#UsingLuaRocks) +* [Introduction to ngx_lua](https://github.com/openresty/lua-nginx-module/wiki/Introduction) +* [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) +* [echo-nginx-module](http://github.com/openresty/echo-nginx-module) +* [drizzle-nginx-module](http://github.com/openresty/drizzle-nginx-module) +* [postgres-nginx-module](https://github.com/FRiCKLE/ngx_postgres) +* [memc-nginx-module](http://github.com/openresty/memc-nginx-module) +* [The OpenResty bundle](http://openresty.org) +* [Nginx Systemtap Toolkit](https://github.com/openresty/nginx-systemtap-toolkit) + +[Back to TOC](#table-of-contents) + +Directives +========== + +* [lua_capture_error_log](#lua_capture_error_log) +* [lua_use_default_type](#lua_use_default_type) +* [lua_malloc_trim](#lua_malloc_trim) +* [lua_code_cache](#lua_code_cache) +* [lua_regex_cache_max_entries](#lua_regex_cache_max_entries) +* [lua_regex_match_limit](#lua_regex_match_limit) +* [lua_package_path](#lua_package_path) +* [lua_package_cpath](#lua_package_cpath) +* [init_by_lua](#init_by_lua) +* [init_by_lua_block](#init_by_lua_block) +* [init_by_lua_file](#init_by_lua_file) +* [init_worker_by_lua](#init_worker_by_lua) +* [init_worker_by_lua_block](#init_worker_by_lua_block) +* [init_worker_by_lua_file](#init_worker_by_lua_file) +* [set_by_lua](#set_by_lua) +* [set_by_lua_block](#set_by_lua_block) +* [set_by_lua_file](#set_by_lua_file) +* [content_by_lua](#content_by_lua) +* [content_by_lua_block](#content_by_lua_block) +* [content_by_lua_file](#content_by_lua_file) +* [rewrite_by_lua](#rewrite_by_lua) +* [rewrite_by_lua_block](#rewrite_by_lua_block) +* [rewrite_by_lua_file](#rewrite_by_lua_file) +* [access_by_lua](#access_by_lua) +* [access_by_lua_block](#access_by_lua_block) +* [access_by_lua_file](#access_by_lua_file) +* [header_filter_by_lua](#header_filter_by_lua) +* [header_filter_by_lua_block](#header_filter_by_lua_block) +* [header_filter_by_lua_file](#header_filter_by_lua_file) +* [body_filter_by_lua](#body_filter_by_lua) +* [body_filter_by_lua_block](#body_filter_by_lua_block) +* [body_filter_by_lua_file](#body_filter_by_lua_file) +* [log_by_lua](#log_by_lua) +* [log_by_lua_block](#log_by_lua_block) +* [log_by_lua_file](#log_by_lua_file) +* [balancer_by_lua_block](#balancer_by_lua_block) +* [balancer_by_lua_file](#balancer_by_lua_file) +* [lua_need_request_body](#lua_need_request_body) +* [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block) +* [ssl_certificate_by_lua_file](#ssl_certificate_by_lua_file) +* [ssl_session_fetch_by_lua_block](#ssl_session_fetch_by_lua_block) +* [ssl_session_fetch_by_lua_file](#ssl_session_fetch_by_lua_file) +* [ssl_session_store_by_lua_block](#ssl_session_store_by_lua_block) +* [ssl_session_store_by_lua_file](#ssl_session_store_by_lua_file) +* [lua_shared_dict](#lua_shared_dict) +* [lua_socket_connect_timeout](#lua_socket_connect_timeout) +* [lua_socket_send_timeout](#lua_socket_send_timeout) +* [lua_socket_send_lowat](#lua_socket_send_lowat) +* [lua_socket_read_timeout](#lua_socket_read_timeout) +* [lua_socket_buffer_size](#lua_socket_buffer_size) +* [lua_socket_pool_size](#lua_socket_pool_size) +* [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout) +* [lua_socket_log_errors](#lua_socket_log_errors) +* [lua_ssl_ciphers](#lua_ssl_ciphers) +* [lua_ssl_crl](#lua_ssl_crl) +* [lua_ssl_protocols](#lua_ssl_protocols) +* [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate) +* [lua_ssl_verify_depth](#lua_ssl_verify_depth) +* [lua_http10_buffering](#lua_http10_buffering) +* [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone) +* [access_by_lua_no_postpone](#access_by_lua_no_postpone) +* [lua_transform_underscores_in_response_headers](#lua_transform_underscores_in_response_headers) +* [lua_check_client_abort](#lua_check_client_abort) +* [lua_max_pending_timers](#lua_max_pending_timers) +* [lua_max_running_timers](#lua_max_running_timers) + + +The basic building blocks of scripting Nginx with Lua are directives. Directives are used to specify when the user Lua code is run and +how the result will be used. Below is a diagram showing the order in which directives are executed. + +![Lua Nginx Modules Directives](https://cloud.githubusercontent.com/assets/2137369/15272097/77d1c09e-1a37-11e6-97ef-d9767035fc3e.png) + +[Back to TOC](#table-of-contents) + +lua_capture_error_log +--------------------- +**syntax:** *lua_capture_error_log size* + +**default:** *none* + +**context:** *http* + +Enables a buffer of the specified `size` for capturing all the nginx error log message data (not just those produced +by this module or the nginx http subsystem, but everything) without touching files or disks. + +You can use units like `k` and `m` in the `size` value, as in + +```nginx + + lua_capture_error_log 100k; +``` + +As a rule of thumb, a 4KB buffer can usually hold about 20 typical error log messages. So do the maths! + +This buffer never grows. If it is full, new error log messages will replace the oldest ones in the buffer. + +The size of the buffer must be bigger than the maximum length of a single error log message (which is 4K in OpenResty and 2K in stock NGINX). + +You can read the messages in the buffer on the Lua land via the +[get_logs()](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#get_logs) +function of the +[ngx.errlog](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#readme) +module of the [lua-resty-core](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#readme) +library. This Lua API function will return the captured error log messages and +also remove these already read from the global capturing buffer, making room +for any new error log data. For this reason, the user should not configure this +buffer to be too big if the user read the buffered error log data fast enough. + +Note that the log level specified in the standard [error_log](http://nginx.org/r/error_log) directive +*does* have effect on this capturing facility. It only captures log +messages of a level no lower than the specified log level in the [error_log](http://nginx.org/r/error_log) directive. +The user can still choose to set an even higher filtering log level on the fly via the Lua API function +[errlog.set_filter_level](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#set_filter_level). +So it is more flexible than the static [error_log](http://nginx.org/r/error_log) directive. + +It is worth noting that there is no way to capture the debugging logs +without building OpenResty or NGINX with the `./configure` +option `--with-debug`. And enabling debugging logs is +strongly discouraged in production builds due to high overhead. + +This directive was first introduced in the `v0.10.9` release. + +[Back to TOC](#directives) + +lua_use_default_type +-------------------- +**syntax:** *lua_use_default_type on | off* + +**default:** *lua_use_default_type on* + +**context:** *http, server, location, location if* + +Specifies whether to use the MIME type specified by the [default_type](http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type) directive for the default value of the `Content-Type` response header. Deactivate this directive if a default `Content-Type` response header for Lua request handlers is not desired. + +This directive is turned on by default. + +This directive was first introduced in the `v0.9.1` release. + +[Back to TOC](#directives) + +lua_malloc_trim +--------------- +**syntax:** *lua_malloc_trim <request-count>* + +**default:** *lua_malloc_trim 1000* + +**context:** *http* + +Asks the underlying `libc` runtime library to release its cached free memory back to the operating system every +`N` requests processed by the NGINX core. By default, `N` is 1000. You can configure the request count +by using your own numbers. Smaller numbers mean more frequent releases, which may introduce higher CPU time consumption and +smaller memory footprint while larger numbers usually lead to less CPU time overhead and relatively larger memory footprint. +Just tune the number for your own use cases. + +Configuring the argument to `0` essentially turns off the periodical memory trimming altogether. + +```nginx + + lua_malloc_trim 0; # turn off trimming completely +``` + +The current implementation uses an NGINX log phase handler to do the request counting. So the appearance of the +[log_subrequest on](http://nginx.org/en/docs/http/ngx_http_core_module.html#log_subrequest) directives in `nginx.conf` +may make the counting faster when subrequests are involved. By default, only "main requests" count. + +Note that this directive does *not* affect the memory allocated by LuaJIT's own allocator based on the `mmap` +system call. + +This directive was first introduced in the `v0.10.7` release. + +[Back to TOC](#directives) + +lua_code_cache +-------------- +**syntax:** *lua_code_cache on | off* + +**default:** *lua_code_cache on* + +**context:** *http, server, location, location if* + +Enables or disables the Lua code cache for Lua code in `*_by_lua_file` directives (like [set_by_lua_file](#set_by_lua_file) and +[content_by_lua_file](#content_by_lua_file)) and Lua modules. + +When turning off, every request served by ngx_lua will run in a separate Lua VM instance, starting from the `0.9.3` release. So the Lua files referenced in [set_by_lua_file](#set_by_lua_file), +[content_by_lua_file](#content_by_lua_file), [access_by_lua_file](#access_by_lua_file), +and etc will not be cached +and all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach. + +Please note however, that Lua code written inlined within nginx.conf +such as those specified by [set_by_lua](#set_by_lua), [content_by_lua](#content_by_lua), +[access_by_lua](#access_by_lua), and [rewrite_by_lua](#rewrite_by_lua) will not be updated when you edit the inlined Lua code in your `nginx.conf` file because only the Nginx config file parser can correctly parse the `nginx.conf` +file and the only way is to reload the config file +by sending a `HUP` signal or just to restart Nginx. + +Even when the code cache is enabled, Lua files which are loaded by `dofile` or `loadfile` +in *_by_lua_file cannot be cached (unless you cache the results yourself). Usually you can either use the [init_by_lua](#init_by_lua) +or [init_by_lua_file](#init-by_lua_file) directives to load all such files or just make these Lua files true Lua modules +and load them via `require`. + +The ngx_lua module does not support the `stat` mode available with the +Apache `mod_lua` module (yet). + +Disabling the Lua code cache is strongly +discouraged for production use and should only be used during +development as it has a significant negative impact on overall performance. For example, the performance of a "hello world" Lua example can drop by an order of magnitude after disabling the Lua code cache. + +[Back to TOC](#directives) + +lua_regex_cache_max_entries +--------------------------- +**syntax:** *lua_regex_cache_max_entries <num>* + +**default:** *lua_regex_cache_max_entries 1024* + +**context:** *http* + +Specifies the maximum number of entries allowed in the worker process level compiled regex cache. + +The regular expressions used in [ngx.re.match](#ngxrematch), [ngx.re.gmatch](#ngxregmatch), [ngx.re.sub](#ngxresub), and [ngx.re.gsub](#ngxregsub) will be cached within this cache if the regex option `o` (i.e., compile-once flag) is specified. + +The default number of entries allowed is 1024 and when this limit is reached, new regular expressions will not be cached (as if the `o` option was not specified) and there will be one, and only one, warning in the `error.log` file: + + + 2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ... + + +If you are using the `ngx.re.*` implementation of [lua-resty-core](https://github.com/openresty/lua-resty-core) by loading the `resty.core.regex` module (or just the `resty.core` module), then an LRU cache is used for the regex cache being used here. + +Do not activate the `o` option for regular expressions (and/or `replace` string arguments for [ngx.re.sub](#ngxresub) and [ngx.re.gsub](#ngxregsub)) that are generated *on the fly* and give rise to infinite variations to avoid hitting the specified limit. + +[Back to TOC](#directives) + +lua_regex_match_limit +--------------------- +**syntax:** *lua_regex_match_limit <num>* + +**default:** *lua_regex_match_limit 0* + +**context:** *http* + +Specifies the "match limit" used by the PCRE library when executing the [ngx.re API](#ngxrematch). To quote the PCRE manpage, "the limit ... has the effect of limiting the amount of backtracking that can take place." + +When the limit is hit, the error string "pcre_exec() failed: -8" will be returned by the [ngx.re API](#ngxrematch) functions on the Lua land. + +When setting the limit to 0, the default "match limit" when compiling the PCRE library is used. And this is the default value of this directive. + +This directive was first introduced in the `v0.8.5` release. + +[Back to TOC](#directives) + +lua_package_path +---------------- + +**syntax:** *lua_package_path <lua-style-path-str>* + +**default:** *The content of LUA_PATH environment variable or Lua's compiled-in defaults.* + +**context:** *http* + +Sets the Lua module search path used by scripts specified by [set_by_lua](#set_by_lua), +[content_by_lua](#content_by_lua) and others. The path string is in standard Lua path form, and `;;` +can be used to stand for the original search paths. + +As from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server. + +[Back to TOC](#directives) + +lua_package_cpath +----------------- + +**syntax:** *lua_package_cpath <lua-style-cpath-str>* + +**default:** *The content of LUA_CPATH environment variable or Lua's compiled-in defaults.* + +**context:** *http* + +Sets the Lua C-module search path used by scripts specified by [set_by_lua](#set_by_lua), +[content_by_lua](#content_by_lua) and others. The cpath string is in standard Lua cpath form, and `;;` +can be used to stand for the original cpath. + +As from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server. + +[Back to TOC](#directives) + +init_by_lua +----------- + +**syntax:** *init_by_lua <lua-script-str>* + +**context:** *http* + +**phase:** *loading-config* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init_by_lua_block](#init_by_lua_block) directive instead. + +Runs the Lua code specified by the argument `` on the global Lua VM level when the Nginx master process (if any) is loading the Nginx config file. + +When Nginx receives the `HUP` signal and starts reloading the config file, the Lua VM will also be re-created and `init_by_lua` will run again on the new Lua VM. In case that the [lua_code_cache](#lua_code_cache) directive is turned off (default on), the `init_by_lua` handler will run upon every request because in this special mode a standalone Lua VM is always created for each request. + +Usually you can pre-load Lua modules at server start-up by means of this hook and take advantage of modern operating systems' copy-on-write (COW) optimization. Here is an example for pre-loading Lua modules: + +```nginx + + # this runs before forking out nginx worker processes: + init_by_lua_block { require "cjson" } + + server { + location = /api { + content_by_lua_block { + -- the following require() will just return + -- the alrady loaded module from package.loaded: + ngx.say(require "cjson".encode{dog = 5, cat = 6}) + } + } + } +``` + +You can also initialize the [lua_shared_dict](#lua_shared_dict) shm storage at this phase. Here is an example for this: + +```nginx + + lua_shared_dict dogs 1m; + + init_by_lua_block { + local dogs = ngx.shared.dogs; + dogs:set("Tom", 56) + } + + server { + location = /api { + content_by_lua_block { + local dogs = ngx.shared.dogs; + ngx.say(dogs:get("Tom")) + } + } + } +``` + +But note that, the [lua_shared_dict](#lua_shared_dict)'s shm storage will not be cleared through a config reload (via the `HUP` signal, for example). So if you do *not* want to re-initialize the shm storage in your `init_by_lua` code in this case, then you just need to set a custom flag in the shm storage and always check the flag in your `init_by_lua` code. + +Because the Lua code in this context runs before Nginx forks its worker processes (if any), data or code loaded here will enjoy the [Copy-on-write (COW)](http://en.wikipedia.org/wiki/Copy-on-write) feature provided by many operating systems among all the worker processes, thus saving a lot of memory. + +Do *not* initialize your own Lua global variables in this context because use of Lua global variables have performance penalties and can lead to global namespace pollution (see the [Lua Variable Scope](#lua-variable-scope) section for more details). The recommended way is to use proper [Lua module](http://www.lua.org/manual/5.1/manual.html#5.3) files (but do not use the standard Lua function [module()](http://www.lua.org/manual/5.1/manual.html#pdf-module) to define Lua modules because it pollutes the global namespace as well) and call [require()](http://www.lua.org/manual/5.1/manual.html#pdf-require) to load your own module files in `init_by_lua` or other contexts ([require()](http://www.lua.org/manual/5.1/manual.html#pdf-require) does cache the loaded Lua modules in the global `package.loaded` table in the Lua registry so your modules will only loaded once for the whole Lua VM instance). + +Only a small set of the [Nginx API for Lua](#nginx-api-for-lua) is supported in this context: + +* Logging APIs: [ngx.log](#ngxlog) and [print](#print), +* Shared Dictionary API: [ngx.shared.DICT](#ngxshareddict). + +More Nginx APIs for Lua may be supported in this context upon future user requests. + +Basically you can safely use Lua libraries that do blocking I/O in this very context because blocking the master process during server start-up is completely okay. Even the Nginx core does blocking I/O (at least on resolving upstream's host names) at the configure-loading phase. + +You should be very careful about potential security vulnerabilities in your Lua code registered in this context because the Nginx master process is often run under the `root` account. + +This directive was first introduced in the `v0.5.5` release. + +[Back to TOC](#directives) + +init_by_lua_block +----------------- + +**syntax:** *init_by_lua_block { lua-script }* + +**context:** *http* + +**phase:** *loading-config* + +Similar to the [init_by_lua](#init_by_lua) directive except that this directive inlines +the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping). + +For instance, + +```nginx + + init_by_lua_block { + print("I need no extra escaping here, for example: \r\nblah") + } +``` + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +init_by_lua_file +---------------- + +**syntax:** *init_by_lua_file <path-to-lua-script-file>* + +**context:** *http* + +**phase:** *loading-config* + +Equivalent to [init_by_lua](#init_by_lua), except that the file specified by `` contains the Lua code or [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +This directive was first introduced in the `v0.5.5` release. + +[Back to TOC](#directives) + +init_worker_by_lua +------------------ + +**syntax:** *init_worker_by_lua <lua-script-str>* + +**context:** *http* + +**phase:** *starting-worker* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init_worker_by_lua_block](#init_worker_by_lua_block) directive instead. + +Runs the specified Lua code upon every Nginx worker process's startup when the master process is enabled. When the master process is disabled, this hook will just run after [init_by_lua*](#init_by_lua). + +This hook is often used to create per-worker reoccurring timers (via the [ngx.timer.at](#ngxtimerat) Lua API), either for backend health-check or other timed routine work. Below is an example, + +```nginx + + init_worker_by_lua ' + local delay = 3 -- in seconds + local new_timer = ngx.timer.at + local log = ngx.log + local ERR = ngx.ERR + local check + + check = function(premature) + if not premature then + -- do the health check or other routine work + local ok, err = new_timer(delay, check) + if not ok then + log(ERR, "failed to create timer: ", err) + return + end + end + end + + local hdl, err = new_timer(delay, check) + if not hdl then + log(ERR, "failed to create timer: ", err) + return + end + '; +``` + +This directive was first introduced in the `v0.9.5` release. + +[Back to TOC](#directives) + +init_worker_by_lua_block +------------------------ + +**syntax:** *init_worker_by_lua_block { lua-script }* + +**context:** *http* + +**phase:** *starting-worker* + +Similar to the [init_worker_by_lua](#init_worker_by_lua) directive except that this directive inlines +the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping). + +For instance, + +```nginx + + init_worker_by_lua_block { + print("I need no extra escaping here, for example: \r\nblah") + } +``` + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +init_worker_by_lua_file +----------------------- + +**syntax:** *init_worker_by_lua_file <lua-file-path>* + +**context:** *http* + +**phase:** *starting-worker* + +Similar to [init_worker_by_lua](#init_worker_by_lua), but accepts the file path to a Lua source file or Lua bytecode file. + +This directive was first introduced in the `v0.9.5` release. + +[Back to TOC](#directives) + +set_by_lua +---------- + +**syntax:** *set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]* + +**context:** *server, server if, location, location if* + +**phase:** *rewrite* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [set_by_lua_block](#set_by_lua_block) directive instead. + +Executes code specified in `` with optional input arguments `$arg1 $arg2 ...`, and returns string output to `$res`. +The code in `` can make [API calls](#nginx-api-for-lua) and can retrieve input arguments from the `ngx.arg` table (index starts from `1` and increases sequentially). + +This directive is designed to execute short, fast running code blocks as the Nginx event loop is blocked during code execution. Time consuming code sequences should therefore be avoided. + +This directive is implemented by injecting custom commands into the standard [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s command list. Because [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html) does not support nonblocking I/O in its commands, Lua APIs requiring yielding the current Lua "light thread" cannot work in this directive. + +At least the following API functions are currently disabled within the context of `set_by_lua`: + +* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers)) +* Control API functions (e.g., [ngx.exit](#ngxexit)) +* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi)) +* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)). +* Sleeping API function [ngx.sleep](#ngxsleep). + +In addition, note that this directive can only write out a value to a single Nginx variable at +a time. However, a workaround is possible using the [ngx.var.VARIABLE](#ngxvarvariable) interface. + +```nginx + + location /foo { + set $diff ''; # we have to predefine the $diff variable here + + set_by_lua $sum ' + local a = 32 + local b = 56 + + ngx.var.diff = a - b; -- write to $diff directly + return a + b; -- return the $sum value normally + '; + + echo "sum = $sum, diff = $diff"; + } +``` + +This directive can be freely mixed with all directives of the [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), [set-misc-nginx-module](http://github.com/openresty/set-misc-nginx-module), and [array-var-nginx-module](http://github.com/openresty/array-var-nginx-module) modules. All of these directives will run in the same order as they appear in the config file. + +```nginx + + set $foo 32; + set_by_lua $bar 'return tonumber(ngx.var.foo) + 1'; + set $baz "bar: $bar"; # $baz == "bar: 33" +``` + +As from the `v0.5.0rc29` release, Nginx variable interpolation is disabled in the `` argument of this directive and therefore, the dollar sign character (`$`) can be used directly. + +This directive requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module. + +[Back to TOC](#directives) + +set_by_lua_block +---------------- + +**syntax:** *set_by_lua_block $res { lua-script }* + +**context:** *server, server if, location, location if* + +**phase:** *rewrite* + +Similar to the [set_by_lua](#set_by_lua) directive except that + +1. this directive inlines the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping), and +1. this directive does not support extra arguments after the Lua script as in [set_by_lua](#set_by_lua). + +For example, + +```nginx + + set_by_lua_block $res { return 32 + math.cos(32) } + # $res now has the value "32.834223360507" or alike. +``` + +No special escaping is required in the Lua code block. + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +set_by_lua_file +--------------- +**syntax:** *set_by_lua_file $res <path-to-lua-script-file> [$arg1 $arg2 ...]* + +**context:** *server, server if, location, location if* + +**phase:** *rewrite* + +Equivalent to [set_by_lua](#set_by_lua), except that the file specified by `` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +Nginx variable interpolation is supported in the `` argument string of this directive. But special care must be taken for injection attacks. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached +and the Nginx config must be reloaded each time the Lua source file is modified. +The Lua code cache can be temporarily disabled during development by +switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. + +This directive requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module. + +[Back to TOC](#directives) + +content_by_lua +-------------- + +**syntax:** *content_by_lua <lua-script-str>* + +**context:** *location, location if* + +**phase:** *content* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [content_by_lua_block](#content_by_lua_block) directive instead. + +Acts as a "content handler" and executes Lua code string specified in `` for every request. +The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox). + +Do not use this directive and other content handler directives in the same location. For example, this directive and the [proxy_pass](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass) directive should not be used in the same location. + +[Back to TOC](#directives) + +content_by_lua_block +-------------------- + +**syntax:** *content_by_lua_block { lua-script }* + +**context:** *location, location if* + +**phase:** *content* + +Similar to the [content_by_lua](#content_by_lua) directive except that this directive inlines +the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping). + +For instance, + +```nginx + + content_by_lua_block { + ngx.say("I need no extra escaping here, for example: \r\nblah") + } +``` + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +content_by_lua_file +------------------- + +**syntax:** *content_by_lua_file <path-to-lua-script-file>* + +**context:** *location, location if* + +**phase:** *content* + +Equivalent to [content_by_lua](#content_by_lua), except that the file specified by `` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +Nginx variables can be used in the `` string to provide flexibility. This however carries some risks and is not ordinarily recommended. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached +and the Nginx config must be reloaded each time the Lua source file is modified. +The Lua code cache can be temporarily disabled during development by +switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. + +Nginx variables are supported in the file path for dynamic dispatch, for example: + +```nginx + + # CAUTION: contents in nginx var must be carefully filtered, + # otherwise there'll be great security risk! + location ~ ^/app/([-_a-zA-Z0-9/]+) { + set $path $1; + content_by_lua_file /path/to/lua/app/root/$path.lua; + } +``` + +But be very careful about malicious user inputs and always carefully validate or filter out the user-supplied path components. + +[Back to TOC](#directives) + +rewrite_by_lua +-------------- + +**syntax:** *rewrite_by_lua <lua-script-str>* + +**context:** *http, server, location, location if* + +**phase:** *rewrite tail* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [rewrite_by_lua_block](#rewrite_by_lua_block) directive instead. + +Acts as a rewrite phase handler and executes Lua code string specified in `` for every request. +The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox). + +Note that this handler always runs *after* the standard [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html). So the following will work as expected: + +```nginx + + location /foo { + set $a 12; # create and initialize $a + set $b ""; # create and initialize $b + rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1'; + echo "res = $b"; + } +``` + +because `set $a 12` and `set $b ""` run *before* [rewrite_by_lua](#rewrite_by_lua). + +On the other hand, the following will not work as expected: + +```nginx + + ? location /foo { + ? set $a 12; # create and initialize $a + ? set $b ''; # create and initialize $b + ? rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1'; + ? if ($b = '13') { + ? rewrite ^ /bar redirect; + ? break; + ? } + ? + ? echo "res = $b"; + ? } +``` + +because `if` runs *before* [rewrite_by_lua](#rewrite_by_lua) even if it is placed after [rewrite_by_lua](#rewrite_by_lua) in the config. + +The right way of doing this is as follows: + +```nginx + + location /foo { + set $a 12; # create and initialize $a + set $b ''; # create and initialize $b + rewrite_by_lua ' + ngx.var.b = tonumber(ngx.var.a) + 1 + if tonumber(ngx.var.b) == 13 then + return ngx.redirect("/bar"); + end + '; + + echo "res = $b"; + } +``` + +Note that the [ngx_eval](http://www.grid.net.ru/nginx/eval.en.html) module can be approximated by using [rewrite_by_lua](#rewrite_by_lua). For example, + +```nginx + + location / { + eval $res { + proxy_pass http://foo.com/check-spam; + } + + if ($res = 'spam') { + rewrite ^ /terms-of-use.html redirect; + } + + fastcgi_pass ...; + } +``` + +can be implemented in ngx_lua as: + +```nginx + + location = /check-spam { + internal; + proxy_pass http://foo.com/check-spam; + } + + location / { + rewrite_by_lua ' + local res = ngx.location.capture("/check-spam") + if res.body == "spam" then + return ngx.redirect("/terms-of-use.html") + end + '; + + fastcgi_pass ...; + } +``` + +Just as any other rewrite phase handlers, [rewrite_by_lua](#rewrite_by_lua) also runs in subrequests. + +Note that when calling `ngx.exit(ngx.OK)` within a [rewrite_by_lua](#rewrite_by_lua) handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [rewrite_by_lua](#rewrite_by_lua) handler, calling [ngx.exit](#ngxexit) with status >= 200 (`ngx.HTTP_OK`) and status < 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures. + +If the [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive is used to change the URI and initiate location re-lookups (internal redirections), then any [rewrite_by_lua](#rewrite_by_lua) or [rewrite_by_lua_file](#rewrite_by_lua_file) code sequences within the current location will not be executed. For example, + +```nginx + + location /foo { + rewrite ^ /bar; + rewrite_by_lua 'ngx.exit(503)'; + } + location /bar { + ... + } +``` + +Here the Lua code `ngx.exit(503)` will never run. This will be the case if `rewrite ^ /bar last` is used as this will similarly initiate an internal redirection. If the `break` modifier is used instead, there will be no internal redirection and the `rewrite_by_lua` code will be executed. + +The `rewrite_by_lua` code will always run at the end of the `rewrite` request-processing phase unless [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone) is turned on. + +[Back to TOC](#directives) + +rewrite_by_lua_block +-------------------- + +**syntax:** *rewrite_by_lua_block { lua-script }* + +**context:** *http, server, location, location if* + +**phase:** *rewrite tail* + +Similar to the [rewrite_by_lua](#rewrite_by_lua) directive except that this directive inlines +the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping). + +For instance, + +```nginx + + rewrite_by_lua_block { + do_something("hello, world!\nhiya\n") + } +``` + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +rewrite_by_lua_file +------------------- + +**syntax:** *rewrite_by_lua_file <path-to-lua-script-file>* + +**context:** *http, server, location, location if* + +**phase:** *rewrite tail* + +Equivalent to [rewrite_by_lua](#rewrite_by_lua), except that the file specified by `` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +Nginx variables can be used in the `` string to provide flexibility. This however carries some risks and is not ordinarily recommended. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. + +The `rewrite_by_lua_file` code will always run at the end of the `rewrite` request-processing phase unless [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone) is turned on. + +Nginx variables are supported in the file path for dynamic dispatch just as in [content_by_lua_file](#content_by_lua_file). + +[Back to TOC](#directives) + +access_by_lua +------------- + +**syntax:** *access_by_lua <lua-script-str>* + +**context:** *http, server, location, location if* + +**phase:** *access tail* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [access_by_lua_block](#access_by_lua_block) directive instead. + +Acts as an access phase handler and executes Lua code string specified in `` for every request. +The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox). + +Note that this handler always runs *after* the standard [ngx_http_access_module](http://nginx.org/en/docs/http/ngx_http_access_module.html). So the following will work as expected: + +```nginx + + location / { + deny 192.168.1.1; + allow 192.168.1.0/24; + allow 10.1.1.0/16; + deny all; + + access_by_lua ' + local res = ngx.location.capture("/mysql", { ... }) + ... + '; + + # proxy_pass/fastcgi_pass/... + } +``` + +That is, if a client IP address is in the blacklist, it will be denied before the MySQL query for more complex authentication is executed by [access_by_lua](#access_by_lua). + +Note that the [ngx_auth_request](http://mdounin.ru/hg/ngx_http_auth_request_module/) module can be approximated by using [access_by_lua](#access_by_lua): + +```nginx + + location / { + auth_request /auth; + + # proxy_pass/fastcgi_pass/postgres_pass/... + } +``` + +can be implemented in ngx_lua as: + +```nginx + + location / { + access_by_lua ' + local res = ngx.location.capture("/auth") + + if res.status == ngx.HTTP_OK then + return + end + + if res.status == ngx.HTTP_FORBIDDEN then + ngx.exit(res.status) + end + + ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) + '; + + # proxy_pass/fastcgi_pass/postgres_pass/... + } +``` + +As with other access phase handlers, [access_by_lua](#access_by_lua) will *not* run in subrequests. + +Note that when calling `ngx.exit(ngx.OK)` within a [access_by_lua](#access_by_lua) handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [access_by_lua](#access_by_lua) handler, calling [ngx.exit](#ngxexit) with status >= 200 (`ngx.HTTP_OK`) and status < 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures. + +Starting from the `v0.9.20` release, you can use the [access_by_lua_no_postpone](#access_by_lua_no_postpone) +directive to control when to run this handler inside the "access" request-processing phase +of NGINX. + +[Back to TOC](#directives) + +access_by_lua_block +------------------- + +**syntax:** *access_by_lua_block { lua-script }* + +**context:** *http, server, location, location if* + +**phase:** *access tail* + +Similar to the [access_by_lua](#access_by_lua) directive except that this directive inlines +the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping). + +For instance, + +```nginx + + access_by_lua_block { + do_something("hello, world!\nhiya\n") + } +``` + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +access_by_lua_file +------------------ + +**syntax:** *access_by_lua_file <path-to-lua-script-file>* + +**context:** *http, server, location, location if* + +**phase:** *access tail* + +Equivalent to [access_by_lua](#access_by_lua), except that the file specified by `` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +Nginx variables can be used in the `` string to provide flexibility. This however carries some risks and is not ordinarily recommended. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached +and the Nginx config must be reloaded each time the Lua source file is modified. +The Lua code cache can be temporarily disabled during development by switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid repeatedly reloading Nginx. + +Nginx variables are supported in the file path for dynamic dispatch just as in [content_by_lua_file](#content_by_lua_file). + +[Back to TOC](#directives) + +header_filter_by_lua +-------------------- + +**syntax:** *header_filter_by_lua <lua-script-str>* + +**context:** *http, server, location, location if* + +**phase:** *output-header-filter* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [header_filter_by_lua_block](#header_filter_by_lua_block) directive instead. + +Uses Lua code specified in `` to define an output header filter. + +Note that the following API functions are currently disabled within this context: + +* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers)) +* Control API functions (e.g., [ngx.redirect](#ngxredirect) and [ngx.exec](#ngxexec)) +* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi)) +* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)). + +Here is an example of overriding a response header (or adding one if absent) in our Lua header filter: + +```nginx + + location / { + proxy_pass http://mybackend; + header_filter_by_lua 'ngx.header.Foo = "blah"'; + } +``` + +This directive was first introduced in the `v0.2.1rc20` release. + +[Back to TOC](#directives) + +header_filter_by_lua_block +-------------------------- + +**syntax:** *header_filter_by_lua_block { lua-script }* + +**context:** *http, server, location, location if* + +**phase:** *output-header-filter* + +Similar to the [header_filter_by_lua](#header_filter_by_lua) directive except that this directive inlines +the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping). + +For instance, + +```nginx + + header_filter_by_lua_block { + ngx.header["content-length"] = nil + } +``` + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +header_filter_by_lua_file +------------------------- + +**syntax:** *header_filter_by_lua_file <path-to-lua-script-file>* + +**context:** *http, server, location, location if* + +**phase:** *output-header-filter* + +Equivalent to [header_filter_by_lua](#header_filter_by_lua), except that the file specified by `` contains the Lua code, or as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +This directive was first introduced in the `v0.2.1rc20` release. + +[Back to TOC](#directives) + +body_filter_by_lua +------------------ + +**syntax:** *body_filter_by_lua <lua-script-str>* + +**context:** *http, server, location, location if* + +**phase:** *output-body-filter* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [body_filter_by_lua_block](#body_filter_by_lua_block) directive instead. + +Uses Lua code specified in `` to define an output body filter. + +The input data chunk is passed via [ngx.arg](#ngxarg)\[1\] (as a Lua string value) and the "eof" flag indicating the end of the response body data stream is passed via [ngx.arg](#ngxarg)\[2\] (as a Lua boolean value). + +Behind the scene, the "eof" flag is just the `last_buf` (for main requests) or `last_in_chain` (for subrequests) flag of the Nginx chain link buffers. (Before the `v0.7.14` release, the "eof" flag does not work at all in subrequests.) + +The output data stream can be aborted immediately by running the following Lua statement: + +```lua + + return ngx.ERROR +``` + +This will truncate the response body and usually result in incomplete and also invalid responses. + +The Lua code can pass its own modified version of the input data chunk to the downstream Nginx output body filters by overriding [ngx.arg](#ngxarg)\[1\] with a Lua string or a Lua table of strings. For example, to transform all the lowercase letters in the response body, we can just write: + +```nginx + + location / { + proxy_pass http://mybackend; + body_filter_by_lua 'ngx.arg[1] = string.upper(ngx.arg[1])'; + } +``` + +When setting `nil` or an empty Lua string value to `ngx.arg[1]`, no data chunk will be passed to the downstream Nginx output filters at all. + +Likewise, new "eof" flag can also be specified by setting a boolean value to [ngx.arg](#ngxarg)\[2\]. For example, + +```nginx + + location /t { + echo hello world; + echo hiya globe; + + body_filter_by_lua ' + local chunk = ngx.arg[1] + if string.match(chunk, "hello") then + ngx.arg[2] = true -- new eof + return + end + + -- just throw away any remaining chunk data + ngx.arg[1] = nil + '; + } +``` + +Then `GET /t` will just return the output + + + hello world + + +That is, when the body filter sees a chunk containing the word "hello", then it will set the "eof" flag to true immediately, resulting in truncated but still valid responses. + +When the Lua code may change the length of the response body, then it is required to always clear out the `Content-Length` response header (if any) in a header filter to enforce streaming output, as in + +```nginx + + location /foo { + # fastcgi_pass/proxy_pass/... + + header_filter_by_lua_block { ngx.header.content_length = nil } + body_filter_by_lua 'ngx.arg[1] = string.len(ngx.arg[1]) .. "\\n"'; + } +``` + +Note that the following API functions are currently disabled within this context due to the limitations in NGINX output filter's current implementation: + +* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers)) +* Control API functions (e.g., [ngx.exit](#ngxexit) and [ngx.exec](#ngxexec)) +* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi)) +* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)). + +Nginx output filters may be called multiple times for a single request because response body may be delivered in chunks. Thus, the Lua code specified by in this directive may also run multiple times in the lifetime of a single HTTP request. + +This directive was first introduced in the `v0.5.0rc32` release. + +[Back to TOC](#directives) + +body_filter_by_lua_block +------------------------ + +**syntax:** *body_filter_by_lua_block { lua-script-str }* + +**context:** *http, server, location, location if* + +**phase:** *output-body-filter* + +Similar to the [body_filter_by_lua](#body_filter_by_lua) directive except that this directive inlines +the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping). + +For instance, + +```nginx + + body_filter_by_lua_block { + local data, eof = ngx.arg[1], ngx.arg[2] + } +``` + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +body_filter_by_lua_file +----------------------- + +**syntax:** *body_filter_by_lua_file <path-to-lua-script-file>* + +**context:** *http, server, location, location if* + +**phase:** *output-body-filter* + +Equivalent to [body_filter_by_lua](#body_filter_by_lua), except that the file specified by `` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +This directive was first introduced in the `v0.5.0rc32` release. + +[Back to TOC](#directives) + +log_by_lua +---------- + +**syntax:** *log_by_lua <lua-script-str>* + +**context:** *http, server, location, location if* + +**phase:** *log* + +**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [log_by_lua_block](#log_by_lua_block) directive instead. + +Runs the Lua source code inlined as the `` at the `log` request processing phase. This does not replace the current access logs, but runs before. + +Note that the following API functions are currently disabled within this context: + +* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers)) +* Control API functions (e.g., [ngx.exit](#ngxexit)) +* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi)) +* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)). + +Here is an example of gathering average data for [$upstream_response_time](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_response_time): + +```nginx + + lua_shared_dict log_dict 5M; + + server { + location / { + proxy_pass http://mybackend; + + log_by_lua ' + local log_dict = ngx.shared.log_dict + local upstream_time = tonumber(ngx.var.upstream_response_time) + + local sum = log_dict:get("upstream_time-sum") or 0 + sum = sum + upstream_time + log_dict:set("upstream_time-sum", sum) + + local newval, err = log_dict:incr("upstream_time-nb", 1) + if not newval and err == "not found" then + log_dict:add("upstream_time-nb", 0) + log_dict:incr("upstream_time-nb", 1) + end + '; + } + + location = /status { + content_by_lua_block { + local log_dict = ngx.shared.log_dict + local sum = log_dict:get("upstream_time-sum") + local nb = log_dict:get("upstream_time-nb") + + if nb and sum then + ngx.say("average upstream response time: ", sum / nb, + " (", nb, " reqs)") + else + ngx.say("no data yet") + end + } + } + } +``` + +This directive was first introduced in the `v0.5.0rc31` release. + +[Back to TOC](#directives) + +log_by_lua_block +---------------- + +**syntax:** *log_by_lua_block { lua-script }* + +**context:** *http, server, location, location if* + +**phase:** *log* + +Similar to the [log_by_lua](#log_by_lua) directive except that this directive inlines +the Lua source directly +inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires +special character escaping). + +For instance, + +```nginx + + log_by_lua_block { + print("I need no extra escaping here, for example: \r\nblah") + } +``` + +This directive was first introduced in the `v0.9.17` release. + +[Back to TOC](#directives) + +log_by_lua_file +--------------- + +**syntax:** *log_by_lua_file <path-to-lua-script-file>* + +**context:** *http, server, location, location if* + +**phase:** *log* + +Equivalent to [log_by_lua](#log_by_lua), except that the file specified by `` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +This directive was first introduced in the `v0.5.0rc31` release. + +[Back to TOC](#directives) + +balancer_by_lua_block +--------------------- + +**syntax:** *balancer_by_lua_block { lua-script }* + +**context:** *upstream* + +**phase:** *content* + +This directive runs Lua code as an upstream balancer for any upstream entities defined +by the `upstream {}` configuration block. + +For instance, + +```nginx + + upstream foo { + server 127.0.0.1; + balancer_by_lua_block { + -- use Lua to do something interesting here + -- as a dynamic balancer + } + } + + server { + location / { + proxy_pass http://foo; + } + } +``` + +The resulting Lua load balancer can work with any existing nginx upstream modules +like [ngx_proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and +[ngx_fastcgi](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html). + +Also, the Lua load balancer can work with the standard upstream connection pool mechanism, +i.e., the standard [keepalive](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive. +Just ensure that the [keepalive](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive +is used *after* this `balancer_by_lua_block` directive in a single `upstream {}` configuration block. + +The Lua load balancer can totally ignore the list of servers defined in the `upstream {}` block +and select peer from a completely dynamic server list (even changing per request) via the +[ngx.balancer](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md) module +from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. + +The Lua code handler registered by this directive might get called more than once in a single +downstream request when the nginx upstream mechanism retries the request on conditions +specified by directives like the [proxy_next_upstream](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream) +directive. + +This Lua code execution context does not support yielding, so Lua APIs that may yield +(like cosockets and "light threads") are disabled in this context. One can usually work +around this limitation by doing such operations in an earlier phase handler (like +[access_by_lua*](#access_by_lua)) and passing along the result into this context +via the [ngx.ctx](#ngxctx) table. + +This directive was first introduced in the `v0.10.0` release. + +[Back to TOC](#directives) + +balancer_by_lua_file +-------------------- + +**syntax:** *balancer_by_lua_file <path-to-lua-script-file>* + +**context:** *upstream* + +**phase:** *content* + +Equivalent to [balancer_by_lua_block](#balancer_by_lua_block), except that the file specified by `` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +This directive was first introduced in the `v0.10.0` release. + +[Back to TOC](#directives) + +lua_need_request_body +--------------------- + +**syntax:** *lua_need_request_body <on|off>* + +**default:** *off* + +**context:** *http, server, location, location if* + +**phase:** *depends on usage* + +Determines whether to force the request body data to be read before running rewrite/access/access_by_lua* or not. The Nginx core does not read the client request body by default and if request body data is required, then this directive should be turned `on` or the [ngx.req.read_body](#ngxreqread_body) function should be called within the Lua code. + +To read the request body data within the [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable, +[client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) must have the same value as [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size). Because when the content length exceeds [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) but less than [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size), Nginx will buffer the data into a temporary file on the disk, which will lead to empty value in the [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable. + +If the current location includes [rewrite_by_lua*](#rewrite_by_lua) directives, +then the request body will be read just before the [rewrite_by_lua*](#rewrite_by_lua) code is run (and also at the +`rewrite` phase). Similarly, if only [content_by_lua](#content_by_lua) is specified, +the request body will not be read until the content handler's Lua code is +about to run (i.e., the request body will be read during the content phase). + +It is recommended however, to use the [ngx.req.read_body](#ngxreqread_body) and [ngx.req.discard_body](#ngxreqdiscard_body) functions for finer control over the request body reading process instead. + +This also applies to [access_by_lua*](#access_by_lua). + +[Back to TOC](#directives) + +ssl_certificate_by_lua_block +---------------------------- + +**syntax:** *ssl_certificate_by_lua_block { lua-script }* + +**context:** *server* + +**phase:** *right-before-SSL-handshake* + +This directive runs user Lua code when NGINX is about to start the SSL handshake for the downstream +SSL (https) connections. + +It is particularly useful for setting the SSL certificate chain and the corresponding private key on a per-request +basis. It is also useful to load such handshake configurations nonblockingly from the remote (for example, +with the [cosocket](#ngxsockettcp) API). And one can also do per-request OCSP stapling handling in pure +Lua here as well. + +Another typical use case is to do SSL handshake traffic control nonblockingly in this context, +with the help of the [lua-resty-limit-traffic#readme](https://github.com/openresty/lua-resty-limit-traffic) +library, for example. + +One can also do interesting things with the SSL handshake requests from the client side, like +rejecting old SSL clients using the SSLv3 protocol or even below selectively. + +The [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) +and [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md) Lua modules +provided by the [lua-resty-core](https://github.com/openresty/lua-resty-core/#readme) +library are particularly useful in this context. You can use the Lua API offered by these two Lua modules +to manipulate the SSL certificate chain and private key for the current SSL connection +being initiated. + +This Lua handler does not run at all, however, when NGINX/OpenSSL successfully resumes +the SSL session via SSL session IDs or TLS session tickets for the current SSL connection. In +other words, this Lua handler only runs when NGINX has to initiate a full SSL handshake. + +Below is a trivial example using the +[ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) module +at the same time: + +```nginx + + server { + listen 443 ssl; + server_name test.com; + + ssl_certificate_by_lua_block { + print("About to initiate a new SSL handshake!") + } + + location / { + root html; + } + } +``` + +See more complicated examples in the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) +and [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md) +Lua modules' official documentation. + +Uncaught Lua exceptions in the user Lua code immediately abort the current SSL session, so does the +[ngx.exit](#ngxexit) call with an error code like `ngx.ERROR`. + +This Lua code execution context *does* support yielding, so Lua APIs that may yield +(like cosockets, sleeping, and "light threads") +are enabled in this context. + +Note, however, you still need to configure the [ssl_certificate](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate) and +[ssl_certificate_key](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate_key) +directives even though you will not use this static certificate and private key at all. This is +because the NGINX core requires their appearance otherwise you are seeing the following error +while starting NGINX: + + + nginx: [emerg] no ssl configured for the server + + +This directive currently requires the following NGINX core patch to work correctly: + + + +The bundled version of the NGINX core in OpenResty 1.9.7.2 (or above) already has this +patch applied. + +Furthermore, one needs at least OpenSSL 1.0.2e for this directive to work. + +This directive was first introduced in the `v0.10.0` release. + +[Back to TOC](#directives) + +ssl_certificate_by_lua_file +--------------------------- + +**syntax:** *ssl_certificate_by_lua_file <path-to-lua-script-file>* + +**context:** *server* + +**phase:** *right-before-SSL-handshake* + +Equivalent to [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block), except that the file specified by `` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +This directive was first introduced in the `v0.10.0` release. + +[Back to TOC](#directives) + +ssl_session_fetch_by_lua_block +------------------------------ + +**syntax:** *ssl_session_fetch_by_lua_block { lua-script }* + +**context:** *http* + +**phase:** *right-before-SSL-handshake* + +This directive runs Lua code to look up and load the SSL session (if any) according to the session ID +provided by the current SSL handshake request for the downstream. + +The Lua API for obtaining the current session ID and loading a cached SSL session data +is provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md) +Lua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme) +library. + +Lua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp), +are enabled in this context. + +This hook, together with the [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block) hook, +can be used to implement distributed caching mechanisms in pure Lua (based +on the [cosocket](#ngxsockettcp) API, for example). If a cached SSL session is found +and loaded into the current SSL connection context, +SSL session resumption can then get immediately initiated and bypass the full SSL handshake process which is very expensive in terms of CPU time. + +Please note that TLS session tickets are very different and it is the clients' responsibility +to cache the SSL session state when session tickets are used. SSL session resumptions based on +TLS session tickets would happen automatically without going through this hook (nor the +[ssl_session_store_by_lua_block](#ssl_session_store_by_lua) hook). This hook is mainly +for older or less capable SSL clients that can only do SSL sessions by session IDs. + +When [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block) is specified at the same time, +this hook usually runs before [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block). +When the SSL session is found and successfully loaded for the current SSL connection, +SSL session resumption will happen and thus bypass the [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block) +hook completely. In this case, NGINX also bypasses the [ssl_session_store_by_lua_block](#ssl_session_store_by_lua) +hook, for obvious reasons. + +To easily test this hook locally with a modern web browser, you can temporarily put the following line +in your https server block to disable the TLS session ticket support: + + ssl_session_tickets off; + +But do not forget to comment this line out before publishing your site to the world. + +If you are using the [official pre-built packages](http://openresty.org/en/linux-packages.html) for [OpenResty](https://openresty.org/) +1.11.2.1 or later, then everything should work out of the box. + +If you are using OpenSSL libraries not provided by [OpenResty](https://openresty.org), +then you need to apply the following patch for OpenSSL 1.0.2h or later: + + + +If you are not using the NGINX core shipped with [OpenResty](https://openresty.org) 1.11.2.1 or later, then you need to +apply the following patch to the standard NGINX core 1.11.2 or later: + + + +This directive was first introduced in the `v0.10.6` release. + +Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release +(because SSL session resumption happens before server name dispatch). + +[Back to TOC](#directives) + +ssl_session_fetch_by_lua_file +----------------------------- + +**syntax:** *ssl_session_fetch_by_lua_file <path-to-lua-script-file>* + +**context:** *http* + +**phase:** *right-before-SSL-handshake* + +Equivalent to [ssl_session_fetch_by_lua_block](#ssl_session_fetch_by_lua_block), except that the file specified by `` contains the Lua code, or rather, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +This directive was first introduced in the `v0.10.6` release. + +Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release +(because SSL session resumption happens before server name dispatch). + +[Back to TOC](#directives) + +ssl_session_store_by_lua_block +------------------------------ + +**syntax:** *ssl_session_store_by_lua_block { lua-script }* + +**context:** *http* + +**phase:** *right-after-SSL-handshake* + +This directive runs Lua code to fetch and save the SSL session (if any) according to the session ID +provided by the current SSL handshake request for the downstream. The saved or cached SSL +session data can be used for future SSL connections to resume SSL sessions without going +through the full SSL handshake process (which is very expensive in terms of CPU time). + +Lua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp), +are *disabled* in this context. You can still, however, use the [ngx.timer.at](#ngxtimerat) API +to create 0-delay timers to save the SSL session data asynchronously to external services (like `redis` or `memcached`). + +The Lua API for obtaining the current session ID and the associated session state data +is provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md#readme) +Lua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme) +library. + +To easily test this hook locally with a modern web browser, you can temporarily put the following line +in your https server block to disable the TLS session ticket support: + + ssl_session_tickets off; + +But do not forget to comment this line out before publishing your site to the world. + +This directive was first introduced in the `v0.10.6` release. + +Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release +(because SSL session resumption happens before server name dispatch). + +[Back to TOC](#directives) + +ssl_session_store_by_lua_file +----------------------------- + +**syntax:** *ssl_session_store_by_lua_file <path-to-lua-script-file>* + +**context:** *http* + +**phase:** *right-after-SSL-handshake* + +Equivalent to [ssl_session_store_by_lua_block](#ssl_session_store_by_lua_block), except that the file specified by `` contains the Lua code, or rather, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed. + +When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server. + +This directive was first introduced in the `v0.10.6` release. + +Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release +(because SSL session resumption happens before server name dispatch). + +[Back to TOC](#directives) + +lua_shared_dict +--------------- + +**syntax:** *lua_shared_dict <name> <size>* + +**default:** *no* + +**context:** *http* + +**phase:** *depends on usage* + +Declares a shared memory zone, ``, to serve as storage for the shm based Lua dictionary `ngx.shared.`. + +Shared memory zones are always shared by all the nginx worker processes in the current nginx server instance. + +The `` argument accepts size units such as `k` and `m`: + +```nginx + + http { + lua_shared_dict dogs 10m; + ... + } +``` + +The hard-coded minimum size is 8KB while the practical minimum size depends +on actual user data set (some people start with 12KB). + +See [ngx.shared.DICT](#ngxshareddict) for details. + +This directive was first introduced in the `v0.3.1rc22` release. + +[Back to TOC](#directives) + +lua_socket_connect_timeout +-------------------------- + +**syntax:** *lua_socket_connect_timeout <time>* + +**default:** *lua_socket_connect_timeout 60s* + +**context:** *http, server, location* + +This directive controls the default timeout value used in TCP/unix-domain socket object's [connect](#tcpsockconnect) method and can be overridden by the [settimeout](#tcpsocksettimeout) or [settimeouts](#tcpsocksettimeouts) methods. + +The `