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