From b584007d4926ea8911a37aa290164bfa99fab266 Mon Sep 17 00:00:00 2001 From: lxsang Date: Wed, 10 Feb 2021 18:41:01 +0100 Subject: [PATCH] Race condition when get IP address from host in proxy mode - ip_from_hostname() is not thread safe - use global lock mechanism --- http_server.c | 20 +++++++++++++++++++- lib/utils.c | 10 +++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/http_server.c b/http_server.c index e94134e..8b7d025 100644 --- a/http_server.c +++ b/http_server.c @@ -839,6 +839,7 @@ static void *proxify(void *data) int port = atoi(dvalue(rq->request, "PROXY_PORT")); char *path = dvalue(rq->request, "PROXY_PATH"); char *query = dvalue(rq->request, "PROXY_QUERY"); + char* ptr, *ip; dictionary_t xheader = dvalue(rq->request, "REQUEST_HEADER"); antd_task_t *task = antd_create_task(NULL, data, NULL, rq->client->last_io); if (!xheader) @@ -846,7 +847,24 @@ static void *proxify(void *data) antd_error(rq->client, 400, "Badd Request"); return task; } - sock_fd = request_socket(ip_from_hostname(host), port); + pthread_mutex_lock(&server_mux); + ip = NULL; + // ip_from_host is not threadsafe, need to lock it + ptr = ip_from_hostname(host); + if(ptr) + { + ip = strdup(ptr); + } + pthread_mutex_unlock(&server_mux); + + if(!ip) + { + antd_error(rq->client, 502, "Badd address"); + return task; + } + + sock_fd = request_socket(ip, port); + free(ip); if (sock_fd == -1) { antd_error(rq->client, 503, "Service Unavailable"); diff --git a/lib/utils.c b/lib/utils.c index dcf4599..fc5d270 100644 --- a/lib/utils.c +++ b/lib/utils.c @@ -605,7 +605,11 @@ int request_socket(const char *ip, int port) { int sockfd; struct sockaddr_in dest; - + if(!ip) + { + ERROR("Invalid IP address"); + return -1; + } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { ERROR("Socket: %s", strerror(errno)); @@ -638,6 +642,10 @@ char* ip_from_hostname(const char *hostname) struct hostent *he; struct in_addr **addr_list; int i; + if(!hostname) + { + return NULL; + } if ((he = gethostbyname(hostname)) == NULL) { // get the host info