Commit c0d5d2fb authored by Robert Lubos's avatar Robert Lubos Committed by Fabio Baltieri
Browse files

net: sockets: tls: Allow handshake during poll()



When using DTLS socket, the application may choose to monitor socket
with poll() before handshake has been complete. This could lead to
potential crash (as the TLS context may have been left uninitialized)
and unexpected POLLIN reports (while handshake was still not complete).
This commit fixes the above - POLLIN will only be reported once
handshake is complete and data is available

Signed-off-by: default avatarRobert Lubos <robert.lubos@nordicsemi.no>
parent 0a1bee48
Loading
Loading
Loading
Loading
+41 −0
Original line number Diff line number Diff line
@@ -2910,10 +2910,51 @@ exit:
	return ret;
}

#include <zephyr/net/net_core.h>

static int ztls_socket_data_check(struct tls_context *ctx)
{
	int ret;

	if (ctx->type == SOCK_STREAM) {
		if (!ctx->is_initialized) {
			return -ENOTCONN;
		}
	}
#if defined(CONFIG_NET_SOCKETS_ENABLE_DTLS)
	else {
		if (!ctx->is_initialized) {
			bool is_server = ctx->options.role == MBEDTLS_SSL_IS_SERVER;

			ret = tls_mbedtls_init(ctx, is_server);
			if (ret < 0) {
				return -ENOMEM;
			}
		}

		if (!is_handshake_complete(ctx)) {
			ret = tls_mbedtls_handshake(ctx, K_NO_WAIT);
			if (ret < 0) {
				if (ret == -EAGAIN) {
					return 0;
				}

				ret = tls_mbedtls_reset(ctx);
				if (ret != 0) {
					return -ENOMEM;
				}

				return 0;
			}

			/* Socket ready to use again. */
			ctx->error = 0;

			return 0;
		}
	}
#endif /* CONFIG_NET_SOCKETS_ENABLE_DTLS */

	ctx->flags = ZSOCK_MSG_DONTWAIT;

	ret = mbedtls_ssl_read(&ctx->ssl, NULL, 0);