From 019f78b09133500f4ef6228fe5b263d0323a8394 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20BRIAND?= Date: Tue, 30 Jul 2024 15:06:11 +0200 Subject: [PATCH] drivers: wifi: eswifi: Fix memory buffer allocation in off_read_work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When receiving data over the eswifi module, we currently read the data first, then allocate a buffer, and finally write the data into the buffer. The issue is that if we can't allocate the buffer, the data that was read is lost. To fix this, we should first attempt to allocate the buffer before reading any data. If we can't allocate the buffer, we should not proceed with reading the data. By allocating a buffer with the MTU size, we can read the packet, write it into the allocated buffer and then resize by removing unused allocated buffer with net_pkt_trim_buffer(). Signed-off-by: Léo BRIAND --- drivers/wifi/eswifi/eswifi_socket.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/drivers/wifi/eswifi/eswifi_socket.c b/drivers/wifi/eswifi/eswifi_socket.c index 9ae607b2341a6..f4c546f0ff0a7 100644 --- a/drivers/wifi/eswifi/eswifi_socket.c +++ b/drivers/wifi/eswifi/eswifi_socket.c @@ -133,33 +133,40 @@ static void eswifi_off_read_work(struct k_work *work) __select_socket(eswifi, socket->index); + /* Verify if we can allocate a rx packet before reading data to prevent leaks */ + pkt = net_pkt_rx_alloc_with_buffer(eswifi->iface, 1460, + AF_UNSPEC, 0, K_NO_WAIT); + if (!pkt) { + LOG_ERR("Cannot allocate rx packet"); + goto done; + } + len = __read_data(eswifi, 1460, &data); /* 1460 is max size */ if (len < 0) { __stop_socket(eswifi, socket); if (socket->recv_cb) { /* send EOF (null pkt) */ + net_pkt_unref(pkt); + pkt = NULL; goto do_recv_cb; } } if (!len || !socket->recv_cb) { + net_pkt_unref(pkt); goto done; } LOG_DBG("payload sz = %d", len); - pkt = net_pkt_rx_alloc_with_buffer(eswifi->iface, len, - AF_UNSPEC, 0, K_NO_WAIT); - if (!pkt) { - LOG_ERR("Cannot allocate rx packet"); - goto done; - } - if (net_pkt_write(pkt, data, len) < 0) { LOG_WRN("Incomplete buffer copy"); } + /* Resize the packet */ + net_pkt_trim_buffer(pkt); + net_pkt_cursor_init(pkt); do_recv_cb: