/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
*
\n" "Reason: ", ap_escape_html(r->pool, message), "", NULL)); /* Allow "error-notes" string to be printed by ap_send_error_response() */ ap_table_setn(r->notes, "verbose-error-to", ap_pstrdup(r->pool, "*")); r->status_line = ap_psprintf(r->pool, "%3.3u Proxy Error", statuscode); return statuscode; } /* * This routine returns its own error message */ const char * ap_proxy_host2addr(const char *host, struct hostent * reqhp) { int i; struct hostent *hp; struct per_thread_data *ptd = get_per_thread_data(); for (i = 0; host[i] != '\0'; i++) if (!ap_isdigit(host[i]) && host[i] != '.') break; if (host[i] != '\0') { hp = gethostbyname(host); if (hp == NULL) return "Host not found"; } else { ptd->ipaddr = ap_inet_addr(host); hp = gethostbyaddr((char *)&ptd->ipaddr, sizeof(ptd->ipaddr), AF_INET); if (hp == NULL) { memset(&ptd->hpbuf, 0, sizeof(ptd->hpbuf)); ptd->hpbuf.h_name = 0; ptd->hpbuf.h_addrtype = AF_INET; ptd->hpbuf.h_length = sizeof(ptd->ipaddr); ptd->hpbuf.h_addr_list = ptd->charpbuf; ptd->hpbuf.h_addr_list[0] = (char *)&ptd->ipaddr; ptd->hpbuf.h_addr_list[1] = 0; hp = &ptd->hpbuf; } } *reqhp = *hp; return NULL; } static const char * proxy_get_host_of_request(request_rec *r) { char *url, *user = NULL, *password = NULL, *err, *host; int port = -1; if (r->hostname != NULL) return r->hostname; /* Set url to the first char after "scheme://" */ if ((url = strchr(r->uri, ':')) == NULL || url[1] != '/' || url[2] != '/') return NULL; url = ap_pstrdup(r->pool, &url[1]); /* make it point to "//", which is * what proxy_canon_netloc expects */ err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port); if (err != NULL) ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, r, "%s", err); r->hostname = host; return host; /* ought to return the port, too */ } /* Return TRUE if addr represents an IP address (or an IP network address) */ int ap_proxy_is_ipaddr(struct dirconn_entry *This, pool *p) { const char *addr = This->name; long ip_addr[4]; int i, quads; long bits; /* if the address is given with an explicit netmask, use that */ /* Due to a deficiency in ap_inet_addr(), it is impossible to parse */ /* "partial" addresses (with less than 4 quads) correctly, i.e. */ /* 192.168.123 is parsed as 192.168.0.123, which is not what I want. */ /* I therefore have to parse the IP address manually: */ /* * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) * == 0) */ /* addr and mask were set by proxy_readmask() */ /* return 1; */ /* Parse IP addr manually, optionally allowing */ /* abbreviated net addresses like 192.168. */ /* Iterate over up to 4 (dotted) quads. */ for (quads = 0; quads < 4 && *addr != '\0'; ++quads) { char *tmp; if (*addr == '/' && quads > 0) /* netmask starts here. */ break; if (!ap_isdigit(*addr)) return 0; /* no digit at start of quad */ ip_addr[quads] = ap_strtol(addr, &tmp, 0); if (tmp == addr) /* expected a digit, found something else */ return 0; if (ip_addr[quads] < 0 || ip_addr[quads] > 255) { /* invalid octet */ return 0; } addr = tmp; if (*addr == '.' && quads != 3) ++addr; /* after the 4th quad, a dot would be illegal */ } for (This->addr.s_addr = 0, i = 0; i < quads; ++i) This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i)); if (addr[0] == '/' && ap_isdigit(addr[1])) { /* net mask follows: */ char *tmp; ++addr; bits = ap_strtol(addr, &tmp, 0); if (tmp == addr) /* expected a digit, found something else */ return 0; addr = tmp; if (bits < 0 || bits > 32) /* netmask must be between 0 and 32 */ return 0; } else { /* Determine (i.e., "guess") netmask by counting the */ /* number of trailing .0's; reduce #quads appropriately */ /* (so that 192.168.0.0 is equivalent to 192.168.) */ while (quads > 0 && ip_addr[quads - 1] == 0) --quads; /* * "IP Address should be given in dotted-quad form, optionally * followed by a netmask (e.g., 192.168.111.0/24)"; */ if (quads < 1) return 0; /* every zero-byte counts as 8 zero-bits */ bits = 8 * quads; if (bits != 32) /* no warning for fully qualified IP address */ fprintf(stderr, "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld\n", inet_ntoa(This->addr), bits); } This->mask.s_addr = htonl(INADDR_NONE << (32 - bits)); if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) { fprintf(stderr, "Warning: NetMask and IP-Addr disagree in %s/%ld\n", inet_ntoa(This->addr), bits); This->addr.s_addr &= This->mask.s_addr; fprintf(stderr, " Set to %s/%ld\n", inet_ntoa(This->addr), bits); } if (*addr == '\0') { This->matcher = proxy_match_ipaddr; return 1; } else return (*addr == '\0'); /* okay iff we've parsed the whole string */ } /* Return TRUE if addr represents an IP address (or an IP network address) */ static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r) { int i; int ip_addr[4]; struct in_addr addr; struct in_addr *ip_list; char **ip_listptr; const char *found; const char *host = proxy_get_host_of_request(r); if (host == NULL) /* oops! */ return 0; memset(&addr, '\0', sizeof addr); memset(ip_addr, '\0', sizeof ip_addr); if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) { for (addr.s_addr = 0, i = 0; i < 4; ++i) addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i)); if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) { #if DEBUGGING fprintf(stderr, "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr)); fprintf(stderr, "%s/", inet_ntoa(This->addr)); fprintf(stderr, "%s\n", inet_ntoa(This->mask)); #endif return 1; } #if DEBUGGING else { fprintf(stderr, "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr)); fprintf(stderr, "%s/", inet_ntoa(This->addr)); fprintf(stderr, "%s\n", inet_ntoa(This->mask)); } #endif } else { struct hostent the_host; memset(&the_host, '\0', sizeof the_host); found = ap_proxy_host2addr(host, &the_host); if (found != NULL) { #if DEBUGGING fprintf(stderr, "2)IP-NoMatch: hostname=%s msg=%s\n", host, found); #endif return 0; } if (the_host.h_name != NULL) found = the_host.h_name; else found = host; /* Try to deal with multiple IP addr's for a host */ for (ip_listptr = the_host.h_addr_list; *ip_listptr; ++ip_listptr) { ip_list = (struct in_addr *)*ip_listptr; if (This->addr.s_addr == (ip_list->s_addr & This->mask.s_addr)) { #if DEBUGGING fprintf(stderr, "3)IP-Match: %s[%s] <-> ", found, inet_ntoa(*ip_list)); fprintf(stderr, "%s/", inet_ntoa(This->addr)); fprintf(stderr, "%s\n", inet_ntoa(This->mask)); #endif return 1; } #if DEBUGGING else { fprintf(stderr, "3)IP-NoMatch: %s[%s] <-> ", found, inet_ntoa(*ip_list)); fprintf(stderr, "%s/", inet_ntoa(This->addr)); fprintf(stderr, "%s\n", inet_ntoa(This->mask)); } #endif } } return 0; } /* Return TRUE if addr represents a domain name */ int ap_proxy_is_domainname(struct dirconn_entry *This, pool *p) { char *addr = This->name; int i; /* Domain name must start with a '.' */ if (addr[0] != '.') return 0; /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */ for (i = 0; ap_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i) continue; if (addr[i] != '\0') return 0; /* Strip trailing dots */ for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) addr[i] = '\0'; This->matcher = proxy_match_domainname; return 1; } /* Return TRUE if host "host" is in domain "domain" */ static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r) { const char *host = proxy_get_host_of_request(r); int d_len = strlen(This->name), h_len; if (host == NULL) /* some error was logged already */ return 0; h_len = strlen(host); /* @@@ do this within the setup? */ /* Ignore trailing dots in domain comparison: */ while (d_len > 0 && This->name[d_len - 1] == '.') --d_len; while (h_len > 0 && host[h_len - 1] == '.') --h_len; return h_len > d_len && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0; } /* Return TRUE if addr represents a host name */ int ap_proxy_is_hostname(struct dirconn_entry *This, pool *p) { struct hostent host; char *addr = This->name; int i; /* Host names must not start with a '.' */ if (addr[0] == '.') return 0; /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */ for (i = 0; ap_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i); if (addr[i] != '\0' || ap_proxy_host2addr(addr, &host) != NULL) return 0; This->hostentry = ap_pduphostent(p, &host); /* Strip trailing dots */ for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) addr[i] = '\0'; This->matcher = proxy_match_hostname; return 1; } /* Return TRUE if host "host" is equal to host2 "host2" */ static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r) { char *host = This->name; const char *host2 = proxy_get_host_of_request(r); int h2_len; int h1_len; if (host == NULL || host2 == NULL) return 0; /* oops! */ h2_len = strlen(host2); h1_len = strlen(host); /* Ignore trailing dots in host2 comparison: */ while (h2_len > 0 && host2[h2_len - 1] == '.') --h2_len; while (h1_len > 0 && host[h1_len - 1] == '.') --h1_len; return h1_len == h2_len && strncasecmp(host, host2, h1_len) == 0; } /* Return TRUE if addr is to be matched as a word */ int ap_proxy_is_word(struct dirconn_entry *This, pool *p) { This->matcher = proxy_match_word; return 1; } /* Return TRUE if string "str2" occurs literally in "str1" */ static int proxy_match_word(struct dirconn_entry *This, request_rec *r) { const char *host = proxy_get_host_of_request(r); return host != NULL && strstr(host, This->name) != NULL; } int ap_proxy_doconnect(int sock, struct sockaddr_in *addr, request_rec *r) { int i; ap_hard_timeout("proxy connect", r); do { i = connect(sock, (struct sockaddr *)addr, sizeof(struct sockaddr_in)); } while (i == -1 && errno == EINTR); if (i == -1) { ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "proxy connect to %s port %d failed", inet_ntoa(addr->sin_addr), ntohs(addr->sin_port)); } ap_kill_timeout(r); return i; } /* This function is called by ap_table_do() for all header lines * (from proxy_http.c and proxy_ftp.c) * It is passed a cache_req struct pointer and a MIME field and value pair */ int ap_proxy_send_hdr_line(void *p, const char *key, const char *value) { cache_req *c = (cache_req *)p; if (key == NULL || value == NULL || value[0] == '\0') return 1; if (c->fp != NULL && ap_bvputs(c->fp, key, ": ", value, CRLF, NULL) == -1) { ap_log_rerror(APLOG_MARK, APLOG_ERR, c->req, "proxy: error writing header to %s", c->tempfile); c = ap_proxy_cache_error(c); return 0; /* no need to continue, it failed already */ } return 1; /* tell ap_table_do() to continue calling us * for more headers */ } /* send a text line to one or two BUFF's; return line length */ unsigned ap_proxy_bputs2(const char *data, BUFF *client, cache_req *cache) { unsigned len = ap_bputs(data, client); if (cache != NULL && cache->fp != NULL) ap_bputs(data, cache->fp); return len; } /* do a HTTP/1.1 age calculation */ time_t ap_proxy_current_age(cache_req *c, const time_t age_value) { time_t apparent_age, corrected_received_age, response_delay, corrected_initial_age, resident_time, current_age; /* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */ apparent_age = MAX(0, c->resp_time - c->date); corrected_received_age = MAX(apparent_age, age_value); response_delay = c->resp_time - c->req_time; corrected_initial_age = corrected_received_age + response_delay; resident_time = time(NULL) - c->resp_time; current_age = corrected_initial_age + resident_time; return (current_age); } /* open a cache file and return a pointer to a BUFF */ BUFF *ap_proxy_open_cachefile(request_rec *r, char *filename) { BUFF *cachefp = NULL; int cfd; if (filename != NULL) { cfd = open(filename, O_RDWR | O_BINARY); if (cfd != -1) { ap_note_cleanups_for_fd(r->pool, cfd); cachefp = ap_bcreate(r->pool, B_RD | B_WR); ap_bpushfd(cachefp, cfd, cfd); } else if (errno != ENOENT) ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "proxy: error opening cache file %s", filename); else ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, r->server, "File %s not found", filename); } return cachefp; } /* create a cache file and return a pointer to a BUFF */ BUFF *ap_proxy_create_cachefile(request_rec *r, char *filename) { BUFF *cachefp = NULL; int cfd; if (filename != NULL) { cfd = open(filename, O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0622); if (cfd != -1) { ap_note_cleanups_for_fd(r->pool, cfd); cachefp = ap_bcreate(r->pool, B_WR); ap_bpushfd(cachefp, -1, cfd); } else if (errno != ENOENT) ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "proxy: error creating cache file %s", filename); } return cachefp; } /* Clear all connection-based headers from headers table */ void ap_proxy_clear_connection(pool *p, table *headers) { const char *name; char *next = ap_pstrdup(p, ap_table_get(headers, "Connection")); /* Some proxies (Squid, ICS) use the non-standard "Proxy-Connection" header. */ ap_table_unset(headers, "Proxy-Connection"); if (next != NULL) { while (*next) { name = next; while (*next && !ap_isspace(*next) && (*next != ',')) ++next; while (*next && (ap_isspace(*next) || (*next == ','))) { *next = '\0'; ++next; } ap_table_unset(headers, name); } ap_table_unset(headers, "Connection"); } /* unset hop-by-hop headers defined in RFC2616 13.5.1 */ ap_table_unset(headers,"Keep-Alive"); /* * XXX: @@@ FIXME: "Proxy-Authenticate" should IMO *not* be stripped * because in a chain of proxies some "front" proxy might need * proxy authentication, while a "back-end" proxy which needs none can * simply pass the "Proxy-Authenticate" back to the client, and pass * the client's "Proxy-Authorization" to the front-end proxy. * (See the note in proxy_http.c for the "Proxy-Authorization" case.) * * MnKr 04/2002 */ ap_table_unset(headers,"Proxy-Authenticate"); ap_table_unset(headers,"TE"); ap_table_unset(headers,"Trailer"); /* it is safe to just chop the transfer-encoding header * here, because proxy doesn't support any other encodings * to the backend other than chunked. */ ap_table_unset(headers,"Transfer-Encoding"); ap_table_unset(headers,"Upgrade"); } /* overlay one table on another * keys in base will be replaced by keys in overlay * * Note: this has to be done in a special way, due * to some nastiness when it comes to having multiple * headers in the overlay table. First, we remove all * the headers in the base table that are found in the * overlay table, then we simply concatenate the * tables together. * * The base and overlay tables need not be in the same * pool (and probably won't be). * * If the base table is changed in any way through * being overlayed with the overlay table, this * function returns a 1. */ int ap_proxy_table_replace(table *base, table *overlay) { table_entry *elts = (table_entry *)overlay->a.elts; int i, q = 0; const char *val; /* remove overlay's keys from base */ for (i = 0; i < overlay->a.nelts; ++i) { val = ap_table_get(base, elts[i].key); if (!val || strcmp(val, elts[i].val)) { q = 1; } if (val) { ap_table_unset(base, elts[i].key); } } /* add overlay to base */ for (i = 0; i < overlay->a.nelts; ++i) { ap_table_add(base, elts[i].key, elts[i].val); } return q; } /* read the response line * This function reads a single line of response from the server, * and returns a status code. * It also populates the request_rec with the resultant status, and * returns backasswards status (HTTP/0.9). */ int ap_proxy_read_response_line(BUFF *f, request_rec *r, char *buffer, int size, int *backasswards, int *major, int *minor) { long len; len = ap_getline(buffer, size-1, f, 0); if (len == -1) { ap_bclose(f); ap_kill_timeout(r); return ap_proxyerror(r, HTTP_BAD_GATEWAY, "Error reading from remote server"); } else if (len == 0) { ap_bclose(f); ap_kill_timeout(r); return ap_proxyerror(r, HTTP_BAD_GATEWAY, "Document contains no data"); } /* * Is it an HTTP/1 response? Do some sanity checks on the response. (This * is buggy if we ever see an HTTP/1.10) */ if (ap_checkmask(buffer, "HTTP/#.# ###*")) { if (2 != sscanf(buffer, "HTTP/%u.%u", major, minor)) { /* if no response, default to HTTP/1.1 - is this correct? */ *major = 1; *minor = 1; } /* If not an HTTP/1 message */ if (*major < 1) { ap_bclose(f); ap_kill_timeout(r); return HTTP_BAD_GATEWAY; } *backasswards = 0; /* there need not be a reason phrase in the response, * and ap_getline() already deleted trailing whitespace. * But RFC2616 requires a SP after the Status-Code. Add one: */ if (strlen(buffer) < sizeof("HTTP/1.x 200 ")-1) buffer = ap_pstrcat(r->pool, buffer, " ", NULL); buffer[12] = '\0'; r->status = atoi(&buffer[9]); buffer[12] = ' '; r->status_line = ap_pstrdup(r->pool, &buffer[9]); /* if the response was 100 continue, soak up any headers */ if (r->status == 100) { ap_proxy_read_headers(r, buffer, size, f); } } else { /* an http/0.9 response */ *backasswards = 1; r->status = 200; r->status_line = "200 OK"; *major = 0; *minor = 9; } return OK; } static struct per_thread_data *get_per_thread_data(void) { static APACHE_TLS struct per_thread_data sptd; return &sptd; }