From f31a0f7f61156aaf4fe81cb57cef4d9229b83603 Mon Sep 17 00:00:00 2001 From: Bernhard Heinloth Date: Thu, 13 Feb 2025 11:24:27 +0100 Subject: [PATCH] fix(esp_http_client): Fix host header for IPv6 address literal An IPv6 IP that occurs in the 'Host:' header of an HTTP request must be enclosed in square brackets (RFC3986 section 3.2.2). Searches for ':' in the host string to efficiently determine if the host is an IPv6 IP address. --- components/esp_http_client/esp_http_client.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/components/esp_http_client/esp_http_client.c b/components/esp_http_client/esp_http_client.c index 9ed66e02be..418b9b3191 100644 --- a/components/esp_http_client/esp_http_client.c +++ b/components/esp_http_client/esp_http_client.c @@ -703,10 +703,13 @@ static char *_get_host_header(char *host, int port) { int err = 0; char *host_name; + assert(host != NULL); + // Check if host is an IPv6 address literal that needs square brackets according to RFC3986 + bool is_ipv6 = (host[0] != '[' && strchr(host, ':') != NULL); if (port != DEFAULT_HTTP_PORT && port != DEFAULT_HTTPS_PORT) { - err = asprintf(&host_name, "%s:%d", host, port); + err = asprintf(&host_name, is_ipv6 ? "[%s]:%d" : "%s:%d", host, port); } else { - err = asprintf(&host_name, "%s", host); + err = asprintf(&host_name, is_ipv6 ? "[%s]" : "%s", host); } if (err == -1) { return NULL;