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