esp_http_server: fix wrong context pointer in httpd_req_cleanup function

Added example which fails without the fix

Closes https://github.com/espressif/esp-idf/issues/10265
This commit is contained in:
Harshit Malpani
2022-11-29 16:56:22 +05:30
parent 6569be485b
commit 89a56392e3
5 changed files with 82 additions and 1 deletions

View File

@@ -99,6 +99,47 @@ static esp_err_t adder_get_handler(httpd_req_t *req)
return ESP_OK;
}
#if CONFIG_EXAMPLE_SESSION_CTX_HANDLERS
// login and logout handler are created to test the server functionality to delete the older sess_ctx if it is changed from another handler.
// login handler creates a new sess_ctx
static esp_err_t login_handler(httpd_req_t *req)
{
/* Log total visitors */
unsigned *visitors = (unsigned *)req->user_ctx;
ESP_LOGI(TAG, "/login visitor count = %d", ++(*visitors));
char outbuf[50];
/* Create session's context if not already available */
if (! req->sess_ctx) {
ESP_LOGI(TAG, "/login GET allocating new session");
req->sess_ctx = malloc(sizeof(int));
if (!req->sess_ctx) {
return ESP_ERR_NO_MEM;
}
*(int *)req->sess_ctx = 1;
}
ESP_LOGI(TAG, "/login GET handler send %d", *(int *)req->sess_ctx);
/* Respond with the accumulated value */
snprintf(outbuf, sizeof(outbuf),"%d", *((int *)req->sess_ctx));
httpd_resp_send(req, outbuf, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
// This handler sets sess_ctx to NULL.
static esp_err_t logout_handler(httpd_req_t *req)
{
ESP_LOGI(TAG, "Logging out");
// Setting sess_ctx to NULL here. This is done to test the server functionality to free the older sesss_ctx if it is changed by some handler.
req->sess_ctx = NULL;
char outbuf[50];
snprintf(outbuf, sizeof(outbuf),"%d", 1);
httpd_resp_send(req, outbuf, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
#endif // CONFIG_EXAMPLE_SESSION_CTX_HANDLERS
/* This handler resets the value of the accumulator */
static esp_err_t adder_put_handler(httpd_req_t *req)
{
@@ -155,6 +196,22 @@ static const httpd_uri_t adder_get = {
.user_ctx = &visitors
};
#if CONFIG_EXAMPLE_SESSION_CTX_HANDLERS
static const httpd_uri_t login = {
.uri = "/login",
.method = HTTP_GET,
.handler = login_handler,
.user_ctx = &visitors
};
static const httpd_uri_t logout = {
.uri = "/logout",
.method = HTTP_GET,
.handler = logout_handler,
.user_ctx = &visitors
};
#endif // CONFIG_EXAMPLE_SESSION_CTX_HANDLERS
static const httpd_uri_t adder_put = {
.uri = "/adder",
.method = HTTP_PUT,
@@ -173,6 +230,10 @@ static httpd_handle_t start_webserver(void)
// Set URI handlers
ESP_LOGI(TAG, "Registering URI handlers");
httpd_register_uri_handler(server, &adder_get);
#if CONFIG_EXAMPLE_SESSION_CTX_HANDLERS
httpd_register_uri_handler(server, &login);
httpd_register_uri_handler(server, &logout);
#endif // CONFIG_EXAMPLE_SESSION_CTX_HANDLERS
httpd_register_uri_handler(server, &adder_put);
httpd_register_uri_handler(server, &adder_post);
return server;