1 /* ====================================================================
2 * Copyright (c) 1996-2000 The Apache Software Foundation. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
16 * 3. All advertising materials mentioning features or use of this
17 * software must display the following acknowledgment:
18 * "This product includes software developed by the Apache Software Foundation
19 * for use in the Apache HTTP server project (http://www.apache.org/)."
21 * 4. The names "Apache Server" and "Apache Software Foundation" must not be used to
22 * endorse or promote products derived from this software without
23 * prior written permission. For written permission, please contact
26 * 5. Products derived from this software may not be called "Apache"
27 * nor may "Apache" appear in their names without prior written
28 * permission of the Apache Software Foundation.
30 * 6. Redistributions of any form whatsoever must retain the following
32 * "This product includes software developed by the Apache Software Foundation
33 * for use in the Apache HTTP server project (http://www.apache.org/)."
35 * THIS SOFTWARE IS PROVIDED BY THE Apache Software Foundation ``AS IS'' AND ANY
36 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE Apache Software Foundation OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46 * OF THE POSSIBILITY OF SUCH DAMAGE.
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation and was originally based
51 * on public domain software written at the National Center for
52 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
53 * For more information on the Apache Software Foundation and the Apache HTTP server
54 * project, please see <http://www.apache.org/>.
58 /* Utility routines for Apache proxy */
59 #include "mod_proxy.h"
60 #include "http_main.h"
64 #include "util_date.h" /* get ap_checkmask() decl. */
68 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
69 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
70 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
71 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
73 /* already called in the knowledge that the characters are hex digits */
74 int ap_proxy_hex2c(const char *x)
78 #ifndef CHARSET_EBCDIC
82 else if (ap_isupper(ch))
91 else if (ap_isupper(ch))
96 #else /*CHARSET_EBCDIC*/
97 return (1 == sscanf(x, "%2x", &i)) ? os_toebcdic[i&0xFF] : 0;
98 #endif /*CHARSET_EBCDIC*/
101 void ap_proxy_c2hex(int ch, char *x)
103 #ifndef CHARSET_EBCDIC
107 i = (ch & 0xF0) >> 4;
109 x[1] = ('A' - 10) + i;
115 x[2] = ('A' - 10) + i;
118 #else /*CHARSET_EBCDIC*/
119 static const char ntoa[] = { "0123456789ABCDEF" };
122 x[1] = ntoa[(os_toascii[ch]>>4)&0x0F];
123 x[2] = ntoa[os_toascii[ch]&0x0F];
125 #endif /*CHARSET_EBCDIC*/
129 * canonicalise a URL-encoded string
133 * Convert a URL-encoded string to canonical form.
134 * It decodes characters which need not be encoded,
135 * and encodes those which must be encoded, and does not touch
136 * those which must not be touched.
139 ap_proxy_canonenc(ap_context_t *p, const char *x, int len, enum enctype t, int isenc)
143 const char *allowed; /* characters which should not be encoded */
144 const char *reserved; /* characters which much not be en/de-coded */
146 /* N.B. in addition to :@&=, this allows ';' in an http path
147 * and '?' in an ftp path -- this may be revised
149 * Also, it makes a '+' character in a search string reserved, as
150 * it may be form-encoded. (Although RFC 1738 doesn't allow this -
151 * it only permits ; / ? : @ = & as reserved chars.)
154 allowed = "$-_.+!*'(),;:@&=";
155 else if (t == enc_search)
156 allowed = "$-_.!*'(),;:@&=";
157 else if (t == enc_user)
158 allowed = "$-_.+!*'(),;@&=";
159 else if (t == enc_fpath)
160 allowed = "$-_.+!*'(),?:@&=";
161 else /* if (t == enc_parm) */
162 allowed = "$-_.+!*'(),?/:@&=";
166 else if (t == enc_search)
171 y = ap_palloc(p, 3 * len + 1);
173 for (i = 0, j = 0; i < len; i++, j++) {
174 /* always handle '/' first */
176 if (strchr(reserved, ch)) {
180 /* decode it if not already done */
181 if (isenc && ch == '%') {
182 if (!ap_isxdigit(x[i + 1]) || !ap_isxdigit(x[i + 2]))
184 ch = ap_proxy_hex2c(&x[i + 1]);
186 if (ch != 0 && strchr(reserved, ch)) { /* keep it encoded */
187 ap_proxy_c2hex(ch, &y[j]);
192 /* recode it, if necessary */
193 if (!ap_isalnum(ch) && !strchr(allowed, ch)) {
194 ap_proxy_c2hex(ch, &y[j]);
205 * Parses network-location.
206 * urlp on input the URL; on output the path, after the leading /
207 * user NULL if no user/password permitted
208 * password holder for password
209 * host holder for host
210 * port port number; only set if one is supplied.
212 * Returns an error string.
215 ap_proxy_canon_netloc(ap_context_t *p, char **const urlp, char **userp,
216 char **passwordp, char **hostp, int *port)
219 char *strp, *host, *url = *urlp;
220 char *user = NULL, *password = NULL;
222 if (url[0] != '/' || url[1] != '/')
223 return "Malformed URL";
225 url = strchr(host, '/');
229 *(url++) = '\0'; /* skip seperating '/' */
231 /* find _last_ '@' since it might occur in user/password part */
232 strp = strrchr(host, '@');
240 strp = strchr(user, ':');
243 password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1);
244 if (password == NULL)
245 return "Bad %-escape in URL (password)";
248 user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1);
250 return "Bad %-escape in URL (username)";
255 if (passwordp != NULL) {
256 *passwordp = password;
259 strp = strrchr(host, ':');
263 for (i = 0; strp[i] != '\0'; i++)
264 if (!ap_isdigit(strp[i]))
267 /* if (i == 0) the no port was given; keep default */
268 if (strp[i] != '\0') {
269 return "Bad port number in URL";
273 return "Port number in URL > 65535";
276 ap_str_tolower(host); /* DNS names are case insensitive */
278 return "Missing host in URL";
279 /* check hostname syntax */
280 for (i = 0; host[i] != '\0'; i++)
281 if (!ap_isdigit(host[i]) && host[i] != '.')
283 /* must be an IP address */
285 if (host[i] == '\0' && (inet_addr(host) == -1))
287 if (host[i] == '\0' && (ap_inet_addr(host) == -1 || inet_network(host) == -1))
290 return "Bad IP address in URL";
293 /* if (strchr(host,'.') == NULL && domain != NULL)
294 host = pstrcat(p, host, domain, NULL);
302 static const char * const lwday[7] =
303 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
306 * If the date is a valid RFC 850 date or asctime() date, then it
307 * is converted to the RFC 1123 format, otherwise it is not modified.
308 * This routine is not very fast at doing conversions, as it uses
309 * sscanf and sprintf. However, if the date is already correctly
310 * formatted, then it exits very quickly.
313 ap_proxy_date_canon(ap_context_t *p, const char *x)
315 int wk, mday, year, hour, min, sec, mon;
316 char *q, month[4], zone[4], week[4];
319 /* check for RFC 850 date */
320 if (q != NULL && q - x > 3 && q[1] == ' ') {
322 for (wk = 0; wk < 7; wk++)
323 if (strcmp(x, lwday[wk]) == 0)
327 return x; /* not a valid date */
328 if (q[4] != '-' || q[8] != '-' || q[11] != ' ' || q[14] != ':' ||
329 q[17] != ':' || strcmp(&q[20], " GMT") != 0)
331 if (sscanf(q + 2, "%u-%3s-%u %u:%u:%u %3s", &mday, month, &year,
332 &hour, &min, &sec, zone) != 7)
340 /* check for acstime() date */
341 if (x[3] != ' ' || x[7] != ' ' || x[10] != ' ' || x[13] != ':' ||
342 x[16] != ':' || x[19] != ' ' || x[24] != '\0')
344 if (sscanf(x, "%3s %3s %u %u:%u:%u %u", week, month, &mday, &hour,
345 &min, &sec, &year) != 7)
347 for (wk = 0; wk < 7; wk++)
348 if (strcmp(week, ap_day_snames[wk]) == 0)
355 for (mon = 0; mon < 12; mon++)
356 if (strcmp(month, ap_month_snames[mon]) == 0)
361 q = ap_palloc(p, 30);
362 ap_snprintf(q, 30, "%s, %.2d %s %d %.2d:%.2d:%.2d GMT", ap_day_snames[wk], mday,
363 ap_month_snames[mon], year, hour, min, sec);
368 /* NOTE: This routine is taken from http_protocol::getline()
369 * because the old code found in the proxy module was too
370 * difficult to understand and maintain.
372 /* Get a line of protocol input, including any continuation lines
373 * caused by MIME folding (or broken clients) if fold != 0, and place it
374 * in the buffer s, of size n bytes, without the ending newline.
376 * Returns -1 on error, or the length of s.
378 * Note: Because bgets uses 1 char for newline and 1 char for NUL,
379 * the most we can get is (n - 2) actual characters if it
380 * was ended by a newline, or (n - 1) characters if the line
381 * length exceeded (n - 1). So, if the result == (n - 1),
382 * then the actual input line exceeded the buffer length,
383 * and it would be a good idea for the caller to puke 400 or 414.
385 static int proxy_getline(char *s, int n, BUFF *in, int fold)
394 retval = ap_bgets(pos, n, in); /* retval == -1 if error, 0 if EOF */
397 return ((retval < 0) && (total == 0)) ? -1 : total;
399 /* retval is the number of characters read, not including NUL */
401 n -= retval; /* Keep track of how much of s is full */
402 pos += (retval - 1); /* and where s ends */
403 total += retval; /* and how long s has become */
405 if (*pos == '\n') { /* Did we get a full line of input? */
411 return total; /* if not, input line exceeded buffer size */
413 /* Continue appending if line folding is desired and
414 * the last line was not empty and we have room in the buffer and
415 * the next line begins with a continuation character.
417 } while (fold && (retval != 1) && (n > 1)
418 && (ap_blookc(&next, in) == 1)
419 && ((next == ' ') || (next == '\t')));
426 * Reads headers from a buffer and returns an array of headers.
427 * Returns NULL on file error
428 * This routine tries to deal with too long lines and continuation lines.
429 * @@@: XXX: FIXME: currently the headers are passed thru un-merged.
430 * Is that okay, or should they be collapsed where possible?
432 table *ap_proxy_read_headers(request_rec *r, char *buffer, int size, BUFF *f)
434 ap_table_t *resp_hdrs;
437 char field[MAX_STRING_LEN];
439 resp_hdrs = ap_make_table(r->pool, 20);
442 * Read header lines until we get the empty separator line, a read error,
443 * the connection closes (EOF), or we timeout.
445 while ((len = proxy_getline(buffer, size, f, 1)) > 0) {
447 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
449 /* Buggy MS IIS servers sometimes return invalid headers
450 * (an extra "HTTP/1.0 200, OK" line sprinkled in between
451 * the usual MIME headers). Try to deal with it in a sensible
452 * way, but log the fact.
453 * XXX: The mask check is buggy if we ever see an HTTP/1.10 */
455 if (!ap_checkmask(buffer, "HTTP/#.# ###*")) {
456 /* Nope, it wasn't even an extra HTTP header. Give up. */
460 ap_log_error(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, r->server,
461 "proxy: Ignoring duplicate HTTP header "
462 "returned by %s (%s)", r->uri, r->method);
468 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
469 * wrong... and so are many others probably.
471 while (ap_isspace(*value))
472 ++value; /* Skip to start of value */
474 /* should strip trailing whitespace as well */
475 for (end = &value[strlen(value)-1]; end > value && ap_isspace(*end); --end)
478 ap_table_add(resp_hdrs, buffer, value);
480 /* the header was too long; at the least we should skip extra data */
481 if (len >= size - 1) {
482 while ((len = proxy_getline(field, MAX_STRING_LEN, f, 1))
483 >= MAX_STRING_LEN - 1) {
484 /* soak up the extra data */
486 if (len == 0) /* time to exit the larger loop as well */
493 long int ap_proxy_send_fb(BUFF *f, request_rec *r, cache_req *c)
497 long total_bytes_rcvd;
498 register int n, o, w;
499 conn_rec *con = r->connection;
500 int alternate_timeouts = 1; /* 1 if we alternate between soft & hard timeouts */
502 total_bytes_rcvd = 0;
506 #ifdef CHARSET_EBCDIC
507 /* The cache copy is ASCII, not EBCDIC, even for text/html) */
508 ap_bsetflag(f, B_ASCII2EBCDIC|B_EBCDIC2ASCII, 0);
509 if (c != NULL && c->fp != NULL)
510 ap_bsetflag(c->fp, B_ASCII2EBCDIC|B_EBCDIC2ASCII, 0);
511 ap_bsetflag(con->client, B_ASCII2EBCDIC|B_EBCDIC2ASCII, 0);
514 /* Since we are reading from one buffer and writing to another,
515 * it is unsafe to do a soft_timeout here, at least until the proxy
516 * has its own timeout handler which can set both buffers to EOUT.
520 /* works fine under win32, so leave it */
522 /* CHECKME! Since hard_timeout won't work in unix on sends with partial
523 * cache completion, we have to alternate between hard_timeout
524 * for reads, and soft_timeout for send. This is because we need
525 * to get a return from ap_bwrite to be able to continue caching.
526 * BUT, if we *can't* continue anyway, just use hard_timeout.
529 if (c == NULL || c->len <= 0 || c->cache_completion == 1.0) {
530 alternate_timeouts = 0;
534 /* Loop and ap_bread() while we can successfully read and write,
535 * or (after the client aborted) while we can successfully
536 * read and finish the configured cache_completion.
539 /* Read block from server */
540 n = ap_bread(f, buf, IOBUFSIZE);
542 if (n == -1) { /* input error */
544 ap_log_rerror(APLOG_MARK, APLOG_ERR, c->req,
545 "proxy: error reading from %s", c->url);
546 c = ap_proxy_cache_error(c);
553 total_bytes_rcvd += n;
555 /* Write to cache first. */
556 /*@@@ XXX FIXME: Assuming that writing the cache file won't time out?!!? */
557 if (c != NULL && c->fp != NULL) {
558 if (ap_bwrite(c->fp, &buf[0], n) != n) {
559 ap_log_rerror(APLOG_MARK, APLOG_ERR, c->req,
560 "proxy: error writing to %s", c->tempfile);
561 c = ap_proxy_cache_error(c);
567 /* Write the block to the client, detect aborted transfers */
568 while (!con->aborted && n > 0) {
569 w = ap_bwrite(con->client, &buf[o], n);
572 if (c != NULL && c->fp != NULL) {
573 /* when a send failure occurs, we need to decide
574 * whether to continue loading and caching the
575 * document, or to abort the whole thing
578 (c->cache_completion > 0) &&
579 (c->len * c->cache_completion < total_bytes_rcvd);
582 ap_pclosef(c->req->pool, c->fp->fd);
593 } /* while client alive and more data to send */
594 } /* loop and ap_bread while "ok" */
597 ap_bflush(con->client);
599 return total_bytes_rcvd;
603 * Sends response line and headers. Uses the client fd and the
604 * headers_out array from the passed request_rec to talk to the client
605 * and to properly set the headers it sends for things such as logging.
607 * A timeout should be set before calling this routine.
609 void ap_proxy_send_headers(request_rec *r, const char *respline, ap_table_t *t)
612 BUFF *fp = r->connection->client;
613 table_entry *elts = (table_entry *) ap_table_elts(t)->elts;
615 ap_bvputs(fp, respline, CRLF, NULL);
617 for (i = 0; i < ap_table_elts(t)->nelts; ++i) {
618 if (elts[i].key != NULL) {
619 ap_bvputs(fp, elts[i].key, ": ", elts[i].val, CRLF, NULL);
620 ap_table_addn(r->headers_out, elts[i].key, elts[i].val);
629 * list is a comma-separated list of case insensitive tokens, with
630 * optional whitespace around the tokens.
631 * The return returns 1 if the token val is found in the list, or 0
634 int ap_proxy_liststr(const char *list, const char *val)
641 while (list != NULL) {
642 p = strchr(list, ',');
647 while (ap_isspace(*p));
652 while (i > 0 && ap_isspace(list[i - 1]))
654 if (i == len && strncasecmp(list, val, len) == 0)
661 #ifdef CASE_BLIND_FILESYSTEM
664 * On some platforms, the file system is NOT case sensitive. So, a == A
665 * need to map to smaller set of characters
667 void ap_proxy_hash(const char *it, char *val, int ndepth, int nlength)
670 unsigned char digest[16];
674 static const char enc_table[32] = "abcdefghijklmnopqrstuvwxyz012345";
676 ap_MD5Init(&context);
677 ap_MD5Update(&context, (const unsigned char *) it, strlen(it));
678 ap_MD5Final(digest, &context);
680 /* encode 128 bits as 26 characters, using a modified uuencoding */
681 /* the encoding is 5 bytes -> 8 characters
682 * i.e. 128 bits is 3 x 5 bytes + 1 byte -> 3 * 8 characters + 2 characters
684 for (i = 0, k = 0; i < 15; i += 5) {
685 x = (digest[i] << 24) | (digest[i + 1] << 16) | (digest[i + 2] << 8) | digest[i + 3];
686 tmp[k++] = enc_table[x >> 27];
687 tmp[k++] = enc_table[(x >> 22) & 0x1f];
688 tmp[k++] = enc_table[(x >> 17) & 0x1f];
689 tmp[k++] = enc_table[(x >> 12) & 0x1f];
690 tmp[k++] = enc_table[(x >> 7) & 0x1f];
691 tmp[k++] = enc_table[(x >> 2) & 0x1f];
692 x = ((x & 0x3) << 8) | digest[i + 4];
693 tmp[k++] = enc_table[x >> 5];
694 tmp[k++] = enc_table[x & 0x1f];
698 tmp[k++] = enc_table[x >> 3]; /* use up 5 bits */
699 tmp[k++] = enc_table[x & 0x7];
700 /* now split into directory levels */
702 for (i = k = d = 0; d < ndepth; ++d) {
703 memcpy(&val[i], &tmp[k], nlength);
705 val[i + nlength] = '/';
708 memcpy(&val[i], &tmp[k], 26 - k);
709 val[i + 26 - k] = '\0';
714 void ap_proxy_hash(const char *it, char *val, int ndepth, int nlength)
717 unsigned char digest[16];
721 #if defined(AIX) && defined(__ps2__)
722 /* Believe it or not, AIX 1.x does not allow you to name a file '@',
723 * so hack around it in the encoding. */
724 static const char enc_table[64] =
725 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_%";
727 static const char enc_table[64] =
728 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
731 ap_MD5Init(&context);
732 ap_MD5Update(&context, (const unsigned char *) it, strlen(it));
733 ap_MD5Final(digest, &context);
735 /* encode 128 bits as 22 characters, using a modified uuencoding */
736 /* the encoding is 3 bytes -> 4 characters
737 * i.e. 128 bits is 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
739 for (i = 0, k = 0; i < 15; i += 3) {
740 x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
741 tmp[k++] = enc_table[x >> 18];
742 tmp[k++] = enc_table[(x >> 12) & 0x3f];
743 tmp[k++] = enc_table[(x >> 6) & 0x3f];
744 tmp[k++] = enc_table[x & 0x3f];
748 tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */
749 tmp[k++] = enc_table[(x << 4) & 0x3f];
750 /* now split into directory levels */
752 for (i = k = d = 0; d < ndepth; ++d) {
753 memcpy(&val[i], &tmp[k], nlength);
755 val[i + nlength] = '/';
758 memcpy(&val[i], &tmp[k], 22 - k);
759 val[i + 22 - k] = '\0';
762 #endif /* CASE_BLIND_FILESYSTEM */
765 * Converts 8 hex digits to a time integer
767 int ap_proxy_hex2sec(const char *x)
772 for (i = 0, j = 0; i < 8; i++) {
777 else if (ap_isupper(ch))
778 j |= ch - ('A' - 10);
780 j |= ch - ('a' - 10);
783 return -1; /* so that it works with 8-byte ints */
789 * Converts a time integer to 8 hex digits
791 void ap_proxy_sec2hex(int t, char *y)
796 for (i = 7; i >= 0; i--) {
800 y[i] = ch + ('A' - 10);
808 cache_req *ap_proxy_cache_error(cache_req *c)
812 ap_pclosef(c->req->pool, c->fp->fd);
815 if (c->tempfile) unlink(c->tempfile);
820 int ap_proxyerror(request_rec *r, int statuscode, const char *message)
822 ap_table_setn(r->notes, "error-notes",
824 "The proxy server could not handle the request "
825 "<EM><A HREF=\"", r->uri, "\">",
826 r->method, " ", r->uri, "</A></EM>.<P>\n"
827 "Reason: <STRONG>", message, "</STRONG>", NULL));
829 /* Allow the "error-notes" string to be printed by ap_send_error_response() */
830 ap_table_setn(r->notes, "verbose-error-to", ap_pstrdup(r->pool, "*"));
832 r->status_line = ap_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
837 * This routine returns its own error message
840 ap_proxy_host2addr(const char *host, struct hostent *reqhp)
844 /* XXX - Either get rid of TLS, or use pthread/APR functions */
846 static APACHE_TLS struct hostent hpbuf;
847 static APACHE_TLS u_long ipaddr;
848 static APACHE_TLS char *charpbuf[2];
850 for (i = 0; host[i] != '\0'; i++)
851 if (!ap_isdigit(host[i]) && host[i] != '.')
854 if (host[i] != '\0') {
855 hp = gethostbyname(host);
857 return "Host not found";
860 ipaddr = ap_inet_addr(host);
861 hp = gethostbyaddr((char *) &ipaddr, sizeof(u_long), AF_INET);
863 memset(&hpbuf, 0, sizeof(hpbuf));
865 hpbuf.h_addrtype = AF_INET;
866 hpbuf.h_length = sizeof(u_long);
867 hpbuf.h_addr_list = charpbuf;
868 hpbuf.h_addr_list[0] = (char *) &ipaddr;
869 hpbuf.h_addr_list[1] = 0;
878 proxy_get_host_of_request(request_rec *r)
880 char *url, *user = NULL, *password = NULL, *err, *host;
883 if (r->hostname != NULL)
886 /* Set url to the first char after "scheme://" */
887 if ((url = strchr(r->uri, ':')) == NULL
888 || url[1] != '/' || url[2] != '/')
891 url = ap_pstrdup(r->pool, &url[1]); /* make it point to "//", which is what proxy_canon_netloc expects */
893 err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
896 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, r,
901 return host; /* ought to return the port, too */
904 /* Return TRUE if addr represents an IP address (or an IP network address) */
905 int ap_proxy_is_ipaddr(struct dirconn_entry *This, ap_context_t *p)
907 const char *addr = This->name;
912 /* if the address is given with an explicit netmask, use that */
913 /* Due to a deficiency in ap_inet_addr(), it is impossible to parse */
914 /* "partial" addresses (with less than 4 quads) correctly, i.e. */
915 /* 192.168.123 is parsed as 192.168.0.123, which is not what I want. */
916 /* I therefore have to parse the IP address manually: */
917 /*if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0) */
918 /* addr and mask were set by proxy_readmask() */
921 /* Parse IP addr manually, optionally allowing */
922 /* abbreviated net addresses like 192.168. */
924 /* Iterate over up to 4 (dotted) quads. */
925 for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
928 if (*addr == '/' && quads > 0) /* netmask starts here. */
931 if (!ap_isdigit(*addr))
932 return 0; /* no digit at start of quad */
934 ip_addr[quads] = strtol(addr, &tmp, 0);
936 if (tmp == addr) /* expected a digit, found something else */
939 if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
946 if (*addr == '.' && quads != 3)
947 ++addr; /* after the 4th quad, a dot would be illegal */
950 for (This->addr.s_addr = 0, i = 0; i < quads; ++i)
951 This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
953 if (addr[0] == '/' && ap_isdigit(addr[1])) { /* net mask follows: */
958 bits = strtol(addr, &tmp, 0);
960 if (tmp == addr) /* expected a digit, found something else */
965 if (bits < 0 || bits > 32) /* netmask must be between 0 and 32 */
970 /* Determine (i.e., "guess") netmask by counting the */
971 /* number of trailing .0's; reduce #quads appropriately */
972 /* (so that 192.168.0.0 is equivalent to 192.168.) */
973 while (quads > 0 && ip_addr[quads - 1] == 0)
976 /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
980 /* every zero-byte counts as 8 zero-bits */
983 if (bits != 32) /* no warning for fully qualified IP address */
984 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
985 "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
986 inet_ntoa(This->addr), bits);
989 This->mask.s_addr = htonl(INADDR_NONE << (32 - bits));
991 if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
992 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "Warning: NetMask and IP-Addr disagree in %s/%ld\n",
993 inet_ntoa(This->addr), bits);
994 This->addr.s_addr &= This->mask.s_addr;
995 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
997 inet_ntoa(This->addr), bits);
1000 if (*addr == '\0') {
1001 This->matcher = proxy_match_ipaddr;
1005 return (*addr == '\0'); /* okay iff we've parsed the whole string */
1008 /* Return TRUE if addr represents an IP address (or an IP network address) */
1009 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
1013 struct in_addr addr;
1014 struct in_addr *ip_list;
1017 const char *host = proxy_get_host_of_request(r);
1019 if (host == NULL) /* oops! */
1022 memset(&addr, '\0', sizeof addr);
1023 memset(ip_addr, '\0', sizeof ip_addr);
1025 if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
1026 for (addr.s_addr = 0, i = 0; i < 4; ++i)
1027 addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
1029 if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
1031 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1032 "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
1033 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1034 "%s/", inet_ntoa(This->addr));
1035 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1036 "%s", inet_ntoa(This->mask));
1042 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1043 "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
1044 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1045 "%s/", inet_ntoa(This->addr));
1046 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1047 "%s", inet_ntoa(This->mask));
1052 struct hostent the_host;
1054 memset(&the_host, '\0', sizeof the_host);
1055 found = ap_proxy_host2addr(host, &the_host);
1057 if (found != NULL) {
1059 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1060 "2)IP-NoMatch: hostname=%s msg=%s", host, found);
1065 if (the_host.h_name != NULL)
1066 found = the_host.h_name;
1070 /* Try to deal with multiple IP addr's for a host */
1071 for (ip_listptr = the_host.h_addr_list; *ip_listptr; ++ip_listptr) {
1072 ip_list = (struct in_addr *) *ip_listptr;
1073 if (This->addr.s_addr == (ip_list->s_addr & This->mask.s_addr)) {
1075 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1076 "3)IP-Match: %s[%s] <-> ", found, inet_ntoa(*ip_list));
1077 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1078 "%s/", inet_ntoa(This->addr));
1079 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1080 "%s", inet_ntoa(This->mask));
1086 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1087 "3)IP-NoMatch: %s[%s] <-> ", found, inet_ntoa(*ip_list));
1088 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1089 "%s/", inet_ntoa(This->addr));
1090 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1091 "%s", inet_ntoa(This->mask));
1100 /* Return TRUE if addr represents a domain name */
1101 int ap_proxy_is_domainname(struct dirconn_entry *This, ap_context_t *p)
1103 char *addr = This->name;
1106 /* Domain name must start with a '.' */
1110 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
1111 for (i = 0; ap_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i)
1115 if (addr[i] == ':') {
1116 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1117 "@@@@ handle optional port in proxy_is_domainname()");
1118 /* @@@@ handle optional port */
1122 if (addr[i] != '\0')
1125 /* Strip trailing dots */
1126 for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i)
1129 This->matcher = proxy_match_domainname;
1133 /* Return TRUE if host "host" is in domain "domain" */
1134 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
1136 const char *host = proxy_get_host_of_request(r);
1137 int d_len = strlen(This->name), h_len;
1139 if (host == NULL) /* some error was logged already */
1142 h_len = strlen(host);
1144 /* @@@ do this within the setup? */
1145 /* Ignore trailing dots in domain comparison: */
1146 while (d_len > 0 && This->name[d_len - 1] == '.')
1148 while (h_len > 0 && host[h_len - 1] == '.')
1150 return h_len > d_len
1151 && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
1154 /* Return TRUE if addr represents a host name */
1155 int ap_proxy_is_hostname(struct dirconn_entry *This, ap_context_t *p)
1157 struct hostent host;
1158 char *addr = This->name;
1161 /* Host names must not start with a '.' */
1165 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
1166 for (i = 0; ap_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i);
1169 if (addr[i] == ':') {
1170 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1171 "@@@@ handle optional port in proxy_is_hostname()");
1172 /* @@@@ handle optional port */
1176 if (addr[i] != '\0' || ap_proxy_host2addr(addr, &host) != NULL)
1179 This->hostentry = ap_pduphostent (p, &host);
1181 /* Strip trailing dots */
1182 for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i)
1185 This->matcher = proxy_match_hostname;
1189 /* Return TRUE if host "host" is equal to host2 "host2" */
1190 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
1192 char *host = This->name;
1193 const char *host2 = proxy_get_host_of_request(r);
1197 if (host == NULL || host2 == NULL)
1198 return 0; /* oops! */
1200 h2_len = strlen(host2);
1201 h1_len = strlen(host);
1204 unsigned long *ip_list;
1206 /* Try to deal with multiple IP addr's for a host */
1207 for (ip_list = *This->hostentry->h_addr_list; *ip_list != 0UL; ++ip_list)
1208 if (*ip_list == ? ? ? ? ? ? ? ? ? ? ? ? ?)
1212 /* Ignore trailing dots in host2 comparison: */
1213 while (h2_len > 0 && host2[h2_len - 1] == '.')
1215 while (h1_len > 0 && host[h1_len - 1] == '.')
1217 return h1_len == h2_len
1218 && strncasecmp(host, host2, h1_len) == 0;
1221 /* Return TRUE if addr is to be matched as a word */
1222 int ap_proxy_is_word(struct dirconn_entry *This, ap_context_t *p)
1224 This->matcher = proxy_match_word;
1228 /* Return TRUE if string "str2" occurs literally in "str1" */
1229 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
1231 const char *host = proxy_get_host_of_request(r);
1232 return host != NULL && strstr(host, This->name) != NULL;
1235 int ap_proxy_doconnect(int sock, struct sockaddr_in *addr, request_rec *r)
1240 i = connect(sock, (struct sockaddr *) addr, sizeof(struct sockaddr_in));
1242 if (i == SOCKET_ERROR)
1243 errno = WSAGetLastError();
1245 } while (i == -1 && errno == EINTR);
1247 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1248 "proxy connect to %s port %d failed",
1249 inet_ntoa(addr->sin_addr), ntohs(addr->sin_port));
1255 /* This function is called by ap_table_do() for all header lines */
1256 /* (from proxy_http.c and proxy_ftp.c) */
1257 /* It is passed a table_do_args struct pointer and a MIME field and value pair */
1258 int ap_proxy_send_hdr_line(void *p, const char *key, const char *value)
1260 struct tbl_do_args *parm = (struct tbl_do_args *)p;
1262 if (key == NULL || value == NULL || value[0] == '\0')
1264 if (!parm->req->assbackwards)
1265 ap_rvputs(parm->req, key, ": ", value, CRLF, NULL);
1266 if (parm->cache != NULL && parm->cache->fp != NULL &&
1267 ap_bvputs(parm->cache->fp, key, ": ", value, CRLF, NULL) == -1) {
1268 ap_log_rerror(APLOG_MARK, APLOG_ERR, parm->cache->req,
1269 "proxy: error writing header to %s", parm->cache->tempfile);
1270 parm->cache = ap_proxy_cache_error(parm->cache);
1272 return 1; /* tell ap_table_do() to continue calling us for more headers */
1275 /* send a text line to one or two BUFF's; return line length */
1276 unsigned ap_proxy_bputs2(const char *data, BUFF *client, cache_req *cache)
1278 unsigned len = ap_bputs(data, client);
1279 if (cache != NULL && cache->fp != NULL)
1280 ap_bputs(data, cache->fp);