Merge branch 'feat/support_authentication_feature_for_ws_v5.4' into 'release/v5.4'

Added pre handshake callback for websocket (v5.4)

See merge request espressif/esp-idf!41038
This commit is contained in:
Mahavir Jain
2025-09-02 09:18:37 +05:30
7 changed files with 142 additions and 9 deletions
+9
View File
@@ -58,4 +58,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
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: 2018-2024 Espressif Systems (Shanghai) CO LTD
* SPDX-FileCopyrightText: 2018-2025 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
@@ -455,6 +455,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;
@@ -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) {