feat(esp_http_server): Added pre handshake callback for websocket

1. If the user wants authenticate the request, then user needs to do
this before upgrading the protocol to websocket.
2. To achieve this, added pre_handshake_callack, which will execute
before handshake, i.e. before switching protocol.
This commit is contained in:
hrushikesh.bhosale
2025-07-18 15:14:33 +05:30
parent b32c31e500
commit a40ceffb19
7 changed files with 139 additions and 3 deletions

View File

@@ -63,4 +63,13 @@ menu "HTTP Server"
help
This config option helps in setting the time in millisecond to wait for event to be posted to the
system default event loop. Set it to -1 if you need to set timeout to portMAX_DELAY.
config HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT
bool "WebSocket pre-handshake callback support"
default n
depends on HTTPD_WS_SUPPORT
help
Enable this option to use WebSocket pre-handshake callback. This will allow the server to register
a callback function that will be called before the WebSocket handshake is processed i.e. before switching
to the WebSocket protocol.
endmenu

View File

@@ -458,6 +458,14 @@ typedef struct httpd_uri {
* Pointer to subprotocol supported by URI
*/
const char *supported_subprotocol;
#if CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT || __DOXYGEN__
/**
* Pointer to WebSocket pre-handshake callback. This will be called before the WebSocket handshake is processed,
* i.e. before the server responds with the WebSocket handshake response or before switching to the WebSocket handler.
*/
esp_err_t (*ws_pre_handshake_cb)(httpd_req_t *req);
#endif
#endif
} httpd_uri_t;

View File

@@ -166,6 +166,9 @@ esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
hd->hd_calls[i]->method = uri_handler->method;
hd->hd_calls[i]->handler = uri_handler->handler;
hd->hd_calls[i]->user_ctx = uri_handler->user_ctx;
#ifdef CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT
hd->hd_calls[i]->ws_pre_handshake_cb = uri_handler->ws_pre_handshake_cb;
#endif
#ifdef CONFIG_HTTPD_WS_SUPPORT
hd->hd_calls[i]->is_websocket = uri_handler->is_websocket;
hd->hd_calls[i]->handle_ws_control_frames = uri_handler->handle_ws_control_frames;
@@ -320,6 +323,13 @@ esp_err_t httpd_uri(struct httpd_data *hd)
#ifdef CONFIG_HTTPD_WS_SUPPORT
struct httpd_req_aux *aux = req->aux;
if (uri->is_websocket && aux->ws_handshake_detect && uri->method == HTTP_GET) {
#ifdef CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT
if (uri->ws_pre_handshake_cb && uri->ws_pre_handshake_cb(req) != ESP_OK) {
ESP_LOGW(TAG, LOG_FMT("ws_pre_handshake_cb failed"));
return ESP_FAIL;
}
#endif
ESP_LOGD(TAG, LOG_FMT("Responding WS handshake to sock %d"), aux->sd->fd);
esp_err_t ret = httpd_ws_respond_server_handshake(&hd->hd_req, uri->supported_subprotocol);
if (ret != ESP_OK) {