Correct session closing procedure with mbedtls_ssl_close_notify()


I was wondering what the correct procedure to close a SSL connection is.

Currently, I call mbedtls_ssl_close_notify() and mbedtls_ssl_free() with the mbedtls_ssl_context.

However, if the peer has already closed the connection, mbedtls_ssl_close_notify() tries to write data and causes a SIGPIPE exception (I am on Linux). Although I can handle (ignore) this exception and continue executing, I was wondering if there is some way to avoid the exception entirely.

I guess what I’m looking for is either a way to detect if the connection was closed by the peer and don’t call mbedtls_ssl_close_notify(), or if I don’t have to call mbedtls_ssl_close_notify() at all.


Hi @ohnx Thank you for your question!

AS you can see from the ssl_client2 example, when the read function (or handshake function), return an error other than MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY or MBEDTLS_ERR_NET_CONN_RESET, it will just exit, freeing all the allocated memory.
If the peer already closed the connetion, the recv bio callback should probably return 0, which will cause the tls code to return MBEDTLS_ERR_SSL_CONN_EOF. This( and probably any other error) will indicate that you should close the connection without sending any message to the peer.
I hope this answers your question
Mbed TLS Team member