Using mbedTLS with non-blocking sockets

Hello, everyone!

I have a strange problem with my web-server getting blocked on mbedtls_ssl_handshake function after a few hours of operation (making a request to it every second). I am doing it on STM32F4 MCU using lwIp as a basis. Really, I do not know where to look at, I read some posts that incorrect configuration of lwIp could lead to it (http://lwip.100.n7.nabble.com/PolarSSL-and-mbedTLS-td28851.html) and tried lots of lwIp configurations, but still face this problem.

So, what I am thinking of is using mbedTLS with non-blocking sockets. My server code is exactly based on ssl_server.c example, just some application logic added. Can anyone point what is it needed to change in the code to make it work with non-blocking sockets?

I already checked mbedtls_net_set_nonblock(…) function and read some threads on forum on its application, however I can not find any real example on how to use it, in all the places there is some non clear explanation about it like rewriting net_sockets.c (how to use nonblock mbedtls_net_connect · Issue #1226 · Mbed-TLS/mbedtls · GitHub), but no exact information on what to change in it…

Any advices on this topis are more than welcome! Thank you!

Hi Evgeniy,
If Socket interface on your platform is a BSD socket, the that Mbed TLS supplied networking interface is compatioble with, you should call mbedtls_net_set_nonblock() on your mbedtls_net_context structure, and that should be enough, as you can see in the ssl_server2 example.
However, if in your platform, setting a socket to non blocking is different than fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL ) | O_NONBLOCK ), then you will need to implement your own API for your interface, and supply your send\recv callbacks.
AS you can see from the code, if a non blocking socket would block otherwise, the recv callback should return MBEDTLS_ERR_SSL_WANT_READ, which tells the application to continue the handshake.
Regards,
Mbed TLS Support
Ron