From a83e7d8c4294b2644d83386a8a44b541a0a2786c Mon Sep 17 00:00:00 2001
From: Deomid Ryabkov <rojer@cesanta.com>
Date: Thu, 16 Mar 2017 00:53:01 +0200
Subject: [PATCH] Properly shut down the SSL connection

By sending close_notify

PUBLISHED_FROM=028a001cb9470a16cc7a6544805bfb042a435779
---
 mongoose.c | 22 ++++++++++++++++++++++
 mongoose.h |  1 +
 2 files changed, 23 insertions(+)

diff --git a/mongoose.c b/mongoose.c
index a24c89f22..3db5e8134 100644
--- a/mongoose.c
+++ b/mongoose.c
@@ -2111,6 +2111,11 @@ static void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
 
 void mg_close_conn(struct mg_connection *conn) {
   DBG(("%p %lu %d", conn, conn->flags, conn->sock));
+#if MG_ENABLE_SSL
+  if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
+    mg_ssl_if_conn_close_notify(conn);
+  }
+#endif
   mg_remove_conn(conn);
   conn->iface->vtable->destroy_conn(conn);
   mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL);
@@ -4150,6 +4155,12 @@ int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
   return n;
 }
 
+void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
+  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
+  if (ctx == NULL) return;
+  SSL_shutdown(ctx->ssl);
+}
+
 void mg_ssl_if_conn_free(struct mg_connection *nc) {
   struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
   if (ctx == NULL) return;
@@ -4637,6 +4648,12 @@ int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
   return n;
 }
 
+void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
+  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
+  if (ctx == NULL) return;
+  mbedtls_ssl_close_notify(ctx->ssl);
+}
+
 void mg_ssl_if_conn_free(struct mg_connection *nc) {
   struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
   if (ctx == NULL) return;
@@ -13638,6 +13655,11 @@ enum mg_ssl_if_result mg_ssl_if_conn_init(
   return MG_SSL_OK;
 }
 
+void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
+  /* Nothing to do */
+  (void) nc;
+}
+
 void mg_ssl_if_conn_free(struct mg_connection *nc) {
   struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
   if (ctx == NULL) return;
diff --git a/mongoose.h b/mongoose.h
index bc8c8c21e..5109171df 100644
--- a/mongoose.h
+++ b/mongoose.h
@@ -3153,6 +3153,7 @@ enum mg_ssl_if_result mg_ssl_if_conn_init(
     const char **err_msg);
 enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
                                             struct mg_connection *lc);
+void mg_ssl_if_conn_close_notify(struct mg_connection *nc);
 void mg_ssl_if_conn_free(struct mg_connection *nc);
 
 enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc);
-- 
GitLab