Skip to content

Conversation

@gabsuren
Copy link
Collaborator

@gabsuren gabsuren commented Oct 28, 2025

TODO - Will remove comments after the review ( left it for easier review)

Description

This PR fixes critical memory leaks and crashes in the ESP WebSocket client that occur during reconnection scenarios(CONFIG_ESP_WS_CLIENT_SEPARATE_TX_LOCK = y).

  • Double-free crashes: Heap corruption during abort/reconnect scenarios
  • Data loss: First packet after reconnection not received
  • Error buffer accumulation: 2KB memory leak on disconnect

Changes Made:

  • Add state check in abort_connection to prevent double-close
  • Fix memory leak: free errormsg_buffer on disconnect
  • Reset connection state on reconnect to prevent stale data
  • Implement lock ordering for separate TX lock mode
  • Added sdkconfig.ci.tx_lock conf

Related

#898

Checklist

Before submitting a Pull Request, please ensure the following:

  • 🚨 This PR does not introduce breaking changes.
  • [ ✓ ] All CI checks (GH Actions) pass.
  • [ ✓] Documentation is updated as needed.
  • Tests are updated or added as necessary.
  • [ ✓] Code is well-commented, especially in complex areas.
  • [ ✓] Git history is clean — commits are squashed to the minimum necessary.

Note

Harden websocket client abort/reconnect paths with proper state checks and lock ordering, fix error-buffer leak, reset/handle early data on connect, and add tx-lock CI config.

  • WebSocket client (components/esp_websocket_client/esp_websocket_client.c):
    • Abort/Reconnect:
      • Add preconditioned esp_websocket_client_abort_connection() with state checks to skip redundant aborts and close transport safely.
      • Free client->errormsg_buffer on disconnect to prevent leaks.
    • Locking (separate TX lock mode):
      • Correct lock ordering and timeouts around send errors and PING/PONG handling; avoid deadlocks and ensure rx_buffer is freed on early returns.
      • On send error, release tx_lock, abort connection under client->lock, and exit cleanly.
    • Connection/reset:
      • On connect, reset payload_len/offset, last_fin, last_opcode and non-blocking poll to process data arriving during handshake.
      • In main loop, acquire client->lock before recv when data is ready; avoid double-locking.
    • Cleanup:
      • After destroying transport list, set client->transport_list and client->transport to NULL.
  • Examples/Config:
    • Add components/esp_websocket_client/examples/target/sdkconfig.ci.tx_lock enabling CONFIG_ESP_WS_CLIENT_SEPARATE_TX_LOCK with timeout and Ethernet settings.

Written by Cursor Bugbot for commit d202ae4. This will update automatically on new commits. Configure here.

@CLAassistant
Copy link

CLAassistant commented Oct 28, 2025

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

cursor[bot]

This comment was marked as outdated.

@gabsuren gabsuren changed the title Fix/ws race on abort fix(websocket): Fix websocket client race on abort and memory leak(IDFGH-16555) Oct 28, 2025
@gabsuren gabsuren force-pushed the fix/ws_race_on_abort branch 3 times, most recently from 67bd7e3 to 46871bf Compare October 28, 2025 13:09
#else
// When separate TX lock is not configured, we already hold client->lock
// which protects the transport, so we can send PONG directly
esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_PONG | WS_TRANSPORT_OPCODES_FIN, data, client->payload_len,

Check warning

Code scanning / clang-tidy

The value '138' provided to the cast expression is not in the valid range of values for 'ws_transport_opcodes' [clang-analyzer-optin.core.EnumCastOutOfRange] Warning

The value '138' provided to the cast expression is not in the valid range of values for 'ws_transport_opcodes' [clang-analyzer-optin.core.EnumCastOutOfRange]
@gabsuren gabsuren requested a review from david-cermak October 29, 2025 09:09
@gabsuren gabsuren force-pushed the fix/ws_race_on_abort branch from 46871bf to 5577e03 Compare October 29, 2025 10:54
cursor[bot]

This comment was marked as outdated.

@gabsuren gabsuren force-pushed the fix/ws_race_on_abort branch 3 times, most recently from ca2956e to 0e58789 Compare October 30, 2025 10:53
}
ESP_LOGD(TAG, "Calling abort_connection due to send error");
#ifdef CONFIG_ESP_WS_CLIENT_SEPARATE_TX_LOCK
xSemaphoreGiveRecursive(client->tx_lock);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is better to move this verification to abort connection function.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@euripedesrocha I am not sure about it, as abort connection is used in 5 different places, if we move it inside abort_connection it adds complex detection logic "which lock am I holding?" Only 1 place (send error path) needs lock switching (tx_lock → client->lock)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right in that sense but looking at it again it might be better to release the tx_lock after acquiring the main lock maybe at the end of this section after we complete the abort process to avoid task to be preempted.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Thank you! Updated accordingly

@gabsuren gabsuren force-pushed the fix/ws_race_on_abort branch from 0e58789 to 62925a5 Compare November 10, 2025 10:13
@gabsuren gabsuren force-pushed the fix/ws_race_on_abort branch 2 times, most recently from 15dcb35 to f474654 Compare November 10, 2025 10:27
@gabsuren
Copy link
Collaborator Author

#898 (comment)

@gabsuren gabsuren force-pushed the fix/ws_race_on_abort branch from 50e3068 to 22eb17e Compare November 19, 2025 11:44
@gabsuren gabsuren force-pushed the fix/ws_race_on_abort branch 2 times, most recently from 52abfc0 to 30778c0 Compare November 25, 2025 11:02
Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is being reviewed by Cursor Bugbot

Details

Your team is on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle for each member of your team.

To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.

- Add state check in abort_connection to prevent double-close
- Fix memory leak: free errormsg_buffer on disconnect
- Reset connection state on reconnect to prevent stale data
- Implement lock ordering for separate TX lock mode
- Read buffered data immediately after connection to prevent data loss
- Added sdkconfig.ci.tx_lock config
@gabsuren gabsuren force-pushed the fix/ws_race_on_abort branch from 30778c0 to d202ae4 Compare November 25, 2025 11:12
esp_event_loop_run(client->event_handle, 0);
}
}
break;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Missing error handling for recv failure after connect

The new immediate poll code after connection calls esp_websocket_client_recv but does not handle the ESP_FAIL return case. When recv_result is not ESP_OK, the code simply skips the event loop run without logging an error or calling esp_websocket_client_abort_connection. This is inconsistent with the existing error handling at lines 1293-1296, which properly logs the error and aborts the connection when esp_websocket_client_recv fails. Since WEBSOCKET_EVENT_CONNECTED is already dispatched at line 1206, failing silently here could leave the client in an inconsistent state where the user believes the connection succeeded but data reception failed.

Fix in Cursor Fix in Web

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants