]> granicus.if.org Git - apache/blob - modules/proxy/proxy_util.c
97b155a3854b605af1e9d73cd6e161b9645b63c8
[apache] / modules / proxy / proxy_util.c
1 /* ====================================================================
2  * Copyright (c) 1996-2000 The Apache Software Foundation.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer. 
10  *
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
14  *    distribution.
15  *
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/)."
20  *
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
24  *    apache@apache.org.
25  *
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.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the Apache Software Foundation
33  *    for use in the Apache HTTP server project (http://www.apache.org/)."
34  *
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  * ====================================================================
48  *
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/>.
55  *
56  */
57
58 /* Utility routines for Apache proxy */
59 #include "mod_proxy.h"
60 #include "http_main.h"
61 #include "ap_md5.h"
62 #include "http_log.h"
63 #include "util_uri.h"
64 #include "util_date.h"  /* get ap_checkmask() decl. */
65
66 #include <pthread.h>
67
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);
72
73 /* already called in the knowledge that the characters are hex digits */
74 int ap_proxy_hex2c(const char *x)
75 {
76     int i, ch;
77
78 #ifndef CHARSET_EBCDIC
79     ch = x[0];
80     if (ap_isdigit(ch))
81         i = ch - '0';
82     else if (ap_isupper(ch))
83         i = ch - ('A' - 10);
84     else
85         i = ch - ('a' - 10);
86     i <<= 4;
87
88     ch = x[1];
89     if (ap_isdigit(ch))
90         i += ch - '0';
91     else if (ap_isupper(ch))
92         i += ch - ('A' - 10);
93     else
94         i += ch - ('a' - 10);
95     return i;
96 #else /*CHARSET_EBCDIC*/
97     return (1 == sscanf(x, "%2x", &i)) ? os_toebcdic[i&0xFF] : 0;
98 #endif /*CHARSET_EBCDIC*/
99 }
100
101 void ap_proxy_c2hex(int ch, char *x)
102 {
103 #ifndef CHARSET_EBCDIC
104     int i;
105
106     x[0] = '%';
107     i = (ch & 0xF0) >> 4;
108     if (i >= 10)
109         x[1] = ('A' - 10) + i;
110     else
111         x[1] = '0' + i;
112
113     i = ch & 0x0F;
114     if (i >= 10)
115         x[2] = ('A' - 10) + i;
116     else
117         x[2] = '0' + i;
118 #else /*CHARSET_EBCDIC*/
119     static const char ntoa[] = { "0123456789ABCDEF" };
120     ch &= 0xFF;
121     x[0] = '%';
122     x[1] = ntoa[(os_toascii[ch]>>4)&0x0F];
123     x[2] = ntoa[os_toascii[ch]&0x0F];
124     x[3] = '\0';
125 #endif /*CHARSET_EBCDIC*/
126 }
127
128 /*
129  * canonicalise a URL-encoded string
130  */
131
132 /*
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.
137  */
138 char *
139      ap_proxy_canonenc(ap_context_t *p, const char *x, int len, enum enctype t, int isenc)
140 {
141     int i, j, ch;
142     char *y;
143     const char *allowed;        /* characters which should not be encoded */
144     const char *reserved;       /* characters which much not be en/de-coded */
145
146 /* N.B. in addition to :@&=, this allows ';' in an http path
147  * and '?' in an ftp path -- this may be revised
148  * 
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.)
152  */
153     if (t == enc_path)
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 = "$-_.+!*'(),?/:@&=";
163
164     if (t == enc_path)
165         reserved = "/";
166     else if (t == enc_search)
167         reserved = "+";
168     else
169         reserved = "";
170
171     y = ap_palloc(p, 3 * len + 1);
172
173     for (i = 0, j = 0; i < len; i++, j++) {
174 /* always handle '/' first */
175         ch = x[i];
176         if (strchr(reserved, ch)) {
177             y[j] = ch;
178             continue;
179         }
180 /* decode it if not already done */
181         if (isenc && ch == '%') {
182             if (!ap_isxdigit(x[i + 1]) || !ap_isxdigit(x[i + 2]))
183                 return NULL;
184             ch = ap_proxy_hex2c(&x[i + 1]);
185             i += 2;
186             if (ch != 0 && strchr(reserved, ch)) {      /* keep it encoded */
187                 ap_proxy_c2hex(ch, &y[j]);
188                 j += 2;
189                 continue;
190             }
191         }
192 /* recode it, if necessary */
193         if (!ap_isalnum(ch) && !strchr(allowed, ch)) {
194             ap_proxy_c2hex(ch, &y[j]);
195             j += 2;
196         }
197         else
198             y[j] = ch;
199     }
200     y[j] = '\0';
201     return y;
202 }
203
204 /*
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.
211  *
212  * Returns an error string.
213  */
214 char *
215      ap_proxy_canon_netloc(ap_context_t *p, char **const urlp, char **userp,
216                         char **passwordp, char **hostp, int *port)
217 {
218     int i;
219     char *strp, *host, *url = *urlp;
220     char *user = NULL, *password = NULL;
221
222     if (url[0] != '/' || url[1] != '/')
223         return "Malformed URL";
224     host = url + 2;
225     url = strchr(host, '/');
226     if (url == NULL)
227         url = "";
228     else
229         *(url++) = '\0';        /* skip seperating '/' */
230
231     /* find _last_ '@' since it might occur in user/password part */
232     strp = strrchr(host, '@');
233
234     if (strp != NULL) {
235         *strp = '\0';
236         user = host;
237         host = strp + 1;
238
239 /* find password */
240         strp = strchr(user, ':');
241         if (strp != NULL) {
242             *strp = '\0';
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)";
246         }
247
248         user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1);
249         if (user == NULL)
250             return "Bad %-escape in URL (username)";
251     }
252     if (userp != NULL) {
253         *userp = user;
254     }
255     if (passwordp != NULL) {
256         *passwordp = password;
257     }
258
259     strp = strrchr(host, ':');
260     if (strp != NULL) {
261         *(strp++) = '\0';
262
263         for (i = 0; strp[i] != '\0'; i++)
264             if (!ap_isdigit(strp[i]))
265                 break;
266
267         /* if (i == 0) the no port was given; keep default */
268         if (strp[i] != '\0') {
269             return "Bad port number in URL";
270         } else if (i > 0) {
271             *port = atoi(strp);
272             if (*port > 65535)
273                 return "Port number in URL > 65535";
274         }
275     }
276     ap_str_tolower(host);               /* DNS names are case insensitive */
277     if (*host == '\0')
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] != '.')
282             break;
283     /* must be an IP address */
284 #ifdef WIN32
285     if (host[i] == '\0' && (inet_addr(host) == -1))
286 #else
287     if (host[i] == '\0' && (ap_inet_addr(host) == -1 || inet_network(host) == -1))
288 #endif
289     {
290         return "Bad IP address in URL";
291     }
292
293 /*    if (strchr(host,'.') == NULL && domain != NULL)
294    host = pstrcat(p, host, domain, NULL);
295  */
296     *urlp = url;
297     *hostp = host;
298
299     return NULL;
300 }
301
302 static const char * const lwday[7] =
303 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
304
305 /*
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.
311  */
312 const char *
313      ap_proxy_date_canon(ap_context_t *p, const char *x)
314 {
315     int wk, mday, year, hour, min, sec, mon;
316     char *q, month[4], zone[4], week[4];
317
318     q = strchr(x, ',');
319     /* check for RFC 850 date */
320     if (q != NULL && q - x > 3 && q[1] == ' ') {
321         *q = '\0';
322         for (wk = 0; wk < 7; wk++)
323             if (strcmp(x, lwday[wk]) == 0)
324                 break;
325         *q = ',';
326         if (wk == 7)
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)
330             return x;
331         if (sscanf(q + 2, "%u-%3s-%u %u:%u:%u %3s", &mday, month, &year,
332                    &hour, &min, &sec, zone) != 7)
333             return x;
334         if (year < 70)
335             year += 2000;
336         else
337             year += 1900;
338     }
339     else {
340 /* check for acstime() date */
341         if (x[3] != ' ' || x[7] != ' ' || x[10] != ' ' || x[13] != ':' ||
342             x[16] != ':' || x[19] != ' ' || x[24] != '\0')
343             return x;
344         if (sscanf(x, "%3s %3s %u %u:%u:%u %u", week, month, &mday, &hour,
345                    &min, &sec, &year) != 7)
346             return x;
347         for (wk = 0; wk < 7; wk++)
348             if (strcmp(week, ap_day_snames[wk]) == 0)
349                 break;
350         if (wk == 7)
351             return x;
352     }
353
354 /* check date */
355     for (mon = 0; mon < 12; mon++)
356         if (strcmp(month, ap_month_snames[mon]) == 0)
357             break;
358     if (mon == 12)
359         return x;
360
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);
364     return q;
365 }
366
367
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.
371  */
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.
375  *
376  * Returns -1 on error, or the length of s.
377  *
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.
384  */
385 static int proxy_getline(char *s, int n, BUFF *in, int fold)
386 {
387     char *pos, next;
388     int retval;
389     int total = 0;
390
391     pos = s;
392
393     do {
394         retval = ap_bgets(pos, n, in);     /* retval == -1 if error, 0 if EOF */
395
396         if (retval <= 0)
397             return ((retval < 0) && (total == 0)) ? -1 : total;
398
399         /* retval is the number of characters read, not including NUL      */
400
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               */
404
405         if (*pos == '\n') {     /* Did we get a full line of input?        */
406             *pos = '\0';
407             --total;
408             ++n;
409         }
410         else
411             return total;       /* if not, input line exceeded buffer size */
412
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.
416          */
417     } while (fold && (retval != 1) && (n > 1)
418                   && (ap_blookc(&next, in) == 1)
419                   && ((next == ' ') || (next == '\t')));
420
421     return total;
422 }
423
424
425 /*
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?
431  */
432 table *ap_proxy_read_headers(request_rec *r, char *buffer, int size, BUFF *f)
433 {
434     ap_table_t *resp_hdrs;
435     int len;
436     char *value, *end;
437     char field[MAX_STRING_LEN];
438
439     resp_hdrs = ap_make_table(r->pool, 20);
440
441     /*
442      * Read header lines until we get the empty separator line, a read error,
443      * the connection closes (EOF), or we timeout.
444      */
445     while ((len = proxy_getline(buffer, size, f, 1)) > 0) {
446         
447         if (!(value = strchr(buffer, ':'))) {     /* Find the colon separator */
448
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 */
454
455             if (!ap_checkmask(buffer, "HTTP/#.# ###*")) {
456                 /* Nope, it wasn't even an extra HTTP header. Give up. */
457                 return NULL;
458             }
459
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);
463             continue;
464         }
465
466         *value = '\0';
467         ++value;
468         /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
469          * wrong... and so are many others probably.
470          */
471         while (ap_isspace(*value))
472             ++value;            /* Skip to start of value   */
473
474         /* should strip trailing whitespace as well */
475         for (end = &value[strlen(value)-1]; end > value && ap_isspace(*end); --end)
476             *end = '\0';
477
478         ap_table_add(resp_hdrs, buffer, value);
479
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 */
485             }
486             if (len == 0) /* time to exit the larger loop as well */
487                 break;
488         }
489     }
490     return resp_hdrs;
491 }
492
493 long int ap_proxy_send_fb(BUFF *f, request_rec *r, cache_req *c)
494 {
495     int  ok;
496     char buf[IOBUFSIZE];
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 */
501
502     total_bytes_rcvd = 0;
503     if (c != NULL)
504         c->written = 0;
505
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);
512 #endif
513
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.
517      */
518
519 #ifdef WIN32
520     /* works fine under win32, so leave it */
521 #else
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.
527      */
528
529     if (c == NULL || c->len <= 0 || c->cache_completion == 1.0) {
530         alternate_timeouts = 0;
531     }
532 #endif
533
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.
537      */
538      for (ok = 1; ok; ) {
539         /* Read block from server */
540         n = ap_bread(f, buf, IOBUFSIZE);
541
542         if (n == -1) {          /* input error */
543             if (c != NULL) {
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);
547             }
548             break;
549         }
550         if (n == 0)
551             break;              /* EOF */
552         o = 0;
553         total_bytes_rcvd += n;
554
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);
562             } else {
563                 c->written += n;
564             }
565         }
566
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);
570
571             if (w <= 0) {
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
576                      */
577                     ok = (c->len > 0) &&
578                          (c->cache_completion > 0) &&
579                          (c->len * c->cache_completion < total_bytes_rcvd);
580
581                     if (! ok) {
582                         ap_pclosef(c->req->pool, c->fp->fd);
583                         c->fp = NULL;
584                         unlink(c->tempfile);
585                         c = NULL;
586                     }
587                 }
588                 con->aborted = 1;
589                 break;
590             }
591             n -= w;
592             o += w;
593         } /* while client alive and more data to send */
594     } /* loop and ap_bread while "ok" */
595
596     if (!con->aborted)
597         ap_bflush(con->client);
598
599     return total_bytes_rcvd;
600 }
601
602 /*
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.
606  * 
607  * A timeout should be set before calling this routine.
608  */
609 void ap_proxy_send_headers(request_rec *r, const char *respline, ap_table_t *t)
610 {
611     int i;
612     BUFF *fp = r->connection->client;
613     table_entry *elts = (table_entry *) ap_table_elts(t)->elts;
614
615     ap_bvputs(fp, respline, CRLF, NULL);
616
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);
621         }
622     }
623
624     ap_bputs(CRLF, fp);
625 }
626
627
628 /*
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
632  * otherwise.
633  */
634 int ap_proxy_liststr(const char *list, const char *val)
635 {
636     int len, i;
637     const char *p;
638
639     len = strlen(val);
640
641     while (list != NULL) {
642         p = strchr(list, ',');
643         if (p != NULL) {
644             i = p - list;
645             do
646                 p++;
647             while (ap_isspace(*p));
648         }
649         else
650             i = strlen(list);
651
652         while (i > 0 && ap_isspace(list[i - 1]))
653             i--;
654         if (i == len && strncasecmp(list, val, len) == 0)
655             return 1;
656         list = p;
657     }
658     return 0;
659 }
660
661 #ifdef CASE_BLIND_FILESYSTEM
662
663 /*
664  * On some platforms, the file system is NOT case sensitive. So, a == A
665  * need to map to smaller set of characters
666  */
667 void ap_proxy_hash(const char *it, char *val, int ndepth, int nlength)
668 {
669     AP_MD5_CTX context;
670     unsigned char digest[16];
671     char tmp[26];
672     int i, k, d;
673     unsigned int x;
674     static const char enc_table[32] = "abcdefghijklmnopqrstuvwxyz012345";
675
676     ap_MD5Init(&context);
677     ap_MD5Update(&context, (const unsigned char *) it, strlen(it));
678     ap_MD5Final(digest, &context);
679
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
683  */
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];
695     }
696 /* one byte left */
697     x = digest[15];
698     tmp[k++] = enc_table[x >> 3];       /* use up 5 bits */
699     tmp[k++] = enc_table[x & 0x7];
700     /* now split into directory levels */
701
702     for (i = k = d = 0; d < ndepth; ++d) {
703         memcpy(&val[i], &tmp[k], nlength);
704         k += nlength;
705         val[i + nlength] = '/';
706         i += nlength + 1;
707     }
708     memcpy(&val[i], &tmp[k], 26 - k);
709     val[i + 26 - k] = '\0';
710 }
711
712 #else
713
714 void ap_proxy_hash(const char *it, char *val, int ndepth, int nlength)
715 {
716     AP_MD5_CTX context;
717     unsigned char digest[16];
718     char tmp[22];
719     int i, k, d;
720     unsigned int x;
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_%";
726 #else
727     static const char enc_table[64] =
728         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
729 #endif
730
731     ap_MD5Init(&context);
732     ap_MD5Update(&context, (const unsigned char *) it, strlen(it));
733     ap_MD5Final(digest, &context);
734
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
738  */
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];
745     }
746 /* one byte left */
747     x = digest[15];
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 */
751
752     for (i = k = d = 0; d < ndepth; ++d) {
753         memcpy(&val[i], &tmp[k], nlength);
754         k += nlength;
755         val[i + nlength] = '/';
756         i += nlength + 1;
757     }
758     memcpy(&val[i], &tmp[k], 22 - k);
759     val[i + 22 - k] = '\0';
760 }
761
762 #endif /* CASE_BLIND_FILESYSTEM */
763
764 /*
765  * Converts 8 hex digits to a time integer
766  */
767 int ap_proxy_hex2sec(const char *x)
768 {
769     int i, ch;
770     unsigned int j;
771
772     for (i = 0, j = 0; i < 8; i++) {
773         ch = x[i];
774         j <<= 4;
775         if (ap_isdigit(ch))
776             j |= ch - '0';
777         else if (ap_isupper(ch))
778             j |= ch - ('A' - 10);
779         else
780             j |= ch - ('a' - 10);
781     }
782     if (j == 0xffffffff)
783         return -1;              /* so that it works with 8-byte ints */
784     else
785         return j;
786 }
787
788 /*
789  * Converts a time integer to 8 hex digits
790  */
791 void ap_proxy_sec2hex(int t, char *y)
792 {
793     int i, ch;
794     unsigned int j = t;
795
796     for (i = 7; i >= 0; i--) {
797         ch = j & 0xF;
798         j >>= 4;
799         if (ch >= 10)
800             y[i] = ch + ('A' - 10);
801         else
802             y[i] = ch + '0';
803     }
804     y[8] = '\0';
805 }
806
807
808 cache_req *ap_proxy_cache_error(cache_req *c)
809 {
810     if (c != NULL) {
811         if (c->fp != NULL) {
812             ap_pclosef(c->req->pool, c->fp->fd);
813             c->fp = NULL;
814         }
815         if (c->tempfile) unlink(c->tempfile);
816     }
817     return NULL;
818 }
819
820 int ap_proxyerror(request_rec *r, int statuscode, const char *message)
821 {
822     ap_table_setn(r->notes, "error-notes",
823                   ap_pstrcat(r->pool, 
824                              "The proxy server could not handle the request "
825                              "<EM><A HREF=\"", r->uri, "\">",
826                              r->method, "&nbsp;", r->uri, "</A></EM>.<P>\n"
827                              "Reason: <STRONG>", message, "</STRONG>", NULL));
828
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, "*"));
831
832     r->status_line = ap_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
833     return statuscode;
834 }
835
836 /*
837  * This routine returns its own error message
838  */
839 const char *
840      ap_proxy_host2addr(const char *host, struct hostent *reqhp)
841 {
842     int i;
843     struct hostent *hp;
844 /* XXX - Either get rid of TLS, or use pthread/APR functions */
845 #define APACHE_TLS
846     static APACHE_TLS struct hostent hpbuf;
847     static APACHE_TLS u_long ipaddr;
848     static APACHE_TLS char *charpbuf[2];
849
850     for (i = 0; host[i] != '\0'; i++)
851         if (!ap_isdigit(host[i]) && host[i] != '.')
852             break;
853
854     if (host[i] != '\0') {
855         hp = gethostbyname(host);
856         if (hp == NULL)
857             return "Host not found";
858     }
859     else {
860         ipaddr = ap_inet_addr(host);
861         hp = gethostbyaddr((char *) &ipaddr, sizeof(u_long), AF_INET);
862         if (hp == NULL) {
863             memset(&hpbuf, 0, sizeof(hpbuf));
864             hpbuf.h_name = 0;
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;
870             hp = &hpbuf;
871         }
872     }
873     *reqhp = *hp;
874     return NULL;
875 }
876
877 static const char *
878      proxy_get_host_of_request(request_rec *r)
879 {
880     char *url, *user = NULL, *password = NULL, *err, *host;
881     int port = -1;
882
883     if (r->hostname != NULL)
884         return r->hostname;
885
886     /* Set url to the first char after "scheme://" */
887     if ((url = strchr(r->uri, ':')) == NULL
888         || url[1] != '/' || url[2] != '/')
889         return NULL;
890
891     url = ap_pstrdup(r->pool, &url[1]); /* make it point to "//", which is what proxy_canon_netloc expects */
892
893     err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
894
895     if (err != NULL)
896         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, r,
897                      "%s", err);
898
899     r->hostname = host;
900
901     return host;                /* ought to return the port, too */
902 }
903
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)
906 {
907     const char *addr = This->name;
908     long ip_addr[4];
909     int i, quads;
910     long bits;
911
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() */
919     /*return 1; */
920
921     /* Parse IP addr manually, optionally allowing */
922     /* abbreviated net addresses like 192.168. */
923
924     /* Iterate over up to 4 (dotted) quads. */
925     for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
926         char *tmp;
927
928         if (*addr == '/' && quads > 0)  /* netmask starts here. */
929             break;
930
931         if (!ap_isdigit(*addr))
932             return 0;           /* no digit at start of quad */
933
934         ip_addr[quads] = strtol(addr, &tmp, 0);
935
936         if (tmp == addr)        /* expected a digit, found something else */
937             return 0;
938
939         if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
940             /* invalid octet */
941             return 0;
942         }
943
944         addr = tmp;
945
946         if (*addr == '.' && quads != 3)
947             ++addr;             /* after the 4th quad, a dot would be illegal */
948     }
949
950     for (This->addr.s_addr = 0, i = 0; i < quads; ++i)
951         This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
952
953     if (addr[0] == '/' && ap_isdigit(addr[1])) {        /* net mask follows: */
954         char *tmp;
955
956         ++addr;
957
958         bits = strtol(addr, &tmp, 0);
959
960         if (tmp == addr)        /* expected a digit, found something else */
961             return 0;
962
963         addr = tmp;
964
965         if (bits < 0 || bits > 32)      /* netmask must be between 0 and 32 */
966             return 0;
967
968     }
969     else {
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)
974             --quads;
975
976         /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
977         if (quads < 1)
978             return 0;
979
980         /* every zero-byte counts as 8 zero-bits */
981         bits = 8 * quads;
982
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);
987     }
988
989     This->mask.s_addr = htonl(INADDR_NONE << (32 - bits));
990
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, 
996                      "         Set to %s/%ld",
997                 inet_ntoa(This->addr), bits);
998     }
999
1000     if (*addr == '\0') {
1001         This->matcher = proxy_match_ipaddr;
1002         return 1;
1003     }
1004     else
1005         return (*addr == '\0'); /* okay iff we've parsed the whole string */
1006 }
1007
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)
1010 {
1011     int i;
1012     int ip_addr[4];
1013     struct in_addr addr;
1014     struct in_addr *ip_list;
1015     char **ip_listptr;
1016     const char *found;
1017     const char *host = proxy_get_host_of_request(r);
1018
1019     if (host == NULL)   /* oops! */
1020        return 0;
1021
1022     memset(&addr, '\0', sizeof addr);
1023     memset(ip_addr, '\0', sizeof ip_addr);
1024
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));
1028
1029         if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
1030 #if DEBUGGING
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));
1037 #endif
1038             return 1;
1039         }
1040 #if DEBUGGING
1041         else {
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));
1048         }
1049 #endif
1050     }
1051     else {
1052         struct hostent the_host;
1053
1054         memset(&the_host, '\0', sizeof the_host);
1055         found = ap_proxy_host2addr(host, &the_host);
1056
1057         if (found != NULL) {
1058 #if DEBUGGING
1059             ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1060                          "2)IP-NoMatch: hostname=%s msg=%s", host, found);
1061 #endif
1062             return 0;
1063         }
1064
1065         if (the_host.h_name != NULL)
1066             found = the_host.h_name;
1067         else
1068             found = host;
1069
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)) {
1074 #if DEBUGGING
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));
1081 #endif
1082                 return 1;
1083             }
1084 #if DEBUGGING
1085             else {
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));
1092             }
1093 #endif
1094         }
1095     }
1096
1097     return 0;
1098 }
1099
1100 /* Return TRUE if addr represents a domain name */
1101 int ap_proxy_is_domainname(struct dirconn_entry *This, ap_context_t *p)
1102 {
1103     char *addr = This->name;
1104     int i;
1105
1106     /* Domain name must start with a '.' */
1107     if (addr[0] != '.')
1108         return 0;
1109
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)
1112         continue;
1113
1114 #if 0
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 */
1119     }
1120 #endif
1121
1122     if (addr[i] != '\0')
1123         return 0;
1124
1125     /* Strip trailing dots */
1126     for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i)
1127         addr[i] = '\0';
1128
1129     This->matcher = proxy_match_domainname;
1130     return 1;
1131 }
1132
1133 /* Return TRUE if host "host" is in domain "domain" */
1134 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
1135 {
1136     const char *host = proxy_get_host_of_request(r);
1137     int d_len = strlen(This->name), h_len;
1138
1139     if (host == NULL)           /* some error was logged already */
1140         return 0;
1141
1142     h_len = strlen(host);
1143
1144     /* @@@ do this within the setup? */
1145     /* Ignore trailing dots in domain comparison: */
1146     while (d_len > 0 && This->name[d_len - 1] == '.')
1147         --d_len;
1148     while (h_len > 0 && host[h_len - 1] == '.')
1149         --h_len;
1150     return h_len > d_len
1151         && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
1152 }
1153
1154 /* Return TRUE if addr represents a host name */
1155 int ap_proxy_is_hostname(struct dirconn_entry *This, ap_context_t *p)
1156 {
1157     struct hostent host;
1158     char *addr = This->name;
1159     int i;
1160
1161     /* Host names must not start with a '.' */
1162     if (addr[0] == '.')
1163         return 0;
1164
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);
1167
1168 #if 0
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 */
1173     }
1174 #endif
1175
1176     if (addr[i] != '\0' || ap_proxy_host2addr(addr, &host) != NULL)
1177         return 0;
1178
1179     This->hostentry = ap_pduphostent (p, &host);
1180
1181     /* Strip trailing dots */
1182     for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i)
1183         addr[i] = '\0';
1184
1185     This->matcher = proxy_match_hostname;
1186     return 1;
1187 }
1188
1189 /* Return TRUE if host "host" is equal to host2 "host2" */
1190 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
1191 {
1192     char *host = This->name;
1193     const char *host2 = proxy_get_host_of_request(r);
1194     int h2_len;
1195     int h1_len;
1196
1197     if (host == NULL || host2 == NULL)
1198        return 0; /* oops! */
1199
1200     h2_len = strlen(host2);
1201     h1_len = strlen(host);
1202
1203 #if 0
1204     unsigned long *ip_list;
1205
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 == ? ? ? ? ? ? ? ? ? ? ? ? ?)
1209             return 1;
1210 #endif
1211
1212     /* Ignore trailing dots in host2 comparison: */
1213     while (h2_len > 0 && host2[h2_len - 1] == '.')
1214         --h2_len;
1215     while (h1_len > 0 && host[h1_len - 1] == '.')
1216         --h1_len;
1217     return h1_len == h2_len
1218         && strncasecmp(host, host2, h1_len) == 0;
1219 }
1220
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)
1223 {
1224     This->matcher = proxy_match_word;
1225     return 1;
1226 }
1227
1228 /* Return TRUE if string "str2" occurs literally in "str1" */
1229 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
1230 {
1231     const char *host = proxy_get_host_of_request(r);
1232     return host != NULL && strstr(host, This->name) != NULL;
1233 }
1234
1235 int ap_proxy_doconnect(int sock, struct sockaddr_in *addr, request_rec *r)
1236 {
1237     int i;
1238
1239     do {
1240         i = connect(sock, (struct sockaddr *) addr, sizeof(struct sockaddr_in));
1241 #ifdef WIN32
1242         if (i == SOCKET_ERROR)
1243             errno = WSAGetLastError();
1244 #endif /* WIN32 */
1245     } while (i == -1 && errno == EINTR);
1246     if (i == -1) {
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));
1250     }
1251
1252     return i;
1253 }
1254
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)
1259 {
1260     struct tbl_do_args *parm = (struct tbl_do_args *)p;
1261
1262     if (key == NULL || value == NULL || value[0] == '\0')
1263         return 1;
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);
1271     }
1272     return 1; /* tell ap_table_do() to continue calling us for more headers */
1273 }
1274
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)
1277 {
1278     unsigned len = ap_bputs(data, client);
1279     if (cache != NULL && cache->fp != NULL)
1280         ap_bputs(data, cache->fp);
1281     return len;
1282 }
1283