]> git.kaiwu.me - nginx.git/commitdiff
Mail: updated ngx_mail_send() to set handlers on s->quit.
authorMaxim Dounin <mdounin@mdounin.ru>
Sat, 20 Jun 2026 02:04:41 +0000 (05:04 +0300)
committerRoman Arutyunyan <arutyunyan.roman@gmail.com>
Wed, 11 Nov 2026 12:17:01 +0000 (16:17 +0400)
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 <v.zhestikov@f5.com>
Origin: <https://freenginx.org/hg/nginx/rev/87725983f346>

src/mail/ngx_mail_handler.c

index 2676f82b8d0f37cdea4f7118aaa7994376785039..5d8c792b84fb94a89260bbe9b74e71915011b746 100644 (file)
@@ -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)
 {