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