esp_http_client example: fix potential buffer overflow while copying data recieved in HTTP response
Closes
*/
#include <string.h>
+#include <sys/param.h>
#include <stdlib.h>
#include "esp_log.h"
#include "nvs_flash.h"
@@ -73,20 +74,28 @@ esp_err_t _http_event_handler(esp_http_client_event_t *evt)
*/
if (!esp_http_client_is_chunked_response(evt->client)) {
// If user_data buffer is configured, copy the response into the buffer
+ int copy_len = 0;
if (evt->user_data) {
- memcpy(evt->user_data + output_len, evt->data, evt->data_len);
+ copy_len = MIN(evt->data_len, (MAX_HTTP_OUTPUT_BUFFER - output_len));
+ if (copy_len) {
+ memcpy(evt->user_data + output_len, evt->data, copy_len);
+ }
} else {
+ const int buffer_len = esp_http_client_get_content_length(evt->client);
if (output_buffer == NULL) {
- output_buffer = (char *) malloc(esp_http_client_get_content_length(evt->client));
+ output_buffer = (char *) malloc(buffer_len);
output_len = 0;
if (output_buffer == NULL) {
ESP_LOGE(TAG, "Failed to allocate memory for output buffer");
return ESP_FAIL;
}
}
- memcpy(output_buffer + output_len, evt->data, evt->data_len);
+ copy_len = MIN(evt->data_len, (buffer_len - output_len));
+ if (copy_len) {
+ memcpy(output_buffer + output_len, evt->data, copy_len);
+ }
}
- output_len += evt->data_len;
+ output_len += copy_len;
}
break;
