Skip to content

Commit 287230f

Browse files
committed
net: sockets: Explicitly flush conn/pkt queue on close()
If a socket is closed without reading all data from peer or accepting all pending connection, they will be leaked. So, flush queues explicitly. Signed-off-by: Paul Sokolovsky <[email protected]>
1 parent ac6ec7f commit 287230f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

subsys/net/lib/sockets/sockets.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,23 @@ static inline void _k_fifo_wait_non_empty(struct k_fifo *fifo, int32_t timeout)
3030
k_poll(events, ARRAY_SIZE(events), timeout);
3131
}
3232

33+
static void zsock_flush_queue(struct net_context *ctx)
34+
{
35+
bool is_listen = net_context_get_state(ctx) == NET_CONTEXT_LISTENING;
36+
void *p;
37+
38+
/* recv_q and accept_q are shared via a union */
39+
while ((p = k_fifo_get(&ctx->recv_q, K_NO_WAIT)) != NULL) {
40+
if (is_listen) {
41+
NET_DBG("discarding ctx %p", p);
42+
net_context_put(p);
43+
} else {
44+
NET_DBG("discarding pkt %p", p);
45+
net_pkt_unref(p);
46+
}
47+
}
48+
}
49+
3350
int zsock_socket(int family, int type, int proto)
3451
{
3552
struct net_context *ctx;
@@ -46,6 +63,14 @@ int zsock_close(int sock)
4663
{
4764
struct net_context *ctx = INT_TO_POINTER(sock);
4865

66+
/* Reset callbacks to avoid any race conditions while
67+
* flushing queues.
68+
*/
69+
net_context_accept(ctx, NULL, K_NO_WAIT, NULL);
70+
net_context_recv(ctx, NULL, K_NO_WAIT, NULL);
71+
72+
zsock_flush_queue(ctx);
73+
4974
SET_ERRNO(net_context_put(ctx));
5075
return 0;
5176
}

0 commit comments

Comments
 (0)