46f11895cec78c9e9c58c858dfd65caa20208e2c
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.34 2001/10/07 18:50:55 oes Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/parsers.c,v $
5  *
6  * Purpose     :  Declares functions to parse/crunch headers and pages.
7  *                Functions declared include:
8  *                   `add_to_iob', `client_cookie_adder', `client_from',
9  *                   `client_referrer', `client_send_cookie', `client_ua',
10  *                   `client_uagent', `client_x_forwarded',
11  *                   `client_x_forwarded_adder', `client_xtra_adder',
12  *                   `content_type', `crumble', `destroy_list', `enlist',
13  *                   `flush_socket', `free_http_request', `get_header',
14  *                   `list_to_text', `parse_http_request', `sed',
15  *                   and `server_set_cookie'.
16  *
17  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
18  *                IJBSWA team.  http://ijbswa.sourceforge.net
19  *
20  *                Based on the Internet Junkbuster originally written
21  *                by and Copyright (C) 1997 Anonymous Coders and 
22  *                Junkbusters Corporation.  http://www.junkbusters.com
23  *
24  *                This program is free software; you can redistribute it 
25  *                and/or modify it under the terms of the GNU General
26  *                Public License as published by the Free Software
27  *                Foundation; either version 2 of the License, or (at
28  *                your option) any later version.
29  *
30  *                This program is distributed in the hope that it will
31  *                be useful, but WITHOUT ANY WARRANTY; without even the
32  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
33  *                PARTICULAR PURPOSE.  See the GNU General Public
34  *                License for more details.
35  *
36  *                The GNU General Public License should be included with
37  *                this file.  If not, you can view it at
38  *                http://www.gnu.org/copyleft/gpl.html
39  *                or write to the Free Software Foundation, Inc., 59
40  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
41  *
42  * Revisions   :
43  *    $Log: parsers.c,v $
44  *    Revision 1.34  2001/10/07 18:50:55  oes
45  *    Added server_content_encoding, renamed server_transfer_encoding
46  *
47  *    Revision 1.33  2001/10/07 18:04:49  oes
48  *    Changed server_http11 to server_http and its pattern to "HTTP".
49  *      Additional functionality: it now saves the HTTP status into
50  *      csp->http->status and sets CT_TABOO for Status 206 (partial range)
51  *
52  *    Revision 1.32  2001/10/07 15:43:28  oes
53  *    Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
54  *       client_te and client_accept_encoding_adder, triggered by the new
55  *       +no-compression action. For HTTP/1.1 the Accept-Encoding header is
56  *       changed to allow only identity and chunked, and the TE header is
57  *       crunched. For HTTP/1.0, Accept-Encoding is crunched.
58  *
59  *    parse_http_request no longer does anything than parsing. The rewriting
60  *      of http->cmd and version mangling are gone. It now also recognizes
61  *      the put and delete methods and saves the url in http->url. Removed
62  *      unused variable.
63  *
64  *    renamed content_type and content_length to have the server_ prefix
65  *
66  *    server_content_type now only works if csp->content_type != CT_TABOO
67  *
68  *    added server_transfer_encoding, which
69  *      - Sets CT_TABOO to prohibit filtering if encoding compresses
70  *      - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
71  *      - Change from "chunked" to "identity" if body was chunked
72  *        but has been de-chunked for filtering.
73  *
74  *    added server_content_md5 which crunches any Content-MD5 headers
75  *      if the body was modified.
76  *
77  *    made server_http11 conditional on +downgrade action
78  *
79  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
80  *
81  *    Revision 1.31  2001/10/05 14:25:02  oes
82  *    Crumble Keep-Alive from Server
83  *
84  *    Revision 1.30  2001/09/29 12:56:03  joergs
85  *    IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
86  *
87  *    Revision 1.29  2001/09/24 21:09:24  jongfoster
88  *    Fixing 2 memory leaks that Guy spotted, where the paramater to
89  *    enlist() was not being free()d.
90  *
91  *    Revision 1.28  2001/09/22 16:32:28  jongfoster
92  *    Removing unused #includes.
93  *
94  *    Revision 1.27  2001/09/20 15:45:25  steudten
95  *
96  *    add casting from size_t to int for printf()
97  *    remove local variable shadow s2
98  *
99  *    Revision 1.26  2001/09/16 17:05:14  jongfoster
100  *    Removing unused #include showarg.h
101  *
102  *    Revision 1.25  2001/09/16 13:21:27  jongfoster
103  *    Changes to use new list functions.
104  *
105  *    Revision 1.24  2001/09/13 23:05:50  jongfoster
106  *    Changing the string paramater to the header parsers a "const".
107  *
108  *    Revision 1.23  2001/09/12 18:08:19  steudten
109  *
110  *    In parse_http_request() header rewriting miss the host value, so
111  *    from http://www.mydomain.com the result was just " / " not
112  *    http://www.mydomain.com/ in case we forward.
113  *
114  *    Revision 1.22  2001/09/10 10:58:53  oes
115  *    Silenced compiler warnings
116  *
117  *    Revision 1.21  2001/07/31 14:46:00  oes
118  *     - Persistant connections now suppressed
119  *     - sed() no longer appends empty header to csp->headers
120  *
121  *    Revision 1.20  2001/07/30 22:08:36  jongfoster
122  *    Tidying up #defines:
123  *    - All feature #defines are now of the form FEATURE_xxx
124  *    - Permanently turned off WIN_GUI_EDIT
125  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
126  *
127  *    Revision 1.19  2001/07/25 17:21:54  oes
128  *    client_uagent now saves copy of User-Agent: header value
129  *
130  *    Revision 1.18  2001/07/13 14:02:46  oes
131  *     - Included fix to repair broken HTTP requests that
132  *       don't contain a path, not even '/'.
133  *     - Removed all #ifdef PCRS
134  *     - content_type now always inspected and classified as
135  *       text, gif or other.
136  *     - formatting / comments
137  *
138  *    Revision 1.17  2001/06/29 21:45:41  oes
139  *    Indentation, CRLF->LF, Tab-> Space
140  *
141  *    Revision 1.16  2001/06/29 13:32:42  oes
142  *    - Fixed a comment
143  *    - Adapted free_http_request
144  *    - Removed logentry from cancelled commit
145  *
146  *    Revision 1.15  2001/06/03 19:12:38  oes
147  *    deleted const struct interceptors
148  *
149  *    Revision 1.14  2001/06/01 18:49:17  jongfoster
150  *    Replaced "list_share" with "list" - the tiny memory gain was not
151  *    worth the extra complexity.
152  *
153  *    Revision 1.13  2001/05/31 21:30:33  jongfoster
154  *    Removed list code - it's now in list.[ch]
155  *    Renamed "permission" to "action", and changed many features
156  *    to use the actions file rather than the global config.
157  *
158  *    Revision 1.12  2001/05/31 17:33:13  oes
159  *
160  *    CRLF -> LF
161  *
162  *    Revision 1.11  2001/05/29 20:11:19  joergs
163  *    '/ * inside comment' warning removed.
164  *
165  *    Revision 1.10  2001/05/29 09:50:24  jongfoster
166  *    Unified blocklist/imagelist/permissionslist.
167  *    File format is still under discussion, but the internal changes
168  *    are (mostly) done.
169  *
170  *    Also modified interceptor behaviour:
171  *    - We now intercept all URLs beginning with one of the following
172  *      prefixes (and *only* these prefixes):
173  *        * http://i.j.b/
174  *        * http://ijbswa.sf.net/config/
175  *        * http://ijbswa.sourceforge.net/config/
176  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
177  *    - Internal changes so that intercepted and fast redirect pages
178  *      are not replaced with an image.
179  *    - Interceptors now have the option to send a binary page direct
180  *      to the client. (i.e. ijb-send-banner uses this)
181  *    - Implemented show-url-info interceptor.  (Which is why I needed
182  *      the above interceptors changes - a typical URL is
183  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
184  *      The previous mechanism would not have intercepted that, and
185  *      if it had been intercepted then it then it would have replaced
186  *      it with an image.)
187  *
188  *    Revision 1.9  2001/05/28 17:26:33  jongfoster
189  *    Fixing segfault if last header was crunched.
190  *    Fixing Windows build (snprintf() is _snprintf() under Win32, but we
191  *    can use the cross-platform sprintf() instead.)
192  *
193  *    Revision 1.8  2001/05/27 22:17:04  oes
194  *
195  *    - re_process_buffer no longer writes the modified buffer
196  *      to the client, which was very ugly. It now returns the
197  *      buffer, which it is then written by chat.
198  *
199  *    - content_length now adjusts the Content-Length: header
200  *      for modified documents rather than crunch()ing it.
201  *      (Length info in csp->content_length, which is 0 for
202  *      unmodified documents)
203  *
204  *    - For this to work, sed() is called twice when filtering.
205  *
206  *    Revision 1.7  2001/05/27 13:19:06  oes
207  *    Patched Joergs solution for the content-length in.
208  *
209  *    Revision 1.6  2001/05/26 13:39:32  jongfoster
210  *    Only crunches Content-Length header if applying RE filtering.
211  *    Without this fix, Microsoft Windows Update wouldn't work.
212  *
213  *    Revision 1.5  2001/05/26 00:28:36  jongfoster
214  *    Automatic reloading of config file.
215  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
216  *    Most of the global variables have been moved to a new
217  *    struct configuration_spec, accessed through csp->config->globalname
218  *    Most of the globals remaining are used by the Win32 GUI.
219  *
220  *    Revision 1.4  2001/05/22 18:46:04  oes
221  *
222  *    - Enabled filtering banners by size rather than URL
223  *      by adding patterns that replace all standard banner
224  *      sizes with the "Junkbuster" gif to the re_filterfile
225  *
226  *    - Enabled filtering WebBugs by providing a pattern
227  *      which kills all 1x1 images
228  *
229  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
230  *      which is selected by the (nonstandard and therefore
231  *      capital) letter 'U' in the option string.
232  *      It causes the quantifiers to be ungreedy by default.
233  *      Appending a ? turns back to greedy (!).
234  *
235  *    - Added a new interceptor ijb-send-banner, which
236  *      sends back the "Junkbuster" gif. Without imagelist or
237  *      MSIE detection support, or if tinygif = 1, or the
238  *      URL isn't recognized as an imageurl, a lame HTML
239  *      explanation is sent instead.
240  *
241  *    - Added new feature, which permits blocking remote
242  *      script redirects and firing back a local redirect
243  *      to the browser.
244  *      The feature is conditionally compiled, i.e. it
245  *      can be disabled with --disable-fast-redirects,
246  *      plus it must be activated by a "fast-redirects"
247  *      line in the config file, has its own log level
248  *      and of course wants to be displayed by show-proxy-args
249  *      Note: Boy, all the #ifdefs in 1001 locations and
250  *      all the fumbling with configure.in and acconfig.h
251  *      were *way* more work than the feature itself :-(
252  *
253  *    - Because a generic redirect template was needed for
254  *      this, tinygif = 3 now uses the same.
255  *
256  *    - Moved GIFs, and other static HTTP response templates
257  *      to project.h
258  *
259  *    - Some minor fixes
260  *
261  *    - Removed some >400 CRs again (Jon, you really worked
262  *      a lot! ;-)
263  *
264  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
265  *    Version 2.9.4 checkin.
266  *    - Merged popupfile and cookiefile, and added control over PCRS
267  *      filtering, in new "permissionsfile".
268  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
269  *      file error you now get a message box (in the Win32 GUI) rather
270  *      than the program exiting with no explanation.
271  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
272  *      skipping.
273  *    - Removed tabs from "config"
274  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
275  *    - Bumped up version number.
276  *
277  *    Revision 1.2  2001/05/17 23:02:36  oes
278  *     - Made referrer option accept 'L' as a substitute for '§'
279  *
280  *    Revision 1.1.1.1  2001/05/15 13:59:01  oes
281  *    Initial import of version 2.9.3 source tree
282  *
283  *
284  *********************************************************************/
285 \f
286
287 #include "config.h"
288
289 #ifndef _WIN32
290 #include <stdio.h>
291 #include <sys/types.h>
292 #include <stdlib.h>
293 #include <ctype.h>
294 #endif
295
296 #include <assert.h>
297 #include <string.h>
298
299 #ifndef _WIN32
300 #include <unistd.h>
301 #endif
302
303 #include "project.h"
304 #include "list.h"
305 #include "parsers.h"
306 #include "encode.h"
307 #include "ssplit.h"
308 #include "errlog.h"
309 #include "jbsockets.h"
310 #include "miscutil.h"
311
312 const char parsers_h_rcs[] = PARSERS_H_VERSION;
313
314 /* Fix a problem with Solaris.  There should be no effect on other
315  * platforms.
316  * Solaris's isspace() is a macro which uses it's argument directly
317  * as an array index.  Therefore we need to make sure that high-bit
318  * characters generate +ve values, and ideally we also want to make
319  * the argument match the declared parameter type of "int".
320  * 
321  * Why did they write a character function that can't take a simple 
322  * "char" argument?  Doh!
323  */
324 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
325 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
326
327
328 const struct parsers client_patterns[] = {
329    { "referer:",                 8,    client_referrer },
330    { "user-agent:",              11,   client_uagent },
331    { "ua-",                      3,    client_ua },
332    { "from:",                    5,    client_from },
333    { "cookie:",                  7,    client_send_cookie },
334    { "x-forwarded-for:",         16,   client_x_forwarded },
335    { "Accept-Encoding:",         16,   client_accept_encoding },
336    { "TE:",                      3,    client_te },
337 #if defined(FEATURE_IMAGE_DETECT_MSIE)
338    { "Accept:",                   7,   client_accept },
339 #endif /* defined(FEATURE_IMAGE_DETECT_MSIE) */
340 #ifdef FEATURE_FORCE_LOAD
341    { "Host:",                     5,   client_host },
342 #endif /* def FEATURE_FORCE_LOAD */
343 /* { "if-modified-since:",       18,   crumble }, */
344    { "Keep-Alive:",              11,   crumble },
345    { "connection:",              11,   crumble },
346    { "proxy-connection:",        17,   crumble },        
347    { NULL,                       0,    NULL }
348 };
349
350
351 const struct parsers server_patterns[] = {
352    { "HTTP",                4, server_http },
353    { "set-cookie:",        11, server_set_cookie },
354    { "connection:",        11, crumble },
355    { "Content-Type:",      13, server_content_type },
356    { "Content-Length:",    15, server_content_length },
357    { "Content-MD5:",       12, server_content_md5 },
358    { "Content-Encoding:",  17, server_content_encoding },   
359    { "Transfer-Encoding:", 18, server_transfer_coding },
360    { "Keep-Alive:",        11, crumble },
361    { NULL, 0, NULL }
362 };
363
364
365 void (* const add_client_headers[])(struct client_state *) = {
366    client_cookie_adder,
367    client_x_forwarded_adder,
368    client_xtra_adder,
369    client_accept_encoding_adder,
370    connection_close_adder, 
371    NULL
372 };
373
374
375 void (* const add_server_headers[])(struct client_state *) = {
376    connection_close_adder, 
377    NULL
378 };
379
380
381 /*********************************************************************
382  *
383  * Function    :  flush_socket
384  *
385  * Description :  Write any pending "buffered" content.
386  *
387  * Parameters  :
388  *          1  :  fd = file descriptor of the socket to read
389  *          2  :  csp = Current client state (buffers, headers, etc...)
390  *
391  * Returns     :  On success, the number of bytes written are returned (zero
392  *                indicates nothing was written).  On error, -1 is returned,
393  *                and errno is set appropriately.  If count is zero and the
394  *                file descriptor refers to a regular file, 0 will be
395  *                returned without causing any other effect.  For a special
396  *                file, the results are not portable.
397  *
398  *********************************************************************/
399 int flush_socket(int fd, struct client_state *csp)
400 {
401    struct iob *iob = csp->iob;
402    int n = iob->eod - iob->cur;
403
404    if (n <= 0)
405    {
406       return(0);
407    }
408
409    n = write_socket(fd, iob->cur, n);
410    iob->eod = iob->cur = iob->buf;
411    return(n);
412
413 }
414
415
416 /*********************************************************************
417  *
418  * Function    :  add_to_iob
419  *
420  * Description :  Add content to the buffered page.
421  *
422  * Parameters  :
423  *          1  :  csp = Current client state (buffers, headers, etc...)
424  *          2  :  buf = holds the content to be added to the page
425  *          3  :  n = number of bytes to be added
426  *
427  * Returns     :  Number of bytes in the content buffer.
428  *
429  *********************************************************************/
430 int add_to_iob(struct client_state *csp, char *buf, int n)
431 {
432    struct iob *iob = csp->iob;
433    int have, need;
434    char *p;
435
436    have = iob->eod - iob->cur;
437
438    if (n <= 0)
439    {
440       return(have);
441    }
442
443    need = have + n;
444
445    if ((p = (char *)malloc(need + 1)) == NULL)
446    {
447       log_error(LOG_LEVEL_ERROR, "malloc() iob failed: %E");
448       return(-1);
449    }
450
451    if (have)
452    {
453       /* there is something in the buffer - save it */
454       memcpy(p, iob->cur, have);
455
456       /* replace the buffer with the new space */
457       freez(iob->buf);
458       iob->buf = p;
459
460       /* point to the end of the data */
461       p += have;
462    }
463    else
464    {
465       /* the buffer is empty, free it and reinitialize */
466       freez(iob->buf);
467       iob->buf = p;
468    }
469
470    /* copy the new data into the iob buffer */
471    memcpy(p, buf, n);
472
473    /* point to the end of the data */
474    p += n;
475
476    /* null terminate == cheap insurance */
477    *p = '\0';
478
479    /* set the pointers to the new values */
480    iob->cur = iob->buf;
481    iob->eod = p;
482
483    return(need);
484
485 }
486
487
488 /*********************************************************************
489  *
490  * Function    :  get_header
491  *
492  * Description :  This (odd) routine will parse the csp->iob
493  *
494  * Parameters  :
495  *          1  :  csp = Current client state (buffers, headers, etc...)
496  *
497  * Returns     :  Any one of the following:
498  *
499  * 1) a pointer to a dynamically allocated string that contains a header line
500  * 2) NULL  indicating that the end of the header was reached
501  * 3) ""    indicating that the end of the iob was reached before finding
502  *          a complete header line.
503  *
504  *********************************************************************/
505 char *get_header(struct client_state *csp)
506 {
507    struct iob *iob;
508    char *p, *q, *ret;
509    iob = csp->iob;
510
511    if ((iob->cur == NULL)
512       || ((p = strchr(iob->cur, '\n')) == NULL))
513    {
514       return(""); /* couldn't find a complete header */
515    }
516
517    *p = '\0';
518
519    ret = strdup(iob->cur);
520
521    iob->cur = p+1;
522
523    if ((q = strchr(ret, '\r'))) *q = '\0';
524
525    /* is this a blank linke (i.e. the end of the header) ? */
526    if (*ret == '\0')
527    {
528       freez(ret);
529       return(NULL);
530    }
531
532    return(ret);
533
534 }
535
536
537 /*********************************************************************
538  *
539  * Function    :  sed
540  *
541  * Description :  add, delete or modify lines in the HTTP header streams.
542  *                On entry, it receives a linked list of headers space
543  *                that was allocated dynamically (both the list nodes
544  *                and the header contents).
545  *
546  *                As a side effect it frees the space used by the original
547  *                header lines.
548  *
549  * Parameters  :
550  *          1  :  pats = list of patterns to match against headers
551  *          2  :  more_headers = list of functions to add more
552  *                headers (client or server)
553  *          3  :  csp = Current client state (buffers, headers, etc...)
554  *
555  * Returns     :  Single pointer to a fully formed header.
556  *
557  *********************************************************************/
558 char *sed(const struct parsers pats[], void (* const more_headers[])(struct client_state *), struct client_state *csp)
559 {
560    struct list_entry *p;
561    const struct parsers *v;
562    char *hdr;
563    void (* const *f)();
564
565    for (v = pats; v->str ; v++)
566    {
567       for (p = csp->headers->first; p ; p = p->next)
568       {
569          /* Header crunch()ed in previous run? -> ignore */
570          if (p->str == NULL) continue;
571
572          if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
573
574          if (strncmpic(p->str, v->str, v->len) == 0)
575          {
576             hdr = v->parser(v, p->str, csp);
577             freez((char *)p->str); /* FIXME: Yuck! patching a list...*/
578             p->str = hdr;
579          }
580       }
581    }
582
583    /* place any additional headers on the csp->headers list */
584    for (f = more_headers; *f ; f++)
585    {
586       (*f)(csp);
587    }
588
589    hdr = list_to_text(csp->headers);
590
591    return(hdr);
592
593 }
594
595
596 /*********************************************************************
597  *
598  * Function    :  free_http_request
599  *
600  * Description :  Freez a http_request structure
601  *
602  * Parameters  :
603  *          1  :  http = points to a http_request structure to free
604  *
605  * Returns     :  N/A
606  *
607  *********************************************************************/
608 void free_http_request(struct http_request *http)
609 {
610    assert(http);
611
612    freez(http->cmd);
613    freez(http->gpc);
614    freez(http->host);
615    freez(http->url);
616    freez(http->hostport);
617    freez(http->path);
618    freez(http->ver);
619    freez(http->host_ip_addr_str);
620    freez(http->user_agent);
621
622 }
623
624
625 /*********************************************************************
626  *
627  * Function    :  parse_http_request
628  *
629  * Description :  Parse out the host and port from the URL.  Find the
630  *                hostname & path, port (if ':'), and/or password (if '@')
631  *
632  * Parameters  :
633  *          1  :  req = URL (or is it URI?) to break down
634  *          2  :  http = pointer to the http structure to hold elements
635  *          3  :  csp = Current client state (buffers, headers, etc...)
636  *
637  * Returns     :  N/A
638  *
639  *********************************************************************/
640 void parse_http_request(char *req, struct http_request *http, struct client_state *csp)
641 {
642    char *buf, *v[10], *url, *p;
643    int n;
644
645    memset(http, '\0', sizeof(*http));
646    http->cmd = strdup(req);  
647
648    buf = strdup(req);
649    n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
650
651    if (n == 3)
652    {
653       /* this could be a CONNECT request */
654       if (strcmpic(v[0], "connect") == 0)
655       {
656          http->ssl      = 1;
657          http->gpc      = strdup(v[0]);
658          http->hostport = strdup(v[1]);
659          http->ver      = strdup(v[2]);
660       }
661
662       /* or it could be any other basic HTTP request type */
663       if ((0 == strcmpic(v[0], "get"))
664        || (0 == strcmpic(v[0], "head"))
665        || (0 == strcmpic(v[0], "post"))
666        || (0 == strcmpic(v[0], "put"))
667        || (0 == strcmpic(v[0], "delete"))
668
669        /* or a webDAV extension (RFC2518) */
670        || (0 == strcmpic(v[0], "propfind"))
671        || (0 == strcmpic(v[0], "proppatch"))
672        || (0 == strcmpic(v[0], "move"))
673        || (0 == strcmpic(v[0], "copy"))
674        || (0 == strcmpic(v[0], "mkcol"))
675        || (0 == strcmpic(v[0], "lock"))
676        || (0 == strcmpic(v[0], "unlock"))
677        )
678       {
679          http->ssl    = 0;
680          http->gpc    = strdup(v[0]);
681          http->url    = strdup(v[1]);
682          http->ver    = strdup(v[2]);
683
684          url = v[1];
685          if (strncmpic(url, "http://",  7) == 0)
686          {
687             url += 7;
688          }
689          else if (strncmpic(url, "https://", 8) == 0)
690          {
691             url += 8;
692          }
693          else
694          {
695             url = NULL;
696          }
697
698          if (url)
699          {
700             if ((p = strchr(url, '/')))
701             {
702                http->path = strdup(p);
703                *p = '\0';
704                http->hostport = strdup(url);
705             }
706             /* 
707              * Repair broken HTTP requests that don't contain a path
708              */
709             else
710             {
711                http->path = strdup("/");
712                http->hostport = strdup(url);
713             }
714          }
715       }
716    }
717
718    freez(buf);
719
720
721    if (http->hostport == NULL)
722    {
723       free_http_request(http);
724       return;
725    }
726
727    buf = strdup(http->hostport);
728
729
730    /* check if url contains password */
731    n = ssplit(buf, "@", v, SZ(v), 1, 1);
732    if (n == 2)
733    {
734       char * newbuf = NULL;
735       newbuf = strdup(v[1]);
736       freez(buf);
737       buf = newbuf;
738    }
739
740    n = ssplit(buf, ":", v, SZ(v), 1, 1);
741
742    if (n == 1)
743    {
744       http->host = strdup(v[0]);
745       http->port = 80;
746    }
747
748    if (n == 2)
749    {
750       http->host = strdup(v[0]);
751       http->port = atoi(v[1]);
752    }
753
754    freez(buf);
755
756    if (http->host == NULL)
757    {
758       free_http_request(http);
759    }
760
761    if (http->path == NULL)
762    {
763       http->path = strdup("/");
764    }
765
766 }
767
768
769 /* here begins the family of parser functions that reformat header lines */
770
771
772 /*********************************************************************
773  *
774  * Function    :  crumble
775  *
776  * Description :  This is called if a header matches a pattern to "crunch"
777  *
778  * Parameters  :
779  *          1  :  v = Pointer to parsers structure, which basically holds
780  *                headers (client or server) that we want to "crunch"
781  *          2  :  s = header (from sed) to "crunch"
782  *          3  :  csp = Current client state (buffers, headers, etc...)
783  *
784  * Returns     :  Always NULL.
785  *
786  *********************************************************************/
787 char *crumble(const struct parsers *v, const char *s, struct client_state *csp)
788 {
789    log_error(LOG_LEVEL_HEADER, "crunch!");
790    return(NULL);
791
792 }
793
794
795 /*********************************************************************
796  *
797  * Function    :  server_content_type
798  *
799  * Description :  Set the content-type for filterable types (text/.*,
800  *                javascript and image/gif) unless filtering has been
801  *                forbidden (CT_TABOO) while parsing earlier headers.
802  *
803  * Parameters  :
804  *          1  :  v = ignored
805  *          2  :  s = header string we are "considering"
806  *          3  :  csp = Current client state (buffers, headers, etc...)
807  *
808  * Returns     :  A duplicate string pointer to this header (ie. pass thru)
809  *
810  *********************************************************************/
811 char *server_content_type(const struct parsers *v, const char *s, struct client_state *csp)
812 {
813    if (csp->content_type != CT_TABOO)
814    {
815       if (strstr(s, " text/") || strstr(s, "application/x-javascript"))
816          csp->content_type = CT_TEXT;
817       else if (strstr(s, " image/gif"))
818          csp->content_type = CT_GIF;
819       else
820          csp->content_type = 0;
821    }
822
823    return(strdup(s));
824
825 }
826
827
828 /*********************************************************************
829  *
830  * Function    :  server_transfer_coding
831  *
832  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
833  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
834  *                - Change from "chunked" to "identity" if body was chunked
835  *                  but has been de-chunked for filtering.
836  *
837  * Parameters  :
838  *          1  :  v = ignored
839  *          2  :  s = header string we are "considering"
840  *          3  :  csp = Current client state (buffers, headers, etc...)
841  *
842  * Returns     :  A duplicate string pointer to this header (ie. pass thru)
843  *
844  *********************************************************************/
845 char *server_transfer_coding(const struct parsers *v, const char *s, struct client_state *csp)
846 {
847    /*
848     * Turn off pcrs and gif filtering if body compressed
849     */
850    if (strstr(s, "gzip") || strstr(s, "compress") || strstr(s, "deflate"))
851    {
852       csp->content_type = CT_TABOO;
853    }
854
855    /* 
856     * Raise flag if body chunked
857     */
858    if (strstr(s, "chunked"))
859    {
860       csp->flags |= CSP_FLAG_CHUNKED;
861
862       /*
863        * If the body was modified, it has been 
864        * de-chunked first, so adjust the header:
865        */
866       if (csp->flags & CSP_FLAG_MODIFIED)
867       {
868          return(strdup("Transfer-Encoding: identity"));
869       }
870    }
871
872    return(strdup(s));
873
874 }
875
876
877 /*********************************************************************
878  *
879  * Function    :  server_content_encoding
880  *
881  * Description :  Prohibit filtering (CT_TABOO) if content encoding compresses
882  *
883  * Parameters  :
884  *          1  :  v = ignored
885  *          2  :  s = header string we are "considering"
886  *          3  :  csp = Current client state (buffers, headers, etc...)
887  *
888  * Returns     :  A duplicate string pointer to this header (ie. pass thru)
889  *
890  *********************************************************************/
891 char *server_content_encoding(const struct parsers *v, const char *s, struct client_state *csp)
892 {
893    /*
894     * Turn off pcrs and gif filtering if body compressed
895     */
896    if (strstr(s, "gzip") || strstr(s, "compress") || strstr(s, "deflate"))
897    {
898       csp->content_type = CT_TABOO;
899    }
900
901    return(strdup(s));
902
903 }
904
905
906 /*********************************************************************
907  *
908  * Function    :  server_content_length
909  *
910  * Description :  Adjust Content-Length header if we modified
911  *                the body.
912  *
913  * Parameters  :
914  *          1  :  v = ignored
915  *          2  :  s = header string we are "considering"
916  *          3  :  csp = Current client state (buffers, headers, etc...)
917  *
918  * Returns     :  A duplicate string pointer to this header (ie. pass thru)
919  *
920  *********************************************************************/
921 char *server_content_length(const struct parsers *v, const char *s, struct client_state *csp)
922 {
923    if (csp->content_length != 0) /* Content length has been modified */
924    {
925       char * s2 = (char *) zalloc(100);
926       sprintf(s2, "Content-Length: %d", (int) csp->content_length);
927
928       log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
929       return(s2);
930    }
931    else
932    {
933       return(strdup(s));
934    }
935
936 }
937
938
939 /*********************************************************************
940  *
941  * Function    :  server_content_md5
942  *
943  * Description :  Crumble any Content-MD5 headers if the document was
944  *                modified. FIXME: Should we re-compute instead?
945  *
946  * Parameters  :
947  *          1  :  v = ignored
948  *          2  :  s = header string we are "considering"
949  *          3  :  csp = Current client state (buffers, headers, etc...)
950  *
951  * Returns     :  A duplicate string pointer to this header (ie. pass thru)
952  *
953  *********************************************************************/
954 char *server_content_md5(const struct parsers *v, const char *s, struct client_state *csp)
955 {
956    if (csp->flags & CSP_FLAG_MODIFIED)
957    {
958       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
959       return(NULL);
960    }
961    else
962    {
963       return(strdup(s));
964    }
965
966 }
967
968
969 /*********************************************************************
970  *
971  * Function    :  client_accept_encoding
972  *
973  * Description :  Rewrite the client's Accept-Encoding header so that
974  *                if doesn't allow compression, if the action applies.
975  *                Note: For HTTP/1.0 the absence of the header is enough.
976  *
977  * Parameters  :
978  *          1  :  v = ignored
979  *          2  :  s = header string we are "considering"
980  *          3  :  csp = Current client state (buffers, headers, etc...)
981  *
982  * Returns     :  A copy of the client's original or the modified header.
983  *
984  *********************************************************************/
985 char *client_accept_encoding(const struct parsers *v, const char *s, struct client_state *csp)
986 {
987    if ((csp->action->flags & ACTION_NO_COMPRESSION) == 0)
988    {
989       return(strdup(s));
990    }
991    else
992    {
993       log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
994
995       if (!strcmpic(csp->http->ver, "HTTP/1.1"))
996       {
997          return(strdup("Accept-Encoding: identity;q=1.0, *;q=0"));
998       }
999       else
1000       {
1001          return(NULL);
1002       }
1003    }
1004
1005 }
1006
1007
1008 /*********************************************************************
1009  *
1010  * Function    :  client_te
1011  *
1012  * Description :  Rewrite the client's TE header so that
1013  *                if doesn't allow compression, if the action applies.
1014  *
1015  * Parameters  :
1016  *          1  :  v = ignored
1017  *          2  :  s = header string we are "considering"
1018  *          3  :  csp = Current client state (buffers, headers, etc...)
1019  *
1020  * Returns     :  A copy of the client's original or the modified header.
1021  *
1022  *********************************************************************/
1023 char *client_te(const struct parsers *v, const char *s, struct client_state *csp)
1024 {
1025    if ((csp->action->flags & ACTION_NO_COMPRESSION) == 0)
1026    {
1027       return(strdup(s));
1028    }
1029    else
1030    {
1031       log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1032       return(NULL);
1033    }
1034
1035 }
1036
1037 /*********************************************************************
1038  *
1039  * Function    :  client_referrer
1040  *
1041  * Description :  Handle the "referer" config setting properly.
1042  *                Called from `sed'.
1043  *
1044  * Parameters  :
1045  *          1  :  v = ignored
1046  *          2  :  s = header (from sed) to "crunch"
1047  *          3  :  csp = Current client state (buffers, headers, etc...)
1048  *
1049  * Returns     :  NULL if crunched, or a malloc'ed string with the original
1050  *                or modified header
1051  *
1052  *********************************************************************/
1053 char *client_referrer(const struct parsers *v, const char *s, struct client_state *csp)
1054 {
1055    const char * newval;
1056    char * s2;
1057 #ifdef FEATURE_FORCE_LOAD
1058    /* Since the referrer can include the prefix even
1059     * even if the request itself is non-forced, we must
1060     * clean it unconditionally 
1061     */
1062    strclean(s, FORCE_PREFIX);
1063 #endif /* def FEATURE_FORCE_LOAD */
1064
1065 #ifdef FEATURE_TRUST
1066    csp->referrer = strdup(s);
1067 #endif /* def FEATURE_TRUST */
1068
1069    /*
1070     * Are we sending referer?
1071     */
1072    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1073    {
1074       return(strdup(s));
1075    }
1076
1077    newval = csp->action->string[ACTION_STRING_REFERER];
1078
1079    /*
1080     * Are we blocking referer?
1081     */
1082    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1083    {
1084       log_error(LOG_LEVEL_HEADER, "crunch!");
1085       return(NULL);
1086    }
1087
1088    /*
1089     * Are we forging referer?
1090     */
1091    if (0 == strcmpic(newval, "forge"))
1092    {
1093       /*
1094        * Forge a referer as http://[hostname:port of REQUEST]/
1095        * to fool stupid checks for in-site links
1096        */
1097       log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1098       s2 = strsav(NULL, "Referer: ");
1099       s2 = strsav(s2, "http://");
1100       s2 = strsav(s2, csp->http->hostport);
1101       s2 = strsav(s2, "/");
1102       return(s2);
1103    }
1104
1105    /*
1106     * Have we got a fixed referer?
1107     */
1108    if (0 == strncmpic(newval, "http://", 7))
1109    {
1110       /*
1111        * We have a specific (fixed) referer we want to send.
1112        */
1113       char * s3;
1114
1115       log_error(LOG_LEVEL_HEADER, "modified");
1116
1117       s3 = strsav( NULL, "Referer: " );
1118       s3 = strsav( s3, newval );
1119       return(s3);
1120    }
1121
1122    /* Should never get here! */
1123    log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1124
1125    /*
1126     * Forge is probably the best default.
1127     *
1128     * Forge a referer as http://[hostname:port of REQUEST]/
1129     * to fool stupid checks for in-site links
1130     */
1131    log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1132    s2 = strsav(NULL, "Referer: ");
1133    s2 = strsav(s2, "http://");
1134    s2 = strsav(s2, csp->http->hostport);
1135    s2 = strsav(s2, "/");
1136    return(s2);
1137 }
1138
1139
1140 /*********************************************************************
1141  *
1142  * Function    :  client_uagent
1143  *
1144  * Description :  Handle the "user-agent" config setting properly
1145  *                and remember its original value to enable browser
1146  *                bug workarounds. Called from `sed'.
1147  *
1148  * Parameters  :
1149  *          1  :  v = ignored
1150  *          2  :  s = header (from sed) to "crunch"
1151  *          3  :  csp = Current client state (buffers, headers, etc...)
1152  *
1153  * Returns     :  A malloc'ed pointer to the default agent, or
1154  *                a malloc'ed string pointer to this header (ie. pass thru).
1155  *
1156  *********************************************************************/
1157 char *client_uagent(const struct parsers *v, const char *s, struct client_state *csp)
1158 {
1159    const char * newval;
1160    char * s2;
1161
1162    /* Save the client's User-Agent: value */
1163    if (strlen(s) >= 12)
1164    {
1165       csp->http->user_agent = strdup(s + 12);
1166    }
1167
1168 #ifdef FEATURE_IMAGE_DETECT_MSIE
1169    if (strstr (s, "MSIE "))
1170    {
1171       /* This is Microsoft Internet Explorer.
1172        * Enable auto-detect.
1173        */
1174       csp->accept_types |= ACCEPT_TYPE_IS_MSIE;
1175    }
1176 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1177
1178    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1179    {
1180       return(strdup(s));
1181    }
1182
1183    newval = csp->action->string[ACTION_STRING_USER_AGENT];
1184    if (newval == NULL)
1185    {
1186       return(strdup(s));
1187    }
1188
1189    log_error(LOG_LEVEL_HEADER, "modified");
1190
1191    s2 = strsav( NULL, "User-Agent: " );
1192    s2 = strsav( s2, newval );
1193    return(s2);
1194
1195 }
1196
1197
1198 /*********************************************************************
1199  *
1200  * Function    :  client_ua
1201  *
1202  * Description :  Handle "ua-" headers properly.  Called from `sed'.
1203  *
1204  * Parameters  :
1205  *          1  :  v = ignored
1206  *          2  :  s = header (from sed) to "crunch"
1207  *          3  :  csp = Current client state (buffers, headers, etc...)
1208  *
1209  * Returns     :  NULL if crunched, or a malloc'ed string to original header
1210  *
1211  *********************************************************************/
1212 char *client_ua(const struct parsers *v, const char *s, struct client_state *csp)
1213 {
1214    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1215    {
1216       return(strdup(s));
1217    }
1218    else
1219    {
1220       log_error(LOG_LEVEL_HEADER, "crunch!");
1221       return(NULL);
1222    }
1223 }
1224
1225
1226 /*********************************************************************
1227  *
1228  * Function    :  client_from
1229  *
1230  * Description :  Handle the "from" config setting properly.
1231  *                Called from `sed'.
1232  *
1233  * Parameters  :
1234  *          1  :  v = ignored
1235  *          2  :  s = header (from sed) to "crunch"
1236  *          3  :  csp = Current client state (buffers, headers, etc...)
1237  *
1238  * Returns     :  NULL if crunched, or a malloc'ed string to
1239  *                modified/original header.
1240  *
1241  *********************************************************************/
1242 char *client_from(const struct parsers *v, const char *s, struct client_state *csp)
1243 {
1244    const char * newval;
1245    char * s2;
1246
1247    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1248    {
1249       return(strdup(s));
1250    }
1251
1252    newval = csp->action->string[ACTION_STRING_FROM];
1253
1254    /*
1255     * Are we blocking referer?
1256     */
1257    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1258    {
1259       log_error(LOG_LEVEL_HEADER, "crunch!");
1260       return(NULL);
1261    }
1262
1263    log_error(LOG_LEVEL_HEADER, " modified");
1264
1265    s2 = strsav( NULL, "From: " );
1266    s2 = strsav( s2, newval );
1267    return(s2);
1268
1269 }
1270
1271
1272 /*********************************************************************
1273  *
1274  * Function    :  client_send_cookie
1275  *
1276  * Description :  Handle the "cookie" header properly.  Called from `sed'.
1277  *                If cookie is accepted, add it to the cookie_list,
1278  *                else we crunch it.  Mmmmmmmmmmm ... cookie ......
1279  *
1280  * Parameters  :
1281  *          1  :  v = pattern of cookie `sed' found matching
1282  *          2  :  s = header (from sed) to "crunch"
1283  *          3  :  csp = Current client state (buffers, headers, etc...)
1284  *
1285  * Returns     :  Always NULL.
1286  *
1287  *********************************************************************/
1288 char *client_send_cookie(const struct parsers *v, const char *s, struct client_state *csp)
1289 {
1290    if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1291    {
1292       enlist(csp->cookie_list, s + v->len + 1);
1293    }
1294    else
1295    {
1296       log_error(LOG_LEVEL_HEADER, " crunch!");
1297    }
1298
1299    /*
1300     * Always return NULL here.  The cookie header
1301     * will be sent at the end of the header.
1302     */
1303    return(NULL);
1304
1305 }
1306
1307
1308 /*********************************************************************
1309  *
1310  * Function    :  client_x_forwarded
1311  *
1312  * Description :  Handle the "x-forwarded-for" config setting properly,
1313  *                also used in the add_client_headers list.  Called from `sed'.
1314  *
1315  * Parameters  :
1316  *          1  :  v = ignored
1317  *          2  :  s = header (from sed) to "crunch"
1318  *          3  :  csp = Current client state (buffers, headers, etc...)
1319  *
1320  * Returns     :  Always NULL.
1321  *
1322  *********************************************************************/
1323 char *client_x_forwarded(const struct parsers *v, const char *s, struct client_state *csp)
1324 {
1325    if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1326    {
1327       /* Save it so we can re-add it later */
1328       csp->x_forwarded = strdup(s);
1329    }
1330
1331    /*
1332     * Always return NULL, since this information
1333     * will be sent at the end of the header.
1334     */
1335
1336    return(NULL);
1337
1338 }
1339
1340 #if defined(FEATURE_IMAGE_DETECT_MSIE)
1341 /*********************************************************************
1342  *
1343  * Function    :  client_accept
1344  *
1345  * Description :  Detect whether the client wants HTML or an image.
1346  *                Clients do not always make this information available
1347  *                in a sane way.  Always passes the header through
1348  *                the proxy unchanged.
1349  *
1350  * Parameters  :
1351  *          1  :  v = Ignored.
1352  *          2  :  s = Header string.  Null terminated.
1353  *          3  :  csp = Current client state (buffers, headers, etc...)
1354  *
1355  * Returns     :  Duplicate of argument s.
1356  *
1357  *********************************************************************/
1358 char *client_accept(const struct parsers *v, const char *s, struct client_state *csp)
1359 {
1360 #ifdef FEATURE_IMAGE_DETECT_MSIE
1361    if (strstr (s, "image/gif"))
1362    {
1363       /* Client will accept HTML.  If this seems counterintuitive,
1364        * blame Microsoft. 
1365        */
1366       csp->accept_types |= ACCEPT_TYPE_MSIE_HTML;
1367    }
1368    else
1369    {
1370       csp->accept_types |= ACCEPT_TYPE_MSIE_IMAGE;
1371    }
1372 #endif /* def FEATURE_IMAGE_DETECT_MSIE */
1373
1374    return(strdup(s));
1375
1376 }
1377 #endif /* defined(FEATURE_IMAGE_DETECT_MSIE) */
1378
1379
1380
1381 /* the following functions add headers directly to the header list */
1382
1383
1384 /*********************************************************************
1385  *
1386  * Function    :  client_cookie_adder
1387  *
1388  * Description :  Used in the add_client_headers list.  Called from `sed'.
1389  *
1390  * Parameters  :
1391  *          1  :  csp = Current client state (buffers, headers, etc...)
1392  *
1393  * Returns     :  N/A
1394  *
1395  *********************************************************************/
1396 void client_cookie_adder(struct client_state *csp)
1397 {
1398    struct list_entry *lst;
1399    char *tmp = NULL;
1400    char *e;
1401
1402    for (lst = csp->cookie_list->first; lst ; lst = lst->next)
1403    {
1404       if (tmp)
1405       {
1406          tmp = strsav(tmp, "; ");
1407       }
1408       tmp = strsav(tmp, lst->str);
1409    }
1410
1411    for (lst = csp->action->multi[ACTION_MULTI_WAFER]->first;  lst ; lst = lst->next)
1412    {
1413       if (tmp)
1414       {
1415          tmp = strsav(tmp, "; ");
1416       }
1417
1418       if ((e = cookie_encode(lst->str)))
1419       {
1420          tmp = strsav(tmp, e);
1421          freez(e);
1422       }
1423    }
1424
1425    if (tmp)
1426    {
1427       char *ret;
1428
1429       ret = strdup("Cookie: ");
1430       ret = strsav(ret, tmp);
1431       log_error(LOG_LEVEL_HEADER, "addh: %s", ret);
1432       enlist(csp->headers, ret);
1433       freez(tmp);
1434       freez(ret);
1435    }
1436
1437 }
1438
1439
1440 /*********************************************************************
1441  *
1442  * Function    :  client_accept_encoding_adder
1443  *
1444  * Description :  Add an Accept-Encoding header to the client's request
1445  *                that disables compression if the action applies, and
1446  *                the header is not already there. Called from `sed'.
1447  *                Note: For HTTP/1.0, the absence of the header is enough.
1448  *
1449  * Parameters  :
1450  *          1  :  csp = Current client state (buffers, headers, etc...)
1451  *
1452  * Returns     :  N/A
1453  *
1454  *********************************************************************/
1455 void client_accept_encoding_adder(struct client_state *csp)
1456 {
1457    if (   ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1458        && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1459    {
1460       enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1461    }
1462
1463 }
1464
1465
1466 /*********************************************************************
1467  *
1468  * Function    :  client_xtra_adder
1469  *
1470  * Description :  Used in the add_client_headers list.  Called from `sed'.
1471  *
1472  * Parameters  :
1473  *          1  :  csp = Current client state (buffers, headers, etc...)
1474  *
1475  * Returns     :  N/A
1476  *
1477  *********************************************************************/
1478 void client_xtra_adder(struct client_state *csp)
1479 {
1480    struct list_entry *lst;
1481
1482    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1483         lst ; lst = lst->next)
1484    {
1485       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1486       enlist(csp->headers, lst->str);
1487    }
1488
1489 }
1490
1491
1492 /*********************************************************************
1493  *
1494  * Function    :  client_x_forwarded_adder
1495  *
1496  * Description :  Used in the add_client_headers list.  Called from `sed'.
1497  *
1498  * Parameters  :
1499  *          1  :  csp = Current client state (buffers, headers, etc...)
1500  *
1501  * Returns     :  N/A
1502  *
1503  *********************************************************************/
1504 void client_x_forwarded_adder(struct client_state *csp)
1505 {
1506    char *p = NULL;
1507
1508    if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1509    {
1510       return;
1511    }
1512
1513    if (csp->x_forwarded)
1514    {
1515       p = strsav(p, csp->x_forwarded);
1516       p = strsav(p, ", ");
1517       p = strsav(p, csp->ip_addr_str);
1518    }
1519    else
1520    {
1521       p = strsav(p, "X-Forwarded-For: ");
1522       p = strsav(p, csp->ip_addr_str);
1523    }
1524
1525    log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1526    enlist(csp->headers, p);
1527
1528    freez(p);
1529 }
1530
1531
1532 /*********************************************************************
1533  *
1534  * Function    :  connection_close_adder
1535  *
1536  * Description :  Adds a "Connection: close" header to csp->headers
1537  *                as a temporary fix for the needed but missing HTTP/1.1
1538  *                support. Called from `sed'.
1539  *                FIXME: This whole function shouldn't be neccessary!
1540  *
1541  * Parameters  :
1542  *          1  :  csp = Current client state (buffers, headers, etc...)
1543  *
1544  * Returns     :  N/A
1545  *
1546  *********************************************************************/
1547 void connection_close_adder(struct client_state *csp)
1548 {
1549    enlist(csp->headers, "Connection: close");
1550 }
1551
1552
1553 /*********************************************************************
1554  *
1555  * Function    :  server_http
1556  *
1557  * Description :  - Save the HTTP Status into csp->http->status
1558  *                - Set CT_TABOO to prevent filtering if the answer
1559  *                  is a partial range (HTTP status 206)
1560  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1561  *                  action applies.
1562  *
1563  * Parameters  :
1564  *          1  :  v = parser pattern that matched this header
1565  *          2  :  s = header that matched this pattern
1566  *          3  :  csp = Current client state (buffers, headers, etc...)
1567  *
1568  * Returns     :  Copy of changed  or original answer.
1569  *
1570  *********************************************************************/
1571 char *server_http(const struct parsers *v, const char *s, struct client_state *csp)
1572 {
1573    char *ret = strdup(s);
1574    
1575    sscanf(ret, "HTTP/%*d.%*d %d", &(csp->http->status));
1576    if (csp->http->status == 206)
1577    {
1578       csp->content_type = CT_TABOO;
1579    }
1580
1581    if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1582    {
1583       ret[7] = '0';
1584       log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1585    }
1586    return(ret);
1587
1588 }
1589
1590
1591 /*********************************************************************
1592  *
1593  * Function    :  server_set_cookie
1594  *
1595  * Description :  Handle the server "cookie" header properly.
1596  *                Log cookie to the jar file.  Then "crunch" it,
1597  *                or accept it.  Called from `sed'.
1598  *
1599  * Parameters  :
1600  *          1  :  v = parser pattern that matched this header
1601  *          2  :  s = header that matched this pattern
1602  *          3  :  csp = Current client state (buffers, headers, etc...)
1603  *
1604  * Returns     :  `crumble' or a newly malloc'ed string.
1605  *
1606  *********************************************************************/
1607 char *server_set_cookie(const struct parsers *v, const char *s, struct client_state *csp)
1608 {
1609 #ifdef FEATURE_COOKIE_JAR
1610    if (csp->config->jar)
1611    {
1612       fprintf(csp->config->jar, "%s\t%s\n", csp->http->host, (s + v->len + 1));
1613    }
1614 #endif /* def FEATURE_COOKIE_JAR */
1615
1616    if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1617    {
1618       return(crumble(v, s, csp));
1619    }
1620
1621    return(strdup(s));
1622
1623 }
1624
1625
1626 #ifdef FEATURE_FORCE_LOAD
1627 /*********************************************************************
1628  *
1629  * Function    :  client_host
1630  *
1631  * Description :  Clean the FORCE_PREFIX out of the 'host' http
1632  *                header, if we use force
1633  *
1634  * Parameters  :
1635  *          1  :  v = ignored
1636  *          2  :  s = header (from sed) to clean
1637  *          3  :  csp = Current client state (buffers, headers, etc...)
1638  *
1639  * Returns     :  A malloc'ed pointer to the cleaned host header 
1640  *
1641  *********************************************************************/
1642 char *client_host(const struct parsers *v, const char *s, struct client_state *csp)
1643 {
1644    char *cleanhost = strdup(s);
1645  
1646    if(csp->flags & CSP_FLAG_FORCED)
1647    {
1648       strclean(cleanhost, FORCE_PREFIX);
1649    }
1650  
1651    return(cleanhost);
1652 }
1653 #endif /* def FEATURE_FORCE_LOAD */
1654  
1655  
1656 #ifdef FEATURE_FORCE_LOAD 
1657 /*********************************************************************
1658  *
1659  * Function    :  strclean
1660  *
1661  * Description :  In-Situ-Eliminate all occurances of substring in 
1662  *                string
1663  *
1664  * Parameters  :
1665  *          1  :  string = string to clean
1666  *          2  :  substring = substring to eliminate
1667  *
1668  * Returns     :  Number of eliminations
1669  *
1670  *********************************************************************/
1671 int strclean(const char *string, const char *substring)
1672 {
1673    int hits = 0, len = strlen(substring);
1674    char *pos, *p;
1675
1676    while((pos = strstr(string, substring)))
1677    {
1678       p = pos + len;
1679       do
1680       {
1681          *(p - len) = *p; 
1682       }
1683       while (*p++ != '\0');
1684
1685       hits++;
1686    }
1687
1688    return(hits);
1689 }
1690 #endif /* def FEATURE_FORCE_LOAD */
1691
1692
1693 /*
1694   Local Variables:
1695   tab-width: 3
1696   end:
1697 */