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