diff --git a/README.markdown b/README.markdown index 171a1e24ea..45a8592f96 100644 --- a/README.markdown +++ b/README.markdown @@ -3873,7 +3873,11 @@ This directive controls whether to check for premature client connection abortio When this directive is on, the ngx_lua module will monitor the premature connection close event on the downstream connections and when there is such an event, it will call the user Lua function callback (registered by [ngx.on_abort](#ngxon_abort)) or just stop and clean up all the Lua "light threads" running in the current request's request handler when there is no user callback function registered. -According to the current implementation, however, if the client closes the connection before the Lua code finishes reading the request body data via [ngx.req.socket](#ngxreqsocket), then ngx_lua will neither stop all the running "light threads" nor call the user callback (if [ngx.on_abort](#ngxon_abort) has been called). Instead, the reading operation on [ngx.req.socket](#ngxreqsocket) will just return the error message "client aborted" as the second return value (the first return value is surely `nil`). +If the client disconnects during a pending [ngx.req.socket](#ngxreqsocket) body read, the read returns `nil` with the error `"client aborted"`. The other light threads continue running. + +If Lua cancels the pending body read first, client-abort monitoring resumes. A later disconnect invokes the registered callback or, if none was registered, stops the request's light threads. This also applies when additional body bytes arrive between cancellation and disconnect. + +For pipelined HTTPS requests, the monitor can detect a TLS `close_notify` even when the next request exactly fills the header buffer. If more application data follows, it stays available for the next request. A TLS close notification behind those unread bytes becomes visible when nginx reads them. When TCP keepalive is disabled, it is relying on the client side to close the socket gracefully (by sending a `FIN` packet or something like that). For (soft) real-time web applications, it is highly recommended to configure the [TCP keepalive](http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) support in your system's TCP stack implementation in order to detect "half-open" TCP connections in time. diff --git a/config b/config index 6de049665d..4aed4f7643 100644 --- a/config +++ b/config @@ -419,6 +419,20 @@ ngx_feature_test='setsockopt(1, SOL_SOCKET, SO_PASSCRED, NULL, 0);' # ---------------------------------------- +if [ "$NGX_PLATFORM" != win32 ]; then + ngx_feature="poll() for downstream socket hangups" + ngx_feature_name=NGX_HTTP_LUA_HAVE_POLL + ngx_feature_run=no + ngx_feature_incs="#include " + ngx_feature_path= + ngx_feature_libs= + ngx_feature_test='struct pollfd pfd = { -1, 0, 0 }; + (void) poll(&pfd, 1, 0);' + . auto/feature +fi + +# ---------------------------------------- + ngx_feature="SA_RESTART" ngx_feature_libs= ngx_feature_name="NGX_HTTP_LUA_HAVE_SA_RESTART" diff --git a/src/ngx_http_lua_accessby.c b/src/ngx_http_lua_accessby.c index fcab72ccbf..ba408a383c 100644 --- a/src/ngx_http_lua_accessby.c +++ b/src/ngx_http_lua_accessby.c @@ -248,13 +248,10 @@ ngx_http_lua_access_by_chunk(lua_State *L, ngx_http_request_t *r) ngx_int_t rc; ngx_uint_t nreqs; lua_State *co; - ngx_event_t *rev; ngx_connection_t *c; ngx_http_lua_ctx_t *ctx; ngx_pool_cleanup_t *cln; - ngx_http_lua_loc_conf_t *llcf; - /* {{{ new coroutine to handle request */ co = ngx_http_lua_new_thread(r, L, &co_ref); @@ -317,29 +314,8 @@ ngx_http_lua_access_by_chunk(lua_State *L, ngx_http_request_t *r) ctx->context = NGX_HTTP_LUA_CONTEXT_ACCESS; - llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module); - - if (llcf->check_client_abort) { - r->read_event_handler = ngx_http_lua_rd_check_broken_connection; - -#if (NGX_HTTP_V2) - if (!r->stream) { -#endif - - rev = r->connection->read; - - if (!rev->active) { - if (ngx_add_event(rev, NGX_READ_EVENT, 0) != NGX_OK) { - return NGX_ERROR; - } - } - -#if (NGX_HTTP_V2) - } -#endif - - } else { - r->read_event_handler = ngx_http_block_reading; + if (ngx_http_lua_set_read_handler(r) != NGX_OK) { + return NGX_ERROR; } c = r->connection; diff --git a/src/ngx_http_lua_contentby.c b/src/ngx_http_lua_contentby.c index 039f23ffcd..124f349605 100644 --- a/src/ngx_http_lua_contentby.c +++ b/src/ngx_http_lua_contentby.c @@ -27,12 +27,9 @@ ngx_http_lua_content_by_chunk(lua_State *L, ngx_http_request_t *r) int co_ref; ngx_int_t rc; lua_State *co; - ngx_event_t *rev; ngx_http_lua_ctx_t *ctx; ngx_pool_cleanup_t *cln; - ngx_http_lua_loc_conf_t *llcf; - dd("content by chunk"); ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); @@ -96,29 +93,8 @@ ngx_http_lua_content_by_chunk(lua_State *L, ngx_http_request_t *r) ctx->context = NGX_HTTP_LUA_CONTEXT_CONTENT; - llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module); - - if (llcf->check_client_abort) { - r->read_event_handler = ngx_http_lua_rd_check_broken_connection; - -#if (NGX_HTTP_V2) - if (!r->stream) { -#endif - - rev = r->connection->read; - - if (!rev->active) { - if (ngx_add_event(rev, NGX_READ_EVENT, 0) != NGX_OK) { - return NGX_ERROR; - } - } - -#if (NGX_HTTP_V2) - } -#endif - - } else { - r->read_event_handler = ngx_http_block_reading; + if (ngx_http_lua_set_read_handler(r) != NGX_OK) { + return NGX_ERROR; } rc = ngx_http_lua_run_thread(L, r, ctx, 0); diff --git a/src/ngx_http_lua_precontentby.c b/src/ngx_http_lua_precontentby.c index 14301e1251..0b789b5694 100644 --- a/src/ngx_http_lua_precontentby.c +++ b/src/ngx_http_lua_precontentby.c @@ -240,13 +240,10 @@ ngx_http_lua_precontent_by_chunk(lua_State *L, ngx_http_request_t *r) ngx_int_t rc; ngx_uint_t nreqs; lua_State *co; - ngx_event_t *rev; ngx_connection_t *c; ngx_http_lua_ctx_t *ctx; ngx_pool_cleanup_t *cln; - ngx_http_lua_loc_conf_t *llcf; - /* {{{ new coroutine to handle request */ co = ngx_http_lua_new_thread(r, L, &co_ref); @@ -309,29 +306,8 @@ ngx_http_lua_precontent_by_chunk(lua_State *L, ngx_http_request_t *r) ctx->context = NGX_HTTP_LUA_CONTEXT_PRECONTENT; - llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module); - - if (llcf->check_client_abort) { - r->read_event_handler = ngx_http_lua_rd_check_broken_connection; - -#if (NGX_HTTP_V2) - if (!r->stream) { -#endif - - rev = r->connection->read; - - if (!rev->active) { - if (ngx_add_event(rev, NGX_READ_EVENT, 0) != NGX_OK) { - return NGX_ERROR; - } - } - -#if (NGX_HTTP_V2) - } -#endif - - } else { - r->read_event_handler = ngx_http_block_reading; + if (ngx_http_lua_set_read_handler(r) != NGX_OK) { + return NGX_ERROR; } c = r->connection; diff --git a/src/ngx_http_lua_rewriteby.c b/src/ngx_http_lua_rewriteby.c index ab8da68df4..5f9fc944bd 100644 --- a/src/ngx_http_lua_rewriteby.c +++ b/src/ngx_http_lua_rewriteby.c @@ -248,13 +248,10 @@ ngx_http_lua_rewrite_by_chunk(lua_State *L, ngx_http_request_t *r) lua_State *co; ngx_int_t rc; ngx_uint_t nreqs; - ngx_event_t *rev; ngx_connection_t *c; ngx_http_lua_ctx_t *ctx; ngx_pool_cleanup_t *cln; - ngx_http_lua_loc_conf_t *llcf; - /* {{{ new coroutine to handle request */ co = ngx_http_lua_new_thread(r, L, &co_ref); @@ -316,29 +313,8 @@ ngx_http_lua_rewrite_by_chunk(lua_State *L, ngx_http_request_t *r) ctx->context = NGX_HTTP_LUA_CONTEXT_REWRITE; - llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module); - - if (llcf->check_client_abort) { - r->read_event_handler = ngx_http_lua_rd_check_broken_connection; - -#if (NGX_HTTP_V2) - if (!r->stream) { -#endif - - rev = r->connection->read; - - if (!rev->active) { - if (ngx_add_event(rev, NGX_READ_EVENT, 0) != NGX_OK) { - return NGX_ERROR; - } - } - -#if (NGX_HTTP_V2) - } -#endif - - } else { - r->read_event_handler = ngx_http_block_reading; + if (ngx_http_lua_set_read_handler(r) != NGX_OK) { + return NGX_ERROR; } c = r->connection; diff --git a/src/ngx_http_lua_server_rewriteby.c b/src/ngx_http_lua_server_rewriteby.c index 1e261ac223..3b050e642f 100644 --- a/src/ngx_http_lua_server_rewriteby.c +++ b/src/ngx_http_lua_server_rewriteby.c @@ -214,13 +214,10 @@ ngx_http_lua_server_rewrite_by_chunk(lua_State *L, ngx_http_request_t *r) lua_State *co; ngx_int_t rc; ngx_uint_t nreqs; - ngx_event_t *rev; ngx_connection_t *c; ngx_http_lua_ctx_t *ctx; ngx_pool_cleanup_t *cln; - ngx_http_lua_loc_conf_t *llcf; - /* {{{ new coroutine to handle request */ co = ngx_http_lua_new_thread(r, L, &co_ref); @@ -282,29 +279,8 @@ ngx_http_lua_server_rewrite_by_chunk(lua_State *L, ngx_http_request_t *r) ctx->context = NGX_HTTP_LUA_CONTEXT_SERVER_REWRITE; - llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module); - - if (llcf->check_client_abort) { - r->read_event_handler = ngx_http_lua_rd_check_broken_connection; - -#if (NGX_HTTP_V2) - if (!r->stream) { -#endif - - rev = r->connection->read; - - if (!rev->active) { - if (ngx_add_event(rev, NGX_READ_EVENT, 0) != NGX_OK) { - return NGX_ERROR; - } - } - -#if (NGX_HTTP_V2) - } -#endif - - } else { - r->read_event_handler = ngx_http_block_reading; + if (ngx_http_lua_set_read_handler(r) != NGX_OK) { + return NGX_ERROR; } c = r->connection; diff --git a/src/ngx_http_lua_socket_tcp.c b/src/ngx_http_lua_socket_tcp.c index 3feead2556..3e3bdae3b5 100644 --- a/src/ngx_http_lua_socket_tcp.c +++ b/src/ngx_http_lua_socket_tcp.c @@ -183,6 +183,7 @@ enum { SOCKET_OP_READ = 0x02, SOCKET_OP_WRITE = 0x04, SOCKET_OP_RESUME_CONN = 0x08, + SOCKET_OP_CLOSED = 0x10, }; @@ -3081,7 +3082,21 @@ ngx_http_lua_socket_tcp_read(ngx_http_request_t *r, "lua tcp socket try to recv data %O: \"%V?%V\"", size, &r->uri, &r->args); - n = c->recv(c, b->last, size); +#if (NGX_HTTP_SSL) && defined ngx_add_async_conn + if ((u->body_downstream || u->raw_downstream) && c->asynch && c->ssl) { + /* A TLS job may outlive the coroutine that owns this buffer. */ + n = ngx_http_lua_req_socket_ssl_recv(r, b->last, size); + if (n == NGX_ABORT) { + ngx_http_lua_socket_handle_read_error(r, u, + NGX_HTTP_LUA_SOCKET_FT_NOMEM); + return NGX_ERROR; + } + + } else +#endif + { + n = c->recv(c, b->last, size); + } dd("read event ready: %d", (int) c->read->ready); @@ -4698,6 +4713,73 @@ ngx_http_lua_socket_tcp_conn_op_resume_retval_handler(ngx_http_request_t *r, } +static void +ngx_http_lua_socket_unlink_downstream(ngx_http_request_t *r, + ngx_http_lua_socket_tcp_upstream_t *u) +{ + ngx_http_lua_ctx_t *ctx; + ngx_http_lua_loc_conf_t *llcf; + + ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); + if (ctx == NULL || ctx->downstream != u) { + return; + } + + ctx->downstream = NULL; + + if (r->read_event_handler == ngx_http_lua_req_socket_rev_handler) { + llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module); + r->read_event_handler = llcf->check_client_abort + ? ngx_http_lua_rd_check_broken_connection + : ngx_http_block_reading; + } +} + + +static ngx_int_t +ngx_http_lua_socket_closed_resume(ngx_http_request_t *r) +{ + return ngx_http_lua_socket_tcp_resume_helper(r, SOCKET_OP_CLOSED); +} + + +static void +ngx_http_lua_socket_closed_handler(ngx_event_t *ev) +{ + ngx_http_lua_co_ctx_t *coctx = ev->data; + ngx_http_lua_socket_tcp_upstream_t *u = coctx->data; + ngx_http_request_t *r = u->request; + ngx_connection_t *c = r->connection; + ngx_http_log_ctx_t *log_ctx = c->log->data; + ngx_http_lua_ctx_t *ctx; + + log_ctx->current_request = r; + ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); + ctx->cur_co_ctx = coctx; + ctx->resume_handler = ngx_http_lua_socket_closed_resume; + r->write_event_handler(r); + ngx_http_run_posted_requests(c); +} + + +static void +ngx_http_lua_socket_clear_waiter(ngx_http_lua_co_ctx_t *coctx) +{ + if (coctx == NULL) { + return; + } + + if (coctx->sleep.handler == ngx_http_lua_socket_closed_handler + && coctx->sleep.timer_set) + { + ngx_del_timer(&coctx->sleep); + } + + coctx->data = NULL; + coctx->cleanup = NULL; +} + + static void ngx_http_lua_socket_tcp_finalize(ngx_http_request_t *r, ngx_http_lua_socket_tcp_upstream_t *u) @@ -4725,6 +4807,13 @@ ngx_http_lua_socket_tcp_finalize(ngx_http_request_t *r, } if (u->raw_downstream || u->body_downstream) { + ngx_http_lua_socket_unlink_downstream(r, u); + ngx_http_lua_socket_clear_waiter(u->read_co_ctx); + ngx_http_lua_socket_clear_waiter(u->write_co_ctx); + u->read_co_ctx = NULL; + u->write_co_ctx = NULL; + u->read_waiting = 0; + u->write_waiting = 0; u->peer.connection = NULL; return; } @@ -5677,6 +5766,8 @@ ngx_http_lua_req_socket(lua_State *L) } if (raw) { + ngx_http_lua_stop_canceled_socket(r); + if (c->write->timer_set) { ngx_del_timer(c->write); } @@ -6379,6 +6470,8 @@ ngx_http_lua_socket_push_input_data(ngx_http_request_t *r, size_t nbufs; luaL_Buffer luabuf; + ngx_http_lua_socket_compiled_pattern_t *cp; + dd("bufs_in: %p, buf_in: %p", u->bufs_in, u->buf_in); nbufs = 0; @@ -6406,6 +6499,19 @@ ngx_http_lua_socket_push_input_data(ngx_http_request_t *r, nbufs++; } + if (u->peer.connection == NULL + && u->ft_type == NGX_HTTP_LUA_SOCKET_FT_CLOSED + && u->input_filter_ctx && u->input_filter_ctx != u) + { + cp = u->input_filter_ctx; + if (cp->state > 0) { + luaL_addlstring(&luabuf, (char *) cp->pattern.data, cp->state); +#if (DDEBUG) || (NGX_DTRACE) + size += cp->state; +#endif + } + } + luaL_pushresult(&luabuf); #if (DDEBUG) @@ -6616,6 +6722,13 @@ ngx_http_lua_socket_tcp_resume_helper(ngx_http_request_t *r, int socket_op) switch (socket_op) { + case SOCKET_OP_CLOSED: + u = coctx->data; + u->ft_type = NGX_HTTP_LUA_SOCKET_FT_CLOSED; + prepare_retvals = u->read_waiting ? u->read_prepare_retvals + : u->write_prepare_retvals; + break; + case SOCKET_OP_RESUME_CONN: conn_op_ctx = coctx->data; u = conn_op_ctx->u; @@ -6643,6 +6756,10 @@ ngx_http_lua_socket_tcp_resume_helper(ngx_http_request_t *r, int socket_op) "u:%p", prepare_retvals, u); nret = prepare_retvals(r, u, ctx->cur_co_ctx->co); + if (socket_op == SOCKET_OP_CLOSED) { + ngx_http_lua_socket_tcp_finalize(r, u); + } + if (socket_op == SOCKET_OP_CONNECT && nret > 1) { ngx_http_lua_socket_tcp_cleanup_failed_connect(r, u); } @@ -6727,6 +6844,9 @@ ngx_http_lua_coctx_cleanup(void *data) ngx_http_lua_socket_tcp_upstream_t *u; ngx_http_lua_co_ctx_t *coctx = data; + ngx_http_lua_co_ctx_t *waiter; + ngx_http_request_t *r; + dd("running coctx cleanup"); u = coctx->data; @@ -6738,7 +6858,43 @@ ngx_http_lua_coctx_cleanup(void *data) return; } - ngx_http_lua_socket_tcp_finalize(u->request, u); + r = u->request; + + if (u->peer.connection && (u->raw_downstream || u->body_downstream)) { + ngx_http_lua_cancel_req_socket(r, u->raw_downstream); + } + + if (u->raw_downstream && u->read_waiting && u->write_waiting) { + /* Resume the other operation after cancellation unwinds. A pending + * reader still owns its buffers until it returns the partial input. */ + if (coctx == u->read_co_ctx) { + waiter = u->write_co_ctx; + u->read_co_ctx = NULL; + u->read_waiting = 0; + ngx_http_lua_socket_tcp_finalize_read_part(r, u); + + } else { + waiter = u->read_co_ctx; + u->write_co_ctx = NULL; + u->write_waiting = 0; + if (r->connection->read->timer_set) { + ngx_del_timer(r->connection->read); + } + } + + coctx->data = NULL; + ngx_http_lua_socket_tcp_finalize_write_part(r, u); + ngx_http_lua_socket_unlink_downstream(r, u); + u->peer.connection = NULL; + + waiter->sleep.handler = ngx_http_lua_socket_closed_handler; + waiter->sleep.data = waiter; + waiter->sleep.log = r->connection->log; + ngx_add_timer(&waiter->sleep, 0); + return; + } + + ngx_http_lua_socket_tcp_finalize(r, u); } diff --git a/src/ngx_http_lua_util.c b/src/ngx_http_lua_util.c index 6d97b21ece..5d3ffe6fba 100644 --- a/src/ngx_http_lua_util.c +++ b/src/ngx_http_lua_util.c @@ -46,6 +46,16 @@ #include "ngx_http_lua_ssl_certby.h" #include "ngx_http_lua_ssl.h" #include "ngx_http_lua_log_ringbuf.h" +#if (NGX_HTTP_SSL) && defined ngx_add_async_conn \ + && !defined ngx_ssl_waiting_for_async +#include +#endif +#if (NGX_HTTP_LUA_HAVE_POLL) +#include +#endif +#if (NGX_FREEBSD && defined TCP_INFO && !defined POLLRDHUP) +#include +#endif #if (NGX_THREADS) #include "ngx_http_lua_worker_thread.h" #endif @@ -3446,6 +3456,39 @@ ngx_http_lua_cleanup_zombie_child_uthreads(ngx_http_request_t *r, } +ngx_int_t +ngx_http_lua_set_read_handler(ngx_http_request_t *r) +{ + ngx_uint_t flags; + ngx_event_t *rev; + ngx_http_lua_loc_conf_t *llcf; + + llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module); + if (!llcf->check_client_abort) { + r->read_event_handler = ngx_http_block_reading; + return NGX_OK; + } + + r->read_event_handler = ngx_http_lua_rd_check_broken_connection; + +#if (NGX_HTTP_V2) + if (r->stream) { + return NGX_OK; + } +#endif + + rev = r->connection->read; + if (rev->active) { + return NGX_OK; + } + + /* Deferred accept can reach Lua before the read event is registered. */ + flags = (ngx_event_flags & NGX_USE_CLEAR_EVENT) ? NGX_CLEAR_EVENT + : NGX_LEVEL_EVENT; + return ngx_add_event(rev, NGX_READ_EVENT, flags); +} + + ngx_int_t ngx_http_lua_check_broken_connection(ngx_http_request_t *r, ngx_event_t *ev) { @@ -3553,31 +3596,815 @@ ngx_http_lua_check_broken_connection(ngx_http_request_t *r, ngx_event_t *ev) } -void -ngx_http_lua_rd_check_broken_connection(ngx_http_request_t *r) +typedef struct { + ngx_recv_pt recv; + u_char *data; + size_t pos; + size_t last; + u_char byte; + unsigned reading_byte:1; + unsigned have_byte:1; +#if (NGX_HTTP_SSL) && defined ngx_add_async_conn + ngx_send_pt send; + ngx_send_chain_pt send_chain; + ngx_event_handler_pt suspended_handler; + ngx_http_request_t *request; + unsigned write_waiting:1; +#endif +} ngx_http_lua_pipeline_t; + + +typedef struct { + ngx_event_t retry; + ngx_http_lua_pipeline_t *pipeline; + size_t limit; + unsigned raw:1; +} ngx_http_lua_canceled_socket_t; + + +static void +ngx_http_lua_pipeline_cleanup(void *data) { - ngx_int_t rc; - ngx_event_t *rev; - ngx_http_lua_ctx_t *ctx; + ngx_http_lua_pipeline_t *p = data; - if (r->done) { + if (p->data) { + ngx_free(p->data); + p->data = NULL; + p->pos = 0; + p->last = 0; + } +} + + +static ngx_http_lua_pipeline_t * +ngx_http_lua_find_pipeline(ngx_connection_t *c) +{ + ngx_pool_cleanup_t *cln; + + for (cln = c->pool->cleanup; cln; cln = cln->next) { + if (cln->handler == ngx_http_lua_pipeline_cleanup) { + return cln->data; + } + } + + return NULL; +} + + +#if (NGX_HTTP_SSL) + +#ifdef ngx_add_async_conn + +static void ngx_http_lua_pipeline_async_ready(ngx_event_t *ev); + + +static ssize_t +ngx_http_lua_pipeline_block_send(ngx_connection_t *c, u_char *buf, size_t size) +{ + ngx_http_lua_pipeline_t *p; + + p = ngx_http_lua_find_pipeline(c); + p->write_waiting = 1; + c->write->ready = 0; + return NGX_AGAIN; +} + + +static ngx_chain_t * +ngx_http_lua_pipeline_block_send_chain(ngx_connection_t *c, ngx_chain_t *in, + off_t limit) +{ + (void) ngx_http_lua_pipeline_block_send(c, NULL, 0); + return in; +} + +#endif + + +/* A paused TLS read must resume into the same connection-owned byte. */ +static ssize_t +ngx_http_lua_pipeline_read_byte(ngx_connection_t *c, + ngx_http_lua_pipeline_t *p, ngx_http_request_t *r) +{ + ssize_t n; + + if (p->have_byte) { + return 1; + } + +#ifdef ngx_add_async_conn + if (p->suspended_handler) { + return NGX_AGAIN; + } +#endif + + n = p->recv(c, &p->byte, 1); + p->reading_byte = (n == NGX_AGAIN); + p->have_byte = (n == 1); + +#ifdef ngx_add_async_conn + if (p->reading_byte && c->asynch) { + if (!ngx_ssl_waiting_for_async(c)) { + /* No job retains the buffer across an ordinary WANT_READ. */ + p->reading_byte = 0; + return n; + } + + if (p->request == NULL) { + /* Keep the HTTP request out of keepalive and its pool alive + * through termination until the SSL job releases the byte. */ + ngx_http_lua_assert(r != NULL && r == r->main); + p->request = r; + r->count++; + r->blocked++; + } + + /* SSL_read and SSL_write share one async job on this connection. */ + p->send = c->send; + p->send_chain = c->send_chain; + c->send = ngx_http_lua_pipeline_block_send; + c->send_chain = ngx_http_lua_pipeline_block_send_chain; + + p->suspended_handler = c->read->handler; + c->async->handler = ngx_http_lua_pipeline_async_ready; + } +#endif + + return n; +} + + +#ifdef ngx_add_async_conn + +static void +ngx_http_lua_pipeline_async_ready(ngx_event_t *ev) +{ + ssize_t n; + ngx_connection_t *c; + ngx_http_request_t *r; + ngx_http_lua_pipeline_t *p; + + c = ev->data; + p = ngx_http_lua_find_pipeline(c); + + /* Restore the handlers saved when the core suspended the SSL read. */ + if (ev->timer_set) { + ngx_del_timer(ev); + } + + ev->timedout = 0; + ev->ready = 0; + ev->handler = p->suspended_handler; + if (c->read->handler == p->suspended_handler) { + c->read->handler = c->read->saved_handler; + } + + c->read->saved_handler = p->suspended_handler; + p->suspended_handler = NULL; + + c->send = p->send; + c->send_chain = p->send_chain; + c->read->ready = 1; + r = p->request; + n = ngx_http_lua_pipeline_read_byte(c, p, r); + if (p->suspended_handler) { + return; + } + + p->request = NULL; + r->blocked--; + if (c->error) { + ngx_http_finalize_request(r, NGX_ERROR); + ngx_http_run_posted_requests(c); + return; + } + + if (!p->have_byte && p->pos == p->last) { + c->recv = p->recv; + } + + if (n != NGX_AGAIN || p->pos < p->last) { + c->read->ready = 1; + } + + ngx_post_event(c->read, &ngx_posted_events); + + if (p->write_waiting) { + p->write_waiting = 0; + c->write->ready = 1; + ngx_post_event(c->write, &ngx_posted_events); + } + + if (r->count == 1) { + ngx_http_finalize_request(r, NGX_DONE); + + } else { + r->count--; + } +} + +#endif + +#endif + + +/* Let the HTTP parser or a raw socket read the saved bytes at its own pace. */ +static ssize_t +ngx_http_lua_pipeline_recv(ngx_connection_t *c, u_char *buf, size_t size) +{ + ssize_t n; + ngx_http_lua_pipeline_t *p; + + p = ngx_http_lua_find_pipeline(c); + ngx_http_lua_assert(p != NULL); + + if (size == 0) { + return 0; + } + +#if (NGX_HTTP_SSL) + if (p->pos == p->last) { + ngx_http_lua_assert(p->reading_byte || p->have_byte); + n = ngx_http_lua_pipeline_read_byte(c, p, NULL); + if (n == NGX_AGAIN) { + return n; + } + + if (n == 1) { + *buf = p->byte; + p->have_byte = 0; + } + + c->recv = p->recv; + return n; + } +#endif + + ngx_http_lua_assert(p->pos < p->last); + n = ngx_min(size, p->last - p->pos); + ngx_memcpy(buf, p->data + p->pos, n); + p->pos += n; + + if (p->pos == p->last) { + ngx_http_lua_pipeline_cleanup(p); + if (!p->reading_byte && !p->have_byte) { + c->recv = p->recv; + } + } + + return n; +} + + +static void +ngx_http_lua_canceled_socket_cleanup(void *data) +{ + ngx_http_lua_canceled_socket_t *cs = data; + + ngx_http_request_t *r; + + if (cs->retry.timer_set) { + ngx_del_timer(&cs->retry); + } + + r = cs->retry.data; +#if (nginx_version < 1007011) + if (!cs->raw && r->request_body->rest > 0) { + /* These cores have no reading_body flag. Wake the keepalive handler + * to close the connection if the request finishes before the drain. */ + r->header_in->pos = r->header_in->last; + r->connection->close = 1; + r->connection->read->ready = 1; return; } +#endif - rc = ngx_http_lua_check_broken_connection(r, r->connection->read); + if (cs->pipeline + && (cs->pipeline->pos < cs->pipeline->last || cs->pipeline->have_byte)) + { + r->connection->read->ready = 1; + } +} - if (rc == NGX_OK) { + +static ngx_http_cleanup_t * +ngx_http_lua_find_canceled_socket(ngx_http_request_t *r) +{ + ngx_http_cleanup_t *cln; + + for (cln = r->cleanup; cln; cln = cln->next) { + if (cln->handler == ngx_http_lua_canceled_socket_cleanup) { + return cln; + } + } + + return NULL; +} + + +void +ngx_http_lua_stop_canceled_socket(ngx_http_request_t *r) +{ + ngx_http_cleanup_t *cln; + + cln = ngx_http_lua_find_canceled_socket(r); + if (cln) { + ngx_http_lua_canceled_socket_cleanup(cln->data); + cln->handler = NULL; + } +} + + +static void +ngx_http_lua_retry_canceled_socket(ngx_event_t *ev) +{ + ngx_http_request_t *r = ev->data; + + if (r->read_event_handler == ngx_http_lua_rd_check_broken_connection) { + ngx_post_event(r->connection->read, &ngx_posted_events); + } +} + + +void +ngx_http_lua_cancel_req_socket(ngx_http_request_t *r, unsigned raw) +{ + ngx_event_t *rev; + ngx_http_cleanup_t *cln; + ngx_http_lua_loc_conf_t *llcf; + ngx_http_lua_canceled_socket_t *cs; + + /* Request cleanups survive internal redirects, which clear r->ctx. */ + cln = ngx_http_cleanup_add(r, sizeof(ngx_http_lua_canceled_socket_t)); + if (cln == NULL) { + r->connection->error = 1; return; } - /* rc == NGX_ERROR || rc > NGX_OK */ + cs = cln->data; + ngx_memzero(cs, sizeof(ngx_http_lua_canceled_socket_t)); + cs->raw = raw; + cs->retry.data = r; + cs->retry.handler = ngx_http_lua_retry_canceled_socket; + cs->retry.log = r->connection->log; + cln->handler = ngx_http_lua_canceled_socket_cleanup; + +#if (nginx_version >= 1007011) + if (!raw && r->request_body->rest > 0) { + /* Prevent keepalive reuse if the request finishes before the drain. */ + r->reading_body = 1; + } +#endif + + llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module); + if (llcf->check_client_abort) { + rev = r->connection->read; + if (rev->ready) { + ngx_post_event(rev, &ngx_posted_events); + + } else if (ngx_handle_read_event(rev, 0) != NGX_OK) { + r->connection->error = 1; + } + } +} + + +static ngx_http_lua_pipeline_t * +ngx_http_lua_get_pipeline(ngx_connection_t *c) +{ + ngx_pool_cleanup_t *cln; + ngx_http_lua_pipeline_t *p; + + p = ngx_http_lua_find_pipeline(c); + if (p == NULL) { + cln = ngx_pool_cleanup_add(c->pool, sizeof(ngx_http_lua_pipeline_t)); + if (cln == NULL) { + return NULL; + } + + p = cln->data; + ngx_memzero(p, sizeof(ngx_http_lua_pipeline_t)); + cln->handler = ngx_http_lua_pipeline_cleanup; + } + + if (c->recv != ngx_http_lua_pipeline_recv) { + p->recv = c->recv; + } + + return p; +} + + +/* Keep monitor read-ahead separate from the HTTP parser's header buffers. + * The connection owns these bytes until a downstream reader consumes them. */ +static ngx_int_t +ngx_http_lua_prepare_pipeline(ngx_http_request_t *r, + ngx_http_lua_canceled_socket_t *cs) +{ + u_char *data; + size_t size, len; + ngx_connection_t *c; + ngx_http_core_srv_conf_t *cscf; + ngx_http_lua_pipeline_t *p; + + c = r->connection; + p = ngx_http_lua_get_pipeline(c); + if (p == NULL) { + return NGX_ERROR; + } + + cscf = ngx_http_get_module_srv_conf(r, ngx_http_core_module); + size = cscf->large_client_header_buffers.size; + len = r->header_in->last - r->header_in->pos; + cs->limit = size - ngx_min(size, len); + + if (p->reading_byte || p->have_byte) { + /* The pending byte follows the buffered prefix. */ + cs->limit = p->last; + + } else if (p->data) { + /* Keep unread bytes ahead of any new transport input. */ + len = p->last - p->pos; + if (len < cs->limit) { + data = ngx_alloc(cs->limit, c->log); + if (data == NULL) { + return NGX_ERROR; + } + + ngx_memcpy(data, p->data + p->pos, len); + ngx_http_lua_pipeline_cleanup(p); + p->data = data; + p->last = len; + + } else { + cs->limit = p->last; + } + } + + cs->pipeline = p; + return NGX_OK; +} + + +/* Check the transport without consuming pipelined application bytes. */ +static ngx_uint_t +ngx_http_lua_pipeline_hangup(ngx_connection_t *c) +{ +#if (NGX_FREEBSD && defined TCP_INFO && !defined POLLRDHUP) + socklen_t len; + struct tcp_info ti; +#endif +#if (NGX_HTTP_LUA_HAVE_POLL || (NGX_WIN32 && NGX_HAVE_POLL)) + int n; + short hangup; + struct pollfd pfd; + + pfd.fd = c->fd; + pfd.events = POLLIN; + hangup = POLLERR | POLLHUP | POLLNVAL; +#ifdef POLLRDHUP + pfd.events |= POLLRDHUP; + hangup |= POLLRDHUP; +#endif +#if (NGX_WIN32) +#if (NGX_LOAD_WSAPOLL) + n = ngx_have_wsapoll ? WSAPoll(&pfd, 1, 0) : 0; +#else + n = WSAPoll(&pfd, 1, 0); +#endif +#else + n = poll(&pfd, 1, 0); +#endif + if (n > 0 && (pfd.revents & hangup)) { + return 1; + } +#endif + +#if (NGX_FREEBSD && defined TCP_INFO && !defined POLLRDHUP) + /* Older FreeBSD reports FIN as readable even with unread data. */ + if (c->sockaddr->sa_family != AF_UNIX) { + len = sizeof(ti); + if (getsockopt(c->fd, IPPROTO_TCP, TCP_INFO, &ti, &len) == 0 + && (ti.tcpi_state == TCPS_CLOSE_WAIT + || ti.tcpi_state == TCPS_CLOSED)) + { + return 1; + } + } +#endif + + return 0; +} + + +static ngx_int_t +ngx_http_lua_wait_pipeline(ngx_http_request_t *r, + ngx_http_lua_canceled_socket_t *cs) +{ + ssize_t n; + char byte; + ngx_err_t err; + ngx_connection_t *c; +#if (NGX_HTTP_SSL) + ngx_http_lua_pipeline_t *p; +#endif + + c = r->connection; + if (c->read->pending_eof) { + return NGX_HTTP_CLIENT_CLOSED_REQUEST; + } + +#if (NGX_HTTP_SSL) + if (c->ssl) { + p = cs->pipeline; + if (c->recv != ngx_http_lua_pipeline_recv) { + p->recv = c->recv; + } + + n = ngx_http_lua_pipeline_read_byte(c, p, r); + if (n == 0 || n == NGX_ERROR) { + if (p->pos == p->last) { + c->recv = p->recv; + ngx_http_lua_pipeline_cleanup(p); + } + + return NGX_HTTP_CLIENT_CLOSED_REQUEST; + } + + if (p->data || p->reading_byte || p->have_byte) { + c->recv = ngx_http_lua_pipeline_recv; + } + if (n == NGX_AGAIN) { + return ngx_handle_read_event(c->read, 0); + } + + } else +#endif + { + n = recv(c->fd, &byte, 1, MSG_PEEK); + if (n == 0) { + return NGX_HTTP_CLIENT_CLOSED_REQUEST; + } + + if (n == -1) { + err = ngx_socket_errno; +#ifdef NGX_EINTR + if (err == NGX_EINTR) { + ngx_post_event(c->read, &ngx_posted_events); + return NGX_OK; + } +#endif + if (err != NGX_EAGAIN) { + return NGX_HTTP_CLIENT_CLOSED_REQUEST; + } + + c->read->ready = 0; + return ngx_handle_read_event(c->read, 0); + } + } + + /* Leave excess pipelined input on the socket. Edge-triggered backends + * report a hangup even when application bytes remain unread. */ +#if (NGX_HAVE_KQUEUE) + if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) { + return NGX_OK; + } +#endif +#if (NGX_HAVE_EPOLLRDHUP && nginx_version >= 1011000) + if ((ngx_event_flags & NGX_USE_EPOLL_EVENT) && ngx_use_epoll_rdhup) { + return NGX_OK; + } +#endif + + /* A level-triggered backend would repeatedly report the same bytes. */ + if (ngx_http_lua_pipeline_hangup(c)) { + return NGX_HTTP_CLIENT_CLOSED_REQUEST; + } + + ngx_add_timer(&cs->retry, 100); + c->read->ready = 1; + return ngx_handle_read_event(c->read, 0); +} + + +#if (NGX_HTTP_SSL) && defined ngx_add_async_conn + +static ssize_t +ngx_http_lua_ssl_recv(ngx_http_request_t *r, ngx_http_lua_pipeline_t *p, + ngx_recv_pt reader, u_char *buf, size_t size) +{ + size_t pending; + ssize_t n; + ngx_connection_t *c; + + if (size == 0) { + return 0; + } + + c = r->connection; + if (reader == ngx_http_lua_pipeline_recv) { + return reader(c, buf, size); + } + + if (p == NULL || (!p->reading_byte && !p->have_byte)) { + /* Read already decrypted bytes in bulk. Do not let ngx_ssl_recv + * start another record with a caller-owned buffer. */ + pending = SSL_pending(c->ssl->connection); + if (pending) { + return reader(c, buf, ngx_min(size, pending)); + } + } + + if (p == NULL) { + p = ngx_http_lua_get_pipeline(c); + if (p == NULL) { + /* Distinguish allocation failure from a transport error. */ + return NGX_ABORT; + } + } + + n = ngx_http_lua_pipeline_read_byte(c, p, r); + if (n == 1) { + *buf = p->byte; + p->have_byte = 0; + + } else if (p->reading_byte) { + c->recv = ngx_http_lua_pipeline_recv; + } + + return n; +} + + +ssize_t +ngx_http_lua_req_socket_ssl_recv(ngx_http_request_t *r, u_char *buf, + size_t size) +{ + return ngx_http_lua_ssl_recv(r, NULL, r->connection->recv, buf, size); +} + +#endif + + +static ngx_int_t +ngx_http_lua_check_canceled_socket(ngx_http_request_t *r, + ngx_http_lua_canceled_socket_t *cs) +{ + u_char buf[NGX_HTTP_DISCARD_BUFFER_SIZE], *dst; + size_t size, budget; + ssize_t n; + ngx_int_t rc; + ngx_recv_pt reader; + ngx_connection_t *c; + ngx_http_lua_pipeline_t *p; + + c = r->connection; + budget = 16 * sizeof(buf); + while (!(c->error || c->read->error || c->read->eof)) { + dst = buf; + size = sizeof(buf); + p = NULL; + reader = c->recv; + + if (!cs->raw && r->request_body->rest > 0) { + size = (size_t) ngx_min(r->request_body->rest, (off_t) size); + + } else if (!cs->raw) { + if (cs->pipeline == NULL + && ngx_http_lua_prepare_pipeline(r, cs) != NGX_OK) + { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + p = cs->pipeline; + if (p->last == cs->limit) { + rc = ngx_http_lua_wait_pipeline(r, cs); + if (rc != NGX_HTTP_CLIENT_CLOSED_REQUEST) { + return rc; + } + + break; + } + + if (p->data) { + reader = p->recv; + dst = p->data + p->last; + size = cs->limit - p->last; + + } else { + size = ngx_min(size, cs->limit); + } + } + + /* The connection reader owns TLS early data, handshake transitions, + * close_notify, and read/write event coordination. */ + size = ngx_min(size, budget); +#if (NGX_HTTP_SSL) && defined ngx_add_async_conn + if (c->ssl && c->asynch) { + n = ngx_http_lua_ssl_recv(r, p, reader, dst, size); + if (n == NGX_ABORT) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + } else +#endif + { + n = reader(c, dst, size); + } + + if (n == NGX_AGAIN) { + return ngx_handle_read_event(c->read, 0); + } + + if (n <= 0) { + break; + } + + if (p) { + if (p->data == NULL) { + /* Allocate payload storage only if the client pipelines. */ + p->data = ngx_alloc(cs->limit, c->log); + if (p->data == NULL) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + + ngx_memcpy(p->data, buf, n); + c->recv = ngx_http_lua_pipeline_recv; + } + + p->last += n; + + } else if (!cs->raw) { + r->request_body->rest -= n; + r->request_length += n; +#if (nginx_version >= 1007011) + if (r->request_body->rest == 0) { + r->reading_body = 0; + } +#endif + } + + if (!c->read->ready) { + return ngx_handle_read_event(c->read, 0); + } + + budget -= n; + if (budget == 0) { + /* Give other connections a turn if a raw sender stays ready. */ + ngx_add_timer(&cs->retry, 0); + return NGX_OK; + } + } + + c->read->eof = 1; + if ((ngx_event_flags & NGX_USE_LEVEL_EVENT) && c->read->active) { + if (ngx_del_event(c->read, NGX_READ_EVENT, 0) != NGX_OK) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + } + + ngx_log_error(NGX_LOG_INFO, c->log, 0, + "client prematurely closed connection"); + return NGX_HTTP_CLIENT_CLOSED_REQUEST; +} + + +void +ngx_http_lua_rd_check_broken_connection(ngx_http_request_t *r) +{ + ngx_int_t rc; + ngx_event_t *rev; + ngx_http_lua_ctx_t *ctx; + ngx_http_cleanup_t *cln; + ngx_http_lua_canceled_socket_t *cs; + + if (r->done) { + return; + } ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); - if (ctx == NULL) { + cln = (r->request_body && r == r->main && ctx && ctx->downstream == NULL) + ? ngx_http_lua_find_canceled_socket(r) : NULL; + if (cln) { + cs = cln->data; + rc = ngx_http_lua_check_canceled_socket(r, cs); + if (rc == NGX_OK && cs->pipeline + && (cs->pipeline->pos < cs->pipeline->last + || cs->pipeline->have_byte)) + { + /* The transport may be idle while a downstream reader has input. */ + r->connection->read->ready = 1; + } + + } else { + rc = ngx_http_lua_check_broken_connection(r, r->connection->read); + } + + if (rc == NGX_OK || ctx == NULL) { return; } - if (ctx->on_abort_co_ctx == NULL) { + if (rc != NGX_HTTP_CLIENT_CLOSED_REQUEST || ctx->on_abort_co_ctx == NULL) { r->connection->error = 1; ngx_http_lua_request_cleanup(ctx, 0); ngx_http_lua_finalize_request(r, rc); diff --git a/src/ngx_http_lua_util.h b/src/ngx_http_lua_util.h index c8dc99d2fc..41b10d4e5a 100644 --- a/src/ngx_http_lua_util.h +++ b/src/ngx_http_lua_util.h @@ -227,8 +227,16 @@ ngx_int_t ngx_http_lua_post_thread(ngx_http_request_t *r, void ngx_http_lua_del_thread(ngx_http_request_t *r, lua_State *L, ngx_http_lua_ctx_t *ctx, ngx_http_lua_co_ctx_t *coctx); +ngx_int_t ngx_http_lua_set_read_handler(ngx_http_request_t *r); +void ngx_http_lua_cancel_req_socket(ngx_http_request_t *r, unsigned raw); +void ngx_http_lua_stop_canceled_socket(ngx_http_request_t *r); void ngx_http_lua_rd_check_broken_connection(ngx_http_request_t *r); +#if (NGX_HTTP_SSL) && defined ngx_add_async_conn +ssize_t ngx_http_lua_req_socket_ssl_recv(ngx_http_request_t *r, u_char *buf, + size_t size); +#endif + ngx_int_t ngx_http_lua_test_expect(ngx_http_request_t *r); ngx_int_t ngx_http_lua_check_broken_connection(ngx_http_request_t *r, diff --git a/t/131-duplex-req-socket.t b/t/131-duplex-req-socket.t index f88649b8d8..85dacd00fc 100644 --- a/t/131-duplex-req-socket.t +++ b/t/131-duplex-req-socket.t @@ -21,9 +21,8 @@ BEGIN { $ENV{TEST_NGINX_EVENT_TYPE} = 'poll'; $ENV{MOCKEAGAIN_WRITE_TIMEOUT_PATTERN} = 'slow'; - if ($ENV{TEST_NGINX_USE_HTTP3}) { - $SkipReason = "http3 does not support ngx.req.socket()"; - } + $SkipReason = "request sockets require HTTP/1.x" + if $ENV{TEST_NGINX_USE_HTTP2} || $ENV{TEST_NGINX_USE_HTTP3}; } use Test::Nginx::Socket::Lua $SkipReason ? (skip_all => $SkipReason) : (); @@ -32,7 +31,7 @@ log_level('debug'); repeat_each(2); -plan tests => repeat_each() * (blocks() * 2); +plan 'no_plan'; run_tests(); @@ -145,3 +144,158 @@ Content-Length: 1 --- wait: 0.1 --- ignore_response --- timeout: 10 + + + +=== TEST 3: canceling a raw reader wakes the pending writer +--- config + lua_socket_log_errors off; + + location = /child { + content_by_lua_block { + ngx.sleep(0.05) + } + } + + location /t { + content_by_lua_block { + local sock = assert(ngx.req.socket(true)) + local writer = ngx.thread.spawn(function() + local bytes, err = sock:send("slow") + assert(bytes == nil and err == "closed", err) + ngx.log(ngx.INFO, "writer resumed in ", ngx.var.uri) + end) + local reader = ngx.thread.spawn(function() + return sock:receive(1) + end) + assert(ngx.thread.kill(reader)) + ngx.location.capture("/child") + assert(ngx.thread.wait(writer)) + } + } +--- request +POST /t +--- more_headers +Content-Length: 8 +--- no_error_log +[error] +--- error_log eval: qr{writer resumed in /t, .*request: "POST /t HTTP/1\.1", host:} +--- ignore_response + + + +=== TEST 4: canceling a raw writer returns partial input to the reader +--- config + lua_socket_log_errors off; + + location /t { + content_by_lua_block { + local sock = assert(ngx.req.socket(true)) + + -- The last "b" rules out the first "xab" as a delimiter start. + -- The iterator returns those three bytes and retains the second + -- "xab" for the next reader, even with one-byte socket reads. + local prime = assert(sock:receiveuntil("xabxa!")) + assert(prime(3) == "xab") + + local iter = assert(sock:receiveuntil("abc")) + local reader = ngx.thread.spawn(function() + return iter() + end) + local writer = ngx.thread.spawn(function() + return sock:send("slow") + end) + assert(ngx.thread.kill(writer)) + local ok, data, err, partial = ngx.thread.wait(reader) + assert(ok and data == nil and err == "closed", err) + assert(partial == "xab", partial) + ngx.log(ngx.INFO, "cancel complete") + } + } +--- request eval +"POST /t\nxabxab" +--- more_headers +Content-Length: 8 +--- no_error_log +[error] +--- error_log: cancel complete +--- ignore_response + + + +=== TEST 5: canceling a pending body read restores client abort monitoring +--- config + lua_check_client_abort on; + lua_socket_log_errors off; + + location /t { + content_by_lua_block { + local start = tonumber(ngx.var.request_length) + local sock = assert(ngx.req.socket()) + assert(ngx.on_abort(function() + assert(tonumber(ngx.var.request_length) - start + == tonumber(ngx.var.arg_sent)) + local data, err = sock:receive(1) + assert(data == nil and err == "closed", err) + ngx.log(ngx.INFO, "client abort after reader cancellation") + ngx.exit(444) + end)) + + local reader = ngx.thread.spawn(function() + return sock:receive(8) + end) + assert(ngx.thread.kill(reader)) + ngx.sleep(1) + } + } +--- request eval +[ + "POST /t?sent=0", + ["POST /t?sent=3\n", { value => "123", delay_before => 0.1 }], + ["POST /t?sent=8\n", { value => "123", delay_before => 0.1 }, + { value => "45678", delay_before => 0.1 }], +] +--- more_headers +Content-Length: 8 +--- no_error_log +[error] +--- grep_error_log: client abort after reader cancellation +--- grep_error_log_out +client abort after reader cancellation +--- timeout: 0.2 +--- abort +--- wait: 0.1 +--- ignore_response + + + +=== TEST 6: cancel both raw socket operations before the close notification +--- config + lua_socket_log_errors off; + + location /t { + content_by_lua_block { + local sock = assert(ngx.req.socket(true)) + local reader = ngx.thread.spawn(function() + return sock:receive(1) + end) + local writer = ngx.thread.spawn(function() + return sock:send("slow") + end) + + assert(ngx.thread.kill(reader)) + assert(ngx.thread.kill(writer)) + ngx.sleep(0.01) + local bytes, err = sock:send("done") + assert(bytes == nil and err == "closed", err) + ngx.log(ngx.INFO, "both canceled") + } + } +--- request +POST /t +--- more_headers +Content-Length: 8 +--- no_error_log +[error] +--- error_log: both canceled +--- ignore_response diff --git a/t/201-canceled-req-socket.t b/t/201-canceled-req-socket.t new file mode 100644 index 0000000000..8b90866d8c --- /dev/null +++ b/t/201-canceled-req-socket.t @@ -0,0 +1,788 @@ +# vim:set ft= ts=4 sw=4 et fdm=marker: + +our $SkipReason; +BEGIN { + $SkipReason = "request sockets require HTTP/1.x" + if $ENV{TEST_NGINX_USE_HTTP2} || $ENV{TEST_NGINX_USE_HTTP3}; +} +use Test::Nginx::Socket::Lua $SkipReason ? (skip_all => $SkipReason) : (); +use Cwd qw(abs_path); +use File::Basename qw(dirname); +use File::Temp qw(tempdir); +use Text::ParseWords qw(shellwords); + +my $test_dir = dirname(abs_path(__FILE__)); +require "$test_dir/NginxEvent.pm"; +$ENV{TEST_NGINX_CERT_DIR} ||= $test_dir; + +my $dir = tempdir(CLEANUP => 1, TMPDIR => 1); +our $EarlyClient = "$dir/early-data-client"; +my $build = `$Test::Nginx::Util::NginxBinary -V 2>&1`; +our $DebugEpoll = $^O eq 'linux' && $build =~ /--with-debug\b/ + && t::NginxEvent::uses_epoll($Test::Nginx::Util::NginxBinary); +our $HaveProxy = $build !~ /--without-http_proxy_module/; +our $HaveSslClient = $build =~ /--with-http_ssl_module/ + && eval { require IO::Socket::SSL; 1 }; +our $HaveEarlyData = $ENV{TEST_NGINX_VERSION_NUM} >= 1015004 + && $build =~ /--with-http_ssl_module/ + && $build =~ /OpenSSL (?:1\.1\.1|[3-9]\.)/; + +if ($HaveEarlyData) { + my @cc = shellwords($ENV{CC} || 'cc'); + push @cc, '-I', $ENV{OPENSSL_INC} if length($ENV{OPENSSL_INC} || ''); + my @libs = ('-lssl', '-lcrypto'); + if (my $lib = $ENV{OPENSSL_LIB}) { + unshift @libs, '-L', $lib, '-Xlinker', '-rpath', '-Xlinker', $lib; + } + + # Distinguish missing client development files from a broken test client. + if (open my $probe, '|-', @cc, '-x', 'c', '-', '-o', "$dir/probe", @libs) { + print $probe "#include \n", + "int main(void) { return SSL_get_early_data_status(0); }\n"; + $HaveEarlyData = close $probe; + + } else { + $HaveEarlyData = 0; + } + + if ($HaveEarlyData) { + system(@cc, "$test_dir/data/early-data-client.c", '-o', $EarlyClient, + @libs) == 0 or die "failed to build the TLS early-data client"; + + } else { + diag "TLS early-data test requires a compiler and OpenSSL development files"; + } +} + +sub read_ok_headers { + my ($sock) = @_; + my $line = <$sock>; + die "missing HTTP 200 response" unless defined $line && $line =~ m{^HTTP/1\.1 200 }; + while (defined($line = <$sock>)) { + return if $line eq "\r\n"; + } + die "incomplete HTTP headers"; +} + +sub tls_upload { + my ($address, $query, $payload, $shutdown, $tail) = @_; + my $sock = IO::Socket::SSL->new(PeerAddr => $address, Timeout => 3, + SSL_verify_mode => 0) + or die "TLS connection failed: " . IO::Socket::SSL::errstr(); + $sock->print("POST /upload?$query HTTP/1.1\r\nHost: localhost\r\n", + "Content-Length: 8\r\n\r\n") or die "write failed"; + read_ok_headers($sock); + my $byte; + $sock->read($byte, 1) == 1 && $byte eq "A" or die "reader was not canceled"; + + if (length $payload) { + $sock->print($payload) or die "upload write failed"; + } + $sock->read($byte, 1) == 1 && $byte eq "B" or die "body was not drained"; + + if ($shutdown) { + # Send close_notify while keeping TCP open for the server's response. + $sock->stop_SSL(SSL_fast_shutdown => 1) or die "TLS shutdown failed"; + my $n = $sock->read($byte, 1); + die "failed to read after TLS shutdown: $!" unless defined $n; + return $n ? "handler finished" : "closed"; + } + + $sock->read($byte, 1) == 1 && $byte eq "C" or die "first response incomplete"; + if (defined $tail) { + $sock->print($tail) or die "pipeline write failed"; + } + read_ok_headers($sock); + my $line = <$sock>; + die "missing pipelined response body" unless defined $line; + chomp $line; + return $line; +} + +sub tls_pipeline { + my ($address, $size, $shutdown, $split) = @_; + my $next = "GET /next HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nX-Pad: "; + $next .= "x" x ($size - length($next) - 4) . "\r\n\r\n"; + my $tail; + if (defined $split) { + $tail = substr($next, $split, length($next), ""); + } + return tls_upload($address, "size=$size", "12345678" . $next, $shutdown, $tail); +} + +repeat_each(1); +plan 'no_plan'; +no_long_string(); +run_tests(); + +__DATA__ + +=== TEST 1: redirected handler sees the disconnect after a partial body +--- config + location = /cancel { + content_by_lua_block { + local sock = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return sock:receive(8) + end) + assert(ngx.thread.kill(reader)) + return ngx.exec("/work") + } + } + + location = /work { + lua_check_client_abort on; + content_by_lua_block { + local start = tonumber(ngx.var.request_length) + assert(ngx.on_abort(function() + ngx.log(ngx.INFO, "redirect drained ", + tonumber(ngx.var.request_length) - start) + ngx.exit(444) + end)) + ngx.sleep(2) + } + } +--- request eval +[["POST /cancel\n", { value => "abc", delay_before => 0.1 }]] +--- more_headers +Content-Length: 8 +--- error_log: redirect drained 3 +--- no_error_log +[error] +--- abort +--- timeout: 0.3 +--- wait: 0.1 +--- ignore_response + + + +=== TEST 2: bytes arriving on a detached raw socket cannot hide a disconnect +--- http_config + lua_shared_dict raw_abort 64k; +--- config + location = /cancel { + lua_check_client_abort on; + lua_socket_log_errors off; + content_by_lua_block { + local sock = assert(ngx.req.socket(true)) + local reader = ngx.thread.spawn(function() + return sock:receive(8) + end) + assert(ngx.thread.kill(reader)) + assert(ngx.on_abort(function() + local data, err = sock:receive(1) + assert(data == nil and err == "closed", err) + assert(ngx.shared.raw_abort:set("closed", true)) + ngx.exit(444) + end)) + assert(ngx.shared.raw_abort:set("ready", true)) + ngx.sleep(10) + } + } + + location = /t { + content_by_lua_block { + local state = ngx.shared.raw_abort + state:delete("ready") + state:delete("closed") + + local function wait_for(key) + local deadline = ngx.now() + 5 + while not state:get(key) do + assert(ngx.now() < deadline, "timed out waiting for " .. key) + ngx.sleep(0.01) + end + end + + local sock = assert(ngx.socket.connect("127.0.0.1", ngx.var.server_port)) + assert(sock:send("GET /cancel HTTP/1.1\r\nHost: localhost\r\n\r\n")) + wait_for("ready") + assert(sock:send(string.rep("raw bytes", 12000))) + assert(sock:close()) + wait_for("closed") + ngx.say("detached raw socket closed") + } + } +--- request +GET /t +--- response_body +detached raw socket closed +--- no_error_log +[error] +--- timeout: 12 + + + +=== TEST 3: a pipelined request cannot hide a later disconnect +--- config + location = /cancel { + lua_check_client_abort on; + content_by_lua_block { + local start = tonumber(ngx.var.request_length) + local sock = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return sock:receive(8) + end) + assert(ngx.thread.kill(reader)) + assert(ngx.on_abort(function() + ngx.log(ngx.INFO, "body bytes before disconnect ", + tonumber(ngx.var.request_length) - start) + ngx.exit(444) + end)) + ngx.sleep(2) + } + } +--- request eval +[map { + my $next = "POST /next HTTP/1.1\r\nHost: localhost\r\nContent-Length: $_\r\n\r\n"; + ["POST /cancel\n", { value => "12345678" . $next . ("x" x $_), delay_before => 0.1 }] +} (0, 20000)] +--- more_headers +Content-Length: 8 +Connection: keep-alive +--- error_log: body bytes before disconnect 8 +--- no_error_log +[error] +--- abort +--- timeout: 0.3 +--- wait: 0.2 +--- ignore_response + + + +=== TEST 4: reuse a TLS connection after canceling a reader during early data +--- http_config + lua_shared_dict early 64k; + server { + listen 127.0.0.1:$TEST_NGINX_RAND_PORT_1 ssl; + ssl_certificate $TEST_NGINX_CERT_DIR/cert/test.crt; + ssl_certificate_key $TEST_NGINX_CERT_DIR/cert/test.key; + ssl_protocols TLSv1.3; + ssl_session_cache shared:TLS:1m; + ssl_early_data on; + client_header_buffer_size 128; + large_client_header_buffers 4 512; + + location = /warm { return 200 "warm"; } + + location = /reset { + content_by_lua_block { + local dict = ngx.shared.early + dict:delete("canceled") + dict:delete("drained") + dict:delete("released") + ngx.header.content_length = 4 + ngx.print("warm") + } + } + + location = /release { + content_by_lua_block { + ngx.shared.early:set("released", true) + ngx.header.content_length = 2 + ngx.print("ok") + } + } + + location = /next { + content_by_lua_block { + while not ngx.shared.early:get("released") do + ngx.sleep(0.01) + end + ngx.header.content_length = 4 + ngx.print("next") + } + } + + location ~ ^/(canceled|drained)$ { + content_by_lua_block { + local stage = ngx.var.uri:sub(2) + while not ngx.shared.early:get(stage) do + ngx.sleep(0.01) + end + ngx.header.content_length = 2 + ngx.print("ok") + } + } + + location = /early { + lua_check_client_abort on; + content_by_lua_block { + assert(ngx.var.ssl_early_data == "1") + local start = tonumber(ngx.var.request_length) + local sock = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return sock:receive(8) + end) + assert(ngx.thread.kill(reader)) + ngx.shared.early:set("canceled", true) + + while tonumber(ngx.var.request_length) - start < 8 do + ngx.sleep(0.01) + end + ngx.shared.early:set("drained", true) + if ngx.var.arg_size == "512" then + -- With no excess input the monitor can finish the handshake. + while ngx.var.ssl_early_data do + ngx.sleep(0.01) + end + end + + ngx.header.content_length = 4 + ngx.print("done") + } + } + } +--- config + location = /t { return 200 "127.0.0.1:$TEST_NGINX_RAND_PORT_1"; } +--- request +GET /t +--- response_body_filters eval +sub { + return system($main::EarlyClient, shift) == 0 + ? "reused\n" : "client failed\n"; +} +--- response_body +reused +--- no_error_log +[crit] +--- skip_eval: 3: !$main::HaveEarlyData + + + +=== TEST 5: preserve a pipelined request larger than the header buffer on keepalive +--- config + client_header_buffer_size 128; + large_client_header_buffers 1 512; + + location = /upload { + lua_check_client_abort on; + content_by_lua_block { + local start = tonumber(ngx.var.request_length) + local sock = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return sock:receive(8) + end) + assert(ngx.thread.kill(reader)) + ngx.header.content_length = 2 + ngx.print("A") + assert(ngx.flush(true)) + while tonumber(ngx.var.request_length) == start do + ngx.sleep(0.01) + end + assert(tonumber(ngx.var.request_length) - start == 8) + assert(ngx.req.raw_header() == "POST /upload HTTP/1.1\r\n" + .. "Host: localhost\r\nContent-Length: 8\r\n\r\n") + ngx.print("B") + } + } + + location = /next { + content_by_lua_block { + if ngx.req.get_method() == "GET" then + assert(ngx.req.get_headers()["X-Pad"] == string.rep("x", 479)) + else + ngx.req.read_body() + assert(ngx.req.get_body_data() == string.rep("z", 3000)) + end + ngx.header.content_length = 4 + ngx.print("next") + } + } + + location = /t { + content_by_lua_block { + local function headers(sock, status) + local line = assert(sock:receive()) + assert(line == status, line) + while assert(sock:receive()) ~= "" do end + end + + local upload = "POST /upload HTTP/1.1\r\nHost: localhost\r\n" + .. "Content-Length: 8\r\n\r\n" + local function pipeline(request, status, repeat_upload) + local sock = assert(ngx.socket.connect("127.0.0.1", ngx.var.server_port)) + assert(sock:send(upload)) + headers(sock, "HTTP/1.1 200 OK") + assert(sock:receive(1) == "A") + if repeat_upload then + assert(sock:send("12345678" .. upload)) + assert(sock:receive(1) == "B") + headers(sock, "HTTP/1.1 200 OK") + assert(sock:receive(1) == "A") + end + assert(sock:send("12345678" .. request)) + assert(sock:receive(1) == "B") + headers(sock, status) + if status == "HTTP/1.1 200 OK" then + ngx.say(assert(sock:receive(4))) + else + ngx.say(status) + end + assert(sock:close()) + end + + pipeline("POST /next HTTP/1.1\r\nHost: localhost\r\n" + .. "Content-Length: 3000\r\nConnection: close\r\n\r\n" + .. string.rep("z", 3000), "HTTP/1.1 200 OK") + + local get = "GET /next HTTP/1.1\r\nHost: localhost\r\n" + .. "Connection: close\r\nX-Pad: " + pipeline(get .. string.rep("x", 479) .. "\r\n\r\n", "HTTP/1.1 200 OK", true) + pipeline(get .. string.rep("x", 479) .. "\r\nY-Pad: " + .. string.rep("y", 100) .. "\r\n\r\n", "HTTP/1.1 400 Bad Request") + pipeline(get .. string.rep("x", 512) .. "\r\n\r\n", + "HTTP/1.1 400 Bad Request") + } + } +--- request +GET /t +--- response_body +next +next +HTTP/1.1 400 Bad Request +HTTP/1.1 400 Bad Request +--- no_error_log +[error] + + + +=== TEST 6: a raw socket can take over preread bytes after body cancellation +--- config + client_header_buffer_size 128; + large_client_header_buffers 1 512; + + location = /take { + lua_check_client_abort on; + content_by_lua_block { + local start = tonumber(ngx.var.request_length) + local body = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return body:receive(8) + end) + assert(ngx.thread.kill(reader)) + while tonumber(ngx.var.request_length) - start < 8 do + ngx.sleep(0.01) + end + + local raw = assert(ngx.req.socket(true)) + local bytes = assert(raw:receive(4)) + assert(raw:receive(512) == string.rep("x", 512)) + assert(raw:send("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n" + .. "Connection: close\r\n\r\n" .. bytes)) + } + } +--- request eval +[["POST /take\n", { value => "12345678next" . ("x" x 512), delay_before => 0.1 }]] +--- more_headers +Content-Length: 8 +Connection: close +--- response_body chomp +next +--- no_error_log +[error] + + + +=== TEST 7: a request finishing before its body drains closes the connection +--- config + location = /stop { + lua_check_client_abort on; + content_by_lua_block { + local body = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return body:receive(8) + end) + assert(ngx.thread.kill(reader)) + ngx.header.content_length = 2 + ngx.print("ok") + } + } + + location = /t { + content_by_lua_block { + local sock = assert(ngx.socket.connect("127.0.0.1", ngx.var.server_port)) + sock:settimeout(1000) + assert(sock:send("POST /stop HTTP/1.1\r\nHost: localhost\r\n" + .. "Content-Length: 8\r\n\r\n")) + assert(sock:receive() == "HTTP/1.1 200 OK") + while assert(sock:receive()) ~= "" do end + assert(sock:receive(2) == "ok") + local data, err = sock:receive(1) + assert(data == nil and err == "closed", err) + ngx.say(err) + } + } +--- request +GET /t +--- response_body +closed +--- no_error_log +[error] + + + +=== TEST 8: TLS close_notify after canceling a request-body read +--- http_config + server { + listen 127.0.0.1:$TEST_NGINX_RAND_PORT_1 ssl; + ssl_certificate $TEST_NGINX_CERT_DIR/cert/test.crt; + ssl_certificate_key $TEST_NGINX_CERT_DIR/cert/test.key; + keepalive_timeout 0; + + location = /upload { + lua_check_client_abort on; + content_by_lua_block { + local start = tonumber(ngx.var.request_length) + local sent = tonumber(ngx.var.arg_sent) + local sock = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return sock:receive(8) + end) + assert(ngx.thread.kill(reader)) + assert(ngx.on_abort(function() + assert(tonumber(ngx.var.request_length) - start == sent) + ngx.log(ngx.INFO, "TLS abort after ", sent, " body bytes") + ngx.exit(444) + end)) + + ngx.header.content_length = 3 + ngx.print("A") + assert(ngx.flush(true)) + local deadline = ngx.now() + 1 + while tonumber(ngx.var.request_length) - start < sent do + assert(ngx.now() < deadline, "canceled body was not drained") + ngx.sleep(0.01) + end + + ngx.print("B") + assert(ngx.flush(true)) + ngx.sleep(1) + ngx.print("C") + } + } + } +--- config + location = /t { return 200 "127.0.0.1:$TEST_NGINX_RAND_PORT_1"; } +--- request +GET /t +--- response_body_filters eval +sub { + my $address = shift; + local $SIG{ALRM} = sub { die "TLS shutdown timed out" }; + alarm 8; + my @results = map { main::tls_upload($address, "sent=$_", "x" x $_, 1) } + (0, 3, 8); + alarm 0; + return (CORE::join "\n", @results) . "\n"; +} +--- response_body +closed +closed +closed +--- grep_error_log eval: qr/TLS abort after \d+ body bytes/ +--- grep_error_log_out +TLS abort after 0 body bytes +TLS abort after 3 body bytes +TLS abort after 8 body bytes +--- no_error_log +[error] +--- skip_eval: 4: !$main::HaveSslClient + + + +=== TEST 9: a partial upload disconnect ends the request without an on_abort callback +--- config + location = /cancel { + lua_check_client_abort on; + content_by_lua_block { + local sock = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return sock:receive(8) + end) + assert(ngx.thread.kill(reader)) + ngx.sleep(2) + } + log_by_lua_block { + ngx.log(ngx.NOTICE, "canceled upload finalized with ", ngx.var.status) + } + } +--- request eval +[["POST /cancel\n", { value => "abc", delay_before => 0.1 }]] +--- more_headers +Content-Length: 8 +--- abort +--- timeout: 0.3 +--- wait: 0.1 +--- ignore_response +--- grep_error_log eval: qr/canceled upload finalized with \d+/ +--- grep_error_log_out +canceled upload finalized with 499 +--- no_error_log +[error] + + + +=== TEST 10: TLS shutdown at the pipeline buffer limit preserves pending input +--- http_config + server { + listen 127.0.0.1:$TEST_NGINX_RAND_PORT_1 ssl; + ssl_certificate $TEST_NGINX_CERT_DIR/cert/test.crt; + ssl_certificate_key $TEST_NGINX_CERT_DIR/cert/test.key; + client_header_buffer_size 128; + large_client_header_buffers 1 512; + + location = /upload { + lua_check_client_abort on; + content_by_lua_block { + local start = tonumber(ngx.var.request_length) + local body = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() return body:receive(8) end) + assert(ngx.thread.kill(reader)) + assert(ngx.on_abort(function() + ngx.log(ngx.INFO, "pipeline TLS shutdown ", ngx.var.arg_size) + ngx.exit(444) + end)) + + ngx.header.content_length = 3 + ngx.print("A") + assert(ngx.flush(true)) + while tonumber(ngx.var.request_length) - start < 8 do + ngx.sleep(0.01) + end + ngx.print("B") + assert(ngx.flush(true)) + ngx.sleep(0.4) + ngx.print("C") + } + } + location = /next { return 200 "next\n"; } + } +--- config + location = /t { return 200 "127.0.0.1:$TEST_NGINX_RAND_PORT_1"; } +--- request +GET /t +--- response_body_filters eval +sub { + my $address = shift; + local $SIG{ALRM} = sub { die "TLS pipeline timed out" }; + alarm 8; + my @results = (main::tls_pipeline($address, 511, 1), + main::tls_pipeline($address, 512, 1), + main::tls_pipeline($address, 513, 0), + main::tls_pipeline($address, 546, 0), + # Finish the next header after the pending 1-byte read + # has passed from the monitor to the keepalive reader. + main::tls_pipeline($address, 513, 0, 512)); + alarm 0; + return (CORE::join "\n", @results) . "\n"; +} +--- response_body +closed +closed +next +next +next +--- grep_error_log eval: qr/pipeline TLS shutdown \d+/ +--- grep_error_log_out +pipeline TLS shutdown 511 +pipeline TLS shutdown 512 +--- no_error_log +[error] +--- skip_eval: 4: !$main::HaveSslClient + + + +=== TEST 11: a proxy upgrade can consume input buffered during access +--- config + location = /upgrade { + lua_check_client_abort on; + access_by_lua_block { + local start = tonumber(ngx.var.request_length) + local body = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() return body:receive(8) end) + assert(ngx.thread.kill(reader)) + while tonumber(ngx.var.request_length) - start < 8 do + ngx.sleep(0.01) + end + } + proxy_http_version 1.1; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header Connection upgrade; + proxy_set_header Upgrade $http_upgrade; + proxy_pass http://127.0.0.1:$server_port/backend; + } + + location = /backend { + content_by_lua_block { + local sock = assert(ngx.req.socket(true)) + assert(sock:send("HTTP/1.1 101 Switching Protocols\r\n" + .. "Connection: upgrade\r\nUpgrade: echo\r\n\r\n")) + local data = assert(sock:receive(4)) + assert(sock:send(data)) + } + } + + location = /t { + content_by_lua_block { + local sock = assert(ngx.socket.connect("127.0.0.1", ngx.var.server_port)) + sock:settimeout(1000) + assert(sock:send("POST /upgrade HTTP/1.1\r\nHost: localhost\r\n" + .. "Connection: upgrade\r\nUpgrade: echo\r\n" + .. "Expect: 100-continue\r\nContent-Length: 8\r\n\r\n")) + assert(sock:receive() == "HTTP/1.1 100 Continue") + assert(sock:receive() == "") + assert(sock:send("12345678PING")) + assert(sock:receive() == "HTTP/1.1 101 Switching Protocols") + while assert(sock:receive()) ~= "" do end + ngx.say(assert(sock:receive(4))) + } + } +--- request +GET /t +--- response_body +PING +--- no_error_log +[error] +--- skip_eval: 3: !$main::HaveProxy + + + +=== TEST 12: abort monitoring uses edge-triggered reads with deferred accept +--- log_level: debug +--- config + listen 127.0.0.1:$TEST_NGINX_RAND_PORT_1 deferred; + + location = /upload { + lua_check_client_abort on; + content_by_lua_block { + local sock = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() + return sock:receive(1) + end) + assert(ngx.thread.kill(reader)) + ngx.say("canceled") + } + } + + location = /t { + content_by_lua_block { + local sock = assert(ngx.socket.connect("127.0.0.1", $TEST_NGINX_RAND_PORT_1)) + assert(sock:send("POST /upload HTTP/1.0\r\nContent-Length: 1\r\n\r\n")) + while assert(sock:receive()) ~= "" do end + ngx.say(assert(sock:receive())) + } + } +--- request +GET /t +--- response_body +canceled +--- grep_error_log eval +qr{\*\d+ (?:epoll add event: fd:\d+ op:1 ev:\w+|http finalize request: \S+, "/upload\?")} +--- grep_error_log_out eval +# Match EPOLLET on the connection that served /upload. +qr{^(\*\d+) epoll add event: fd:\d+ op:1 ev:8000(?:20|00)01\n.*?^\1 http finalize request:}ms +--- no_error_log +[error] +--- skip_eval: 4: !$main::DebugEpoll diff --git a/t/202-async-req-socket.t b/t/202-async-req-socket.t new file mode 100644 index 0000000000..65f407948c --- /dev/null +++ b/t/202-async-req-socket.t @@ -0,0 +1,302 @@ +# vim:set ft= ts=4 sw=4 et fdm=marker: + +use Test::Nginx::Socket::Lua; +use Cwd qw(abs_path); +use File::Basename qw(dirname); +use File::Temp qw(tempdir); +use IPC::Open3; +use Symbol qw(gensym); +use Text::ParseWords qw(shellwords); + +plan skip_all => 'async TLS completion requires HTTP/1.x on Linux' + if $^O ne 'linux' || $ENV{TEST_NGINX_USE_HTTP2} || $ENV{TEST_NGINX_USE_HTTP3}; + +my $nginx = $Test::Nginx::Util::NginxBinary; +my $build = `$nginx -V 2>&1`; +plan skip_all => 'requires OpenSSL 1.1.1 or later with HTTP SSL' + unless $build =~ /--with-http_ssl_module/ && $build =~ /OpenSSL (?:1\.1\.1|[3-9]\.)/; + +my $test_dir = dirname(abs_path(__FILE__)); +require "$test_dir/NginxEvent.pm"; +plan skip_all => 'async TLS completion requires epoll' + unless t::NginxEvent::uses_epoll($nginx); + +# Exercise build paths longer than a Linux Unix-domain socket address. +my $dir = tempdir('async-read-' . ('X' x 108), CLEANUP => 1, TMPDIR => 1); +mkdir "$dir/logs" or die $!; +open my $conf, '>', "$dir/probe.conf" or die $!; +my $port = Test::Nginx::Util::server_port(); +t::NginxEvent::write_probe_main_config($conf); +print $conf qq{events {} http { server { listen 127.0.0.1:$port asynch; + ssl_certificate "$test_dir/cert/test.crt"; ssl_certificate_key "$test_dir/cert/test.key"; } }\n}; +close $conf or die $!; +my $err = gensym; +my $pid = open3(undef, undef, $err, $nginx, '-tq', '-p', $dir, '-c', "$dir/probe.conf"); +my $output = do { local $/; <$err> }; +waitpid $pid, 0; +if ($?) { + plan skip_all => 'nginx lacks async TLS support' if $output =~ /invalid parameter "asynch"/; + die "nginx configuration check failed: $output"; +} + +$ENV{TEST_NGINX_CERT_DIR} ||= $test_dir; +$ENV{OPENSSL_ENGINES} = $dir; +$ENV{TEST_NGINX_ASYNC_READ_LIB} = "$dir/dasync.so"; +my @cc = shellwords($ENV{CC} || 'cc'); +push @cc, '-I', $ENV{OPENSSL_INC} if length($ENV{OPENSSL_INC} || ''); +if (open my $probe, '|-', @cc, '-fsyntax-only', '-x', 'c', '-') { + print $probe "#include \n#include \n#include \n", + "#ifndef IMPLEMENT_DYNAMIC_BIND_FN\n#error no dynamic engine support\n#endif\n", + "void probe(void) { (void) BIO_set_callback_ex; (void) ASYNC_pause_job; }\n"; + close $probe or plan skip_all => 'async OpenSSL development headers unavailable'; +} else { + plan skip_all => 'C compiler unavailable'; +} +system(@cc, '-fPIC', '-shared', "$test_dir/data/async-read.c", '-o', + $ENV{TEST_NGINX_ASYNC_READ_LIB}) == 0 or die "failed to build async TLS fixture"; + +repeat_each(1); +plan 'no_plan'; +run_tests(); + +__DATA__ + +=== TEST 1: async TLS request socket reads preserve response writes and keepalive reuse +--- main_config + env OPENSSL_ENGINES; + ssl_engine { use_engine dasync; } +--- http_config + init_by_lua_block { + local ffi = require "ffi" + ffi.cdef[[ + int ASYNC_is_capable(void); + int arm_read(void *ssl); + int read_paused(void); + int release_read(void); + void close_read_fds(void); + ]] + package.loaded.async_read = ffi.load("$TEST_NGINX_ASYNC_READ_LIB") + } + + server { + listen 127.0.0.1:$TEST_NGINX_RAND_PORT_1 asynch; + ssl_certificate $TEST_NGINX_CERT_DIR/cert/test.crt; + ssl_certificate_key $TEST_NGINX_CERT_DIR/cert/test.key; + client_header_buffer_size 128; + large_client_header_buffers 1 512; + + location = /upload { + lua_check_client_abort on; + content_by_lua_block { + local fixture = require "async_read" + local start = tonumber(ngx.var.request_length) + local first_body = tonumber(ngx.var.arg_body) + local body = assert(ngx.req.socket()) + local reader = ngx.thread.spawn(function() return body:receive(8) end) + assert(ngx.thread.kill(reader)) + local order = ngx.var.arg_order + local finish = order == "finish" or order == "abort" + ngx.header.content_length = finish and 2 or 4 + ngx.print("A") + assert(ngx.flush(true)) + while tonumber(ngx.var.request_length) - start < first_body do + ngx.sleep(0.001) + end + + assert(fixture.arm_read(assert(require("ngx.ssl").get_req_ssl_pointer())) == 1) + ngx.print("B") + assert(ngx.flush(true)) + while fixture.read_paused() == 0 do + ngx.sleep(0.001) + end + + if finish then + -- Release the read after the request handler has returned. + assert(ngx.timer.at(0, function() + assert(fixture.release_read() == 1) + end)) + if order == "abort" then + return ngx.exit(444) + end + + return + end + + assert(fixture.release_read() == 1) + if order == "read" then + while fixture.read_paused() ~= 0 do + ngx.sleep(0.001) + end + end + + ngx.print("C") + assert(ngx.flush(false)) + ngx.print("D") + assert(ngx.flush(true)) + } + } + + location = /reader { + lua_check_client_abort on; + content_by_lua_block { + local fixture = require "async_read" + local raw = ngx.var.arg_kind == "raw" + local cancel = ngx.var.arg_mode == "cancel" + local start = tonumber(ngx.var.request_length) + + ngx.header.content_length = raw and (cancel and 1 or 10) or 9 + ngx.print("A") + assert(ngx.flush(true)) + local sock = assert(ngx.req.socket(raw)) + assert(fixture.arm_read(assert(require("ngx.ssl").get_req_ssl_pointer())) == 1) + local reader = ngx.thread.spawn(function() return sock:receive(8) end) + while fixture.read_paused() == 0 do + ngx.sleep(0.001) + end + + if cancel then + assert(ngx.thread.kill(reader)) + end + assert(ngx.timer.at(0, function() assert(fixture.release_read() == 1) end)) + + if raw and cancel then + return + end + if raw then + -- Write while the original read is still paused. + assert(sock:send("B")) + end + + local reply = "canceled" + if not cancel then + local ok, data = ngx.thread.wait(reader) + assert(ok and data, data) + reply = data + end + + if raw then + assert(sock:send(reply)) + else + ngx.print(reply) + assert(ngx.flush(true)) + while tonumber(ngx.var.request_length) - start < 8 do + ngx.sleep(0.001) + end + end + } + } + location = /next { return 200 "$http_x_pad\n"; } + } +--- config + location = /t { + content_by_lua_block { + local ffi = require "ffi" + if ffi.C.ASYNC_is_capable() == 0 then + return ngx.say("async unavailable") + end + + local function headers(sock) + assert(sock:receive() == "HTTP/1.1 200 OK") + while assert(sock:receive()) ~= "" do end + end + + local function upload(path) + local sock = assert(ngx.socket.connect("127.0.0.1", $TEST_NGINX_RAND_PORT_1)) + sock:settimeout(3000) + assert(sock:sslhandshake(false)) + assert(sock:send("POST " .. path .. " HTTP/1.1\r\n" + .. "Host: localhost\r\nContent-Length: 8\r\n\r\n")) + headers(sock) + assert(sock:receive(1) == "A") + return sock + end + + local function close(sock) + local fixture = require "async_read" + assert(fixture.read_paused() == 0) + fixture.close_read_fds() + sock:close() + end + + local function pipeline(order, size, first_body) + first_body = first_body or 8 + local sock = upload("/upload?order=" .. order .. "&body=" .. first_body) + local next_req = "GET /next HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nX-Pad: " + local pad = string.rep("x", math.max(128, size) - 3 - #next_req) + local data = "12345678" .. next_req .. pad .. "\r\n\r\n" + local split = first_body + size + assert(sock:send(data:sub(1, split))) + assert(sock:receive(1) == "B") + assert(sock:send(data:sub(split + 1))) + if order == "abort" then + local byte, err = sock:receive(1) + assert(byte == nil and err == "closed", err) + else + if order ~= "finish" then + assert(sock:receive(2) == "CD", "incomplete first response") + end + headers(sock) + assert(sock:receive() == pad, "pipelined header changed") + end + close(sock) + ngx.say(size, " ", order, " ok") + end + + for _, size in ipairs({511, 512}) do + pipeline("read", size) + pipeline("write", size) + pipeline("finish", size) + end + pipeline("write", 0, 7) + pipeline("finish", 0) + pipeline("abort", 511) + + for _, kind in ipairs({"body", "raw"}) do + for _, mode in ipairs({"resume", "cancel"}) do + local sock = upload("/reader?kind=" .. kind .. "&mode=" .. mode) + local data = "12345678" + if kind == "body" then + data = data .. "GET /next HTTP/1.1\r\nHost: localhost\r\n" + .. "X-Pad: second\r\nConnection: close\r\n\r\n" + end + assert(sock:send(data)) + if kind == "raw" and mode == "cancel" then + local byte, err = sock:receive(1) + assert(byte == nil and err == "closed", err) + else + if kind == "raw" then + assert(sock:receive(1) == "B") + end + assert(sock:receive(8) == (mode == "cancel" and "canceled" or "12345678")) + if kind == "body" then + headers(sock) + assert(sock:receive() == "second") + end + end + close(sock) + ngx.say(kind, " ", mode, " ok") + end + end + } + } +--- request +GET /t +--- response_body_filters eval +sub { + my $body = shift; + SKIP: { + Test::More::skip("OpenSSL runtime lacks async jobs", 1) if $body eq "async unavailable\n"; + my $expected = CORE::join '', map { "$_ read ok\n$_ write ok\n$_ finish ok\n" } (511, 512); + $expected .= "0 write ok\n0 finish ok\n511 abort ok\n"; + $expected .= "body resume ok\nbody cancel ok\nraw resume ok\nraw cancel ok\n"; + Test::More::is($body, $expected, "complete responses across async reads and cancellation"); + } + return "done\n"; +} +--- response_body +done +--- timeout: 10 +--- no_error_log +[error] +[alert] +[crit] diff --git a/t/NginxEvent.pm b/t/NginxEvent.pm new file mode 100644 index 0000000000..ac2729a3dd --- /dev/null +++ b/t/NginxEvent.pm @@ -0,0 +1,55 @@ +package t::NginxEvent; + +use strict; +use warnings; +use File::Temp qw(tempdir); +use IPC::Run qw(start timeout); +use Test::Nginx::Util (); + +sub write_probe_main_config { + my ($conf) = @_; + print $conf "pid logs/nginx.pid;\n"; + + # Match the worker credentials used by the Test::Nginx server. + my $user = $Test::Nginx::Util::WorkerUser; + $user = 'root' if !defined $user && $> == 0; + print $conf "user $user;\n" if defined $user; +} + +sub uses_epoll { + my ($nginx) = @_; + if ($ENV{TEST_NGINX_EVENT_TYPE}) { + return $ENV{TEST_NGINX_EVENT_TYPE} eq 'epoll'; + } + + # nginx reports its default event method at startup, but omits it in -t mode. + my $dir = tempdir(CLEANUP => 1, TMPDIR => 1); + mkdir "$dir/logs" or die $!; + open my $conf, '>', "$dir/nginx.conf" or die $!; + write_probe_main_config($conf); + print $conf <<'EOF'; +daemon off; +master_process off; +error_log stderr notice; +events {} +EOF + close $conf or die $!; + + my $log = ''; + my $probe = start [$nginx, '-p', "$dir/", '-c', 'nginx.conf'], + '2>', \$log, timeout(5); + my $method; + eval { + while ($probe->pumpable) { + $probe->pump; + ($method) = $log =~ /using the "(\w+)" event method/; + last if defined $method; + } + }; + my $err = $@; + $probe->kill_kill(grace => 1); + die "could not determine nginx event method: $err$log" unless defined $method; + return $method eq 'epoll'; +} + +1; diff --git a/t/data/async-read.c b/t/data/async-read.c new file mode 100644 index 0000000000..f72bd32478 --- /dev/null +++ b/t/data/async-read.c @@ -0,0 +1,87 @@ +/* Pause one TLS read until the test explicitly signals its completion fd. */ +#define OPENSSL_SUPPRESS_DEPRECATED +#include +#include +#include +#include + +static int fds[2]; +static int paused; +static int released; + +/* Selecting an engine makes nginx allocate per-connection async events. + * The BIO callback below supplies the job, so no algorithms are needed. */ +static int +bind_async_read(ENGINE *engine, const char *id) +{ + return ENGINE_set_id(engine, "dasync") + && ENGINE_set_name(engine, "request socket test"); +} + +IMPLEMENT_DYNAMIC_BIND_FN(bind_async_read) +IMPLEMENT_DYNAMIC_CHECK_FN() + +static long +pause_read(BIO *bio, int op, const char *buf, size_t len, int arg, long larg, + int ret, size_t *processed) +{ + ASYNC_JOB *job; + ASYNC_WAIT_CTX *ctx; + + if (op != BIO_CB_READ) { + return ret; + } + + job = ASYNC_get_current_job(); + if (job == NULL) { + return 0; + } + + ctx = ASYNC_get_wait_ctx(job); + if (!ASYNC_WAIT_CTX_set_wait_fd(ctx, fds, fds[0], NULL, NULL)) { + return 0; + } + + paused = 1; + while (!released) { + if (!ASYNC_pause_job()) { + return 0; + } + } + + BIO_set_callback_ex(bio, NULL); + paused = 0; + return ASYNC_WAIT_CTX_clear_fd(ctx, fds) ? ret : 0; +} + +int +arm_read(SSL *ssl) +{ + if (!(SSL_get_mode(ssl) & SSL_MODE_ASYNC) || pipe(fds) == -1) { + return 0; + } + + released = 0; + BIO_set_callback_ex(SSL_get_rbio(ssl), pause_read); + return 1; +} + +int +read_paused(void) +{ + return paused; +} + +int +release_read(void) +{ + released = 1; + return write(fds[1], "!", 1) == 1; +} + +void +close_read_fds(void) +{ + close(fds[0]); + close(fds[1]); +} diff --git a/t/data/early-data-client.c b/t/data/early-data-client.c new file mode 100644 index 0000000000..412983dde4 --- /dev/null +++ b/t/data/early-data-client.c @@ -0,0 +1,130 @@ +/* Test client for a body sent in two TLS 1.3 early-data records. */ +#include +#include +#include +#include +#include +#include + +static SSL * +open_connection(SSL_CTX *ctx, const char *address) +{ + SSL *ssl; + BIO *bio; + + ssl = SSL_new(ctx); + bio = BIO_new_connect(address); + if (ssl == NULL || bio == NULL || BIO_do_connect(bio) <= 0) { + return NULL; + } + + SSL_set_bio(ssl, bio, bio); + SSL_set_connect_state(ssl); + return ssl; +} + +static int +read_response(SSL *ssl, const char *body) +{ + char response[2048]; + int n; + char *payload; + size_t used = 0; + + while (used < sizeof(response) - 1) { + n = SSL_read(ssl, response + used, sizeof(response) - 1 - used); + if (n <= 0) { + break; + } + used += n; + response[used] = '\0'; + payload = strstr(response, "\r\n\r\n"); + if (payload != NULL && strcmp(payload + 4, body) == 0) { + return strncmp(response, "HTTP/1.1 200 ", 13) == 0; + } + } + return 0; +} + +static int +get(SSL *ssl, const char *path, const char *body) +{ + char request[128]; + int len = snprintf(request, sizeof(request), + "GET %s HTTP/1.1\r\nHost: localhost\r\n\r\n", path); + + return SSL_write(ssl, request, len) == len && read_response(ssl, body); +} + +static int +run(const char *address, size_t pipeline_len) +{ + static const char next[] = "GET /next HTTP/1.1\r\nHost: localhost\r\nX-Pad: "; + char post[128], payload[8 + 513]; + SSL_CTX *ctx; + SSL *ssl, *control; + SSL_SESSION *session; + size_t n; + + ctx = SSL_CTX_new(TLS_client_method()); + if (ctx == NULL || !SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION)) { + return 0; + } + ssl = open_connection(ctx, address); + if (ssl == NULL || !get(ssl, "/reset", "warm")) { + return 0; + } + + session = SSL_get1_session(ssl); + control = ssl; + + snprintf(post, sizeof(post), "POST /early?size=%zu HTTP/1.1\r\n" + "Host: localhost\r\nContent-Length: 8\r\n\r\n", pipeline_len); + ssl = open_connection(ctx, address); + if (ssl == NULL || session == NULL || !SSL_SESSION_get_max_early_data(session) + || !SSL_set_session(ssl, session) + || !SSL_write_early_data(ssl, post, strlen(post), &n) + || n != strlen(post)) + { + return 0; + } + + /* Wait on the warm connection before sending the next early-data record + * and again before finishing the handshake on the resumed connection. */ + memcpy(payload, "12345678", 8); + memcpy(payload + 8, next, sizeof(next) - 1); + memset(payload + 8 + sizeof(next) - 1, 'x', + pipeline_len - (sizeof(next) - 1) - 4); + memcpy(payload + 8 + pipeline_len - 4, "\r\n\r\n", 4); + + if (!get(control, "/canceled", "ok") + || !SSL_write_early_data(ssl, payload, 8 + pipeline_len, &n) + || n != 8 + pipeline_len + || !get(control, "/drained", "ok") || SSL_connect(ssl) != 1 + || SSL_get_early_data_status(ssl) != SSL_EARLY_DATA_ACCEPTED + || !read_response(ssl, "done") + || !get(control, "/release", "ok") || !read_response(ssl, "next") + || !get(ssl, "/warm", "warm")) + { + return 0; + } + + SSL_shutdown(ssl); + SSL_free(ssl); + SSL_shutdown(control); + SSL_free(control); + SSL_SESSION_free(session); + SSL_CTX_free(ctx); + return 1; +} + +int +main(int argc, char **argv) +{ + alarm(8); + if (argc != 2 || !run(argv[1], 512) || !run(argv[1], 513)) { + ERR_print_errors_fp(stderr); + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +}