Introduce SSL helper function to mark pending alerts
diff --git a/include/mbedtls/ssl.h b/include/mbedtls/ssl.h
index a41182c..a871540 100644
--- a/include/mbedtls/ssl.h
+++ b/include/mbedtls/ssl.h
@@ -366,6 +366,7 @@
 #define MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME    112  /* 0x70 */
 #define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY 115  /* 0x73 */
 #define MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL 120 /* 0x78 */
+#define MBEDTLS_SSL_ALERT_MSG_NONE                 255  /* internal */
 
 #define MBEDTLS_SSL_HS_HELLO_REQUEST            0
 #define MBEDTLS_SSL_HS_CLIENT_HELLO             1
@@ -1234,6 +1235,9 @@
 {
     const mbedtls_ssl_config *conf; /*!< configuration information          */
 
+    unsigned char pend_alert_level;
+    unsigned char pend_alert_msg;
+
     /*
      * Miscellaneous
      */
diff --git a/include/mbedtls/ssl_internal.h b/include/mbedtls/ssl_internal.h
index b8875ab..0db867c 100644
--- a/include/mbedtls/ssl_internal.h
+++ b/include/mbedtls/ssl_internal.h
@@ -1724,4 +1724,15 @@
 
 #endif /* MBEDTLS_SSL_CONF_SINGLE_SIG_HASH */
 
+__attribute__((always_inline)) static inline int mbedtls_ssl_pend_alert_message(
+    mbedtls_ssl_context *ssl,
+    unsigned char level,
+    unsigned char message )
+{
+    if( level != MBEDTLS_SSL_ALERT_LEVEL_FATAL )
+        ssl->pend_alert_level = level;
+    ssl->pend_alert_msg = message;
+    return( 0 );
+}
+
 #endif /* ssl_internal.h */
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index fc7ece7..8e394cf 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -7983,6 +7983,9 @@
     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
         goto error;
 
+    ssl->pend_alert_msg   = MBEDTLS_SSL_ALERT_MSG_NONE;
+    ssl->pend_alert_level = MBEDTLS_SSL_ALERT_LEVEL_FATAL;
+
     return( 0 );
 
 error:
@@ -9835,6 +9838,14 @@
         ret = mbedtls_ssl_handshake_server_step( ssl );
 #endif
 
+    if( ssl->pend_alert_msg != MBEDTLS_SSL_ALERT_MSG_NONE )
+    {
+        mbedtls_ssl_send_alert_message( ssl,
+                                        ssl->pend_alert_level,
+                                        ssl->pend_alert_msg );
+        ssl->pend_alert_msg   = MBEDTLS_SSL_ALERT_MSG_NONE;
+        ssl->pend_alert_level = MBEDTLS_SSL_ALERT_LEVEL_FATAL;
+    }
     return( ret );
 }