From: Maxim Dounin Date: Sat, 20 Jun 2026 02:04:41 +0000 (+0300) Subject: Mail: updated ngx_mail_send() to set handlers on s->quit. X-Git-Tag: release-1.31.9~8 X-Git-Url: https://git.kaiwu.me/web/%22data:,/doc/static/%7B@url%7D?a=commitdiff_plain;h=e505109a3f21074bf0414eb8241a37085d2da8cb;p=nginx.git Mail: updated ngx_mail_send() to set handlers on s->quit. Most notably, this fixes potential issues when a fatal error message is sent with ngx_mail_send() with s->quit set, but the read handler is not updated. Despite s->quit, ngx_mail_send() might not be able to send the error message immediately, and the read handler might be called on read events. In particular, in ngx_mail_auth_http_block_read() and in ngx_mail_proxy_block_read() this could potentially cause accesses to freed memory or already closed connections in ngx_handle_read_event() error handling code paths. Reported by Evan Hellman, https://github.com/freenginx/nginx/issues/23 https://github.com/freenginx/nginx/issues/24 Signed-off-by: Vadim Zhestikov Origin: --- diff --git a/src/mail/ngx_mail_handler.c b/src/mail/ngx_mail_handler.c index 2676f82b8..5d8c792b8 100644 --- a/src/mail/ngx_mail_handler.c +++ b/src/mail/ngx_mail_handler.c @@ -14,6 +14,7 @@ static void ngx_mail_proxy_protocol_handler(ngx_event_t *rev); static void ngx_mail_init_session_handler(ngx_event_t *rev); static void ngx_mail_init_session(ngx_connection_t *c); +static void ngx_mail_block_read(ngx_event_t *rev); #if (NGX_MAIL_SSL) static void ngx_mail_ssl_init_connection(ngx_ssl_t *ssl, ngx_connection_t *c); @@ -413,8 +414,6 @@ ngx_mail_verify_cert(ngx_mail_session_t *s, ngx_connection_t *c) s->out = cscf->protocol->cert_error; s->quit = 1; - c->write->handler = ngx_mail_send; - ngx_mail_send(s->connection->write); return NGX_ERROR; } @@ -434,8 +433,6 @@ ngx_mail_verify_cert(ngx_mail_session_t *s, ngx_connection_t *c) s->out = cscf->protocol->no_cert; s->quit = 1; - c->write->handler = ngx_mail_send; - ngx_mail_send(s->connection->write); return NGX_ERROR; } @@ -822,6 +819,11 @@ again: ngx_add_timer(c->write, cscf->timeout); + if (s->quit) { + c->read->handler = ngx_mail_block_read; + c->write->handler = ngx_mail_send; + } + if (ngx_handle_write_event(c->write, 0) != NGX_OK) { ngx_mail_close_connection(c); return; @@ -940,6 +942,17 @@ ngx_mail_session_internal_server_error(ngx_mail_session_t *s) } +static void +ngx_mail_block_read(ngx_event_t *rev) +{ + ngx_log_debug0(NGX_LOG_DEBUG_MAIL, rev->log, 0, "mail block read"); + + if (ngx_handle_read_event(rev, 0) != NGX_OK) { + ngx_mail_close_connection(rev->data); + } +} + + void ngx_mail_close_connection(ngx_connection_t *c) {