Commit Graph

5237 Commits

Author SHA1 Message Date
Roman Arutyunyan
dd7dba520c Generate error for unsupported IPv6 transparent proxy.
On some platforms (for example, Linux with glibc 2.12-2.25) IPv4 transparent
proxying is available, but IPv6 transparent proxying is not.  The entire feature
is enabled in this case and NGX_HAVE_TRANSPARENT_PROXY macro is set to 1.
Previously, an attempt to enable transparency for an IPv6 socket was silently
ignored in this case and was usually followed by a bind(2) EADDRNOTAVAIL error
(ticket #1487).  Now the error is generated for unavailable IPv6 transparent
proxy.
2018-02-22 13:16:21 +03:00
Ruslan Ermilov
bcda92e843 HTTP/2: style.
Unified the style of validity checks in ngx_http_v2_validate_header().
2018-02-22 12:42:29 +03:00
Sergey Kandaurov
b3b4a98a5c Geo: fixed indentation. 2018-02-21 17:26:00 +03:00
Ruslan Ermilov
7a45918e0b Geo: optimized configuration parser.
If the geo block parser has failed, doing more things is pointless.
2018-02-21 15:50:43 +03:00
Ruslan Ermilov
f98a8c4db6 Geo: fixed memory allocation error handling (closes #1482).
If during configuration parsing of the geo directive the memory
allocation has failed, pool used to parse configuration inside
the block, and sometimes the temporary pool were not destroyed.
2018-02-21 15:50:42 +03:00
Ruslan Ermilov
864d93965b Version bump. 2018-02-21 15:50:35 +03:00
Maxim Dounin
9e2cd6282f HTTP/2: precalculate hash for "Cookie".
There is no need to calculate hashes of static strings at runtime.  The
ngx_hash() macro can be used to do it during compilation instead, similarly
to how it is done in ngx_http_proxy_module.c for "Server" and "Date" headers.
2018-02-15 19:06:22 +03:00
Ruslan Ermilov
89661c0e7d HTTP/2: fixed ngx_http_v2_push_stream() allocation error handling.
In particular, if a stream object allocation failed, and a client sent
the PRIORITY frame for this stream, ngx_http_v2_set_dependency() could
dereference a null pointer while trying to re-parent a dependency node.
2018-02-15 17:51:37 +03:00
Ruslan Ermilov
2437532e7f HTTP/2: push additional request headers (closes #1478).
The Accept-Encoding, Accept-Language, and User-Agent header fields
are now copied from the original request to pushed requests.
2018-02-15 17:51:32 +03:00
Ruslan Ermilov
8a84dd4f32 Expose more headers with NGX_HTTP_HEADERS. 2018-02-15 17:51:26 +03:00
Vladimir Homutov
9d00f9e449 Core: added a stub for additional zone configuration. 2018-02-15 16:08:05 +03:00
Sergey Kandaurov
5e28302dfc HTTP/2: style. 2018-02-15 02:34:16 +03:00
Ruslan Ermilov
c32d9d28fd HTTP/2: fixed null pointer dereference with server push.
r->headers_in.host can be NULL in ngx_http_v2_push_resource().

This happens when a request is terminated with 400 before the :authority
or Host header is parsed, and either pushing is enabled on the server{}
level or error_page 400 redirects to a location with pushes configured.

Found by Coverity (CID 1429156).
2018-02-09 23:20:08 +03:00
Ruslan Ermilov
09eb20c8a7 HTTP/2: fixed build with -Werror=unused-but-set-variable. 2018-02-08 12:11:30 +03:00
Ruslan Ermilov
6e52265b42 HTTP/2: server push.
Resources to be pushed are configured with the "http2_push" directive.

Also, preload links from the Link response headers, as described in
https://www.w3.org/TR/preload/#server-push-http-2, can be pushed, if
enabled with the "http2_push_preload" directive.

Only relative URIs with absolute paths can be pushed.

The number of concurrent pushes is normally limited by a client, but
cannot exceed a hard limit set by the "http2_max_concurrent_pushes"
directive.
2018-02-08 09:55:03 +03:00
Ruslan Ermilov
ac3c8ff364 HTTP/2: changed prototypes of request pseudo-headers parsers.
No functional changes.
2018-02-08 09:54:49 +03:00
Ruslan Ermilov
8590d9d615 Basic support of the Link response header. 2018-02-08 09:54:18 +03:00
Roman Arutyunyan
d31d547dba Dav: added error logging.
Previously, when request body was not available or was previously read in
memory rather than a file, client received HTTP 500 error, but no explanation
was logged in error log.  This could happen, for example, if request body was
read or discarded prior to error_page redirect, or if mirroring was enabled
along with dav.
2018-02-07 16:44:29 +03:00
Sergey Kandaurov
bde18907ac HTTP/2: removed unused field from ngx_http_v2_stream_t. 2018-02-06 20:02:59 +03:00
Ruslan Ermilov
c8f46e070f Upstream: removed X-Powered-By from the list of special headers.
After 1e720b0be7ec, it's neither specially processed nor copied
when redirecting with X-Accel-Redirect.
2018-01-30 22:23:58 +03:00
Sergey Kandaurov
57dde2ab37 SSL: using default server context in session remove (closes #1464).
This fixes segfault in configurations with multiple virtual servers sharing
the same port, where a non-default virtual server block misses certificate.
2018-01-30 17:46:31 +03:00
Ruslan Ermilov
2213695368 HTTP/2: finalize request as bad if parsing of pseudo-headers fails.
This is in line when the required pseudo-headers are missing, and
avoids spurious zero statuses in access.log.
2018-01-30 14:44:31 +03:00
Ruslan Ermilov
0b8b91f45f HTTP/2: more style, comments, and debugging. 2018-01-29 16:06:33 +03:00
Ruslan Ermilov
34cf5d5e6a HTTP/2: handle duplicate INITIAL_WINDOW_SIZE settings. 2018-01-29 15:54:36 +03:00
Ruslan Ermilov
63a4dab7b0 Fixed --test-build-eventport on macOS 10.12 and later.
In macOS 10.12, CLOCK_REALTIME and clockid_t were added, but not timer_t.
2018-01-16 13:52:03 +03:00
Maxim Dounin
3377c00119 Upstream: fixed "header already sent" alerts on backend errors.
Following ad3f342f14ba046c (1.9.13), it is possible that a request where
header was already sent will be finalized with NGX_HTTP_BAD_GATEWAY,
triggering an attempt to return additional error response and the
"header already sent" alert as a result.

In particular, it is trivial to reproduce the problem with a HEAD request
and caching enabled.  With caching enabled nginx will change HEAD to GET
and will set u->pipe->downstream_error to suppress sending the response
body to the client.  When a backend-related error occurs (for example,
proxy_read_timeout expires), ngx_http_finalize_upstream_request() will
be called with NGX_HTTP_BAD_GATEWAY.  After ad3f342f14ba046c this will
result in ngx_http_finalize_request(NGX_HTTP_BAD_GATEWAY).

Fix is to move u->pipe->downstream_error handling to a later point,
where all special response codes are changed to NGX_ERROR.

Reported by Jan Prachar,
http://mailman.nginx.org/pipermail/nginx-devel/2018-January/010737.html.
2018-01-11 21:43:49 +03:00
Maxim Dounin
742f413e91 Version bump. 2017-12-30 00:15:07 +03:00
Roman Arutyunyan
0ad556fe59 Allowed configuration token to start with a variable.
Specifically, it is now allowed to start with a variable expression with braces:
${name}.  The opening curly bracket in such a token was previously considered
the start of a new block.  Variables located anywhere else in a token worked
fine: foo${name}.
2017-12-21 13:29:40 +03:00
Roman Arutyunyan
ce45ded2a8 Fixed capabilities version.
Previously, capset(2) was called with the 64-bit capabilities version
_LINUX_CAPABILITY_VERSION_3.  With this version Linux kernel expected two
copies of struct __user_cap_data_struct, while only one was submitted.  As a
result, random stack memory was accessed and random capabilities were requested
by the worker.  This sometimes caused capset() errors.  Now the 32-bit version
_LINUX_CAPABILITY_VERSION_1 is used instead.  This is OK since CAP_NET_RAW is
a 32-bit capability (CAP_NET_RAW = 13).
2017-12-19 19:00:27 +03:00
Roman Arutyunyan
0e92c213f5 Improved the capabilities feature detection.
Previously included file sys/capability.h mentioned in capset(2) man page,
belongs to the libcap-dev package, which may not be installed on some Linux
systems when compiling nginx.  This prevented the capabilities feature from
being detected and compiled on that systems.

Now linux/capability.h system header is included instead.  Since capset()
declaration is located in sys/capability.h, now capset() syscall is defined
explicitly in code using the SYS_capset constant, similarly to other
Linux-specific features in nginx.
2017-12-18 21:09:39 +03:00
Roman Arutyunyan
752f66bf7d Retain CAP_NET_RAW capability for transparent proxying.
The capability is retained automatically in unprivileged worker processes after
changing UID if transparent proxying is enabled at least once in nginx
configuration.

The feature is only available in Linux.
2017-12-13 20:40:53 +03:00
Debayan Ghosh
d2d737e70b Use sysconf to determine cacheline size at runtime.
Determine cacheline size at runtime if supported
using sysconf(_SC_LEVEL1_DCACHE_LINESIZE). In case not supported,
fallback to compile time defaults.
2017-12-11 16:28:11 +00:00
Roman Arutyunyan
6754a40466 Proxy: escape explicit space in URI in default cache key.
If the flag space_in_uri is set, the URI in HTTP upstream request is escaped to
convert space to %20.  However this flag is not checked while creating the
default cache key.  This leads to different cache keys for requests
'/foo bar' and '/foo%20bar', while the upstream requests are identical.

Additionally, the change fixes background cache updates when the client URI
contains unescaped space.  Default cache key in a subrequest is always based on
escaped URI, while the main request may not escape it.  As a result, background
cache update subrequest may update a different cache entry.
2017-11-20 20:50:35 +03:00
Roman Arutyunyan
891908cd0c Inherit valid_unparsed_uri in cloned subrequests (ticket #1430).
Inheriting this flag will make the cloned subrequest behave consistently with
the parent.  Specifically, the upstream HTTP request and cache key created by
the proxy module may depend directly on unparsed_uri if valid_unparsed_uri flag
is set.  Previously, the flag was zero for cloned requests, which could make
background update proxy a request different than its parent and cache the result
with a different key.  For example, if client URI contained the escaped slash
character %2F, it was used as is by the proxy module in the main request, but
was unescaped in the subrequests.

Similar problems exist in the slice module.
2017-11-20 21:11:19 +03:00
Roman Arutyunyan
de11c2ad09 Proxy: simplified conditions of using unparsed uri.
Previously, the unparsed uri was explicitly allowed to be used only by the main
request.  However the valid_unparsed_uri flag is nonzero only in the main
request, which makes the main request check pointless.
2017-11-20 13:47:17 +03:00
Patryk Lesiewicz
7b3f187bc6 Upstream: flush low-level buffers on write retry.
If the data to write is bigger than what the socket can send, and the
reminder is smaller than NGX_SSL_BUFSIZE, then SSL_write() fails with
SSL_ERROR_WANT_WRITE. The reminder of payload however is successfully
copied to the low-level buffer and all the output chain buffers are
flushed. This means that retry logic doesn't work because
ngx_http_upstream_process_non_buffered_request() checks only if there's
anything in the output chain buffers and ignores the fact that something
may be buffered in low-level parts of the stack.

Signed-off-by: Patryk Lesiewicz <patryk@google.com>
2017-12-01 15:59:14 -08:00
Roman Arutyunyan
e13268714f Upstream keepalive: clean read delayed flag in stored connections.
If a connection with the read delayed flag set was stored in the keepalive
cache, and after picking it from the cache a read timer was set on that
connection, this timer was considered a delay timer rather than a socket read
event timer as expected.  The latter timeout is usually much longer than the
former, which caused a significant delay in request processing.

The issue manifested itself with proxy_limit_rate and upstream keepalive
enabled and exists since 973ee2276300 (1.7.7) when proxy_limit_rate was
introduced.
2017-11-28 14:00:00 +03:00
Maxim Dounin
53e5a746bf Autoindex: discard request body (ticket #1439). 2017-12-04 17:30:02 +03:00
Sergey Kandaurov
e3baa90da9 Removed unused FreeBSD-specific definitions in ngx_posix_config.h. 2017-11-28 13:09:54 +03:00
Ruslan Ermilov
afad219175 Fixed "changing binary" when reaper is not init.
On some systems, it's possible that reaper of orphaned processes is
set to something other than "init" process.  On such systems, the
changing binary procedure did not work.

The fix is to check if PPID has changed, instead of assuming it's
always 1 for orphaned processes.
2017-11-28 12:00:24 +03:00
Maxim Dounin
3656f2eb63 Version bump. 2017-11-23 16:32:58 +03:00
Maxim Dounin
b32cb6b610 Fixed worker_shutdown_timeout in various cases.
The ngx_http_upstream_process_upgraded() did not handle c->close request,
and upgraded connections do not use the write filter.  As a result,
worker_shutdown_timeout did not affect upgraded connections (ticket #1419).
Fix is to handle c->close in the ngx_http_request_handler() function, thus
covering most of the possible cases in http handling.

Additionally, mail proxying did not handle neither c->close nor c->error,
and thus worker_shutdown_timeout did not work for mail connections.  Fix is
to add c->close handling to ngx_mail_proxy_handler().

Also, added explicit handling of c->close to stream proxy,
ngx_stream_proxy_process_connection().  This improves worker_shutdown_timeout
handling in stream, it will no longer wait for some data being transferred
in a connection before closing it, and will also provide appropriate
logging at the "info" level.
2017-11-20 16:31:07 +03:00
Maxim Dounin
f1c4853ea1 Gzip: support for a zlib variant from Intel.
A zlib variant from Intel as available from https://github.com/jtkukunas/zlib
uses 64K hash instead of scaling it from the specified memory level, and
also uses 16-byte padding in one of the window-sized memory buffers, and can
force window bits to 13 if compression level is set to 1 and appropriate
compile options are used.  As a result, nginx complained with "gzip filter
failed to use preallocated memory" alerts.

This change improves deflate_state allocation detection by testing that
items is 1 (deflate_state is the only allocation where items is 1).
Additionally, on first failure to use preallocated memory we now assume
that we are working with the Intel's modified zlib, and switch to using
appropriate preallocations.  If this does not help, we complain with the
usual alerts.

Previous version of this patch was published at
http://mailman.nginx.org/pipermail/nginx/2014-July/044568.html.
The zlib variant in question is used by default in ClearLinux from Intel,
see http://mailman.nginx.org/pipermail/nginx-ru/2017-October/060421.html,
http://mailman.nginx.org/pipermail/nginx-ru/2017-November/060544.html.
2017-11-18 04:03:27 +03:00
Ruslan Ermilov
cdbdbbd842 Xslt: fixed parameters parsing (ticket #1416).
If parameters were specified in xslt_stylesheet without variables,
any request except the first would cause an internal server error.
2017-11-16 13:20:47 +03:00
hucongcong
d303a95594 SSI: fixed type. 2017-10-27 00:30:38 +08:00
Maxim Dounin
cfc8c28259 FastCGI: adjust buffer position when parsing incomplete records.
Previously, nginx failed to move buffer position when parsing an incomplete
record header, and due to this wasn't be able to continue parsing once
remaining bytes of the record header were received.

This can affect response header parsing, potentially generating spurious errors
like "upstream sent unexpected FastCGI request id high byte: 1 while reading
response header from upstream".  While this is very unlikely, since usually
record headers are written in a single buffer, this still can happen in real
life, for example, if a record header will be split across two TCP packets
and the second packet will be delayed.

This does not affect non-buffered response body proxying, due to "buf->pos =
buf->last;" at the start of the ngx_http_fastcgi_non_buffered_filter()
function.  Also this does not affect buffered response body proxying, as
each input buffer is only passed to the filter once.
2017-11-09 15:35:20 +03:00
Maxim Dounin
9cb9ce78b1 Core: free shared memory zones only after reconfiguration.
This is what usually happens for zones no longer used in the new
configuration, but zones where size or tag were changed were freed
when creating new memory zones.  If reconfiguration failed (for
example, due to a conflicting listening socket), this resulted in a
segmentation fault in the master process.

Reported by Zhihua Cao,
http://mailman.nginx.org/pipermail/nginx-devel/2017-October/010536.html.
2017-10-17 19:52:16 +03:00
Sergey Kandaurov
fdbf551602 Postpone filter: handled ngx_http_postpone_filter_add() failures.
In particular, if ngx_http_postpone_filter_add() fails in ngx_chain_add_copy(),
the output chain of the postponed request was left in an invalid state.
2017-10-16 13:13:25 +03:00
Ruslan Ermilov
77c7875a7b Fixed type of ngx_conf_t.handler_conf.
The type should have been changed in c9b243802a17 along with
changing ngx_conf_handler_pt.
2017-10-13 00:32:26 +03:00
Alessandro Ghedini
5fee8f76b5 SSL: include <openssl/hmac.h>.
This header carries the definition of HMAC_Init_ex(). In OpenSSL this
header is included by <openssl/ssl.h>, but it's not so in BoringSSL.

It's probably a good idea to explicitly include this header anyway,
regardless of whether it's included by other headers or not.
2017-10-11 15:43:50 -07:00
Roman Arutyunyan
80f2e8f656 Upstream: disabled upgrading in subrequests.
Upgrading an upstream connection is usually followed by reading from the client
which a subrequest is not allowed to do.  Moreover, accessing the header_in
request field while processing upgraded connection ends up with a null pointer
dereference since the header_in buffer is only created for the the main request.
2017-10-11 17:38:21 +03:00
Ruslan Ermilov
f1be23bc8a Upstream: fixed $upstream_status when upstream returns 503/504.
If proxy_next_upstream includes http_503/http_504, and upstream
returns 503/504, $upstream_status converted this to 502 for any
values except the last one.
2017-10-11 22:04:28 +03:00
Ruslan Ermilov
211d20a230 Version bump. 2017-10-11 22:04:11 +03:00
Sergey Kandaurov
661e40864f Upstream: fixed error handling of stale and revalidated cache send.
The NGX_DONE value returned from ngx_http_upstream_cache_send() indicates
that upstream was already finalized in ngx_http_upstream_process_headers().
It was treated as a generic error which resulted in duplicate finalization.

Handled NGX_HTTP_UPSTREAM_INVALID_HEADER from ngx_http_upstream_cache_send().
Previously, it could return within ngx_http_upstream_finalize_request(), and
since it's below NGX_HTTP_SPECIAL_RESPONSE, a client connection could stuck.
2017-10-10 01:04:54 +03:00
Maxim Dounin
0737e6d841 Upstream: even better handling of invalid headers in cache files.
When parsing of headers in a cache file fails, already parsed headers
need to be cleared, and protocol state needs to be reinitialized.  To do
so, u->request_sent is now set to ensure ngx_http_upstream_reinit() will
be called.

This change complements improvements in 46ddff109e72.
2017-10-09 15:59:10 +03:00
Maxim Dounin
53d655f894 Upstream hash: reordered peer checks.
This slightly reduces cost of selecting a peer if all or almost all peers
failed, see ticket #1030.  There should be no measureable difference with
other workloads.
2017-10-05 17:43:05 +03:00
Maxim Dounin
a10ec2db91 Upstream hash: limited number of tries in consistent case.
While this may result in non-ideal distribution of requests if nginx
won't be able to select a server in a reasonable number of attempts,
this still looks better than severe performance degradation observed
if there is no limit and there are many points configured (ticket #1030).
This is also in line with what we do for other hash balancing methods.
2017-10-05 17:42:59 +03:00
Maxim Dounin
3a2ca34548 Fixed build without IPv6, broken by 874171c3c71a. 2017-10-05 16:50:35 +03:00
Maxim Dounin
41d8ea8c8d Fixed handling of unix sockets in $binary_remote_addr.
Previously, unix sockets were treated as AF_INET ones, and this may
result in buffer overread on Linux, where unbound unix sockets have
2-byte addresses.

Note that it is not correct to use just sun_path as a binary representation
for unix sockets.  This will result in an empty string for unbound unix
sockets, and thus behaviour of limit_req and limit_conn will change when
switching from $remote_addr to $binary_remote_addr.  As such, normal text
representation is used.

Reported by Stephan Dollberg.
2017-10-04 21:19:42 +03:00
Maxim Dounin
cba23f88ec Fixed handling of non-null-terminated unix sockets.
At least FreeBSD, macOS, NetBSD, and OpenBSD can return unix sockets
with non-null-terminated sun_path.  Additionally, the address may become
non-null-terminated if it does not fit into the buffer provided and was
truncated (may happen on macOS, NetBSD, and Solaris, which allow unix socket
addresess larger than struct sockaddr_un).  As such, ngx_sock_ntop() might
overread the sockaddr provided, as it used "%s" format and thus assumed
null-terminated string.

To fix this, the ngx_strnlen() function was introduced, and it is now used
to calculate correct length of sun_path.
2017-10-04 21:19:38 +03:00
Maxim Dounin
2e1e65a5c0 Fixed buffer overread with unix sockets after accept().
Some OSes (notably macOS, NetBSD, and Solaris) allow unix socket addresses
larger than struct sockaddr_un.  Moreover, some of them (macOS, Solaris)
return socklen of the socket address before it was truncated to fit the
buffer provided.  As such, on these systems socklen must not be used without
additional check that it is within the buffer provided.

Appropriate checks added to ngx_event_accept() (after accept()),
ngx_event_recvmsg() (after recvmsg()), and ngx_set_inherited_sockets()
(after getsockname()).

We also obtain socket addresses via getsockname() in
ngx_connection_local_sockaddr(), but it does not need any checks as
it is only used for INET and INET6 sockets (as there can be no
wildcard unix sockets).
2017-10-04 21:19:33 +03:00
Valentin Bartenev
328bfbe0d4 HTTP/2: enforce writing the sync request body buffer to file.
The sync flag of HTTP/2 request body buffer is used when the size of request
body is unknown or bigger than configured "client_body_buffer_size".  In this
case the buffer points to body data inside the global receive buffer that is
used for reading all HTTP/2 connections in the worker process.  Thus, when the
sync flag is set, the buffer must be flushed to a temporary file, otherwise
the request body data can be overwritten.

Previously, the sync buffer wasn't flushed to a temporary file if the whole
body was received in one DATA frame with the END_STREAM flag and wasn't
copied into the HTTP/2 body preread buffer.  As a result, the request body
might be corrupted (ticket #1384).

Now, setting r->request_body_in_file_only enforces writing the sync buffer
to a temporary file in all cases.
2017-10-04 21:15:15 +03:00
Maxim Dounin
d07d598c28 Cache: fixed caching of intercepted errors (ticket #1382).
When caching intercepted errors, previous behaviour was to use
proxy_cache_valid times specified, regardless of various cache control
headers present in the response.  Fix is to check u->cacheable and
use u->cache->valid_sec as set by various cache control response headers,
similar to how we do this in the normal caching code path.
2017-10-03 18:19:27 +03:00
Maxim Dounin
105dd42bd7 Upstream: better handling of invalid headers in cache files.
If cache file is truncated, it is possible that u->process_header()
will return NGX_AGAIN.  Added appropriate handling of this case by
changing the error to NGX_HTTP_UPSTREAM_INVALID_HEADER.

Also, added appropriate logging of this and NGX_HTTP_UPSTREAM_INVALID_HEADER
cases at the "crit" level.  Note that this will result in duplicate logging
in case of NGX_HTTP_UPSTREAM_INVALID_HEADER.  While this is something better
to avoid, it is considered to be an overkill to implement cache-specific
error logging in u->process_header().

Additionally, u->buffer.start is now reset to be able to receive a new
response, and u->cache_status set to MISS to provide the value in the
$upstream_cache_status variable, much like it happens on other cache file
errors detected by ngx_http_file_cache_read(), instead of HIT, which is
believed to be misleading.
2017-10-02 19:10:20 +03:00
Ruslan Ermilov
316a34951a Fixed the NGX_UNIX_ADDRSTRLEN macro. 2017-09-25 15:19:24 +03:00
Ruslan Ermilov
e7738ce82d Modules compatibility: down flag promoted to a bitmask.
It is to be used as a bitmask with various bits set/reset when appropriate.
63b8b157b776 made a similar change to ngx_http_upstream_rr_peer_t.down and
ngx_stream_upstream_rr_peer_t.down.
2017-09-22 22:49:42 +03:00
Ruslan Ermilov
ccd7e1037e Style. 2017-09-22 18:37:49 +03:00
Ruslan Ermilov
0cda728c6f Do not use the obsolete NGX_SOCKADDRLEN macro.
The change in ac120e797d28 re-used the macro which was made obsolete
in adf25b8d0431.
2017-09-22 13:10:49 +03:00
Ruslan Ermilov
05e87e19af Removed more remnants of the old pthread implementation.
After e284f3ff6831, ngx_crypt() can no longer return NGX_AGAIN.
2017-09-18 11:09:41 +03:00
Maxim Dounin
99cc4c72c7 HTTP/2: shortened some debug log messages.
This ensures slightly more readable debug logs on 80-character-wide
terminals.
2017-09-14 19:06:06 +03:00
Maxim Dounin
fc1575109e HTTP/2: fixed debug log about indexed headers.
Previously, "get indexed header" message was logged when in fact only
header name was obtained using an index, and "get indexed header name"
was logged when full header representation (name and value) was obtained
using an index.  Fixed version logs "get indexed name" and "get indexed
header" respectively.
2017-09-14 19:06:05 +03:00
Maxim Dounin
8f6c5306fb HTTP/2: added logging of 400 (Bad Request) reasons. 2017-09-14 19:06:03 +03:00
Roman Arutyunyan
c36a3c0cba Stream: fixed logging UDP upstream timeout.
Previously, when the first UDP response packet was not received from the
proxied server within proxy_timeout, no error message was logged before
switching to the next upstream.  Additionally, when one of succeeding response
packets was not received within the timeout, the timeout error had low severity
because it was logged as a client connection error as opposed to upstream
connection error.
2017-09-12 13:44:04 +03:00
Maxim Dounin
b900cc28fc Introduced time truncation to December 31, 9999 (ticket #1368).
Various buffers are allocated in an assumption that there would be
no more than 4 year digits.  This might not be true on platforms
with 64-bit time_t, as 64-bit time_t is able to represent more than that.
Such dates with more than 4 year digits hardly make sense though, as
various date formats in use do not allow them anyway.

As such, all dates are now truncated by ngx_gmtime() to December 31, 9999.
This should have no effect on valid dates, though will prevent potential
buffer overflows on invalid ones.
2017-09-13 15:53:19 +03:00
Maxim Dounin
0206ebe76f Fixed ngx_gmtime() on 32-bit platforms with 64-bit time_t.
In ngx_gmtime(), instead of casting to ngx_uint_t we now work with
time_t directly.  This allows using dates after 2038 on 32-bit platforms
which use 64-bit time_t, notably NetBSD and OpenBSD.

As the code is not able to work with negative time_t values, argument
is now set to 0 for negative values.  As a positive side effect, this
results in Epoch being used for such values instead of a date in distant
future.
2017-09-13 15:52:01 +03:00
Maxim Dounin
53bea399a0 Fixed reference to time parsing code after 8b6fa4842133. 2017-09-13 15:51:58 +03:00
Maxim Dounin
559017768e Style. 2017-09-13 15:51:52 +03:00
Piotr Sikora
63f5d46f58 HTTP/2: signal 0-byte HPACK's dynamic table size.
This change lets NGINX talk to clients with SETTINGS_HEADER_TABLE_SIZE
smaller than the default 4KB. Previously, NGINX would ACK the SETTINGS
frame with a small dynamic table size, but it would never send dynamic
table size update, leading to a connection-level COMPRESSION_ERROR.

Also, it allows clients to release 4KB of memory per connection, since
NGINX doesn't use HPACK's dynamic table when encoding headers, however
clients had to maintain it, since NGINX never signaled that it doesn't
use it.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-08-30 14:52:11 -07:00
Roman Arutyunyan
15f81e0bbf Stream: relaxed next upstream condition (ticket #1317).
When switching to a next upstream, some buffers could be stuck in the middle
of the filter chain.  A condition existed that raised an error when this
happened.  As it turned out, this condition prevented switching to a next
upstream if ssl preread was used with the TCP protocol (see the ticket).

In fact, the condition does not make sense for TCP, since after successful
connection to an upstream switching to another upstream never happens.  As for
UDP, the issue with stuck buffers is unlikely to happen, but is still possible.
Specifically, if a filter delays sending data to upstream.

The condition can be relaxed to only check the "buffered" bitmask of the
upstream connection.  The new condition is simpler and fixes the ticket issue
as well.  Additionally, the upstream_out chain is now reset for UDP prior to
connecting to a new upstream to prevent repeating the client data twice.
2017-09-11 15:32:31 +03:00
Roman Arutyunyan
13e29a65f6 Version bump. 2017-09-11 15:46:23 +03:00
Roman Arutyunyan
418124e219 Secure link: fixed stack buffer overflow.
When secure link checksum has length of 23 or 24 bytes, decoded base64 value
could occupy 17 or 18 bytes which is more than 16 bytes previously allocated
for it on stack.  The buffer overflow does not have any security implications
since only one local variable was corrupted and this variable was not used in
this case.

The fix is to increase buffer size up to 18 bytes.  Useless buffer size
initialization is removed as well.
2017-08-22 21:22:59 +03:00
Maxim Dounin
6a2e409833 Upstream: unconditional parsing of last_modified_time.
This fixes at least the following cases, where no last_modified_time
(assuming caching is not enabled) resulted in incorrect behaviour:

- slice filter and If-Range requests (ticket #1357);
- If-Range requests with proxy_force_ranges;
- expires modified.
2017-08-23 19:20:06 +03:00
Maxim Dounin
ed0cc4d523 SSL: fixed possible use-after-free in $ssl_server_name.
The $ssl_server_name variable used SSL_get_servername() result directly,
but this is not safe: it references a memory allocation in an SSL
session, and this memory might be freed at any time due to renegotiation.
Instead, copy the name to memory allocated from the pool.
2017-08-22 17:36:12 +03:00
Maxim Dounin
50a0f25c60 SSL: the $ssl_client_escaped_cert variable (ticket #857).
This variable contains URL-encoded client SSL certificate.  In contrast
to $ssl_client_cert, it doesn't depend on deprecated header continuation.
The NGX_ESCAPE_URI_COMPONENT variant of encoding is used, so the resulting
variable can be safely used not only in headers, but also as a request
argument.

The $ssl_client_cert variable should be considered deprecated now.
The $ssl_client_raw_cert variable will be eventually renambed back
to $ssl_client_cert.
2017-08-22 15:18:10 +03:00
Maxim Dounin
008e9caa2a Range filter: changed type for total length to off_t.
Total length of a response with multiple ranges can be larger than a size_t
variable can hold, so type changed to off_t.  Previously, an incorrect
Content-Length was returned when requesting more than 4G of ranges from
a large enough file on a 32-bit system.

An additional size_t variable introduced to calculate size of the boundary
header buffer, as off_t is not needed here and will require type casts on
win32.

Reported by Shuxin Yang,
http://mailman.nginx.org/pipermail/nginx/2017-July/054384.html.
2017-08-10 22:21:23 +03:00
Maxim Dounin
dd5ab4a11f Restored ngx_event_aio_t layout for debug logging.
The "fd" field should be after 3 pointers for ngx_event_ident() to use it.
This was broken by ccad84a174e0.  While it does not seem to be currently used
for aio-related events, it should be a good idea to preserve the correct
layout nevertheless.
2017-08-10 22:21:22 +03:00
Maxim Dounin
0f841fcdee Style. 2017-08-10 22:21:20 +03:00
Sergey Kandaurov
b986b4314b Fixed calls to ngx_open_file() in certain places.
Pass NGX_FILE_OPEN to ngx_open_file() to fix "The parameter is incorrect"
error on win32 when using the ssl_session_ticket_key directive or loading
a binary geo base.  On UNIX, this change is a no-op.
2017-08-09 15:03:27 +03:00
Sergey Kandaurov
32c7bd5102 Style. 2017-08-09 14:59:46 +03:00
Sergey Kandaurov
c7c13a21ad Version bump. 2017-08-09 14:59:44 +03:00
Ruslan Ermilov
5f628fef3b Slab: fixed initialization on win32.
On Windows, a worker process does not call ngx_slab_init() from
ngx_init_zone_pool(), so ngx_slab_max_size, ngx_slab_exact_size,
and ngx_slab_exact_shift were left uninitialized.
2017-08-08 15:16:01 +03:00
Ruslan Ermilov
c9a81b29b5 Upstream: copy peer data in shared memory.
This, in addition to 1eb753aa8e5e, fixes "upstream zone" on Windows.
2017-08-04 17:03:10 +03:00
Ruslan Ermilov
c09bba400d Referer: fixed $invalid_referer.
The variable was considered non-existent in the absence of any
valid_referers directives.

Given the following config snippet,

    location / {
        return 200 $invalid_referer;
    }

    location /referer {
        valid_referers server_names;
    }

"location /" should work identically and independently on other
"location /referer".

The fix is to always add the $invalid_referer variable as long
as the module is compiled in, as is done by other modules.
2017-08-04 08:01:55 +03:00
Ruslan Ermilov
d846f27638 Upstream zone: store peers->name and its data in shared memory.
The shared objects should generally be allocated from shared memory.
While peers->name and the data it points to allocated from cf->pool
happened to work on UNIX, it broke on Windows.  On UNIX this worked
only because the shared memory zone for upstreams is re-created for
every new configuration.

But on Windows, a worker process does not inherit the address space
of the master process, so the peers->name pointed to data allocated
from cf->pool by the master process, and was invalid.
2017-08-01 19:12:10 +03:00
Ruslan Ermilov
b992f7259b Variables: macros for null variables.
No functional changes.
2017-08-01 14:28:33 +03:00
Ruslan Ermilov
83be971bc7 Browser: style.
Removed custom variable type and renamed function that adds variables.
2017-08-01 14:27:23 +03:00
Ruslan Ermilov
aa953f5346 Cache: fixed max_size on win32. 2017-07-26 13:13:51 +03:00
Sergey Kandaurov
9edd64fcd8 SSL: fixed typo in the error message. 2017-07-25 17:21:59 +03:00
Roman Arutyunyan
fb18ba2930 Mirror: "off" paramater of the "mirror" directive. 2017-07-21 19:47:56 +03:00
Roman Arutyunyan
3900d1cb3c Mirror module. 2017-07-20 08:50:49 +03:00
Roman Arutyunyan
129b06dc5d Precontent phase.
The phase is added instead of the try_files phase.  Unlike the old phase, the
new one supports registering multiple handlers.  The try_files implementation is
moved to a separate ngx_http_try_files_module, which now registers a precontent
phase handler.
2017-07-20 15:51:11 +03:00
Roman Arutyunyan
a87e05a331 Upstream: keep request body file from removal if requested.
The new request flag "preserve_body" indicates that the request body file should
not be removed by the upstream module because it may be used later by a
subrequest.  The flag is set by the SSI (ticket #585), addition and slice
modules.  Additionally, it is also set by the upstream module when a background
cache update subrequest is started to prevent the request body file removal
after an internal redirect.  Only the main request is now allowed to remove the
file.
2017-07-19 20:38:17 +03:00
Alex Zhang
2c8f93df87 Style.
Signed-off-by: Alex Zhang <zchao1995@gmail.com>
2017-07-19 21:39:40 +08:00
Valentin Bartenev
9197a3c874 Parenthesized ASCII-related calculations.
This also fixes potential undefined behaviour in the range and slice filter
modules, caused by local overflows of signed integers in expressions.
2017-07-17 17:23:51 +03:00
Ruslan Ermilov
7b06d9c326 Style: aligned ngx_null_command. 2017-07-12 11:34:04 +03:00
Maxim Dounin
bedd9c5645 Core: fixed error message on setsockopt(SO_REUSEPORT) failure.
The error is fatal when configuring a new socket, so the ", ignored" part
is not appropriate and was removed.
2017-07-11 20:06:52 +03:00
Maxim Dounin
da165aae88 Core: disabled SO_REUSEPORT when testing config (ticket #1300).
When closing a socket with SO_REUSEPORT, Linux drops all connections waiting
in this socket's listen queue.  Previously, it was believed to only result
in connection resets when reconfiguring nginx to use smaller number of worker
processes.  It also results in connection resets during configuration
testing though.

Workaround is to avoid using SO_REUSEPORT when testing configuration.  It
should prevent listening sockets from being created if a conflicting socket
already exists, while still preserving detection of other possible errors.
It should also cover UDP sockets.

The only downside of this approach seems to be that a configuration testing
won't be able to properly report the case when nginx was compiled with
SO_REUSEPORT, but the kernel is not able to set it.  Such errors will be
reported on a real start instead.
2017-07-11 19:59:56 +03:00
Maxim Dounin
5a5e74082d Version bump. 2017-07-11 19:59:16 +03:00
Maxim Dounin
d289616b0f Range filter: avoid negative range start.
Suffix ranges no longer allowed to set negative start values, to prevent
ranges with negative start from appearing even if total size protection
will be removed.
2017-07-11 16:06:26 +03:00
Maxim Dounin
92111c92e5 Range filter: protect from total size overflows.
The overflow can be used to circumvent the restriction on total size of
ranges introduced in c2a91088b0c0 (1.1.2).  Additionally, overflow
allows producing ranges with negative start (such ranges can be created
by using a suffix, "bytes=-100"; normally this results in 200 due to
the total size check).  These can result in the following errors in logs:

[crit] ... pread() ... failed (22: Invalid argument)
[alert] ... sendfile() failed (22: Invalid argument)

When using cache, it can be also used to reveal cache file header.
It is believed that there are no other negative effects, at least with
standard nginx modules.

In theory, this can also result in memory disclosure and/or segmentation
faults if multiple ranges are allowed, and the response is returned in a
single in-memory buffer.  This never happens with standard nginx modules
though, as well as known 3rd party modules.

Fix is to properly protect from possible overflow when incrementing size.
2017-07-11 16:06:23 +03:00
Ruslan Ermilov
a54e3193bf Variables: use ngx_http_variable_null_value where appropriate. 2017-07-07 14:34:21 +03:00
Ruslan Ermilov
6330817a96 Resolver: cancelable resend timer event.
It is safe because re-sending still works during graceful shutdown as
long as resolving takes place (and resolve tasks set their own timeouts
that are not cancelable).

Also, the new ctx->cancelable flag can be set to make resolve task's
timeout event cancelable.
2017-07-04 18:50:41 +03:00
Sergey Kandaurov
225a5c7704 Resolver: factored out setting a timer for resolver timeout.
No functional changes.
2017-07-04 18:46:30 +03:00
Ruslan Ermilov
d0071f08e8 Slab: fixed small allocations on systems with large pagesize.
Notably, on ppc64 with 64k pagesize, slab 0 (of size 8) requires
128 64-bit elements for bitmasks.  The code bogusly assumed that
one uintptr_t is enough for bitmasks plus at least one free slot.
2017-07-04 18:32:30 +03:00
Ruslan Ermilov
75c3f8958b Slab: style. 2017-07-04 18:32:28 +03:00
Roman Arutyunyan
7570718594 Resolver: fixed possible use-after-free while resolving SRV.
Resolving an SRV record includes resolving its host names in subrequests.
Previously, if memory allocation failed while reporting a subrequest result
after receiving a response from a DNS server, the SRV resolve handler was
called immediately with the NGX_ERROR state.  However, if the SRV record
included another copy of the resolved name, it was reported once again.
This could trigger the use-after-free memory access after SRV resolve
handler freed the resolve context by calling ngx_resolve_name_done().

Now the SRV resolve handler is called only when all its subrequests are
completed.
2017-07-04 18:07:29 +03:00
Piotr Sikora
32e3d0e693 Proxy: split configured header names and values.
Previously, each configured header was represented in one of two ways,
depending on whether or not its value included any variables.

If the value didn't include any variables, then it would be represented
as as a single script that contained complete header line with HTTP/1.1
delimiters, i.e.:

     "Header: value\r\n"

But if the value included any variables, then it would be represented
as a series of three scripts: first contained header name and the ": "
delimiter, second evaluated to header value, and third contained only
"\r\n", i.e.:

     "Header: "
     "$value"
     "\r\n"

This commit changes that, so that each configured header is represented
as a series of two scripts: first contains only header name, and second
contains (or evaluates to) only header value, i.e.:

    "Header"
    "$value"

or

    "Header"
    "value"

This not only makes things more consistent, but also allows header name
and value to be accessed separately.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-15 15:55:35 -07:00
Maxim Dounin
3057fca368 Version bump. 2017-07-03 16:58:08 +03:00
Maxim Dounin
774f179a9b Range filter: allowed ranges on empty files (ticket #1031).
As per RFC 2616 / RFC 7233, any range request to an empty file
is expected to result in 416 Range Not Satisfiable response, as
there cannot be a "byte-range-spec whose first-byte-pos is less
than the current length of the entity-body".  On the other hand,
this makes use of byte-range requests inconvenient in some cases,
as reported for the slice module here:

http://mailman.nginx.org/pipermail/nginx-devel/2017-June/010177.html

This commit changes range filter to instead return 200 if the file
is empty and the range requested starts at 0.
2017-06-27 00:53:46 +03:00
Maxim Dounin
6433c841a0 Upstream: introduced ngx_http_upstream_ssl_handshake_handler().
This change reworks 13a5f4765887 to only run posted requests once,
with nothing on stack.  Running posted requests with other request
functions on stack may result in use-after-free in case of errors,
similar to the one reported in #788.

To only run posted request once, a separate function was introduced
to be used as ssl handshake handler in c->ssl->handler,
ngx_http_upstream_ssl_handshake_handler().  The ngx_http_run_posted_requests()
is only called in this function, and not in ngx_http_upstream_ssl_handshake()
which may be called directly on stack.

Additionaly, ngx_http_upstream_ssl_handshake_handler() now does appropriate
debug logging of the current subrequest, similar to what is done in other
event handlers.
2017-06-22 21:09:06 +03:00
Roman Arutyunyan
efa61f42c1 Upstream: fixed running posted requests (ticket #788).
Previously, the upstream resolve handler always called
ngx_http_run_posted_requests() to run posted requests after processing the
resolver response.  However, if the handler was called directly from the
ngx_resolve_name() function (for example, if the resolver response was cached),
running posted requests from the handler could lead to the following errors:

- If the request was scheduled for termination, it could actually be terminated
in the resolve handler.  Upper stack frames could reference the freed request
object in this case.

- If a significant number of requests were posted, and for each of them the
resolve handler was called directly from the ngx_resolve_name() function,
posted requests could be run recursively and lead to stack overflow.

Now ngx_http_run_posted_requests() is only called from asynchronously invoked
resolve handlers.
2017-06-14 20:13:41 +03:00
Roman Arutyunyan
439e205255 Resolver: added the "async" flag to resolver context.
The flag indicates that the resolve handler is called asynchronously after the
resolve function ngx_resolve_name()/ngx_resolve_addr() exited.
2017-06-14 18:13:31 +03:00
Bart Warmerdam
b0b24e8a30 Resolver: fixed allocation error handling while resolving SRV. 2017-06-19 14:25:42 +03:00
Ruslan Ermilov
6a4a1f0e23 Introduced ngx_rwlock_downgrade(). 2017-06-16 18:15:58 +03:00
Ruslan Ermilov
3f26c20756 Added memory barrier semantics to ngx_rwlock_unlock(). 2017-06-16 18:15:53 +03:00
Piotr Sikora
8310d81dc7 Headers filter: added "add_trailer" directive.
Trailers added using this directive are evaluated after response body
is processed by output filters (but before it's written to the wire),
so it's possible to use variables calculated from the response body
as the trailer value.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-24 03:37:34 -07:00
Piotr Sikora
d85f2f9e92 HTTP/2: added support for trailers in HTTP responses.
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-24 03:37:34 -07:00
Piotr Sikora
cfdce50657 Added support for trailers in HTTP responses.
Example:

   ngx_table_elt_t  *h;

   h = ngx_list_push(&r->headers_out.trailers);
   if (h == NULL) {
       return NGX_ERROR;
   }

   ngx_str_set(&h->key, "Fun");
   ngx_str_set(&h->value, "with trailers");
   h->hash = ngx_hash_key_lc(h->key.data, h->key.len);

The code above adds "Fun: with trailers" trailer to the response.

Modules that want to emit trailers must set r->expect_trailers = 1
in header filter, otherwise they might not be emitted for HTTP/1.1
responses that aren't already chunked.

This change also adds $sent_trailer_* variables.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-24 03:37:34 -07:00
Ruslan Ermilov
fa0992ed29 Gzip: fixed style in $gzip_ratio variable handler.
The current style in variable handlers returning NGX_OK is to either set
v->not_found to 1, or to initialize the entire ngx_http_variable_value_t
structure.

In theory, always setting v->valid = 1 for NGX_OK would be useful, which
would mean that the value was computed and is thus valid, including the
special case of v->not_found = 1.  But currently that's not the case and
causes the (v->valid || v->not_found) check to access an uninitialized
v->valid value, which is safe only because its value doesn't matter when
v->not_found is set.
2017-06-14 12:49:20 +03:00
Ruslan Ermilov
731d1fee8a Removed excessive casts for ngx_file_info(). 2017-06-14 12:29:52 +03:00
Piotr Sikora
13f49b0013 HTTP/2: reject HTTP/2 requests without ":scheme" pseudo-header.
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-06-13 17:01:08 +03:00
Sergey Kandaurov
aa04b091ae Userid: ngx_http_get_indexed_variable() error handling.
When evaluating a mapped $reset_uid variable in the userid filter,
if get_handler set to ngx_http_map_variable() returned an error,
this previously resulted in a NULL pointer dereference.
2017-06-07 18:46:36 +03:00
Sergey Kandaurov
b0de3d7013 Fixed segfault in try_files with nested location.
If memory allocation of a new r->uri.data storage failed, reset its length as
well.  Request URI is used in ngx_http_finalize_request() for debug logging.
2017-06-07 18:46:35 +03:00
Sergey Kandaurov
dec513d6e4 SSI: return NGX_ERROR when timefmt memory allocation failed.
Previously, when using NGX_HTTP_SSI_ERROR, error was ignored in ssi processing,
thus timefmt could be accessed later in ngx_http_ssi_date_gmt_local_variable()
as part of "set" handler, or NULL format pointer could be passed to strftime().
2017-06-07 15:21:42 +03:00
Piotr Sikora
51a4a414ca HTTP/2: don't send SETTINGS ACK before already queued DATA frames.
Previously, SETTINGS ACK was sent immediately upon receipt of SETTINGS
frame, before already queued DATA frames created using old SETTINGS.

This incorrect behavior was source of interoperability issues, because
peers rely on the fact that new SETTINGS are in effect after receiving
SETTINGS ACK.

Reported by Feng Li.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-06-02 15:05:32 +03:00
Piotr Sikora
ca53600ac0 HTTP/2: make SETTINGS ACK frame reusable.
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-06-02 15:05:28 +03:00
Piotr Sikora
1429139c57 HTTP/2: send SETTINGS ACK after applying all SETTINGS params.
This avoids sending unnecessary SETTINGS ACK in case of PROTOCOL_ERROR.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-06-02 15:05:24 +03:00
Piotr Sikora
6cfc65c993 HTTP/2: emit new frames only after applying all SETTINGS params.
Previously, new frames could be emitted in the middle of applying
new (and already acknowledged) SETTINGS params, which is illegal.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-06-02 15:05:20 +03:00
Maxim Dounin
62a95ace42 Style. 2017-06-01 16:49:14 +03:00
Piotr Sikora
a9908c9685 Upstream: style.
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-05-31 13:51:36 -07:00
Piotr Sikora
7820e569af Headers filter: style.
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-05-31 13:51:35 -07:00
Piotr Sikora
95955b7c04 HTTP/2: add debug logging of pseudo-headers and cookies.
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-05-30 17:42:27 +03:00
Valentin Bartenev
92cc3059fe Version bump. 2017-05-30 19:29:45 +03:00
Roman Arutyunyan
d1d48ed844 Fixed background requests with asynchronous operations.
If the main request was finalized while a background request performed an
asynchronous operation, the main request ended up in ngx_http_writer() and was
not finalized until a network event or a timeout.  For example, cache
background update with aio enabled made nginx unable to process further client
requests or close the connection, keeping it open until client closes it.

Now regular finalization of the main request is not suspended because of an
asynchronous operation in another request.

If a background request was terminated while an asynchronous operation was in
progress, background request's write event handler was changed to
ngx_http_request_finalizer() and never called again.

Now, whenever a request is terminated while an asynchronous operation is in
progress, connection error flag is set to make further finalizations of any
request with this connection lead to termination.

These issues appeared in 1aeaae6e9446 (not yet released).
2017-05-29 23:33:38 +03:00
Maxim Dounin
0514e14a8b Style: changed checks of ngx_ssl_create_connection() to != NGX_OK.
In http these checks were changed in a6d6d762c554, though mail module
was missed at that time.  Since then, the stream module was introduced
based on mail, using "== NGX_ERROR" check.
2017-05-29 16:34:35 +03:00
Maxim Dounin
2db69fed2c SSL: set TCP_NODELAY on SSL connections before handshake.
With OpenSSL 1.1.0+, the workaround for handshake buffer size as introduced
in a720f0b0e083 (ticket #413) no longer works, as OpenSSL no longer exposes
handshake buffers, see https://github.com/openssl/openssl/commit/2e7dc7cd688.
Moreover, it is no longer possible to adjust handshake buffers at all now.

To avoid additional RTT if handshake uses more than 4k we now set TCP_NODELAY
on SSL connections before handshake.  While this still results in sub-optimal
network utilization due to incomplete packets being sent, it seems to be
better than nothing.
2017-05-29 16:34:29 +03:00
Ruslan Ermilov
b66c18d2d5 Introduced ngx_tcp_nodelay(). 2017-05-26 22:52:48 +03:00
Roman Arutyunyan
8644d9491a Background subrequests for cache updates.
Previously, cache background update might not work as expected, making client
wait for it to complete before receiving the final part of a stale response.
This could happen if the response could not be sent to the client socket in one
filter chain call.

Now background cache update is done in a background subrequest.  This type of
subrequest does not block any other subrequests or the main request.
2017-05-25 15:57:59 +03:00
Roman Arutyunyan
c83922b18d Fixed deferred accept with EPOLLRDHUP enabled (ticket #1278).
Previously, the read event of the accepted connection was marked ready, but not
available.  This made EPOLLRDHUP-related code (for example, in ngx_unix_recv())
expect more data from the socket, leading to unexpected behavior.

For example, if SSL, PROXY protocol and deferred accept were enabled on a listen
socket, the client connection was aborted due to unexpected return value of
c->recv().
2017-05-24 13:17:08 +03:00
Valentin Bartenev
cce3934461 HTTP/2: fixed segfault when memory allocation failed.
If allocation of cleanup handler in the HTTP/2 header filter failed, then
a stream might be freed with a HEADERS frame left in the output queue.

Now the HEADERS frame is accounted in the queue before trying to allocate
the cleanup handler.
2017-05-23 20:19:39 +03:00
Dmitry Volyntsev
c6df6bf923 Cache: ignore long locked entries during forced expire.
Abnormally exited workers may leave locked cache entries, this can
result in the cache size on disk exceeding max_size and shared memory
exhaustion.

This change mitigates the issue by ignoring locked entries during forced
expire.  It also increases the visibility of the problem by logging such
entries.
2017-05-18 18:39:16 +03:00
Sergey Kandaurov
9359155b2f Upstream: fixed u->headers_in.headers allocation error handling.
Previously, an allocation error resulted in uninitialized memory access
when evaluating $upstream_http_ variables.

On a related note, see r->headers_out.headers cleanup work in 0cdee26605f3.
2017-05-18 14:17:00 +03:00
Ruslan Ermilov
a464d07f0a Realip: allow hostnames in set_real_ip_from (ticket #1180). 2017-05-15 17:17:01 +03:00
Ruslan Ermilov
b313bc4bd3 Access: simplified rule parser code. 2017-05-15 17:16:32 +03:00
Sergey Kandaurov
9961198879 SSL: allowed renegotiation in client mode with OpenSSL < 1.1.0.
In ac9b1df5b246 (1.13.0) we attempted to allow renegotiation in client mode,
but when using OpenSSL 1.0.2 or older versions it was additionally disabled
by SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS.
2017-05-03 15:15:56 +03:00
Maxim Dounin
8449f750e6 Added missing "fall through" comments (ticket #1259).
Found by gcc7 (-Wimplicit-fallthrough).
2017-04-27 16:57:18 +03:00
Ruslan Ermilov
8ae2bc9320 Don't pretend we support HTTP major versions >1 as HTTP/1.1. 2017-04-25 23:39:13 +03:00
Ruslan Ermilov
53e63ff7c3 Version bump. 2017-04-25 23:39:06 +03:00
Valentin Bartenev
55b37eff8f HTTP/2: reduced difference to HTTP/1.x in reading request body.
Particularly, this eliminates difference in behavior for requests without body
and deduplicates code.

Prodded by Piotr Sikora.
2017-04-24 14:17:13 +03:00
Valentin Bartenev
d35c83a325 HTTP/2: rejecting zero WINDOW_UPDATE with PROTOCOL_ERROR.
It's required by RFC 7540.  While there is no real harm from such frames,
that should help to detect broken clients.

Based on a patch by Piotr Sikora.
2017-04-24 14:16:57 +03:00
Sergey Kandaurov
beaaeb9f9e Gzip static: use an appropriate error on memory allocation failure. 2017-04-20 18:26:38 +03:00
Sergey Kandaurov
9ecf842864 Cleaned up r->headers_out.headers allocation error handling.
If initialization of a header failed for some reason after ngx_list_push(),
leaving the header as is can result in uninitialized memory access by
the header filter or the log module.  The fix is to clear partially
initialized headers in case of errors.

For the Cache-Control header, the fix is to postpone pushing
r->headers_out.cache_control until its value is completed.
2017-04-20 18:26:37 +03:00
Igor Sysoev
30e26a8c57 Core: signal sender pid logging. 2017-04-20 13:58:16 +03:00
Sergey Kandaurov
cb7427d86c Sub filter: restored ngx_http_set_ctx() at the proper place.
Previously, ngx_http_sub_header_filter() could fail with a partially
initialized context, later accessed in ngx_http_sub_body_filter()
if called from the perl content handler.

The issue had appeared in 2c045e5b8291 (1.9.4).

A better fix would be to handle ngx_http_send_header() errors in
the perl module, though this doesn't seem to be easy enough.
2017-04-18 19:55:23 +03:00
Sergey Kandaurov
e8c579a187 SSL: compatibility with OpenSSL master branch.
The SSL_CTRL_SET_CURVES_LIST macro is removed in the OpenSSL master branch.
SSL_CTX_set1_curves_list is preserved as compatibility with previous versions.
2017-04-18 16:08:46 +03:00
Sergey Kandaurov
36be79301e SSL: disabled renegotiation detection in client mode.
CVE-2009-3555 is no longer relevant and mitigated by the renegotiation
info extension (secure renegotiation).  On the other hand, unexpected
renegotiation still introduces potential security risks, and hence we do
not allow renegotiation on the server side, as we never request renegotiation.

On the client side the situation is different though.  There are backends
which explicitly request renegotiation, and disabled renegotiation
introduces interoperability problems.  This change allows renegotiation
on the client side, and fixes interoperability problems as observed with
such backends (ticket #872).

Additionally, with TLSv1.3 the SSL_CB_HANDSHAKE_START flag is currently set
by OpenSSL when receiving a NewSessionTicket message, and was detected by
nginx as a renegotiation attempt.  This looks like a bug in OpenSSL, though
this change also allows better interoperability till the problem is fixed.
2017-04-18 16:08:44 +03:00
Sergey Kandaurov
9a37eb3a62 SSL: added support for TLSv1.3 in ssl_protocols directive.
Support for the TLSv1.3 protocol will be introduced in OpenSSL 1.1.1.
2017-04-18 15:12:38 +03:00
Roman Arutyunyan
05841adfb2 Set UDP datagram source address (ticket #1239).
Previously, the source IP address of a response UDP datagram could differ from
the original datagram destination address.  This could happen if the server UDP
socket is bound to a wildcard address and the network interface chosen to output
the response packet has a different default address than the destination address
of the original packet.  For example, if two addresses from the same network are
configured on an interface.

Now source address is set explicitly if a response is sent for a server UDP
socket bound to a wildcard address.
2017-04-11 16:41:53 +03:00
Sergey Kandaurov
62b20ce87a Core: removed extra ngx_alloc() and ngx_calloc() prototypes. 2017-04-18 13:01:19 +03:00
Sergey Kandaurov
97210c717d Enabled IPV6_RECVPKTINFO / IPV6_PKTINFO on macOS.
This change allows setting the destination IPv6 address of a UDP datagram
received on a wildcard socket.
2017-04-17 14:42:12 +03:00
Simon Leblanc
8ee2de5e9c Added support for the "308 Permanent Redirect" (ticket #877). 2017-04-11 03:13:46 +02:00
Vladimir Homutov
a965e1d766 Mail: configurable socket buffer sizes.
The "rcvbuf" and "sndbuf" parameters are now supported by
the "listen" directive.
2017-04-03 17:30:34 +03:00
Vladimir Homutov
9f7b557673 Stream: configurable socket buffer sizes.
The "rcvbuf" and "sndbuf" parameters are now supported by
the "listen" directive.
2017-04-03 17:29:19 +03:00
Valentin Bartenev
97cb30370f Core: improved JSON escaping.
Two-character representations are now used for \b, \f, \n, \r, and \t.
2017-04-12 22:47:57 +03:00
Ruslan Ermilov
cac361718c Use ngx_calloc_buf() where appropriate. 2017-04-12 22:21:04 +03:00
Ruslan Ermilov
f947167442 Version bump. 2017-04-12 22:14:24 +03:00
Piotr Sikora
ca1a5057e2 Upstream: allow recovery from "429 Too Many Requests" response.
This change adds "http_429" parameter to "proxy_next_upstream" for
retrying rate-limited requests, and to "proxy_cache_use_stale" for
serving stale cached responses after being rate-limited.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-24 02:48:03 -07:00
Piotr Sikora
c3ce606652 Added support for "429 Too Many Requests" response (RFC6585).
This change adds reason phrase in status line and pretty response body
when "429" status code is used in "return", "limit_conn_status" and/or
"limit_req_status" directives.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-24 02:48:03 -07:00
hucongcong
9ac9fe2f3e Fixed type. 2017-04-03 14:29:40 +08:00
Roman Arutyunyan
c31239ffb4 Slice filter: prevented slice redirection (ticket #1219).
When a slice subrequest was redirected to a new location, its context was lost.
After its completion, a new slice subrequest for the same slice was created.
This could lead to infinite loop.  Now the slice module makes sure each slice
subrequest starts output with the slice context available.
2017-03-31 21:47:56 +03:00
Roman Arutyunyan
8c9a66298c Slice filter: allowed at most one subrequest at a time.
Previously, if slice main request write handler was called while a slice
subrequest was running, a new subrequest for the same slice was started.
2017-03-28 14:03:57 +03:00
Maxim Dounin
5d5f0dcac4 Moved handling of wev->delayed to the connection event handler.
With post_action or subrequests, it is possible that the timer set for
wev->delayed will expire while the active subrequest write event handler
is not ready to handle this.  This results in request hangs as observed
with limit_rate / sendfile_max_chunk and post_action (ticket #776) or
subrequests (ticket #1228).

Moving the handling to the connection event handler fixes the hangs observed,
and also slightly simplifies the code.
2017-04-02 14:32:29 +03:00
Maxim Dounin
96e4e84ce2 Perl: fixed delaying subrequests.
Much like in limit_req, use the wev->delayed flag to ensure proper handling
and interoperability with limit_rate.
2017-04-02 14:32:28 +03:00
Maxim Dounin
fae6878f20 Limit req: fixed delaying subrequests.
Since limit_req uses connection's write event to delay request processing,
it can conflict with timers in other subrequests.  In particular, even
if applied to an active subrequest, it can break things if wev->delayed
is already set (due to limit_rate or sendfile_max_chunk), since after
limit_req finishes the wev->delayed flag will be set and no timer will be
active.

Fix is to use the wev->delayed flag in limit_req as well.  This ensures that
wev->delayed won't be set after limit_req finishes, and also ensures that
limit_req's timers will be properly handled by other subrequests if the one
delayed by limit_req is not active.
2017-04-02 14:32:26 +03:00
Piotr Sikora
679bd07b42 HTTP/2: style and typos.
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-26 01:25:01 -07:00
Valentin Bartenev
0a5e969dd0 HTTP/2: fixed connection finalization.
All streams in connection must be finalized before the connection
itself can be finalized and all related memory is freed.  That's
not always possible on the current event loop iteration.

Thus when the last stream is finalized, it sets the special read
event handler ngx_http_v2_handle_connection_handler() and posts
the event.

Previously, this handler didn't check the connection state and
could call the regular event handler on a connection that was
already in finalization stage.  In the worst case that could
lead to a segmentation fault, since some data structures aren't
supposed to be used during connection finalization.  Particularly,
the waiting queue can contain already freed streams, so the
WINDOW_UPDATE frame received by that moment could trigger
accessing to these freed streams.

Now, the connection error flag is explicitly checked in
ngx_http_v2_handle_connection_handler().
2017-03-29 20:21:01 +03:00
Valentin Bartenev
e825598266 HTTP/2: fixed stream finalization.
In order to finalize stream the error flag is set on fake connection and
either "write" or "read" event handler is called.  The read events of fake
connections are always ready, but it's not the case with the write events.

When the ready flag isn't set, the error flag can be not checked in some
cases and as a result stream isn't finalized.  Now the ready flag is
explicilty set on write events for proper finalization in all cases.
2017-03-29 20:16:23 +03:00
Piotr Sikora
239e5ac063 HTTP/2: emit PROTOCOL_ERROR on padding errors.
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-26 01:25:05 -07:00
Piotr Sikora
f2393f8fef HTTP/2: fix flow control with padded DATA frames.
Previously, flow control didn't account for padding in DATA frames,
which meant that its view of the world could drift from peer's view
by up to 256 bytes per received padded DATA frame, which could lead
to a deadlock.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-26 01:25:04 -07:00
Piotr Sikora
d2008dbc7d HTTP/2: fix $body_bytes_sent variable.
Previously, its value included payloads and frame headers of HEADERS
and CONTINUATION frames.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-26 01:25:03 -07:00
Piotr Sikora
1506e438cb HTTP/2: fix $bytes_sent variable.
Previously, its value accounted for payloads of HEADERS, CONTINUATION
and DATA frames, as well as frame headers of HEADERS and DATA frames,
but it didn't account for frame headers of CONTINUATION frames.

Signed-off-by: Piotr Sikora <piotrsikora@google.com>
2017-03-26 01:25:02 -07:00
Maxim Dounin
1f76260583 Copy filter: wake up subrequests after aio operations.
Previously, connection write handler was called, resulting in wake up
of the active subrequest.  This change makes it possible to read data
in non-active subrequests as well.  For example, this allows SSI to
process instructions in non-active subrequests earlier and start
additional subrequests if needed, reducing overall response time.
2017-03-28 18:15:42 +03:00
Maxim Dounin
a450865b5a Threads: fixed request hang with aio_write and subrequests.
If the subrequest is already finalized, the handler set with aio_write
may still be used by sendfile in threads when using range requests
(see also e4c1f5b32868, and the original note in 9fd738b85fad).  Calling
already finalized subrequest's r->write_event_handler in practice
results in request hang in some cases.

Fix is to trigger connection event handler if the subrequest was already
finalized.
2017-03-28 18:15:41 +03:00
Maxim Dounin
ff33d9fa55 Simplified and improved sendfile() code on Linux.
The ngx_linux_sendfile() function is now used for both normal sendfile()
and sendfile in threads.  The ngx_linux_sendfile_thread() function was
modified to use the same interface as ngx_linux_sendfile(), and is simply
called from ngx_linux_sendfile() when threads are enabled.

Special return code NGX_DONE is used to indicate that a thread task was
posted and no further actions are needed.

If number of bytes sent is less that what we were sending, we now always
retry sending.  This is needed for sendfile() in threads as the number
of bytes we are sending might have been changed since the thread task
was posted.  And this is also needed for Linux 4.3+, as sendfile() might
be interrupted at any time and provides no indication if it was interrupted
or not (ticket #1174).
2017-03-28 18:15:39 +03:00
Sergey Kandaurov
9ad18e43ac Fixed ngx_open_cached_file() error handling.
If of.err is 0, it means that there was a memory allocation error
and no further logging and/or processing is needed.  The of.failed
string can be only accessed if of.err is not 0.
2017-03-28 14:21:38 +03:00
Ruslan Ermilov
eb017e75cf Core: set nginx_shared_zone name via ngx_str_set(). 2017-03-28 11:28:51 +03:00
Ruslan Ermilov
65f0ad22fa Use ngx_array_init() to initialize arrays. 2017-03-28 11:28:42 +03:00
Ruslan Ermilov
3d5cebe0f5 Version bump. 2017-03-28 11:28:36 +03:00
Maxim Dounin
77bac4d57c Fixed CPU hog while freeing hc->busy after e662cbf1b932 (1.11.11).
Reported by Richard Stanway,
http://mailman.nginx.org/pipermail/nginx/2017-March/053296.html.
2017-03-24 16:26:12 +03:00
Ruslan Ermilov
e81ad21fea Simplified code about duplicate root/alias directive. 2017-03-22 23:36:35 +03:00