home *** CD-ROM | disk | FTP | other *** search
/ PC Online 1999 April / PCO0499.ISO / filesbbs / os2 / apach134.arj / APACH134.ZIP / src / modules / proxy / proxy_http.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-01-01  |  16.6 KB  |  528 lines

  1. /* ====================================================================
  2.  * Copyright (c) 1996-1999 The Apache Group.  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 Group
  19.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  20.  *
  21.  * 4. The names "Apache Server" and "Apache Group" 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 Group.
  29.  *
  30.  * 6. Redistributions of any form whatsoever must retain the following
  31.  *    acknowledgment:
  32.  *    "This product includes software developed by the Apache Group
  33.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  34.  *
  35.  * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``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 GROUP 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 Group 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 Group and the Apache HTTP server
  54.  * project, please see <http://www.apache.org/>.
  55.  *
  56.  */
  57.  
  58. /* HTTP routines for Apache proxy */
  59.  
  60. #include "mod_proxy.h"
  61. #include "http_log.h"
  62. #include "http_main.h"
  63. #include "http_core.h"
  64. #include "util_date.h"
  65.  
  66. /*
  67.  * Canonicalise http-like URLs.
  68.  *  scheme is the scheme for the URL
  69.  *  url    is the URL starting with the first '/'
  70.  *  def_port is the default port for this scheme.
  71.  */
  72. int ap_proxy_http_canon(request_rec *r, char *url, const char *scheme, int def_port)
  73. {
  74.     char *host, *path, *search, sport[7];
  75.     const char *err;
  76.     int port;
  77.  
  78. /* do syntatic check.
  79.  * We break the URL into host, port, path, search
  80.  */
  81.     port = def_port;
  82.     err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
  83.     if (err)
  84.     return HTTP_BAD_REQUEST;
  85.  
  86. /* now parse path/search args, according to rfc1738 */
  87. /* N.B. if this isn't a true proxy request, then the URL _path_
  88.  * has already been decoded.  True proxy requests have r->uri
  89.  * == r->unparsed_uri, and no others have that property.
  90.  */
  91.     if (r->uri == r->unparsed_uri) {
  92.     search = strchr(url, '?');
  93.     if (search != NULL)
  94.         *(search++) = '\0';
  95.     }
  96.     else
  97.     search = r->args;
  98.  
  99. /* process path */
  100.     path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, r->proxyreq);
  101.     if (path == NULL)
  102.     return HTTP_BAD_REQUEST;
  103.  
  104.     if (port != def_port)
  105.     ap_snprintf(sport, sizeof(sport), ":%d", port);
  106.     else
  107.     sport[0] = '\0';
  108.  
  109.     r->filename = ap_pstrcat(r->pool, "proxy:", scheme, "://", host, sport, "/",
  110.            path, (search) ? "?" : "", (search) ? search : "", NULL);
  111.     return OK;
  112. }
  113.  
  114. static const char *proxy_location_reverse_map(request_rec *r, const char *url)
  115. {
  116.     void *sconf;
  117.     proxy_server_conf *conf;
  118.     struct proxy_alias *ent;
  119.     int i, l1, l2;
  120.     char *u;
  121.  
  122.     sconf = r->server->module_config;
  123.     conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
  124.     l1 = strlen(url);
  125.     ent = (struct proxy_alias *)conf->raliases->elts;
  126.     for (i = 0; i < conf->raliases->nelts; i++) {
  127.         l2 = strlen(ent[i].real);
  128.         if (l1 >= l2 && strncmp(ent[i].real, url, l2) == 0) {
  129.             u = ap_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
  130.             return ap_construct_url(r->pool, u, r);
  131.         }
  132.     }
  133.     return url;
  134. }
  135.  
  136. /* Clear all connection-based headers from the incoming headers table */
  137. static void clear_connection(pool *p, table *headers)
  138. {
  139.     const char *name;
  140.     char *next = ap_pstrdup(p, ap_table_get(headers, "Connection"));
  141.  
  142.     ap_table_unset(headers, "Proxy-Connection");
  143.     if (!next)
  144.     return;
  145.  
  146.     while (*next) {
  147.     name = next;
  148.     while (*next && !ap_isspace(*next) && (*next != ','))
  149.         ++next;
  150.     while (*next && (ap_isspace(*next) || (*next == ','))) {
  151.         *next = '\0';
  152.         ++next;
  153.     }
  154.     ap_table_unset(headers, name);
  155.     }
  156.     ap_table_unset(headers, "Connection");
  157. }
  158.  
  159. /*
  160.  * This handles http:// URLs, and other URLs using a remote proxy over http
  161.  * If proxyhost is NULL, then contact the server directly, otherwise
  162.  * go via the proxy.
  163.  * Note that if a proxy is used, then URLs other than http: can be accessed,
  164.  * also, if we have trouble which is clearly specific to the proxy, then
  165.  * we return DECLINED so that we can try another proxy. (Or the direct
  166.  * route.)
  167.  */
  168. int ap_proxy_http_handler(request_rec *r, cache_req *c, char *url,
  169.                const char *proxyhost, int proxyport)
  170. {
  171.     const char *strp;
  172.     char *strp2;
  173.     const char *err, *desthost;
  174.     int i, j, sock, len, backasswards;
  175.     array_header *reqhdrs_arr;
  176.     table *resp_hdrs;
  177.     table_entry *reqhdrs;
  178.     struct sockaddr_in server;
  179.     struct in_addr destaddr;
  180.     struct hostent server_hp;
  181.     BUFF *f;
  182.     char buffer[HUGE_STRING_LEN];
  183.     char portstr[32];
  184.     pool *p = r->pool;
  185.     const long int zero = 0L;
  186.     int destport = 0;
  187.     char *destportstr = NULL;
  188.     const char *urlptr = NULL;
  189.     const char *datestr;
  190.     struct tbl_do_args tdo;
  191.  
  192.     void *sconf = r->server->module_config;
  193.     proxy_server_conf *conf =
  194.     (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
  195.     struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
  196.     struct nocache_entry *ncent = (struct nocache_entry *) conf->nocaches->elts;
  197.     int nocache = 0;
  198.  
  199.     memset(&server, '\0', sizeof(server));
  200.     server.sin_family = AF_INET;
  201.  
  202. /* We break the URL into host, port, path-search */
  203.  
  204.     urlptr = strstr(url, "://");
  205.     if (urlptr == NULL)
  206.     return HTTP_BAD_REQUEST;
  207.     urlptr += 3;
  208.     destport = DEFAULT_HTTP_PORT;
  209.     strp = strchr(urlptr, '/');
  210.     if (strp == NULL) {
  211.     desthost = ap_pstrdup(p, urlptr);
  212.     urlptr = "/";
  213.     }
  214.     else {
  215.     char *q = ap_palloc(p, strp - urlptr + 1);
  216.     memcpy(q, urlptr, strp - urlptr);
  217.     q[strp - urlptr] = '\0';
  218.     urlptr = strp;
  219.     desthost = q;
  220.     }
  221.  
  222.     strp2 = strchr(desthost, ':');
  223.     if (strp2 != NULL) {
  224.     *(strp2++) = '\0';
  225.     if (ap_isdigit(*strp2)) {
  226.         destport = atoi(strp2);
  227.         destportstr = strp2;
  228.     }
  229.     }
  230.  
  231. /* check if ProxyBlock directive on this host */
  232.     destaddr.s_addr = ap_inet_addr(desthost);
  233.     for (i = 0; i < conf->noproxies->nelts; i++) {
  234.     if ((npent[i].name != NULL && strstr(desthost, npent[i].name) != NULL)
  235.         || destaddr.s_addr == npent[i].addr.s_addr || npent[i].name[0] == '*')
  236.         return ap_proxyerror(r, "Connect to remote machine blocked");
  237.     }
  238.  
  239.     if (proxyhost != NULL) {
  240.     server.sin_port = htons(proxyport);
  241.     err = ap_proxy_host2addr(proxyhost, &server_hp);
  242.     if (err != NULL)
  243.         return DECLINED;    /* try another */
  244.     }
  245.     else {
  246.     server.sin_port = htons(destport);
  247.     err = ap_proxy_host2addr(desthost, &server_hp);
  248.     if (err != NULL)
  249.         return ap_proxyerror(r, err);    /* give up */
  250.     }
  251.  
  252.     sock = ap_psocket(p, PF_INET, SOCK_STREAM, IPPROTO_TCP);
  253.     if (sock == -1) {
  254.     ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
  255.             "proxy: error creating socket");
  256.     return HTTP_INTERNAL_SERVER_ERROR;
  257.     }
  258.  
  259.     if (conf->recv_buffer_size) {
  260.     if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  261.                (const char *) &conf->recv_buffer_size, sizeof(int))
  262.         == -1) {
  263.         ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
  264.              "setsockopt(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
  265.     }
  266.     }
  267.  
  268. #ifdef SINIX_D_RESOLVER_BUG
  269.     {
  270.     struct in_addr *ip_addr = (struct in_addr *) *server_hp.h_addr_list;
  271.  
  272.     for (; ip_addr->s_addr != 0; ++ip_addr) {
  273.         memcpy(&server.sin_addr, ip_addr, sizeof(struct in_addr));
  274.         i = ap_proxy_doconnect(sock, &server, r);
  275.         if (i == 0)
  276.         break;
  277.     }
  278.     }
  279. #else
  280.     j = 0;
  281.     while (server_hp.h_addr_list[j] != NULL) {
  282.     memcpy(&server.sin_addr, server_hp.h_addr_list[j],
  283.            sizeof(struct in_addr));
  284.     i = ap_proxy_doconnect(sock, &server, r);
  285.     if (i == 0)
  286.         break;
  287.     j++;
  288.     }
  289. #endif
  290.     if (i == -1) {
  291.     if (proxyhost != NULL)
  292.         return DECLINED;    /* try again another way */
  293.     else
  294.         return ap_proxyerror(r, /*HTTP_BAD_GATEWAY*/ ap_pstrcat(r->pool,
  295.                 "Could not connect to remote machine: ",
  296.                 strerror(errno), NULL));
  297.     }
  298.  
  299.     clear_connection(r->pool, r->headers_in);    /* Strip connection-based headers */
  300.  
  301.     f = ap_bcreate(p, B_RDWR | B_SOCKET);
  302.     ap_bpushfd(f, sock, sock);
  303.  
  304.     ap_hard_timeout("proxy send", r);
  305.     ap_bvputs(f, r->method, " ", proxyhost ? url : urlptr, " HTTP/1.0" CRLF,
  306.        NULL);
  307.     if (destportstr != NULL && destport != DEFAULT_HTTP_PORT)
  308.     ap_bvputs(f, "Host: ", desthost, ":", destportstr, CRLF, NULL);
  309.     else
  310.     ap_bvputs(f, "Host: ", desthost, CRLF, NULL);
  311.  
  312.     if (conf->viaopt == via_block) {
  313.     /* Block all outgoing Via: headers */
  314.     ap_table_unset(r->headers_in, "Via");
  315.     } else if (conf->viaopt != via_off) {
  316.     /* Create a "Via:" request header entry and merge it */
  317.     i = ap_get_server_port(r);
  318.     if (ap_is_default_port(i,r)) {
  319.         strcpy(portstr,"");
  320.     } else {
  321.         ap_snprintf(portstr, sizeof portstr, ":%d", i);
  322.     }
  323.     /* Generate outgoing Via: header with/without server comment: */
  324.     ap_table_mergen(r->headers_in, "Via",
  325.             (conf->viaopt == via_full)
  326.             ? ap_psprintf(p, "%d.%d %s%s (%s)",
  327.                 HTTP_VERSION_MAJOR(r->proto_num),
  328.                 HTTP_VERSION_MINOR(r->proto_num),
  329.                 ap_get_server_name(r), portstr,
  330.                 SERVER_BASEVERSION)
  331.             : ap_psprintf(p, "%d.%d %s%s",
  332.                 HTTP_VERSION_MAJOR(r->proto_num),
  333.                 HTTP_VERSION_MINOR(r->proto_num),
  334.                 ap_get_server_name(r), portstr)
  335.             );
  336.     }
  337.  
  338.     reqhdrs_arr = ap_table_elts(r->headers_in);
  339.     reqhdrs = (table_entry *) reqhdrs_arr->elts;
  340.     for (i = 0; i < reqhdrs_arr->nelts; i++) {
  341.     if (reqhdrs[i].key == NULL || reqhdrs[i].val == NULL
  342.     /* Clear out headers not to send */
  343.         || !strcasecmp(reqhdrs[i].key, "Host")    /* Already sent */
  344.         /* XXX: @@@ FIXME: "Proxy-Authorization" should *only* be 
  345.          * suppressed if THIS server requested the authentication,
  346.          * not when a frontend proxy requested it!
  347.          */
  348.         || !strcasecmp(reqhdrs[i].key, "Proxy-Authorization"))
  349.         continue;
  350.     ap_bvputs(f, reqhdrs[i].key, ": ", reqhdrs[i].val, CRLF, NULL);
  351.     }
  352.  
  353.     ap_bputs(CRLF, f);
  354. /* send the request data, if any. N.B. should we trap SIGPIPE ? */
  355.  
  356.     if (ap_should_client_block(r)) {
  357.     while ((i = ap_get_client_block(r, buffer, sizeof buffer)) > 0)
  358.         ap_bwrite(f, buffer, i);
  359.     }
  360.     ap_bflush(f);
  361.     ap_kill_timeout(r);
  362.  
  363.     ap_hard_timeout("proxy receive", r);
  364.  
  365.     len = ap_bgets(buffer, sizeof buffer - 1, f);
  366.     if (len == -1 || len == 0) {
  367.     ap_bclose(f);
  368.     ap_kill_timeout(r);
  369.     ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
  370.              "ap_bgets() - proxy receive - Error reading from remote server %s",
  371.              proxyhost ? proxyhost : desthost);
  372.     return ap_proxyerror(r, "Error reading from remote server");
  373.     }
  374.  
  375. /* Is it an HTTP/1 response?  This is buggy if we ever see an HTTP/1.10 */
  376.     if (ap_checkmask(buffer, "HTTP/#.# ###*")) {
  377.     int major, minor;
  378.     if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
  379.         major = 1;
  380.         minor = 0;
  381.     }
  382.  
  383. /* If not an HTTP/1 message or if the status line was > 8192 bytes */
  384.     if (buffer[5] != '1' || buffer[len - 1] != '\n') {
  385.         ap_bclose(f);
  386.         ap_kill_timeout(r);
  387.         return HTTP_BAD_GATEWAY;
  388.     }
  389.     backasswards = 0;
  390.     buffer[--len] = '\0';
  391.  
  392.     buffer[12] = '\0';
  393.     r->status = atoi(&buffer[9]);
  394.     buffer[12] = ' ';
  395.     r->status_line = ap_pstrdup(p, &buffer[9]);
  396.  
  397. /* read the headers. */
  398. /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers */
  399. /* Also, take care with headers with multiple occurences. */
  400.  
  401.     resp_hdrs = ap_proxy_read_headers(r, buffer, HUGE_STRING_LEN, f);
  402.     if (resp_hdrs == NULL) {
  403.         ap_log_error(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, r->server,
  404.          "proxy: Bad HTTP/%d.%d header returned by %s (%s)",
  405.          major, minor, r->uri, r->method);
  406.         resp_hdrs = ap_make_table(p, 20);
  407.         nocache = 1;    /* do not cache this broken file */
  408.     }
  409.  
  410.     if (conf->viaopt != via_off && conf->viaopt != via_block) {
  411.         /* Create a "Via:" response header entry and merge it */
  412.         i = ap_get_server_port(r);
  413.         if (ap_is_default_port(i,r)) {
  414.         strcpy(portstr,"");
  415.         } else {
  416.         ap_snprintf(portstr, sizeof portstr, ":%d", i);
  417.         }
  418.         ap_table_mergen((table *)resp_hdrs, "Via",
  419.                 (conf->viaopt == via_full)
  420.                 ? ap_psprintf(p, "%d.%d %s%s (%s)",
  421.                 major, minor,
  422.                 ap_get_server_name(r), portstr,
  423.                 SERVER_BASEVERSION)
  424.                 : ap_psprintf(p, "%d.%d %s%s",
  425.                 major, minor,
  426.                 ap_get_server_name(r), portstr)
  427.                 );
  428.     }
  429.  
  430.     clear_connection(p, resp_hdrs);    /* Strip Connection hdrs */
  431.     }
  432.     else {
  433. /* an http/0.9 response */
  434.     backasswards = 1;
  435.     r->status = 200;
  436.     r->status_line = "200 OK";
  437.  
  438. /* no headers */
  439.     resp_hdrs = ap_make_table(p, 20);
  440.     }
  441.  
  442.     c->hdrs = resp_hdrs;
  443.  
  444.     ap_kill_timeout(r);
  445.  
  446. /*
  447.  * HTTP/1.0 requires us to accept 3 types of dates, but only generate
  448.  * one type
  449.  */
  450.     if ((datestr = ap_table_get(resp_hdrs, "Date")) != NULL)
  451.     ap_table_set(resp_hdrs, "Date", ap_proxy_date_canon(p, datestr));
  452.     if ((datestr = ap_table_get(resp_hdrs, "Last-Modified")) != NULL)
  453.     ap_table_set(resp_hdrs, "Last-Modified", ap_proxy_date_canon(p, datestr));
  454.     if ((datestr = ap_table_get(resp_hdrs, "Expires")) != NULL)
  455.     ap_table_set(resp_hdrs, "Expires", ap_proxy_date_canon(p, datestr));
  456.  
  457.     if ((datestr = ap_table_get(resp_hdrs, "Location")) != NULL)
  458.     ap_table_set(resp_hdrs, "Location", proxy_location_reverse_map(r, datestr));
  459.     if ((datestr = ap_table_get(resp_hdrs, "URI")) != NULL)
  460.     ap_table_set(resp_hdrs, "URI", proxy_location_reverse_map(r, datestr));
  461.  
  462. /* check if NoCache directive on this host */
  463.     for (i = 0; i < conf->nocaches->nelts; i++) {
  464.     if ((ncent[i].name != NULL && strstr(desthost, ncent[i].name) != NULL)
  465.         || destaddr.s_addr == ncent[i].addr.s_addr || ncent[i].name[0] == '*')
  466.         nocache = 1;
  467.     }
  468.  
  469.     i = ap_proxy_cache_update(c, resp_hdrs, !backasswards, nocache);
  470.     if (i != DECLINED) {
  471.     ap_bclose(f);
  472.     return i;
  473.     }
  474.  
  475.     ap_hard_timeout("proxy receive", r);
  476.  
  477. /* write status line */
  478.     if (!r->assbackwards)
  479.     ap_rvputs(r, "HTTP/1.0 ", r->status_line, CRLF, NULL);
  480.     if (c != NULL && c->fp != NULL &&
  481.     ap_bvputs(c->fp, "HTTP/1.0 ", r->status_line, CRLF, NULL) == -1)
  482.     c = ap_proxy_cache_error(c);
  483.  
  484. /* send headers */
  485.     tdo.req = r;
  486.     tdo.cache = c;
  487.     ap_table_do(ap_proxy_send_hdr_line, &tdo, resp_hdrs, NULL);
  488.  
  489.     if (!r->assbackwards)
  490.     ap_rputs(CRLF, r);
  491.     if (c != NULL && c->fp != NULL && ap_bputs(CRLF, c->fp) == -1)
  492.     c = ap_proxy_cache_error(c);
  493.  
  494.     ap_bsetopt(r->connection->client, BO_BYTECT, &zero);
  495.     r->sent_bodyct = 1;
  496. /* Is it an HTTP/0.9 respose? If so, send the extra data */
  497.     if (backasswards) {
  498.     ap_bwrite(r->connection->client, buffer, len);
  499.     if (c != NULL && c->fp != NULL && ap_bwrite(c->fp, buffer, len) != len)
  500.         c = ap_proxy_cache_error(c);
  501.     }
  502.     ap_kill_timeout(r);
  503.  
  504. #ifdef CHARSET_EBCDIC
  505.     /* What we read/write after the header should not be modified
  506.      * (i.e., the cache copy is ASCII, not EBCDIC, even for text/html)
  507.      */
  508.     ap_bsetflag(f, B_ASCII2EBCDIC|B_EBCDIC2ASCII, 0);
  509.     ap_bsetflag(r->connection->client, B_ASCII2EBCDIC|B_EBCDIC2ASCII, 0);
  510. #endif
  511.  
  512. /* send body */
  513. /* if header only, then cache will be NULL */
  514. /* HTTP/1.0 tells us to read to EOF, rather than content-length bytes */
  515.     if (!r->header_only) {
  516. /* we need to set this for ap_proxy_send_fb()... */
  517.     c->cache_completion = conf->cache.cache_completion;
  518.     ap_proxy_send_fb(f, r, c);
  519.     }
  520.  
  521.     ap_proxy_cache_tidy(c);
  522.  
  523.     ap_bclose(f);
  524.  
  525.     ap_proxy_garbage_coll(r);
  526.     return OK;
  527. }
  528.