From 6264c048f81687ae529dffe0e39d145b2fc8b40c Mon Sep 17 00:00:00 2001 From: kikuchan Date: Fri, 30 Mar 2018 02:31:41 +0900 Subject: [PATCH] Make upstream works properly when IP/mask is specified closes #83 --- src/upstream.c | 71 ++++++++++++++++++++++++++++++++++---------------- 1 file changed, 49 insertions(+), 22 deletions(-) diff --git a/src/upstream.c b/src/upstream.c index 327b727..536b3cd 100644 --- a/src/upstream.c +++ b/src/upstream.c @@ -43,6 +43,45 @@ proxy_type_name(proxy_type type) } } +/** + * Parse and process a netmask format (IP/mask), otherwise treat as a domain + */ +static int upstream_handle_netmask_or_domain(struct upstream *up, const char *domain) +{ + char *ptr; + char *domain_work; + + domain_work = safestrdup (domain); + + ptr = strchr (domain_work, '/'); + if (ptr) { + struct in_addr addrstruct; + + *ptr = '\0'; + if (inet_aton (domain_work, &addrstruct) != 0) { + up->ip = ntohl (addrstruct.s_addr); + *ptr++ = '/'; + + if (strchr (ptr, '.')) { + if (inet_aton (ptr, &addrstruct) != 0) + up->mask = + ntohl (addrstruct.s_addr); + } else { + up->mask = + ~((1 << (32 - atoi (ptr))) - 1); + } + } else { + return 0; + } + + safefree (domain_work); + } else { + up->domain = domain_work; + } + + return 1; +} + /** * Construct an upstream struct from input data. */ @@ -50,7 +89,6 @@ static struct upstream *upstream_build (const char *host, int port, const char * const char *user, const char *pass, proxy_type type) { - char *ptr; struct upstream *up; up = (struct upstream *) safemalloc (sizeof (struct upstream)); @@ -99,26 +137,10 @@ static struct upstream *upstream_build (const char *host, int port, const char * goto fail; } - ptr = strchr (domain, '/'); - if (ptr) { - struct in_addr addrstruct; - - *ptr = '\0'; - if (inet_aton (domain, &addrstruct) != 0) { - up->ip = ntohl (addrstruct.s_addr); - *ptr++ = '/'; - - if (strchr (ptr, '.')) { - if (inet_aton (ptr, &addrstruct) != 0) - up->mask = - ntohl (addrstruct.s_addr); - } else { - up->mask = - ~((1 << (32 - atoi (ptr))) - 1); - } - } - } else { - up->domain = safestrdup (domain); + if (!upstream_handle_netmask_or_domain(up, domain)) { + log_message (LOG_WARNING, + "Nonsense no-upstream rule: invalid domain"); + goto fail; } log_message (LOG_INFO, "Added no-upstream for %s", domain); @@ -132,7 +154,12 @@ static struct upstream *upstream_build (const char *host, int port, const char * up->host = safestrdup (host); up->port = port; - up->domain = safestrdup (domain); + + if (!upstream_handle_netmask_or_domain(up, domain)) { + log_message (LOG_WARNING, + "Nonsense upstream rule: invalid domain"); + goto fail; + } log_message (LOG_INFO, "Added upstream %s %s:%d for %s", proxy_type_name(type), host, port, domain);