Skip to content

Commit b4366a8

Browse files
rluboscfriedt
authored andcommitted
net: sockets: tls: Fix handshake on non blocking sockets
The TLS/DTLS handshake in most cases is a blocking process, therefore the underlying socket should be in a blocking mode to prevent busy looping in the handshake thread. Fix this by clearing the O_NONBLOCK flag on the underlying socket before the handshake, and restoring it afterards. Signed-off-by: Robert Lubos <[email protected]>
1 parent 1531863 commit b4366a8

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

subsys/net/lib/sockets/sockets_tls.c

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,20 @@ static int tls_mbedtls_reset(struct tls_context *context)
820820
static int tls_mbedtls_handshake(struct tls_context *context, bool block)
821821
{
822822
int ret;
823+
int sock_flags;
824+
825+
sock_flags = zsock_fcntl(context->sock, F_GETFL, 0);
826+
if (sock_flags < 0) {
827+
return -EIO;
828+
}
829+
830+
if (block && sock_flags & O_NONBLOCK) {
831+
/* Clear the O_NONBLOCK flag for the handshake to prevent busy
832+
* looping in the handshake thread.
833+
*/
834+
(void)zsock_fcntl(context->sock, F_SETFL,
835+
sock_flags & ~O_NONBLOCK);
836+
}
823837

824838
while ((ret = mbedtls_ssl_handshake(&context->ssl)) != 0) {
825839
if (ret == MBEDTLS_ERR_SSL_WANT_READ ||
@@ -847,6 +861,10 @@ static int tls_mbedtls_handshake(struct tls_context *context, bool block)
847861
break;
848862
}
849863

864+
if (block && sock_flags & O_NONBLOCK) {
865+
(void)zsock_fcntl(context->sock, F_SETFL, sock_flags);
866+
}
867+
850868
if (ret == 0) {
851869
k_sem_give(&context->tls_established);
852870
}

0 commit comments

Comments
 (0)