From 6e1a205819de6956584a0670f6d3eba23ca56650 Mon Sep 17 00:00:00 2001 From: Robert Lubos Date: Thu, 24 Aug 2023 12:55:07 +0200 Subject: [PATCH] net: sockets: Fix connected datagram socket packet filtering The previous patch to address race condition on STREAM sockets had a side effect on DGRAM socket, where net_context_recv() is not only installing recv callback, but also registering a connection at net_conn level. Doing so before setting remote address first (which is done in net_context_connect()) had an impact on the connected DGRAM socket operation, which now accepted packets from any remote peer, and not only the one socket was connected to. Signed-off-by: Robert Lubos --- subsys/net/lib/sockets/sockets.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/subsys/net/lib/sockets/sockets.c b/subsys/net/lib/sockets/sockets.c index 3a0705266d5..8a9b8ce8dfb 100644 --- a/subsys/net/lib/sockets/sockets.c +++ b/subsys/net/lib/sockets/sockets.c @@ -525,10 +525,22 @@ int zsock_connect_ctx(struct net_context *ctx, const struct sockaddr *addr, cb = zsock_connected_cb; } - SET_ERRNO(net_context_recv(ctx, zsock_received_cb, K_NO_WAIT, - ctx->user_data)); - SET_ERRNO(net_context_connect(ctx, addr, addrlen, cb, timeout, - ctx->user_data)); + if (net_context_get_type(ctx) == SOCK_STREAM) { + /* For STREAM sockets net_context_recv() only installs + * recv callback w/o side effects, and it has to be done + * first to avoid race condition, when TCP stream data + * arrives right after connect. + */ + SET_ERRNO(net_context_recv(ctx, zsock_received_cb, + K_NO_WAIT, ctx->user_data)); + SET_ERRNO(net_context_connect(ctx, addr, addrlen, cb, + timeout, ctx->user_data)); + } else { + SET_ERRNO(net_context_connect(ctx, addr, addrlen, cb, + timeout, ctx->user_data)); + SET_ERRNO(net_context_recv(ctx, zsock_received_cb, + K_NO_WAIT, ctx->user_data)); + } } return 0;