- Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.91 2007/02/24 12:27:32 fabiankeil 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', `filter_server_header'
14  *                   `filter_client_header', `filter_header', `crunch_server_header',
15  *                   `server_content_encoding', `server_content_disposition',
16  *                   `server_last_modified', `client_accept_language',
17  *                   `crunch_client_header', `client_if_modified_since',
18  *                   `client_if_none_match', `get_destination_from_headers',
19  *                   `parse_header_time' and `server_set_cookie'.
20  *
21  * Copyright   :  Written by and Copyright (C) 2001-2007 the SourceForge
22  *                Privoxy team. http://www.privoxy.org/
23  *
24  *                Based on the Internet Junkbuster originally written
25  *                by and Copyright (C) 1997 Anonymous Coders and
26  *                Junkbusters Corporation.  http://www.junkbusters.com
27  *
28  *                This program is free software; you can redistribute it
29  *                and/or modify it under the terms of the GNU General
30  *                Public License as published by the Free Software
31  *                Foundation; either version 2 of the License, or (at
32  *                your option) any later version.
33  *
34  *                This program is distributed in the hope that it will
35  *                be useful, but WITHOUT ANY WARRANTY; without even the
36  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
37  *                PARTICULAR PURPOSE.  See the GNU General Public
38  *                License for more details.
39  *
40  *                The GNU General Public License should be included with
41  *                this file.  If not, you can view it at
42  *                http://www.gnu.org/copyleft/gpl.html
43  *                or write to the Free Software Foundation, Inc., 59
44  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
45  *
46  * Revisions   :
47  *    $Log: parsers.c,v $
48  *    Revision 1.91  2007/02/24 12:27:32  fabiankeil
49  *    Improve cookie expiration date detection.
50  *
51  *    Revision 1.90  2007/02/08 19:12:35  fabiankeil
52  *    Don't run server_content_length() the first time
53  *    sed() parses server headers; only adjust the
54  *    Content-Length header if the page was modified.
55  *
56  *    Revision 1.89  2007/02/07 16:52:11  fabiankeil
57  *    Fix log messages regarding the cookie time format
58  *    (cookie and request URL were mixed up).
59  *
60  *    Revision 1.88  2007/02/07 11:27:12  fabiankeil
61  *    - Let decompress_iob()
62  *      - not corrupt the content if decompression fails
63  *        early. (the first byte(s) were lost).
64  *      - use pointer arithmetics with defined outcome for
65  *        a change.
66  *    - Use a different kludge to remember a failed decompression.
67  *
68  *    Revision 1.87  2007/01/31 16:21:38  fabiankeil
69  *    Search for Max-Forwards headers case-insensitive,
70  *    don't generate the "501 unsupported" message for invalid
71  *    Max-Forwards values and don't increase negative ones.
72  *
73  *    Revision 1.86  2007/01/30 13:05:26  fabiankeil
74  *    - Let server_set_cookie() check the expiration date
75  *      of cookies and don't touch the ones that are already
76  *      expired. Fixes problems with low quality web applications
77  *      as described in BR 932612.
78  *
79  *    - Adjust comment in client_max_forwards to reality;
80  *      remove invalid Max-Forwards headers.
81  *
82  *    Revision 1.85  2007/01/26 15:33:46  fabiankeil
83  *    Stop filter_header() from unintentionally removing
84  *    empty header lines that were enlisted by the continue
85  *    hack.
86  *
87  *    Revision 1.84  2007/01/24 12:56:52  fabiankeil
88  *    - Repeat the request URL before logging any headers.
89  *      Makes reading the log easier in case of simultaneous requests.
90  *    - If there are more than one Content-Type headers in one request,
91  *      use the first one and remove the others.
92  *    - Remove "newval" variable in server_content_type().
93  *      It's only used once.
94  *
95  *    Revision 1.83  2007/01/12 15:03:02  fabiankeil
96  *    Correct a cast, check inflateEnd() exit code
97  *    to see if we have to, replace sprintf calls
98  *    with snprintf.
99  *
100  *    Revision 1.82  2007/01/01 19:36:37  fabiankeil
101  *    Integrate a modified version of Wil Mahan's
102  *    zlib patch (PR #895531).
103  *
104  *    Revision 1.81  2006/12/31 22:21:33  fabiankeil
105  *    Skip empty filter files in filter_header()
106  *    but don't ignore the ones that come afterwards.
107  *    Fixes BR 1619208, this time for real.
108  *
109  *    Revision 1.80  2006/12/29 19:08:22  fabiankeil
110  *    Reverted parts of my last commit
111  *    to keep error handling working.
112  *
113  *    Revision 1.79  2006/12/29 18:04:40  fabiankeil
114  *    Fixed gcc43 conversion warnings.
115  *
116  *    Revision 1.78  2006/12/26 17:19:20  fabiankeil
117  *    Bringing back the "useless" localtime() call
118  *    I removed in revision 1.67. On some platforms
119  *    it's necessary to prevent time zone offsets.
120  *
121  *    Revision 1.77  2006/12/07 18:44:26  fabiankeil
122  *    Rebuild request URL in get_destination_from_headers()
123  *    to make sure redirect{pcrs command} works as expected
124  *    for intercepted requests.
125  *
126  *    Revision 1.76  2006/12/06 19:52:25  fabiankeil
127  *    Added get_destination_from_headers().
128  *
129  *    Revision 1.75  2006/11/13 19:05:51  fabiankeil
130  *    Make pthread mutex locking more generic. Instead of
131  *    checking for OSX and OpenBSD, check for FEATURE_PTHREAD
132  *    and use mutex locking unless there is an _r function
133  *    available. Better safe than sorry.
134  *
135  *    Fixes "./configure --disable-pthread" and should result
136  *    in less threading-related problems on pthread-using platforms,
137  *    but it still doesn't fix BR#1122404.
138  *
139  *    Revision 1.74  2006/10/02 16:59:12  fabiankeil
140  *    The special header "X-Filter: No" now disables
141  *    header filtering as well.
142  *
143  *    Revision 1.73  2006/09/23 13:26:38  roro
144  *    Replace TABs by spaces in source code.
145  *
146  *    Revision 1.72  2006/09/23 12:37:21  fabiankeil
147  *    Don't print a log message every time filter_headers is
148  *    entered or left. It only creates noise without any real
149  *    information.
150  *
151  *    Revision 1.71  2006/09/21 19:55:17  fabiankeil
152  *    Fix +hide-if-modified-since{-n}.
153  *
154  *    Revision 1.70  2006/09/08 12:06:34  fabiankeil
155  *    Have hide-if-modified-since interpret the random
156  *    range value as minutes instead of hours. Allows
157  *    more fine-grained configuration.
158  *
159  *    Revision 1.69  2006/09/06 16:25:51  fabiankeil
160  *    Always have parse_header_time return a pointer
161  *    that actual makes sense, even though we currently
162  *    only need it to detect problems.
163  *
164  *    Revision 1.68  2006/09/06 10:43:32  fabiankeil
165  *    Added config option enable-remote-http-toggle
166  *    to specify if Privoxy should recognize special
167  *    headers (currently only X-Filter) to change its
168  *    behaviour. Disabled by default.
169  *
170  *    Revision 1.67  2006/09/04 11:01:26  fabiankeil
171  *    After filtering de-chunked instances, remove
172  *    "Transfer-Encoding" header entirely instead of changing
173  *    it to "Transfer-Encoding: identity", which is invalid.
174  *    Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
175  *
176  *    Don't use localtime in parse_header_time. An empty time struct
177  *    is good enough, it gets overwritten by strptime anyway.
178  *
179  *    Revision 1.66  2006/09/03 19:38:28  fabiankeil
180  *    Use gmtime_r if available, fallback to gmtime with mutex
181  *    protection for MacOSX and use vanilla gmtime for the rest.
182  *
183  *    Revision 1.65  2006/08/22 10:55:56  fabiankeil
184  *    Changed client_referrer to use the right type (size_t) for
185  *    hostlenght and to shorten the temporary referrer string with
186  *    '\0' instead of adding a useless line break.
187  *
188  *    Revision 1.64  2006/08/17 17:15:10  fabiankeil
189  *    - Back to timegm() using GnuPG's replacement if necessary.
190  *      Using mktime() and localtime() could add a on hour offset if
191  *      the randomize factor was big enough to lead to a summer/wintertime
192  *      switch.
193  *
194  *    - Removed now-useless Privoxy 3.0.3 compatibility glue.
195  *
196  *    - Moved randomization code into pick_from_range().
197  *
198  *    - Changed parse_header_time definition.
199  *      time_t isn't guaranteed to be signed and
200  *      if it isn't, -1 isn't available as error code.
201  *      Changed some variable types in client_if_modified_since()
202  *      because of the same reason.
203  *
204  *    Revision 1.63  2006/08/14 13:18:08  david__schmidt
205  *    OS/2 compilation compatibility fixups
206  *
207  *    Revision 1.62  2006/08/14 08:58:42  fabiankeil
208  *    Changed include from strptime.c to strptime.h
209  *
210  *    Revision 1.61  2006/08/14 08:25:19  fabiankeil
211  *    Split filter-headers{} into filter-client-headers{}
212  *    and filter-server-headers{}.
213  *    Added parse_header_time() to share some code.
214  *    Replaced timegm() with mktime().
215  *
216  *    Revision 1.60  2006/08/12 03:54:37  david__schmidt
217  *    Windows service integration
218  *
219  *    Revision 1.59  2006/08/03 02:46:41  david__schmidt
220  *    Incorporate Fabian Keil's patch work:\rhttp://www.fabiankeil.de/sourcecode/privoxy/
221  *
222  *    Revision 1.58  2006/07/18 14:48:47  david__schmidt
223  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
224  *    with what was really the latest development (the v_3_0_branch branch)
225  *
226  *    Revision 1.56.2.10  2006/01/21 16:16:08  david__schmidt
227  *    Thanks to  Edward Carrel for his patch to modernize OSX's\rpthreads support.  See bug #1409623.
228  *
229  *    Revision 1.56.2.9  2004/10/03 12:53:45  david__schmidt
230  *    Add the ability to check jpeg images for invalid
231  *    lengths of comment blocks.  Defensive strategy
232  *    against the exploit:
233  *       Microsoft Security Bulletin MS04-028
234  *       Buffer Overrun in JPEG Processing (GDI+) Could
235  *       Allow Code Execution (833987)
236  *    Enabled with +inspect-jpegs in actions files.
237  *
238  *    Revision 1.56.2.8  2003/07/11 13:21:25  oes
239  *    Excluded text/plain objects from filtering. This fixes a
240  *    couple of client-crashing, download corruption and
241  *    Privoxy performance issues, whose root cause lies in
242  *    web servers labelling content of unknown type as text/plain.
243  *
244  *    Revision 1.56.2.7  2003/05/06 12:07:26  oes
245  *    Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
246  *
247  *    Revision 1.56.2.6  2003/04/14 21:28:30  oes
248  *    Completing the previous change
249  *
250  *    Revision 1.56.2.5  2003/04/14 12:08:16  oes
251  *    Added temporary workaround for bug in PHP < 4.2.3
252  *
253  *    Revision 1.56.2.4  2003/03/07 03:41:05  david__schmidt
254  *    Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX.  Hopefully this will take care of all of those pesky crash reports.
255  *
256  *    Revision 1.56.2.3  2002/11/10 04:20:02  hal9
257  *    Fix typo: supressed -> suppressed
258  *
259  *    Revision 1.56.2.2  2002/09/25 14:59:53  oes
260  *    Improved cookie logging
261  *
262  *    Revision 1.56.2.1  2002/09/25 14:52:45  oes
263  *    Added basic support for OPTIONS and TRACE HTTP methods:
264  *     - New parser function client_max_forwards which decrements
265  *       the Max-Forwards HTTP header field of OPTIONS and TRACE
266  *       requests by one before forwarding
267  *     - New parser function client_host which extracts the host
268  *       and port information from the HTTP header field if the
269  *       request URI was not absolute
270  *     - Don't crumble and re-add the Host: header, but only generate
271  *       and append if missing
272  *
273  *    Revision 1.56  2002/05/12 15:34:22  jongfoster
274  *    Fixing typo in a comment
275  *
276  *    Revision 1.55  2002/05/08 16:01:07  oes
277  *    Optimized add_to_iob:
278  *     - Use realloc instead of malloc(), memcpy(), free()
279  *     - Expand to powers of two if possible, to get
280  *       O(log n) reallocs instead of O(n).
281  *     - Moved check for buffer limit here from chat
282  *     - Report failure via returncode
283  *
284  *    Revision 1.54  2002/04/02 15:03:16  oes
285  *    Tiny code cosmetics
286  *
287  *    Revision 1.53  2002/03/26 22:29:55  swa
288  *    we have a new homepage!
289  *
290  *    Revision 1.52  2002/03/24 13:25:43  swa
291  *    name change related issues
292  *
293  *    Revision 1.51  2002/03/13 00:27:05  jongfoster
294  *    Killing warnings
295  *
296  *    Revision 1.50  2002/03/12 01:45:35  oes
297  *    More verbose logging
298  *
299  *    Revision 1.49  2002/03/09 20:03:52  jongfoster
300  *    - Making various functions return int rather than size_t.
301  *      (Undoing a recent change).  Since size_t is unsigned on
302  *      Windows, functions like read_socket that return -1 on
303  *      error cannot return a size_t.
304  *
305  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
306  *      crashes, and also frequently caused JB to jump to 100%
307  *      CPU and stay there.  (Because it thought it had just
308  *      read ((unsigned)-1) == 4Gb of data...)
309  *
310  *    - The signature of write_socket has changed, it now simply
311  *      returns success=0/failure=nonzero.
312  *
313  *    - Trying to get rid of a few warnings --with-debug on
314  *      Windows, I've introduced a new type "jb_socket".  This is
315  *      used for the socket file descriptors.  On Windows, this
316  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
317  *      an int.  The error value can't be -1 any more, so it's
318  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
319  *      Windows it maps to the #define INVALID_SOCKET.)
320  *
321  *    - The signature of bind_port has changed.
322  *
323  *    Revision 1.48  2002/03/07 03:46:53  oes
324  *    Fixed compiler warnings etc
325  *
326  *    Revision 1.47  2002/02/20 23:15:13  jongfoster
327  *    Parsing functions now handle out-of-memory gracefully by returning
328  *    an error code.
329  *
330  *    Revision 1.46  2002/01/17 21:03:47  jongfoster
331  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
332  *
333  *    Revision 1.45  2002/01/09 14:33:03  oes
334  *    Added support for localtime_r.
335  *
336  *    Revision 1.44  2001/12/14 01:22:54  steudten
337  *    Remove 'user:pass@' from 'proto://user:pass@host' for the
338  *    new added header 'Host: ..'. (See Req ID 491818)
339  *
340  *    Revision 1.43  2001/11/23 00:26:38  jongfoster
341  *    Fixing two really stupid errors in my previous commit
342  *
343  *    Revision 1.42  2001/11/22 21:59:30  jongfoster
344  *    Adding code to handle +no-cookies-keep
345  *
346  *    Revision 1.41  2001/11/05 23:43:05  steudten
347  *    Add time+date to log files.
348  *
349  *    Revision 1.40  2001/10/26 20:13:09  jongfoster
350  *    ctype.h is needed in Windows, too.
351  *
352  *    Revision 1.39  2001/10/26 17:40:04  oes
353  *    Introduced get_header_value()
354  *    Removed http->user_agent, csp->referrer and csp->accept_types
355  *    Removed client_accept()
356  *
357  *    Revision 1.38  2001/10/25 03:40:48  david__schmidt
358  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
359  *    threads to call select() simultaneously.  So, it's time to do a real, live,
360  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
361  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
362  *
363  *    Revision 1.37  2001/10/23 21:36:02  jongfoster
364  *    Documenting sed()'s error behaviou (doc change only)
365  *
366  *    Revision 1.36  2001/10/13 12:51:51  joergs
367  *    Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
368  *    force-load), instead crumble Host: and add it (again) in client_host_adder
369  *    (in case we get a HTTP/1.0 request without Host: header and forward it to
370  *    a HTTP/1.1 server/proxy).
371  *
372  *    Revision 1.35  2001/10/09 22:39:21  jongfoster
373  *    assert.h is also required under Win32, so moving out of #ifndef _WIN32
374  *    block.
375  *
376  *    Revision 1.34  2001/10/07 18:50:55  oes
377  *    Added server_content_encoding, renamed server_transfer_encoding
378  *
379  *    Revision 1.33  2001/10/07 18:04:49  oes
380  *    Changed server_http11 to server_http and its pattern to "HTTP".
381  *      Additional functionality: it now saves the HTTP status into
382  *      csp->http->status and sets CT_TABOO for Status 206 (partial range)
383  *
384  *    Revision 1.32  2001/10/07 15:43:28  oes
385  *    Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
386  *       client_te and client_accept_encoding_adder, triggered by the new
387  *       +no-compression action. For HTTP/1.1 the Accept-Encoding header is
388  *       changed to allow only identity and chunked, and the TE header is
389  *       crunched. For HTTP/1.0, Accept-Encoding is crunched.
390  *
391  *    parse_http_request no longer does anything than parsing. The rewriting
392  *      of http->cmd and version mangling are gone. It now also recognizes
393  *      the put and delete methods and saves the url in http->url. Removed
394  *      unused variable.
395  *
396  *    renamed content_type and content_length to have the server_ prefix
397  *
398  *    server_content_type now only works if csp->content_type != CT_TABOO
399  *
400  *    added server_transfer_encoding, which
401  *      - Sets CT_TABOO to prohibit filtering if encoding compresses
402  *      - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
403  *      - Change from "chunked" to "identity" if body was chunked
404  *        but has been de-chunked for filtering.
405  *
406  *    added server_content_md5 which crunches any Content-MD5 headers
407  *      if the body was modified.
408  *
409  *    made server_http11 conditional on +downgrade action
410  *
411  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
412  *
413  *    Revision 1.31  2001/10/05 14:25:02  oes
414  *    Crumble Keep-Alive from Server
415  *
416  *    Revision 1.30  2001/09/29 12:56:03  joergs
417  *    IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
418  *
419  *    Revision 1.29  2001/09/24 21:09:24  jongfoster
420  *    Fixing 2 memory leaks that Guy spotted, where the paramater to
421  *    enlist() was not being free()d.
422  *
423  *    Revision 1.28  2001/09/22 16:32:28  jongfoster
424  *    Removing unused #includes.
425  *
426  *    Revision 1.27  2001/09/20 15:45:25  steudten
427  *
428  *    add casting from size_t to int for printf()
429  *    remove local variable shadow s2
430  *
431  *    Revision 1.26  2001/09/16 17:05:14  jongfoster
432  *    Removing unused #include showarg.h
433  *
434  *    Revision 1.25  2001/09/16 13:21:27  jongfoster
435  *    Changes to use new list functions.
436  *
437  *    Revision 1.24  2001/09/13 23:05:50  jongfoster
438  *    Changing the string paramater to the header parsers a "const".
439  *
440  *    Revision 1.23  2001/09/12 18:08:19  steudten
441  *
442  *    In parse_http_request() header rewriting miss the host value, so
443  *    from http://www.mydomain.com the result was just " / " not
444  *    http://www.mydomain.com/ in case we forward.
445  *
446  *    Revision 1.22  2001/09/10 10:58:53  oes
447  *    Silenced compiler warnings
448  *
449  *    Revision 1.21  2001/07/31 14:46:00  oes
450  *     - Persistant connections now suppressed
451  *     - sed() no longer appends empty header to csp->headers
452  *
453  *    Revision 1.20  2001/07/30 22:08:36  jongfoster
454  *    Tidying up #defines:
455  *    - All feature #defines are now of the form FEATURE_xxx
456  *    - Permanently turned off WIN_GUI_EDIT
457  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
458  *
459  *    Revision 1.19  2001/07/25 17:21:54  oes
460  *    client_uagent now saves copy of User-Agent: header value
461  *
462  *    Revision 1.18  2001/07/13 14:02:46  oes
463  *     - Included fix to repair broken HTTP requests that
464  *       don't contain a path, not even '/'.
465  *     - Removed all #ifdef PCRS
466  *     - content_type now always inspected and classified as
467  *       text, gif or other.
468  *     - formatting / comments
469  *
470  *    Revision 1.17  2001/06/29 21:45:41  oes
471  *    Indentation, CRLF->LF, Tab-> Space
472  *
473  *    Revision 1.16  2001/06/29 13:32:42  oes
474  *    - Fixed a comment
475  *    - Adapted free_http_request
476  *    - Removed logentry from cancelled commit
477  *
478  *    Revision 1.15  2001/06/03 19:12:38  oes
479  *    deleted const struct interceptors
480  *
481  *    Revision 1.14  2001/06/01 18:49:17  jongfoster
482  *    Replaced "list_share" with "list" - the tiny memory gain was not
483  *    worth the extra complexity.
484  *
485  *    Revision 1.13  2001/05/31 21:30:33  jongfoster
486  *    Removed list code - it's now in list.[ch]
487  *    Renamed "permission" to "action", and changed many features
488  *    to use the actions file rather than the global config.
489  *
490  *    Revision 1.12  2001/05/31 17:33:13  oes
491  *
492  *    CRLF -> LF
493  *
494  *    Revision 1.11  2001/05/29 20:11:19  joergs
495  *    '/ * inside comment' warning removed.
496  *
497  *    Revision 1.10  2001/05/29 09:50:24  jongfoster
498  *    Unified blocklist/imagelist/permissionslist.
499  *    File format is still under discussion, but the internal changes
500  *    are (mostly) done.
501  *
502  *    Also modified interceptor behaviour:
503  *    - We now intercept all URLs beginning with one of the following
504  *      prefixes (and *only* these prefixes):
505  *        * http://i.j.b/
506  *        * http://ijbswa.sf.net/config/
507  *        * http://ijbswa.sourceforge.net/config/
508  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
509  *    - Internal changes so that intercepted and fast redirect pages
510  *      are not replaced with an image.
511  *    - Interceptors now have the option to send a binary page direct
512  *      to the client. (i.e. ijb-send-banner uses this)
513  *    - Implemented show-url-info interceptor.  (Which is why I needed
514  *      the above interceptors changes - a typical URL is
515  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
516  *      The previous mechanism would not have intercepted that, and
517  *      if it had been intercepted then it then it would have replaced
518  *      it with an image.)
519  *
520  *    Revision 1.9  2001/05/28 17:26:33  jongfoster
521  *    Fixing segfault if last header was crunched.
522  *    Fixing Windows build (snprintf() is _snprintf() under Win32, but we
523  *    can use the cross-platform sprintf() instead.)
524  *
525  *    Revision 1.8  2001/05/27 22:17:04  oes
526  *
527  *    - re_process_buffer no longer writes the modified buffer
528  *      to the client, which was very ugly. It now returns the
529  *      buffer, which it is then written by chat.
530  *
531  *    - content_length now adjusts the Content-Length: header
532  *      for modified documents rather than crunch()ing it.
533  *      (Length info in csp->content_length, which is 0 for
534  *      unmodified documents)
535  *
536  *    - For this to work, sed() is called twice when filtering.
537  *
538  *    Revision 1.7  2001/05/27 13:19:06  oes
539  *    Patched Joergs solution for the content-length in.
540  *
541  *    Revision 1.6  2001/05/26 13:39:32  jongfoster
542  *    Only crunches Content-Length header if applying RE filtering.
543  *    Without this fix, Microsoft Windows Update wouldn't work.
544  *
545  *    Revision 1.5  2001/05/26 00:28:36  jongfoster
546  *    Automatic reloading of config file.
547  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
548  *    Most of the global variables have been moved to a new
549  *    struct configuration_spec, accessed through csp->config->globalname
550  *    Most of the globals remaining are used by the Win32 GUI.
551  *
552  *    Revision 1.4  2001/05/22 18:46:04  oes
553  *
554  *    - Enabled filtering banners by size rather than URL
555  *      by adding patterns that replace all standard banner
556  *      sizes with the "Junkbuster" gif to the re_filterfile
557  *
558  *    - Enabled filtering WebBugs by providing a pattern
559  *      which kills all 1x1 images
560  *
561  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
562  *      which is selected by the (nonstandard and therefore
563  *      capital) letter 'U' in the option string.
564  *      It causes the quantifiers to be ungreedy by default.
565  *      Appending a ? turns back to greedy (!).
566  *
567  *    - Added a new interceptor ijb-send-banner, which
568  *      sends back the "Junkbuster" gif. Without imagelist or
569  *      MSIE detection support, or if tinygif = 1, or the
570  *      URL isn't recognized as an imageurl, a lame HTML
571  *      explanation is sent instead.
572  *
573  *    - Added new feature, which permits blocking remote
574  *      script redirects and firing back a local redirect
575  *      to the browser.
576  *      The feature is conditionally compiled, i.e. it
577  *      can be disabled with --disable-fast-redirects,
578  *      plus it must be activated by a "fast-redirects"
579  *      line in the config file, has its own log level
580  *      and of course wants to be displayed by show-proxy-args
581  *      Note: Boy, all the #ifdefs in 1001 locations and
582  *      all the fumbling with configure.in and acconfig.h
583  *      were *way* more work than the feature itself :-(
584  *
585  *    - Because a generic redirect template was needed for
586  *      this, tinygif = 3 now uses the same.
587  *
588  *    - Moved GIFs, and other static HTTP response templates
589  *      to project.h
590  *
591  *    - Some minor fixes
592  *
593  *    - Removed some >400 CRs again (Jon, you really worked
594  *      a lot! ;-)
595  *
596  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
597  *    Version 2.9.4 checkin.
598  *    - Merged popupfile and cookiefile, and added control over PCRS
599  *      filtering, in new "permissionsfile".
600  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
601  *      file error you now get a message box (in the Win32 GUI) rather
602  *      than the program exiting with no explanation.
603  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
604  *      skipping.
605  *    - Removed tabs from "config"
606  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
607  *    - Bumped up version number.
608  *
609  *    Revision 1.2  2001/05/17 23:02:36  oes
610  *     - Made referrer option accept 'L' as a substitute for '§'
611  *
612  *    Revision 1.1.1.1  2001/05/15 13:59:01  oes
613  *    Initial import of version 2.9.3 source tree
614  *
615  *
616  *********************************************************************/
617 \f
618
619 #include "config.h"
620
621 #ifndef _WIN32
622 #include <stdio.h>
623 #include <sys/types.h>
624 #endif
625
626 #include <stdlib.h>
627 #include <ctype.h>
628 #include <assert.h>
629 #include <string.h>
630 #include <time.h>
631
632 #ifdef FEATURE_ZLIB
633 #include <zlib.h>
634 #endif
635
636 #if !defined(_WIN32) && !defined(__OS2__)
637 #include <unistd.h>
638 #endif
639
640 #include "project.h"
641
642 #ifdef FEATURE_PTHREAD
643 #include "jcc.h"
644 /* jcc.h is for mutex semapores only */
645 #endif /* def FEATURE_PTHREAD */
646 #include "list.h"
647 #include "parsers.h"
648 #include "encode.h"
649 #include "ssplit.h"
650 #include "errlog.h"
651 #include "jbsockets.h"
652 #include "miscutil.h"
653 #include "list.h"
654
655 #ifndef HAVE_STRPTIME
656 #include "strptime.h"
657 #endif
658
659 const char parsers_h_rcs[] = PARSERS_H_VERSION;
660
661 /* Fix a problem with Solaris.  There should be no effect on other
662  * platforms.
663  * Solaris's isspace() is a macro which uses it's argument directly
664  * as an array index.  Therefore we need to make sure that high-bit
665  * characters generate +ve values, and ideally we also want to make
666  * the argument match the declared parameter type of "int".
667  *
668  * Why did they write a character function that can't take a simple
669  * "char" argument?  Doh!
670  */
671 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
672 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
673
674
675 const struct parsers client_patterns[] = {
676    { "referer:",                  8,   client_referrer },
677    { "user-agent:",              11,   client_uagent },
678    { "ua-",                       3,   client_ua },
679    { "from:",                     5,   client_from },
680    { "cookie:",                   7,   client_send_cookie },
681    { "x-forwarded-for:",         16,   client_x_forwarded },
682    { "Accept-Encoding:",         16,   client_accept_encoding },
683    { "TE:",                       3,   client_te },
684    { "Host:",                     5,   client_host },
685    { "if-modified-since:",       18,   client_if_modified_since },
686    { "Keep-Alive:",              11,   crumble },
687    { "connection:",              11,   connection },
688    { "proxy-connection:",        17,   crumble },
689    { "max-forwards:",            13,   client_max_forwards },
690    { "Accept-Language:",         16,   client_accept_language },
691    { "if-none-match:",           14,   client_if_none_match },
692    { "X-Filter:",                 9,   client_x_filter },
693    { "*",                         0,   crunch_client_header },
694    { "*",                         0,   filter_client_header },
695    { NULL,                        0,   NULL }
696 };
697
698 const struct parsers server_patterns[] = {
699    { "HTTP",                      4, server_http },
700    { "set-cookie:",              11, server_set_cookie },
701    { "connection:",              11, connection },
702    { "Content-Type:",            13, server_content_type },
703    { "Content-MD5:",             12, server_content_md5 },
704    { "Content-Encoding:",        17, server_content_encoding },
705    { "Transfer-Encoding:",       18, server_transfer_coding },
706    { "Keep-Alive:",              11, crumble },
707    { "content-disposition:",     20, server_content_disposition },
708    { "Last-Modified:",           14, server_last_modified },
709    { "*",                         0, crunch_server_header },
710    { "*",                         0, filter_server_header },
711    { NULL, 0, NULL }
712 };
713
714 const struct parsers server_patterns_light[] = {
715    { "Content-Length:",          15, server_content_length },
716    { "Transfer-Encoding:",       18, server_transfer_coding },
717 #ifdef FEATURE_ZLIB
718    { "Content-Encoding:",        17, server_content_encoding },
719 #endif /* def FEATURE_ZLIB */
720    { NULL, 0, NULL }
721 };
722
723 const add_header_func_ptr add_client_headers[] = {
724    client_host_adder,
725    client_cookie_adder,
726    client_x_forwarded_adder,
727    client_xtra_adder,
728    /* Temporarily disabled:    client_accept_encoding_adder, */
729    connection_close_adder,
730    NULL
731 };
732
733
734 const add_header_func_ptr add_server_headers[] = {
735    connection_close_adder,
736    NULL
737 };
738
739 /*********************************************************************
740  *
741  * Function    :  flush_socket
742  *
743  * Description :  Write any pending "buffered" content.
744  *
745  * Parameters  :
746  *          1  :  fd = file descriptor of the socket to read
747  *          2  :  csp = Current client state (buffers, headers, etc...)
748  *
749  * Returns     :  On success, the number of bytes written are returned (zero
750  *                indicates nothing was written).  On error, -1 is returned,
751  *                and errno is set appropriately.  If count is zero and the
752  *                file descriptor refers to a regular file, 0 will be
753  *                returned without causing any other effect.  For a special
754  *                file, the results are not portable.
755  *
756  *********************************************************************/
757 int flush_socket(jb_socket fd, struct client_state *csp)
758 {
759    struct iob *iob = csp->iob;
760    int len = iob->eod - iob->cur;
761
762    if (len <= 0)
763    {
764       return(0);
765    }
766
767    if (write_socket(fd, iob->cur, (size_t)len))
768    {
769       return(-1);
770    }
771    iob->eod = iob->cur = iob->buf;
772    return(len);
773
774 }
775
776
777 /*********************************************************************
778  *
779  * Function    :  add_to_iob
780  *
781  * Description :  Add content to the buffered page, expanding the
782  *                buffer if necessary.
783  *
784  * Parameters  :
785  *          1  :  csp = Current client state (buffers, headers, etc...)
786  *          2  :  buf = holds the content to be added to the page
787  *          3  :  n = number of bytes to be added
788  *
789  * Returns     :  JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
790  *                or buffer limit reached.
791  *
792  *********************************************************************/
793 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
794 {
795    struct iob *iob = csp->iob;
796    size_t used, offset, need, want;
797    char *p;
798
799    if (n <= 0) return JB_ERR_OK;
800
801    used   = (size_t)(iob->eod - iob->buf);
802    offset = (size_t)(iob->cur - iob->buf);
803    need   = used + (size_t)n + 1;
804
805    /*
806     * If the buffer can't hold the new data, extend it first.
807     * Use the next power of two if possible, else use the actual need.
808     */
809    if (need > csp->config->buffer_limit)
810    {
811       log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
812       return JB_ERR_MEMORY;
813    }
814
815    if (need > iob->size)
816    {
817       for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
818       
819       if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
820       {
821          iob->size = want;
822       }
823       else if (NULL != (p = (char *)realloc(iob->buf, need)))
824       {
825          iob->size = need;
826       }
827       else
828       {
829          log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
830          return JB_ERR_MEMORY;
831       }
832
833       /* Update the iob pointers */
834       iob->cur = p + offset;
835       iob->eod = p + used;
836       iob->buf = p;
837    }
838
839    /* copy the new data into the iob buffer */
840    memcpy(iob->eod, buf, (size_t)n);
841
842    /* point to the end of the data */
843    iob->eod += n;
844
845    /* null terminate == cheap insurance */
846    *iob->eod = '\0';
847
848    return JB_ERR_OK;
849
850 }
851
852
853 #ifdef FEATURE_ZLIB
854 /*********************************************************************
855  *
856  * Function    :  decompress_iob
857  *
858  * Description :  Decompress buffered page, expanding the
859  *                buffer as necessary.  csp->iob->cur
860  *                should point to the the beginning of the
861  *                compressed data block.
862  *
863  * Parameters  :
864  *          1  :  csp = Current client state (buffers, headers, etc...)
865  *
866  * Returns     :  JB_ERR_OK on success,
867  *                JB_ERR_MEMORY if out-of-memory limit reached, and
868  *                JB_ERR_COMPRESS if error decompressing buffer.
869  *
870  *********************************************************************/
871 jb_err decompress_iob(struct client_state *csp)
872 {
873    char  *buf;       /* new, uncompressed buffer */
874    char  *cur;       /* Current iob position (to keep the original 
875                       * iob->cur unmodified if we return early) */
876    size_t bufsize;   /* allocated size of the new buffer */
877    size_t skip_size; /* Number of bytes at the beginning of the iob
878                         that we should NOT decompress. */
879    int status;       /* return status of the inflate() call */
880    z_stream zstr;    /* used by calls to zlib */
881
882    bufsize = csp->iob->size;
883    skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
884
885    cur = csp->iob->cur;
886
887    if (bufsize < 10)
888    {
889       /*
890        * This is to protect the parsing of gzipped data,
891        * but it should(?) be valid for deflated data also.
892        */
893       log_error (LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
894       return JB_ERR_COMPRESS;
895    }
896
897    if (csp->content_type & CT_GZIP)
898    {
899       /*
900        * Our task is slightly complicated by the facts that data
901        * compressed by gzip does not include a zlib header, and
902        * that there is no easily accessible interface in zlib to
903        * handle a gzip header. We strip off the gzip header by
904        * hand, and later inform zlib not to expect a header.
905        */
906
907       /*
908        * Strip off the gzip header. Please see RFC 1952 for more
909        * explanation of the appropriate fields.
910        */
911       if ((*cur++ != (char)0x1f)
912        || (*cur++ != (char)0x8b)
913        || (*cur++ != Z_DEFLATED))
914       {
915          log_error (LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
916          return JB_ERR_COMPRESS;
917       }
918       else
919       {
920          int flags = *cur++;
921          /*
922           * XXX: These magic numbers should be replaced
923           * with macros to give a better idea what they do.
924           */
925          if (flags & 0xe0)
926          {
927             /* The gzip header has reserved bits set; bail out. */
928             log_error (LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
929             return JB_ERR_COMPRESS;
930          }
931          cur += 6;
932
933          /* Skip extra fields if necessary. */
934          if (flags & 0x04)
935          {
936             /*
937              * Skip a given number of bytes, specified
938              * as a 16-bit little-endian value.
939              */
940             /*
941              * XXX: This code used to be:
942              * 
943              * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
944              *
945              * which I had to change into:
946              *
947              * cur += *cur++ + (*cur++ << 8);
948              *
949              * at which point gcc43 finally noticed that the value
950              * of cur is undefined (it depends on which of the
951              * summands is evaluated first).
952              *
953              * I haven't come across a site where this
954              * code is actually executed yet, but I hope
955              * it works anyway.
956              */
957             int skip_bytes;
958             skip_bytes = *cur++;
959             skip_bytes = *cur++ << 8;
960
961             assert(skip_bytes == *csp->iob->cur-2 + ((*csp->iob->cur-1) << 8));
962
963             /*
964              * The number of bytes to skip should be positive
965              * and we'd like to stay in the buffer.
966              */
967             if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
968             {
969                log_error (LOG_LEVEL_ERROR,
970                   "Unreasonable amount of bytes to skip (%d). Stopping decompression",
971                   skip_bytes);
972                return JB_ERR_COMPRESS;
973             }
974             log_error (LOG_LEVEL_INFO,
975                "Skipping %d bytes for gzip compression. Does this sound right?",
976                skip_bytes);
977             cur += skip_bytes;
978          }
979
980          /* Skip the filename if necessary. */
981          if (flags & 0x08)
982          {
983             /* A null-terminated string follows. */
984             while (*cur++);
985          }
986
987          /* Skip the comment if necessary. */
988          if (flags & 0x10)
989          {
990             while (*cur++);
991          }
992
993          /* Skip the CRC if necessary. */
994          if (flags & 0x02)
995          {
996             cur += 2;
997          }
998       }
999    }
1000    else if (csp->content_type & CT_DEFLATE)
1001    {
1002       /*
1003        * XXX: The debug level should be lowered
1004        * before the next stable release.
1005        */
1006       log_error (LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1007       /*
1008        * In theory (that is, according to RFC 1950), deflate-compressed
1009        * data should begin with a two-byte zlib header and have an
1010        * adler32 checksum at the end. It seems that in practice only
1011        * the raw compressed data is sent. Note that this means that
1012        * we are not RFC 1950-compliant here, but the advantage is that
1013        * this actually works. :)
1014        *
1015        * We add a dummy null byte to tell zlib where the data ends,
1016        * and later inform it not to expect a header.
1017        *
1018        * Fortunately, add_to_iob() has thoughtfully null-terminated
1019        * the buffer; we can just increment the end pointer to include
1020        * the dummy byte.  
1021        */
1022       csp->iob->eod++;
1023    }
1024    else
1025    {
1026       log_error (LOG_LEVEL_ERROR,
1027          "Unable to determine compression format for decompression");
1028       return JB_ERR_COMPRESS;
1029    }
1030
1031    /* Set up the fields required by zlib. */
1032    zstr.next_in  = (Bytef *)cur;
1033    zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1034    zstr.zalloc   = Z_NULL;
1035    zstr.zfree    = Z_NULL;
1036    zstr.opaque   = Z_NULL;
1037
1038    /*
1039     * Passing -MAX_WBITS to inflateInit2 tells the library
1040     * that there is no zlib header.
1041     */
1042    if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1043    {
1044       log_error (LOG_LEVEL_ERROR, "Error initializing decompression");
1045       return JB_ERR_COMPRESS;
1046    }
1047
1048    /*
1049     * Next, we allocate new storage for the inflated data.
1050     * We don't modify the existing iob yet, so in case there
1051     * is error in decompression we can recover gracefully.
1052     */
1053    buf = zalloc (bufsize);
1054    if (NULL == buf)
1055    {
1056       log_error (LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1057       return JB_ERR_MEMORY;
1058    }
1059
1060    assert(bufsize >= skip_size);
1061    memcpy(buf, csp->iob->buf, skip_size);
1062    zstr.avail_out = bufsize - skip_size;
1063    zstr.next_out  = (Bytef *)buf + skip_size;
1064
1065    /* Try to decompress the whole stream in one shot. */
1066    while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1067    {
1068       /* We need to allocate more memory for the output buffer. */
1069
1070       char *tmpbuf;                /* used for realloc'ing the buffer */
1071       size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1072
1073       /*
1074        * If zlib wants more data then there's a problem, because
1075        * the complete compressed file should have been buffered.
1076        */
1077       if (0 == zstr.avail_in)
1078       {
1079          log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1080          return JB_ERR_COMPRESS;
1081       }
1082
1083       /*
1084        * If we tried the limit and still didn't have enough
1085        * memory, just give up.
1086        */
1087       if (bufsize == csp->config->buffer_limit)
1088       {
1089          log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1090          return JB_ERR_MEMORY;
1091       }
1092
1093       /* Try doubling the buffer size each time. */
1094       bufsize *= 2;
1095
1096       /* Don't exceed the buffer limit. */
1097       if (bufsize > csp->config->buffer_limit)
1098       {
1099          bufsize = csp->config->buffer_limit;
1100       }
1101     
1102       /* Try to allocate the new buffer. */
1103       tmpbuf = realloc(buf, bufsize);
1104       if (NULL == tmpbuf)
1105       {
1106          log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1107          freez(buf);
1108          return JB_ERR_MEMORY;
1109       }
1110       else
1111       {
1112          char *oldnext_out = (char *)zstr.next_out;
1113
1114          /*
1115           * Update the fields for inflate() to use the new
1116           * buffer, which may be in a location different from
1117           * the old one.
1118           */
1119          zstr.avail_out += bufsize - oldbufsize;
1120          zstr.next_out   = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1121
1122          /*
1123           * Compare with an uglier method of calculating these values
1124           * that doesn't require the extra oldbufsize variable.
1125           */
1126          assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1127          assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1128          assert(zstr.avail_out > 0);
1129
1130          buf = tmpbuf;
1131       }
1132    }
1133
1134    if (Z_STREAM_ERROR == inflateEnd(&zstr))
1135    {
1136       log_error(LOG_LEVEL_ERROR,
1137          "Inconsistent stream state after decompression: %s", zstr.msg);
1138       /*
1139        * XXX: Intentionally no return.
1140        *
1141        * According to zlib.h, Z_STREAM_ERROR is returned
1142        * "if the stream state was inconsistent".
1143        *
1144        * I assume in this case inflate()'s status
1145        * would also be something different than Z_STREAM_END
1146        * so this check should be redundant, but lets see.
1147        */
1148    }
1149
1150    if (status != Z_STREAM_END)
1151    {
1152       /* We failed to decompress the stream. */
1153       log_error(LOG_LEVEL_ERROR,
1154          "Error in decompressing to the buffer (iob): %s", zstr.msg);
1155       return JB_ERR_COMPRESS;
1156    }
1157
1158    /*
1159     * Finally, we can actually update the iob, since the
1160     * decompression was successful. First, free the old
1161     * buffer.
1162     */
1163    freez(csp->iob->buf);
1164
1165    /* Now, update the iob to use the new buffer. */
1166    csp->iob->buf  = buf;
1167    csp->iob->cur  = csp->iob->buf + skip_size;
1168    csp->iob->eod  = (char *)zstr.next_out;
1169    csp->iob->size = bufsize;
1170   
1171    /*
1172     * Make sure the new uncompressed iob obeys some minimal
1173     * consistency conditions.
1174     */
1175    if ((csp->iob->buf <  csp->iob->cur)
1176     && (csp->iob->cur <= csp->iob->eod)
1177     && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1178    {
1179       char t = csp->iob->cur[100];
1180       csp->iob->cur[100] = '\0';
1181       /*
1182        * XXX: The debug level should be lowered
1183        * before the next stable release.
1184        */
1185       log_error(LOG_LEVEL_INFO, "Sucessfully decompressed: %s", csp->iob->cur);
1186       csp->iob->cur[100] = t;
1187       return JB_ERR_OK;
1188    }
1189    else
1190    {
1191       /* It seems that zlib did something weird. */
1192       log_error(LOG_LEVEL_ERROR,
1193          "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1194          csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1195          csp->iob->eod, csp->iob->buf + csp->iob->size);
1196       return JB_ERR_COMPRESS;
1197    }
1198
1199 }
1200 #endif /* defined(FEATURE_ZLIB) */
1201
1202
1203 /*********************************************************************
1204  *
1205  * Function    :  get_header
1206  *
1207  * Description :  This (odd) routine will parse the csp->iob
1208  *
1209  * Parameters  :
1210  *          1  :  csp = Current client state (buffers, headers, etc...)
1211  *
1212  * Returns     :  Any one of the following:
1213  *
1214  * 1) a pointer to a dynamically allocated string that contains a header line
1215  * 2) NULL  indicating that the end of the header was reached
1216  * 3) ""    indicating that the end of the iob was reached before finding
1217  *          a complete header line.
1218  *
1219  *********************************************************************/
1220 char *get_header(struct client_state *csp)
1221 {
1222    struct iob *iob;
1223    char *p, *q, *ret;
1224    iob = csp->iob;
1225
1226    if ((iob->cur == NULL)
1227       || ((p = strchr(iob->cur, '\n')) == NULL))
1228    {
1229       return(""); /* couldn't find a complete header */
1230    }
1231
1232    *p = '\0';
1233
1234    ret = strdup(iob->cur);
1235    if (ret == NULL)
1236    {
1237       /* FIXME No way to handle error properly */
1238       log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1239    }
1240
1241    iob->cur = p+1;
1242
1243    if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1244
1245    /* is this a blank line (i.e. the end of the header) ? */
1246    if (*ret == '\0')
1247    {
1248       freez(ret);
1249       return(NULL);
1250    }
1251
1252    return(ret);
1253
1254 }
1255
1256
1257 /*********************************************************************
1258  *
1259  * Function    :  get_header_value
1260  *
1261  * Description :  Get the value of a given header from a chained list
1262  *                of header lines or return NULL if no such header is
1263  *                present in the list.
1264  *
1265  * Parameters  :
1266  *          1  :  header_list = pointer to list
1267  *          2  :  header_name = string with name of header to look for.
1268  *                              Trailing colon required, capitalization
1269  *                              doesn't matter.
1270  *
1271  * Returns     :  NULL if not found, else value of header
1272  *
1273  *********************************************************************/
1274 char *get_header_value(const struct list *header_list, const char *header_name)
1275 {
1276    struct list_entry *cur_entry;
1277    char *ret = NULL;
1278    size_t length = 0;
1279
1280    assert(header_list);
1281    assert(header_name);
1282    length = strlen(header_name);
1283
1284    for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1285    {
1286       if (cur_entry->str)
1287       {
1288          if (!strncmpic(cur_entry->str, header_name, length))
1289          {
1290             /*
1291              * Found: return pointer to start of value
1292              */
1293             ret = (char *) (cur_entry->str + length);
1294             while (*ret && ijb_isspace(*ret)) ret++;
1295             return(ret);
1296          }
1297       }
1298    }
1299
1300    /* 
1301     * Not found
1302     */
1303    return NULL;
1304
1305 }
1306
1307 /*********************************************************************
1308  *
1309  * Function    :  sed
1310  *
1311  * Description :  add, delete or modify lines in the HTTP header streams.
1312  *                On entry, it receives a linked list of headers space
1313  *                that was allocated dynamically (both the list nodes
1314  *                and the header contents).
1315  *
1316  *                As a side effect it frees the space used by the original
1317  *                header lines.
1318  *
1319  * Parameters  :
1320  *          1  :  pats = list of patterns to match against headers
1321  *          2  :  more_headers = list of functions to add more
1322  *                headers (client or server)
1323  *          3  :  csp = Current client state (buffers, headers, etc...)
1324  *
1325  * Returns     :  Single pointer to a fully formed header, or NULL
1326  *                on out-of-memory error.
1327  *
1328  *********************************************************************/
1329 char *sed(const struct parsers pats[],
1330           const add_header_func_ptr more_headers[],
1331           struct client_state *csp)
1332 {
1333    struct list_entry *p;
1334    const struct parsers *v;
1335    const add_header_func_ptr *f;
1336    jb_err err = JB_ERR_OK;
1337    int first_run;
1338
1339    /*
1340     * If filtering is enabled, sed is run twice,
1341     * but most of the work needs to be done only once.
1342     */
1343    first_run = (more_headers != NULL ) ? 1 : 0;
1344
1345    if (first_run) /* Parse and print */
1346    {
1347       log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1348       for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1349       {
1350          for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1351          {
1352             /* Header crunch()ed in previous run? -> ignore */
1353             if (p->str == NULL) continue;
1354
1355             if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
1356
1357             /* Does the current parser handle this header? */
1358             if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1359             {
1360                err = v->parser(csp, (char **)&(p->str));
1361             }
1362          }
1363       }
1364       /* place any additional headers on the csp->headers list */
1365       for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1366       {
1367          err = (*f)(csp);
1368       }
1369    }
1370    else /* Parse only */
1371    {
1372       /*
1373        * The second run is only needed if the body was modified
1374        * and the content-lenght has changed.
1375        */
1376       if (strncmpic(csp->http->cmd, "HEAD", 4))
1377       {
1378          /*XXX: Code duplication */
1379          for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1380          {
1381             for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1382             {
1383                /* Header crunch()ed in previous run? -> ignore */
1384                if (p->str == NULL) continue;
1385
1386                /* Does the current parser handle this header? */
1387                if (strncmpic(p->str, v->str, v->len) == 0)
1388                {
1389                   err = v->parser(csp, (char **)&(p->str));
1390                }
1391             }
1392          }
1393       }
1394    }
1395
1396    if (err != JB_ERR_OK)
1397    {
1398       return NULL;
1399    }
1400
1401    return list_to_text(csp->headers);
1402 }
1403
1404
1405 /* here begins the family of parser functions that reformat header lines */
1406
1407 /*********************************************************************
1408  *
1409  * Function    :  filter_server_header
1410  *
1411  * Description :  Checks if server header filtering is enabled.
1412  *                If it is, filter_header is called to do the work. 
1413  *
1414  * Parameters  :
1415  *          1  :  csp = Current client state (buffers, headers, etc...)
1416  *          2  :  header = On input, pointer to header to modify.
1417  *                On output, pointer to the modified header, or NULL
1418  *                to remove the header.  This function frees the
1419  *                original string if necessary.
1420  *
1421  * Returns     :  JB_ERR_OK on success and always succeeds
1422  *
1423  *********************************************************************/
1424 jb_err filter_server_header(struct client_state *csp, char **header)
1425 {
1426    if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
1427    {
1428       filter_header(csp, header);
1429    }
1430    return(JB_ERR_OK);
1431 }
1432
1433 /*********************************************************************
1434  *
1435  * Function    :  filter_client_header
1436  *
1437  * Description :  Checks if client header filtering is enabled.
1438  *                If it is, filter_header is called to do the work. 
1439  *
1440  * Parameters  :
1441  *          1  :  csp = Current client state (buffers, headers, etc...)
1442  *          2  :  header = On input, pointer to header to modify.
1443  *                On output, pointer to the modified header, or NULL
1444  *                to remove the header.  This function frees the
1445  *                original string if necessary.
1446  *
1447  * Returns     :  JB_ERR_OK on success and always succeeds
1448  *
1449  *********************************************************************/
1450 jb_err filter_client_header(struct client_state *csp, char **header)
1451 {
1452    if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
1453    {
1454       filter_header(csp, header);
1455    }
1456    return(JB_ERR_OK);
1457 }
1458
1459 /*********************************************************************
1460  *
1461  * Function    :  filter_header
1462  *
1463  * Description :  Executes all text substitutions from all applying
1464  *                +filter actions on the header.
1465  *                Most of the code was copied from pcrs_filter_response,
1466  *                including the rather short variable names
1467  *
1468  * Parameters  :
1469  *          1  :  csp = Current client state (buffers, headers, etc...)
1470  *          2  :  header = On input, pointer to header to modify.
1471  *                On output, pointer to the modified header, or NULL
1472  *                to remove the header.  This function frees the
1473  *                original string if necessary.
1474  *
1475  * Returns     :  JB_ERR_OK on success and always succeeds
1476  *
1477  *********************************************************************/
1478 jb_err filter_header(struct client_state *csp, char **header)
1479 {
1480    int hits=0;
1481    int matches;
1482    size_t size = strlen(*header);
1483
1484    char *newheader = NULL;
1485    pcrs_job *job;
1486
1487    struct file_list *fl;
1488    struct re_filterfile_spec *b;
1489    struct list_entry *filtername;
1490
1491    int i, found_filters = 0;
1492
1493    /*
1494     * Need to check the set of re_filterfiles...
1495     */
1496    for (i = 0; i < MAX_AF_FILES; i++)
1497    {
1498       fl = csp->rlist[i];
1499       if (NULL != fl)
1500       {
1501          if (NULL != fl->f)
1502          {
1503            found_filters = 1;
1504            break;
1505          }
1506       }
1507    }
1508
1509    if (0 == found_filters)
1510    {
1511       log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1512       return(JB_ERR_OK);
1513    }
1514
1515    for (i = 0; i < MAX_AF_FILES; i++)
1516    {
1517       fl = csp->rlist[i];
1518       if ((NULL == fl) || (NULL == fl->f))
1519       {
1520          /*
1521           * Either there are no filter files
1522           * left, or this filter file just
1523           * contains no valid filters.
1524           *
1525           * Continue to be sure we don't miss
1526           * valid filter files that are chained
1527           * after empty or invalid ones.
1528           */
1529          continue;
1530       }
1531       /*
1532        * For all applying +filter actions, look if a filter by that
1533        * name exists and if yes, execute its pcrs_joblist on the
1534        * buffer.
1535        */
1536       for (b = fl->f; b; b = b->next)
1537       {
1538          for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1539               filtername ; filtername = filtername->next)
1540          {
1541             if (strcmp(b->name, filtername->str) == 0)
1542             {
1543                int current_hits = 0;
1544
1545                if ( NULL == b->joblist )
1546                {
1547                   log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1548                   continue;
1549                }
1550
1551                log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1552                          *header, size, b->name);
1553
1554                /* Apply all jobs from the joblist */
1555                for (job = b->joblist; NULL != job; job = job->next)
1556                {
1557                   matches = pcrs_execute(job, *header, size, &newheader, &size);
1558                   if ( 0 < matches )
1559                   {
1560                      current_hits += matches; 
1561                      log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1562                      freez(*header);
1563                      *header = newheader;
1564                   }
1565                   else if ( 0 == matches )
1566                   {
1567                      /* Filter doesn't change header */
1568                      freez(newheader);
1569                   }
1570                   else
1571                   {
1572                      /* RegEx failure */
1573                      log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1574                         *header, b->name, pcrs_strerror(matches));
1575                      if( newheader != NULL)
1576                      {
1577                         log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1578                         freez(newheader);
1579                      }
1580                   }
1581                }
1582                log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1583                hits += current_hits;
1584             }
1585          }
1586       }
1587    }
1588
1589    /*
1590     * Additionally checking for hits is important because if
1591     * the continue hack is triggered, server headers can
1592     * arrive empty to separate multiple heads from each other.
1593     */
1594    if ((0 == size) && hits)
1595    {
1596       log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1597       freez(*header);
1598    }
1599
1600    return(JB_ERR_OK);
1601 }
1602
1603
1604 /*********************************************************************
1605  *
1606  * Function    :  connection
1607  *
1608  * Description :  Makes sure that the value of the Connection: header
1609  *                is "close" and signals connection_close_adder 
1610  *                to do nothing.
1611  *
1612  * Parameters  :
1613  *          1  :  csp = Current client state (buffers, headers, etc...)
1614  *          2  :  header = On input, pointer to header to modify.
1615  *                On output, pointer to the modified header, or NULL
1616  *                to remove the header.  This function frees the
1617  *                original string if necessary.
1618  *
1619  * Returns     :  JB_ERR_OK on success, or
1620  *                JB_ERR_MEMORY on out-of-memory error.
1621  *
1622  *********************************************************************/
1623 jb_err connection(struct client_state *csp, char **header)
1624 {
1625    char *old_header = *header;
1626
1627    /* Do we have a 'Connection: close' header? */
1628    if (strcmpic(*header, "Connection: close"))
1629    {
1630       /* No, create one */
1631       *header = strdup("Connection: close");
1632       if (header == NULL)
1633       { 
1634          return JB_ERR_MEMORY;
1635       }
1636       log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1637       freez(old_header);
1638    }
1639
1640    /* Signal connection_close_adder() to return early. */
1641    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1642    {
1643       csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
1644    }
1645    else
1646    {
1647       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
1648    }
1649
1650    return JB_ERR_OK;
1651 }
1652
1653
1654 /*********************************************************************
1655  *
1656  * Function    :  crumble
1657  *
1658  * Description :  This is called if a header matches a pattern to "crunch"
1659  *
1660  * Parameters  :
1661  *          1  :  csp = Current client state (buffers, headers, etc...)
1662  *          2  :  header = On input, pointer to header to modify.
1663  *                On output, pointer to the modified header, or NULL
1664  *                to remove the header.  This function frees the
1665  *                original string if necessary.
1666  *
1667  * Returns     :  JB_ERR_OK on success, or
1668  *                JB_ERR_MEMORY on out-of-memory error.
1669  *
1670  *********************************************************************/
1671 jb_err crumble(struct client_state *csp, char **header)
1672 {
1673    log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1674    freez(*header);
1675    return JB_ERR_OK;
1676 }
1677
1678 /*********************************************************************
1679  *
1680  * Function    :  crunch_server_header
1681  *
1682  * Description :  Crunch server header if it matches a string supplied by the
1683  *                user. Called from `sed'.
1684  *
1685  * Parameters  :
1686  *          1  :  csp = Current client state (buffers, headers, etc...)
1687  *          2  :  header = On input, pointer to header to modify.
1688  *                On output, pointer to the modified header, or NULL
1689  *                to remove the header.  This function frees the
1690  *                original string if necessary.
1691  *
1692  * Returns     :  JB_ERR_OK on success and always succeeds
1693  *
1694  *********************************************************************/
1695 jb_err crunch_server_header(struct client_state *csp, char **header)
1696 {
1697    const char *crunch_pattern;
1698
1699    /* Do we feel like crunching? */
1700    if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1701    {
1702       crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1703
1704       /* Is the current header the lucky one? */
1705       if (strstr(*header, crunch_pattern))
1706       {
1707          log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);  
1708          freez(*header);
1709       }
1710    }
1711
1712    return JB_ERR_OK;
1713 }
1714
1715
1716 /*********************************************************************
1717  *
1718  * Function    :  server_content_type
1719  *
1720  * Description :  Set the content-type for filterable types (text/.*,
1721  *                .*xml.*, javascript and image/gif) unless filtering has been
1722  *                forbidden (CT_TABOO) while parsing earlier headers.
1723  *                NOTE: Since text/plain is commonly used by web servers
1724  *                      for files whose correct type is unknown, we don't
1725  *                      set CT_TEXT for it.
1726  *
1727  * Parameters  :
1728  *          1  :  csp = Current client state (buffers, headers, etc...)
1729  *          2  :  header = On input, pointer to header to modify.
1730  *                On output, pointer to the modified header, or NULL
1731  *                to remove the header.  This function frees the
1732  *                original string if necessary.
1733  *
1734  * Returns     :  JB_ERR_OK on success, or
1735  *                JB_ERR_MEMORY on out-of-memory error.
1736  *
1737  *********************************************************************/
1738 jb_err server_content_type(struct client_state *csp, char **header)
1739 {
1740    /* Remove header if it isn't the first Content-Type header */
1741    if(csp->content_type && (csp->content_type != CT_TABOO))
1742    {
1743      /*
1744       * Another, slightly slower, way to see if
1745       * we already parsed another Content-Type header.
1746       */
1747       assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1748
1749       log_error(LOG_LEVEL_ERROR,
1750          "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1751          *header);
1752       freez(*header);
1753
1754       return JB_ERR_OK;
1755    }
1756
1757    if (!(csp->content_type & CT_TABOO))
1758    {
1759       if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1760         || strstr(*header, "xml")
1761         || strstr(*header, "application/x-javascript"))
1762       {
1763          csp->content_type |= CT_TEXT;
1764       }
1765       else if (strstr(*header, " image/gif"))
1766       {
1767          csp->content_type |= CT_GIF;
1768       }
1769       else if (strstr(*header, " image/jpeg"))
1770       {
1771          csp->content_type |= CT_JPEG;
1772       }
1773       else
1774       {
1775          csp->content_type = 0;
1776       }
1777    }
1778    /*
1779     * Are we enabling text mode by force?
1780     */
1781    if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1782    {
1783       /*
1784        * Do we really have to?
1785        */
1786       if (csp->content_type & CT_TEXT)
1787       {
1788          log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");   
1789       }
1790       else
1791       {
1792          csp->content_type |= CT_TEXT;
1793          log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");   
1794       }
1795    }
1796    /*
1797     * Are we messing with the content type?
1798     */ 
1799    if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1800    { 
1801       /*
1802        * Make sure the user doesn't accidently
1803        * change the content type of binary documents. 
1804        */ 
1805       if (csp->content_type & CT_TEXT)
1806       { 
1807          freez(*header);
1808          *header = strdup("Content-Type: ");
1809          string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1810
1811          if (header == NULL)
1812          { 
1813             log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1814             return JB_ERR_MEMORY;
1815          }
1816          log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1817       }
1818       else
1819       {
1820          log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1821             "Enable force-text-mode if you know what you're doing.", *header);   
1822       }
1823    }  
1824    return JB_ERR_OK;
1825 }
1826
1827
1828 /*********************************************************************
1829  *
1830  * Function    :  server_transfer_coding
1831  *
1832  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
1833  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1834  *                - Remove header if body was chunked but has been
1835  *                  de-chunked for filtering.
1836  *
1837  * Parameters  :
1838  *          1  :  csp = Current client state (buffers, headers, etc...)
1839  *          2  :  header = On input, pointer to header to modify.
1840  *                On output, pointer to the modified header, or NULL
1841  *                to remove the header.  This function frees the
1842  *                original string if necessary.
1843  *
1844  * Returns     :  JB_ERR_OK on success, or
1845  *                JB_ERR_MEMORY on out-of-memory error.
1846  *
1847  *********************************************************************/
1848 jb_err server_transfer_coding(struct client_state *csp, char **header)
1849 {
1850    /*
1851     * Turn off pcrs and gif filtering if body compressed
1852     */
1853    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1854    {
1855 #ifdef FEATURE_ZLIB
1856       /*
1857        * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1858        */
1859       log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1860          csp->http->cmd, *header);
1861 #endif /* def FEATURE_ZLIB */
1862       csp->content_type = CT_TABOO;
1863    }
1864
1865    /*
1866     * Raise flag if body chunked
1867     */
1868    if (strstr(*header, "chunked"))
1869    {
1870       csp->flags |= CSP_FLAG_CHUNKED;
1871
1872       /*
1873        * If the body was modified, it has been de-chunked first
1874        * and the header must be removed.
1875        *
1876        * FIXME: If there is more than one transfer encoding,
1877        * only the "chunked" part should be removed here.
1878        */
1879       if (csp->flags & CSP_FLAG_MODIFIED)
1880       {
1881          log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1882          freez(*header);
1883       }
1884    }
1885
1886    return JB_ERR_OK;
1887 }
1888
1889
1890 /*********************************************************************
1891  *
1892  * Function    :  server_content_encoding
1893  *
1894  * Description :  This function is run twice for each request,
1895  *                unless FEATURE_ZLIB and filtering are disabled.
1896  *
1897  *                The first run is used to check if the content
1898  *                is compressed, if FEATURE_ZLIB is disabled
1899  *                filtering is then disabled as well, if FEATURE_ZLIB
1900  *                is enabled the content is marked for decompression.
1901  *                
1902  *                The second run is used to remove the Content-Encoding
1903  *                header if the decompression was successful.
1904  *
1905  * Parameters  :
1906  *          1  :  csp = Current client state (buffers, headers, etc...)
1907  *          2  :  header = On input, pointer to header to modify.
1908  *                On output, pointer to the modified header, or NULL
1909  *                to remove the header.  This function frees the
1910  *                original string if necessary.
1911  *
1912  * Returns     :  JB_ERR_OK on success, or
1913  *                JB_ERR_MEMORY on out-of-memory error.
1914  *
1915  *********************************************************************/
1916 jb_err server_content_encoding(struct client_state *csp, char **header)
1917 {
1918 #ifdef FEATURE_ZLIB
1919    if ((csp->flags & CSP_FLAG_MODIFIED)
1920     && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1921    {
1922       /*
1923        * We successfully decompressed the content,
1924        * and have to clean the header now, so the
1925        * client no longer expects compressed data..
1926        *
1927        * XXX: There is a difference between cleaning
1928        * and removing it completely.
1929        */
1930       log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1931       freez(*header);
1932    }
1933    else if (strstr(*header, "gzip"))
1934    {
1935       /* Mark for gzip decompression */
1936       csp->content_type |= CT_GZIP;
1937    }
1938    else if (strstr(*header, "deflate"))
1939    {
1940       /* Mark for zlib decompression */
1941       csp->content_type |= CT_DEFLATE;
1942    }
1943    else if (strstr(*header, "compress"))
1944    {
1945       /*
1946        * We can't decompress this; therefore we can't filter
1947        * it either.
1948        */
1949       csp->content_type |= CT_TABOO;
1950    }
1951 #else /* !defined(FEATURE_ZLIB) */
1952    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1953    {
1954       /*
1955        * Body is compressed, turn off pcrs and gif filtering.
1956        */
1957       csp->content_type |= CT_TABOO;
1958    }
1959 #endif /* !defined(FEATURE_ZLIB) */
1960
1961    return JB_ERR_OK;
1962
1963 }
1964
1965
1966 /*********************************************************************
1967  *
1968  * Function    :  server_content_length
1969  *
1970  * Description :  Adjust Content-Length header if we modified
1971  *                the body.
1972  *
1973  * Parameters  :
1974  *          1  :  csp = Current client state (buffers, headers, etc...)
1975  *          2  :  header = On input, pointer to header to modify.
1976  *                On output, pointer to the modified header, or NULL
1977  *                to remove the header.  This function frees the
1978  *                original string if necessary.
1979  *
1980  * Returns     :  JB_ERR_OK on success, or
1981  *                JB_ERR_MEMORY on out-of-memory error.
1982  *
1983  *********************************************************************/
1984 jb_err server_content_length(struct client_state *csp, char **header)
1985 {
1986    const size_t max_header_length = 80;
1987
1988    /* Regenerate header if the content was modified. */
1989    if (csp->flags & CSP_FLAG_MODIFIED)
1990    {
1991       freez(*header);
1992       *header = (char *) zalloc(max_header_length);
1993       if (*header == NULL)
1994       {
1995          return JB_ERR_MEMORY;
1996       }
1997
1998       snprintf(*header, max_header_length, "Content-Length: %d",
1999          (int)csp->content_length);
2000       log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2001          (int)csp->content_length);
2002    }
2003
2004    return JB_ERR_OK;
2005 }
2006
2007
2008 /*********************************************************************
2009  *
2010  * Function    :  server_content_md5
2011  *
2012  * Description :  Crumble any Content-MD5 headers if the document was
2013  *                modified. FIXME: Should we re-compute instead?
2014  *
2015  * Parameters  :
2016  *          1  :  csp = Current client state (buffers, headers, etc...)
2017  *          2  :  header = On input, pointer to header to modify.
2018  *                On output, pointer to the modified header, or NULL
2019  *                to remove the header.  This function frees the
2020  *                original string if necessary.
2021  *
2022  * Returns     :  JB_ERR_OK on success, or
2023  *                JB_ERR_MEMORY on out-of-memory error.
2024  *
2025  *********************************************************************/
2026 jb_err server_content_md5(struct client_state *csp, char **header)
2027 {
2028    if (csp->flags & CSP_FLAG_MODIFIED)
2029    {
2030       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2031       freez(*header);
2032    }
2033
2034    return JB_ERR_OK;
2035 }
2036
2037 /*********************************************************************
2038  *
2039  * Function    :  server_content_disposition
2040  *
2041  * Description :  If enabled, blocks or modifies the "content-disposition" header.
2042  *                Called from `sed'.
2043  *
2044  * Parameters  :
2045  *          1  :  csp = Current client state (buffers, headers, etc...)
2046  *          2  :  header = On input, pointer to header to modify.
2047  *                On output, pointer to the modified header, or NULL
2048  *                to remove the header.  This function frees the
2049  *                original string if necessary.
2050  *
2051  * Returns     :  JB_ERR_OK on success, or
2052  *                JB_ERR_MEMORY on out-of-memory error.
2053  *
2054  *********************************************************************/
2055 jb_err server_content_disposition(struct client_state *csp, char **header)
2056 {
2057    const char *newval;
2058
2059    /*
2060     * Are we messing with the content-disposition header?
2061     */
2062    if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2063    {
2064       /*Me tinks not*/
2065       return JB_ERR_OK;
2066    }
2067
2068    newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2069
2070    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2071    {
2072       /*
2073        * Blocking content-disposition header
2074        */
2075       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2076       freez(*header);
2077       return JB_ERR_OK;
2078    }
2079    else
2080    {  
2081       /*
2082        * Replacing content-disposition header
2083        */
2084       freez(*header);
2085       *header = strdup("content-disposition: ");
2086       string_append(header, newval);   
2087
2088       if (*header == NULL)
2089       {
2090          log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");  
2091       }
2092       else
2093       {
2094          log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2095       }
2096    }
2097    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2098 }
2099
2100 /*********************************************************************
2101  *
2102  * Function    :  server_last_modified
2103  *
2104  * Description :  Changes Last-Modified header to the actual date
2105  *                to help hide-if-modified-since.
2106  *                Called from `sed'.
2107  *
2108  * Parameters  :
2109  *          1  :  csp = Current client state (buffers, headers, etc...)
2110  *          2  :  header = On input, pointer to header to modify.
2111  *                On output, pointer to the modified header, or NULL
2112  *                to remove the header.  This function frees the
2113  *                original string if necessary.
2114  *
2115  * Returns     :  JB_ERR_OK on success, or
2116  *                JB_ERR_MEMORY on out-of-memory error.
2117  *
2118  *********************************************************************/
2119 jb_err server_last_modified(struct client_state *csp, char **header)
2120 {
2121    const char *newval;
2122    char buf[BUFFER_SIZE];
2123
2124    char newheader[50];
2125 #ifdef HAVE_GMTIME_R
2126    struct tm gmt;
2127 #endif
2128    struct tm *timeptr = NULL;
2129    time_t now, last_modified;                  
2130    long int rtime;
2131    long int days, hours, minutes, seconds;
2132    
2133    /*
2134     * Are we messing with the Last-Modified header?
2135     */
2136    if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2137    {
2138       /*Nope*/
2139       return JB_ERR_OK;
2140    }
2141
2142    newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2143
2144    if (0 == strcmpic(newval, "block") )
2145    {
2146       /*
2147        * Blocking Last-Modified header. Useless but why not.
2148        */
2149       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2150       freez(*header);
2151       return JB_ERR_OK;
2152    }
2153    else if (0 == strcmpic(newval, "reset-to-request-time"))
2154    {  
2155       /*
2156        * Setting Last-Modified Header to now.
2157        */
2158       get_http_time(0, buf);
2159       freez(*header);
2160       *header = strdup("Last-Modified: ");
2161       string_append(header, buf);   
2162
2163       if (*header == NULL)
2164       {
2165          log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");  
2166       }
2167       else
2168       {
2169          log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2170       }
2171    }
2172    else if (0 == strcmpic(newval, "randomize"))
2173    {
2174       log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2175       now = time(NULL);
2176 #ifdef HAVE_GMTIME_R
2177       timeptr = gmtime_r(&now, &gmt);
2178 #elif FEATURE_PTHREAD
2179       pthread_mutex_lock(&gmtime_mutex);
2180       timeptr = gmtime(&now);
2181       pthread_mutex_unlock(&gmtime_mutex);
2182 #else
2183       timeptr = gmtime(&now);
2184 #endif
2185       if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
2186       {
2187          log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2188          freez(*header);
2189       }
2190       else
2191       {
2192          rtime = (long int)difftime(now, last_modified);
2193          if (rtime)
2194          {
2195             rtime = pick_from_range(rtime);
2196             last_modified += rtime;
2197 #ifdef HAVE_GMTIME_R
2198             timeptr = gmtime_r(&last_modified, &gmt);
2199 #elif FEATURE_PTHREAD
2200             pthread_mutex_lock(&gmtime_mutex);
2201             timeptr = gmtime(&last_modified);
2202             pthread_mutex_unlock(&gmtime_mutex);
2203 #else
2204             timeptr = gmtime(&last_modified);
2205 #endif
2206             strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2207             freez(*header);
2208             *header = strdup("Last-Modified: ");
2209             string_append(header, newheader);
2210
2211             if (*header == NULL)
2212             {
2213                log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2214                return JB_ERR_MEMORY;  
2215             }
2216
2217             if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2218             {
2219                days    = rtime / (3600 * 24);
2220                hours   = rtime / 3600 % 24;
2221                minutes = rtime / 60 % 60;
2222                seconds = rtime % 60;            
2223
2224                log_error(LOG_LEVEL_HEADER, "Randomized:  %s (added %d da%s %d hou%s %d minut%s %d second%s",
2225                   *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2226                   minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2227             }
2228          }
2229          else
2230          {
2231             log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2232          }
2233       }
2234    }
2235
2236    return JB_ERR_OK;
2237 }
2238
2239
2240 /*********************************************************************
2241  *
2242  * Function    :  client_accept_encoding
2243  *
2244  * Description :  Rewrite the client's Accept-Encoding header so that
2245  *                if doesn't allow compression, if the action applies.
2246  *                Note: For HTTP/1.0 the absence of the header is enough.
2247  *
2248  * Parameters  :
2249  *          1  :  csp = Current client state (buffers, headers, etc...)
2250  *          2  :  header = On input, pointer to header to modify.
2251  *                On output, pointer to the modified header, or NULL
2252  *                to remove the header.  This function frees the
2253  *                original string if necessary.
2254  *
2255  * Returns     :  JB_ERR_OK on success, or
2256  *                JB_ERR_MEMORY on out-of-memory error.
2257  *
2258  *********************************************************************/
2259 jb_err client_accept_encoding(struct client_state *csp, char **header)
2260 {
2261    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2262    {
2263       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2264
2265       freez(*header);
2266
2267       /* Temporarily disable the correct behaviour to
2268        * work around a PHP bug. 
2269        *
2270        * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2271        * {
2272        *    *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2273        *    if (*header == NULL)
2274        *    {
2275        *       return JB_ERR_MEMORY;
2276        *    }
2277        * }
2278        * 
2279        */
2280    }
2281
2282    return JB_ERR_OK;
2283 }
2284
2285
2286 /*********************************************************************
2287  *
2288  * Function    :  client_te
2289  *
2290  * Description :  Rewrite the client's TE header so that
2291  *                if doesn't allow compression, if the action applies.
2292  *
2293  * Parameters  :
2294  *          1  :  csp = Current client state (buffers, headers, etc...)
2295  *          2  :  header = On input, pointer to header to modify.
2296  *                On output, pointer to the modified header, or NULL
2297  *                to remove the header.  This function frees the
2298  *                original string if necessary.
2299  *
2300  * Returns     :  JB_ERR_OK on success, or
2301  *                JB_ERR_MEMORY on out-of-memory error.
2302  *
2303  *********************************************************************/
2304 jb_err client_te(struct client_state *csp, char **header)
2305 {
2306    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2307    {
2308       freez(*header);
2309       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2310    }
2311
2312    return JB_ERR_OK;
2313 }
2314
2315 /*********************************************************************
2316  *
2317  * Function    :  client_referrer
2318  *
2319  * Description :  Handle the "referer" config setting properly.
2320  *                Called from `sed'.
2321  *
2322  * Parameters  :
2323  *          1  :  csp = Current client state (buffers, headers, etc...)
2324  *          2  :  header = On input, pointer to header to modify.
2325  *                On output, pointer to the modified header, or NULL
2326  *                to remove the header.  This function frees the
2327  *                original string if necessary.
2328  *
2329  * Returns     :  JB_ERR_OK on success, or
2330  *                JB_ERR_MEMORY on out-of-memory error.
2331  *
2332  *********************************************************************/
2333 jb_err client_referrer(struct client_state *csp, char **header)
2334 {
2335    const char *newval;
2336    const char *host;
2337    char *referer;
2338    size_t hostlenght;
2339  
2340 #ifdef FEATURE_FORCE_LOAD
2341    /* Since the referrer can include the prefix even
2342     * if the request itself is non-forced, we must
2343     * clean it unconditionally
2344     */
2345    strclean(*header, FORCE_PREFIX);
2346 #endif /* def FEATURE_FORCE_LOAD */
2347
2348    /*
2349     * Are we sending referer?
2350     */
2351    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2352    {
2353       return JB_ERR_OK;
2354    }
2355
2356    newval = csp->action->string[ACTION_STRING_REFERER];
2357
2358    if ((0 != strcmpic(newval, "conditional-block")))
2359    {  
2360       freez(*header);
2361    }
2362    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2363    {
2364       /*
2365        * Blocking referer
2366        */
2367       log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2368       return JB_ERR_OK;
2369    }
2370    else if (0 == strcmpic(newval, "conditional-block"))
2371    {
2372       /*
2373        * Block referer if host has changed.
2374        */
2375
2376       if (NULL == (host = strdup(csp->http->hostport)))
2377       {
2378          freez(*header);
2379          log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
2380          return JB_ERR_MEMORY;
2381       }
2382       if (NULL == (referer = strdup(*header)))
2383       {
2384          freez(*header);
2385          freez(host);
2386          log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
2387          return JB_ERR_MEMORY;
2388       }
2389       hostlenght = strlen(host);
2390       if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
2391       {
2392          /*Shorten referer to make sure the referer is blocked
2393           *if www.example.org/www.example.com-shall-see-the-referer/
2394           *links to www.example.com/
2395           */
2396          referer[hostlenght+17] = '\0';
2397       }
2398       if ( 0 == strstr(referer, host)) /*Host has changed*/
2399       {
2400          log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
2401          freez(*header);
2402       }
2403       else
2404       {
2405          log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
2406       }
2407       freez(referer);
2408       freez(host);
2409       return JB_ERR_OK;    
2410    }
2411    else if (0 != strcmpic(newval, "forge"))
2412    {
2413       /*
2414        * We have a specific (fixed) referer we want to send.
2415        */
2416       if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
2417       {
2418          log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
2419       }
2420       *header = strdup("Referer: ");
2421       string_append(header, newval);
2422       log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
2423
2424       return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2425    }
2426    else
2427    {
2428       /*
2429        * Forge a referer as http://[hostname:port of REQUEST]/
2430        * to fool stupid checks for in-site links
2431        */
2432
2433       *header = strdup("Referer: http://");
2434       string_append(header, csp->http->hostport);
2435       string_append(header, "/");
2436       log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
2437       
2438       return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2439    }
2440 }
2441
2442 /*********************************************************************
2443  *
2444  * Function    :  client_accept_language
2445  *
2446  * Description :  Handle the "Accept-Language" config setting properly.
2447  *                Called from `sed'.
2448  *
2449  * Parameters  :
2450  *          1  :  csp = Current client state (buffers, headers, etc...)
2451  *          2  :  header = On input, pointer to header to modify.
2452  *                On output, pointer to the modified header, or NULL
2453  *                to remove the header.  This function frees the
2454  *                original string if necessary.
2455  *
2456  * Returns     :  JB_ERR_OK on success, or
2457  *                JB_ERR_MEMORY on out-of-memory error.
2458  *
2459  *********************************************************************/
2460 jb_err client_accept_language(struct client_state *csp, char **header)
2461 {
2462    const char *newval;
2463
2464    /*
2465     * Are we messing with the Accept-Language?
2466     */
2467    if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2468    {
2469       /*I don't think so*/
2470       return JB_ERR_OK;
2471    }
2472
2473    newval = csp->action->string[ACTION_STRING_LANGUAGE];
2474
2475    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2476    {
2477       /*
2478        * Blocking Accept-Language header
2479        */
2480       log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2481       freez(*header);
2482       return JB_ERR_OK;
2483    }
2484    else
2485    {  
2486       /*
2487        * Replacing Accept-Language header
2488        */
2489       freez(*header);
2490       *header = strdup("Accept-Language: ");
2491       string_append(header, newval);   
2492
2493       if (*header == NULL)
2494       {
2495          log_error(LOG_LEVEL_ERROR,
2496             "Insufficent memory. Accept-Language header crunched without replacement.");  
2497       }
2498       else
2499       {
2500          log_error(LOG_LEVEL_HEADER,
2501             "Accept-Language header crunched and replaced with: %s", *header);
2502       }
2503    }
2504    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2505 }
2506
2507 /*********************************************************************
2508  *
2509  * Function    :  crunch_client_header
2510  *
2511  * Description :  Crunch client header if it matches a string supplied by the
2512  *                user. Called from `sed'.
2513  *
2514  * Parameters  :
2515  *          1  :  csp = Current client state (buffers, headers, etc...)
2516  *          2  :  header = On input, pointer to header to modify.
2517  *                On output, pointer to the modified header, or NULL
2518  *                to remove the header.  This function frees the
2519  *                original string if necessary.
2520  *
2521  * Returns     :  JB_ERR_OK on success and always succeeds
2522  *
2523  *********************************************************************/
2524 jb_err crunch_client_header(struct client_state *csp, char **header)
2525 {
2526    const char *crunch_pattern;
2527
2528    /* Do we feel like crunching? */
2529    if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2530    {
2531       crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2532
2533       /* Is the current header the lucky one? */
2534       if (strstr(*header, crunch_pattern))
2535       {
2536          log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);  
2537          freez(*header);
2538       }
2539    }
2540    return JB_ERR_OK;
2541 }
2542
2543
2544 /*********************************************************************
2545  *
2546  * Function    :  client_uagent
2547  *
2548  * Description :  Handle the "user-agent" config setting properly
2549  *                and remember its original value to enable browser
2550  *                bug workarounds. Called from `sed'.
2551  *
2552  * Parameters  :
2553  *          1  :  csp = Current client state (buffers, headers, etc...)
2554  *          2  :  header = On input, pointer to header to modify.
2555  *                On output, pointer to the modified header, or NULL
2556  *                to remove the header.  This function frees the
2557  *                original string if necessary.
2558  *
2559  * Returns     :  JB_ERR_OK on success, or
2560  *                JB_ERR_MEMORY on out-of-memory error.
2561  *
2562  *********************************************************************/
2563 jb_err client_uagent(struct client_state *csp, char **header)
2564 {
2565    const char *newval;
2566
2567    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2568    {
2569       return JB_ERR_OK;
2570    }
2571
2572    newval = csp->action->string[ACTION_STRING_USER_AGENT];
2573    if (newval == NULL)
2574    {
2575       return JB_ERR_OK;
2576    }
2577
2578    freez(*header);
2579    *header = strdup("User-Agent: ");
2580    string_append(header, newval);
2581
2582    log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2583
2584    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2585 }
2586
2587 /*********************************************************************
2588  *
2589  * Function    :  client_ua
2590  *
2591  * Description :  Handle "ua-" headers properly.  Called from `sed'.
2592  *
2593  * Parameters  :
2594  *          1  :  csp = Current client state (buffers, headers, etc...)
2595  *          2  :  header = On input, pointer to header to modify.
2596  *                On output, pointer to the modified header, or NULL
2597  *                to remove the header.  This function frees the
2598  *                original string if necessary.
2599  *
2600  * Returns     :  JB_ERR_OK on success, or
2601  *                JB_ERR_MEMORY on out-of-memory error.
2602  *
2603  *********************************************************************/
2604 jb_err client_ua(struct client_state *csp, char **header)
2605 {
2606    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2607    {
2608       log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2609       freez(*header);
2610    }
2611
2612    return JB_ERR_OK;
2613 }
2614
2615
2616 /*********************************************************************
2617  *
2618  * Function    :  client_from
2619  *
2620  * Description :  Handle the "from" config setting properly.
2621  *                Called from `sed'.
2622  *
2623  * Parameters  :
2624  *          1  :  csp = Current client state (buffers, headers, etc...)
2625  *          2  :  header = On input, pointer to header to modify.
2626  *                On output, pointer to the modified header, or NULL
2627  *                to remove the header.  This function frees the
2628  *                original string if necessary.
2629  *
2630  * Returns     :  JB_ERR_OK on success, or
2631  *                JB_ERR_MEMORY on out-of-memory error.
2632  *
2633  *********************************************************************/
2634 jb_err client_from(struct client_state *csp, char **header)
2635 {
2636    const char *newval;
2637
2638    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2639    {
2640       return JB_ERR_OK;
2641    }
2642
2643    freez(*header);
2644
2645    newval = csp->action->string[ACTION_STRING_FROM];
2646
2647    /*
2648     * Are we blocking the e-mail address?
2649     */
2650    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2651    {
2652       log_error(LOG_LEVEL_HEADER, "crunched From!");
2653       return JB_ERR_OK;
2654    }
2655
2656    log_error(LOG_LEVEL_HEADER, " modified");
2657
2658    *header = strdup("From: ");
2659    string_append(header, newval);
2660
2661    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2662 }
2663
2664
2665 /*********************************************************************
2666  *
2667  * Function    :  client_send_cookie
2668  *
2669  * Description :  Crunches the "cookie" header if necessary.
2670  *                Called from `sed'.
2671  *
2672  *                XXX: Stupid name, doesn't send squat.
2673  *
2674  * Parameters  :
2675  *          1  :  csp = Current client state (buffers, headers, etc...)
2676  *          2  :  header = On input, pointer to header to modify.
2677  *                On output, pointer to the modified header, or NULL
2678  *                to remove the header.  This function frees the
2679  *                original string if necessary.
2680  *
2681  * Returns     :  JB_ERR_OK on success, or
2682  *                JB_ERR_MEMORY on out-of-memory error.
2683  *
2684  *********************************************************************/
2685 jb_err client_send_cookie(struct client_state *csp, char **header)
2686 {
2687    if (csp->action->flags & ACTION_NO_COOKIE_READ)
2688    {
2689       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2690       freez(*header);
2691    }
2692
2693    return JB_ERR_OK;
2694 }
2695
2696
2697 /*********************************************************************
2698  *
2699  * Function    :  client_x_forwarded
2700  *
2701  * Description :  Handle the "x-forwarded-for" config setting properly,
2702  *                also used in the add_client_headers list.  Called from `sed'.
2703  *
2704  * Parameters  :
2705  *          1  :  csp = Current client state (buffers, headers, etc...)
2706  *          2  :  header = On input, pointer to header to modify.
2707  *                On output, pointer to the modified header, or NULL
2708  *                to remove the header.  This function frees the
2709  *                original string if necessary.
2710  *
2711  * Returns     :  JB_ERR_OK on success, or
2712  *                JB_ERR_MEMORY on out-of-memory error.
2713  *
2714  *********************************************************************/
2715 jb_err client_x_forwarded(struct client_state *csp, char **header)
2716 {
2717    if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2718    {
2719       /* Save it so we can re-add it later */
2720       freez(csp->x_forwarded);
2721       csp->x_forwarded = *header;
2722
2723       /*
2724        * Always set *header = NULL, since this information
2725        * will be sent at the end of the header.
2726        */
2727       *header = NULL;
2728    }
2729    else
2730    {
2731       freez(*header);
2732       log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2733    }
2734
2735    return JB_ERR_OK;
2736 }
2737
2738
2739 /*********************************************************************
2740  *
2741  * Function    :  client_max_forwards
2742  *
2743  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
2744  *                from the value of the Max-Forwards header field.
2745  *
2746  * Parameters  :
2747  *          1  :  csp = Current client state (buffers, headers, etc...)
2748  *          2  :  header = On input, pointer to header to modify.
2749  *                On output, pointer to the modified header, or NULL
2750  *                to remove the header.  This function frees the
2751  *                original string if necessary.
2752  *
2753  * Returns     :  JB_ERR_OK on success, or
2754  *                JB_ERR_MEMORY on out-of-memory error.
2755  *
2756  *********************************************************************/
2757 jb_err client_max_forwards(struct client_state *csp, char **header)
2758 {
2759    int max_forwards;
2760
2761    if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2762        (0 == strcmpic(csp->http->gpc, "options")))
2763    {
2764       assert(*(*header+12) == ':');
2765       if (1 == sscanf(*header+12, ": %u", &max_forwards))
2766       {
2767          if (max_forwards > 0)
2768          {
2769             snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
2770             log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
2771                csp->http->gpc, max_forwards);
2772          }
2773          else if (max_forwards < 0)
2774          {
2775             log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2776             freez(*header);
2777          }
2778          else
2779          {
2780             /*
2781              * Not supposed to be reached. direct_response() which
2782              * was already called earlier in chat() should have
2783              * intercepted the request.
2784              */
2785             log_error(LOG_LEVEL_ERROR,
2786                "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2787             assert(max_forwards != 0);
2788          }
2789       }
2790       else
2791       {
2792          log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2793          freez(*header);
2794       }
2795    }
2796
2797    return JB_ERR_OK;
2798 }
2799
2800
2801 /*********************************************************************
2802  *
2803  * Function    :  client_host
2804  *
2805  * Description :  If the request URI did not contain host and
2806  *                port information, parse and evaluate the Host
2807  *                header field.
2808  *
2809  *                Also, kill ill-formed HOST: headers as sent by
2810  *                Apple's iTunes software when used with a proxy.
2811  *
2812  * Parameters  :
2813  *          1  :  csp = Current client state (buffers, headers, etc...)
2814  *          2  :  header = On input, pointer to header to modify.
2815  *                On output, pointer to the modified header, or NULL
2816  *                to remove the header.  This function frees the
2817  *                original string if necessary.
2818  *
2819  * Returns     :  JB_ERR_OK on success, or
2820  *                JB_ERR_MEMORY on out-of-memory error.
2821  *
2822  *********************************************************************/
2823 jb_err client_host(struct client_state *csp, char **header)
2824 {
2825    char *p, *q;
2826
2827    /*
2828     * If the header field name is all upper-case, chances are that it's
2829     * an ill-formed one from iTunes. BTW, killing innocent headers here is
2830     * not a problem -- they are regenerated later.
2831     */
2832    if ((*header)[1] == 'O')
2833    {
2834       log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2835       freez(*header);
2836       return JB_ERR_OK;
2837    }
2838
2839    if (!csp->http->hostport || (*csp->http->hostport == '*') ||  
2840        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2841    {
2842       
2843       if (NULL == (p = strdup((*header)+6)))
2844       {
2845          return JB_ERR_MEMORY;
2846       }
2847       chomp(p);
2848       if (NULL == (q = strdup(p)))
2849       {
2850          freez(p);
2851          return JB_ERR_MEMORY;
2852       }
2853
2854       freez(csp->http->hostport);
2855       csp->http->hostport = p;
2856       freez(csp->http->host);
2857       csp->http->host = q;
2858       q = strchr(csp->http->host, ':');
2859       if (q != NULL)
2860       {
2861          /* Terminate hostname and evaluate port string */
2862          *q++ = '\0';
2863          csp->http->port = atoi(q);
2864       }
2865       else
2866       {
2867          csp->http->port = csp->http->ssl ? 443 : 80;
2868       }
2869
2870       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2871                 csp->http->hostport, csp->http->host, csp->http->port);
2872    }
2873
2874    /* Signal client_host_adder() to return right away */
2875    csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2876
2877    return JB_ERR_OK;
2878 }
2879
2880 /*********************************************************************
2881  *
2882  * Function    :  client_if_modified_since
2883  *
2884  * Description :  Remove or modify the If-Modified-Since header.
2885  *
2886  * Parameters  :
2887  *          1  :  csp = Current client state (buffers, headers, etc...)
2888  *          2  :  header = On input, pointer to header to modify.
2889  *                On output, pointer to the modified header, or NULL
2890  *                to remove the header.  This function frees the
2891  *                original string if necessary.
2892  *
2893  * Returns     :  JB_ERR_OK on success, or
2894  *                JB_ERR_MEMORY on out-of-memory error.
2895  *
2896  *********************************************************************/
2897 jb_err client_if_modified_since(struct client_state *csp, char **header)
2898 {
2899    char newheader[50];
2900 #ifdef HAVE_GMTIME_R
2901    struct tm gmt;
2902 #endif
2903    struct tm *timeptr = NULL;
2904    time_t tm = 0;                  
2905    const char *newval;
2906    long int rtime;
2907    long int hours, minutes, seconds;
2908    int negative = 0;
2909    char * endptr;
2910    
2911    if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2912    {
2913       /* 
2914        * The client got an error message because of a temporary problem,
2915        * the problem is gone and the client now tries to revalidate our
2916        * error message on the real server. The revalidation would always
2917        * end with the transmission of the whole document and there is
2918        * no need to expose the bogus If-Modified-Since header.
2919        */
2920       log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2921       freez(*header);
2922    }
2923    else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2924    {
2925       newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2926
2927       if ((0 == strcmpic(newval, "block")))
2928       {
2929          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2930          freez(*header);
2931       }
2932       else /* add random value */
2933       {
2934          if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2935          {
2936             log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2937             freez(*header);
2938          }
2939          else
2940          {
2941             rtime = strtol(newval, &endptr, 0);
2942             if(rtime)
2943             {
2944                log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2945                   *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2946                if(rtime < 0)
2947                {
2948                   rtime *= -1; 
2949                   negative = 1;
2950                }
2951                rtime *= 60;
2952                rtime = pick_from_range(rtime);
2953             }
2954             else
2955             {
2956                log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2957                   *header);
2958             }
2959             tm += rtime * (negative ? -1 : 1);
2960 #ifdef HAVE_GMTIME_R
2961             timeptr = gmtime_r(&tm, &gmt);
2962 #elif FEATURE_PTHREAD
2963             pthread_mutex_lock(&gmtime_mutex);
2964             timeptr = gmtime(&tm);
2965             pthread_mutex_unlock(&gmtime_mutex);
2966 #else
2967             timeptr = gmtime(&tm);
2968 #endif
2969             strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2970
2971             freez(*header);
2972             *header = strdup("If-Modified-Since: ");
2973             string_append(header, newheader);
2974
2975             if (*header == NULL)
2976             {
2977                log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2978                return JB_ERR_MEMORY;  
2979             }
2980
2981             if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2982             {
2983                hours   = rtime / 3600;
2984                minutes = rtime / 60 % 60;
2985                seconds = rtime % 60;            
2986
2987                log_error(LOG_LEVEL_HEADER, "Randomized:  %s (%s %d hou%s %d minut%s %d second%s",
2988                   *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2989                   minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2990             }
2991          }
2992       }
2993    }
2994
2995    return JB_ERR_OK;
2996 }
2997
2998 /*********************************************************************
2999  *
3000  * Function    :  client_if_none_match
3001  *
3002  * Description :  Remove the If-None-Match header.
3003  *
3004  * Parameters  :
3005  *          1  :  csp = Current client state (buffers, headers, etc...)
3006  *          2  :  header = On input, pointer to header to modify.
3007  *                On output, pointer to the modified header, or NULL
3008  *                to remove the header.  This function frees the
3009  *                original string if necessary.
3010  *
3011  * Returns     :  JB_ERR_OK on success, or
3012  *                JB_ERR_MEMORY on out-of-memory error.
3013  *
3014  *********************************************************************/
3015 jb_err client_if_none_match(struct client_state *csp, char **header)
3016 {
3017    if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3018    {  
3019       log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3020       freez(*header);
3021    }
3022
3023    return JB_ERR_OK;
3024 }
3025
3026 /*********************************************************************
3027  *
3028  * Function    :  client_x_filter
3029  *
3030  * Description :  Disables filtering if the client set "X-Filter: No".
3031  *                Called from `sed'.
3032  *
3033  * Parameters  :
3034  *          1  :  csp = Current client state (buffers, headers, etc...)
3035  *          2  :  header = On input, pointer to header to modify.
3036  *                On output, pointer to the modified header, or NULL
3037  *                to remove the header.  This function frees the
3038  *                original string if necessary.
3039  *
3040  * Returns     :  JB_ERR_OK on success
3041  *
3042  *********************************************************************/
3043 jb_err client_x_filter(struct client_state *csp, char **header)
3044 {
3045    if ( 0 == strcmpic(*header, "X-Filter: No"))
3046    {
3047       if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3048       {
3049          log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3050       }
3051       else
3052       {
3053          if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3054          {
3055             log_error(LOG_LEVEL_HEADER,
3056                "force-text-mode overruled the client's request to fetch without filtering!");
3057          }
3058          else
3059          {  
3060             csp->content_type = CT_TABOO;
3061             csp->action->flags &= ~ACTION_FILTER_SERVER_HEADERS;
3062             csp->action->flags &= ~ACTION_FILTER_CLIENT_HEADERS;
3063             log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3064          }
3065          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3066          freez(*header);
3067       }
3068    }
3069    return JB_ERR_OK; 
3070 }
3071
3072 /* the following functions add headers directly to the header list */
3073
3074 /*********************************************************************
3075  *
3076  * Function    :  client_host_adder
3077  *
3078  * Description :  Adds the Host: header field if it is missing.
3079  *                Called from `sed'.
3080  *
3081  * Parameters  :
3082  *          1  :  csp = Current client state (buffers, headers, etc...)
3083  *
3084  * Returns     :  JB_ERR_OK on success, or
3085  *                JB_ERR_MEMORY on out-of-memory error.
3086  *
3087  *********************************************************************/
3088 jb_err client_host_adder(struct client_state *csp)
3089 {
3090    char *p;
3091    jb_err err;
3092
3093    if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3094    {
3095       /* Header already set by the client, nothing to do. */
3096       return JB_ERR_OK;
3097    }
3098
3099    if ( !csp->http->hostport || !*(csp->http->hostport))
3100    {
3101       /* XXX: When does this happen and why is it OK? */
3102       log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3103       return JB_ERR_OK;
3104    }
3105
3106    /*
3107     * remove 'user:pass@' from 'proto://user:pass@host'
3108     */
3109    if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3110    {
3111       p++;
3112    }
3113    else
3114    {
3115       p = csp->http->hostport;
3116    }
3117
3118    /* XXX: Just add it, we already made sure that it will be unique */
3119    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3120    err = enlist_unique_header(csp->headers, "Host", p);
3121    return err;
3122
3123 }
3124
3125
3126 /*********************************************************************
3127  *
3128  * Function    :  client_cookie_adder
3129  *
3130  * Description :  Used in the add_client_headers list.  Called from `sed'.
3131  *
3132  *                XXX: Remove csp->cookie_list which is no longer used.
3133  *
3134  * Parameters  :
3135  *          1  :  csp = Current client state (buffers, headers, etc...)
3136  *
3137  * Returns     :  JB_ERR_OK on success, or
3138  *                JB_ERR_MEMORY on out-of-memory error.
3139  *
3140  *********************************************************************/
3141 jb_err client_cookie_adder(struct client_state *csp)
3142 {
3143    struct list_entry *lst;
3144    char *tmp;
3145    struct list_entry *list1 = csp->cookie_list->first;
3146    struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
3147    int first_cookie = 1;
3148    jb_err err;
3149
3150    if ((list1 == NULL) && (list2 == NULL))
3151    {
3152       /* Nothing to do */
3153       return JB_ERR_OK;
3154    }
3155
3156    tmp = strdup("Cookie: ");
3157
3158    for (lst = list1; lst ; lst = lst->next)
3159    {
3160       if (first_cookie)
3161       {
3162          first_cookie = 0;
3163       }
3164       else
3165       {
3166          string_append(&tmp, "; ");
3167       }
3168       string_append(&tmp, lst->str);
3169    }
3170
3171    for (lst = list2;  lst ; lst = lst->next)
3172    {
3173       if (first_cookie)
3174       {
3175          first_cookie = 0;
3176       }
3177       else
3178       {
3179          string_append(&tmp, "; ");
3180       }
3181       string_join(&tmp, cookie_encode(lst->str));
3182    }
3183
3184    if (tmp == NULL)
3185    {
3186       return JB_ERR_MEMORY;
3187    }
3188
3189    log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3190    err = enlist(csp->headers, tmp);
3191    free(tmp);
3192    return err;
3193 }
3194
3195
3196 /*********************************************************************
3197  *
3198  * Function    :  client_accept_encoding_adder
3199  *
3200  * Description :  Add an Accept-Encoding header to the client's request
3201  *                that disables compression if the action applies, and
3202  *                the header is not already there. Called from `sed'.
3203  *                Note: For HTTP/1.0, the absence of the header is enough.
3204  *
3205  * Parameters  :
3206  *          1  :  csp = Current client state (buffers, headers, etc...)
3207  *
3208  * Returns     :  JB_ERR_OK on success, or
3209  *                JB_ERR_MEMORY on out-of-memory error.
3210  *
3211  *********************************************************************/
3212 jb_err client_accept_encoding_adder(struct client_state *csp)
3213 {
3214    assert(0); /* Not in use */
3215
3216    if (   ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3217        && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3218    {
3219       return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3220    }
3221
3222    return JB_ERR_OK;
3223 }
3224
3225
3226 /*********************************************************************
3227  *
3228  * Function    :  client_xtra_adder
3229  *
3230  * Description :  Used in the add_client_headers list.  Called from `sed'.
3231  *
3232  * Parameters  :
3233  *          1  :  csp = Current client state (buffers, headers, etc...)
3234  *
3235  * Returns     :  JB_ERR_OK on success, or
3236  *                JB_ERR_MEMORY on out-of-memory error.
3237  *
3238  *********************************************************************/
3239 jb_err client_xtra_adder(struct client_state *csp)
3240 {
3241    struct list_entry *lst;
3242    jb_err err;
3243
3244    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3245         lst ; lst = lst->next)
3246    {
3247       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3248       err = enlist(csp->headers, lst->str);
3249       if (err)
3250       {
3251          return err;
3252       }
3253
3254    }
3255
3256    return JB_ERR_OK;
3257 }
3258
3259
3260 /*********************************************************************
3261  *
3262  * Function    :  client_x_forwarded_adder
3263  *
3264  * Description :  Used in the add_client_headers list.  Called from `sed'.
3265  *
3266  * Parameters  :
3267  *          1  :  csp = Current client state (buffers, headers, etc...)
3268  *
3269  * Returns     :  JB_ERR_OK on success, or
3270  *                JB_ERR_MEMORY on out-of-memory error.
3271  *
3272  *********************************************************************/
3273 jb_err client_x_forwarded_adder(struct client_state *csp)
3274 {
3275    char *p = NULL;
3276    jb_err err;
3277
3278    if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3279    {
3280       return JB_ERR_OK;
3281    }
3282
3283    if (csp->x_forwarded)
3284    {
3285       p = strdup(csp->x_forwarded);
3286       string_append(&p, ", ");
3287    }
3288    else
3289    {
3290       p = strdup("X-Forwarded-For: ");
3291    }
3292    string_append(&p, csp->ip_addr_str);
3293
3294    if (p == NULL)
3295    {
3296       return JB_ERR_MEMORY;
3297    }
3298
3299    log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3300    err = enlist(csp->headers, p);
3301    free(p);
3302
3303    return err;
3304 }
3305
3306
3307 /*********************************************************************
3308  *
3309  * Function    :  connection_close_adder
3310  *
3311  * Description :  "Temporary" fix for the needed but missing HTTP/1.1
3312  *                support. Adds a "Connection: close" header to csp->headers
3313  *                unless the header was already present. Called from `sed'.
3314  *
3315  *                FIXME: This whole function shouldn't be neccessary!
3316  *
3317  * Parameters  :
3318  *          1  :  csp = Current client state (buffers, headers, etc...)
3319  *
3320  * Returns     :  JB_ERR_OK on success, or
3321  *                JB_ERR_MEMORY on out-of-memory error.
3322  *
3323  *********************************************************************/
3324 jb_err connection_close_adder(struct client_state *csp)
3325 {
3326    const unsigned int flags = csp->flags;
3327
3328    /*
3329     * Return right away if
3330     *
3331     * - we're parsing server headers and the server header
3332     *   "Connection: close" is already set, or if
3333     *
3334     * - we're parsing client headers and the client header 
3335     *   "Connection: close" is already set.
3336     */
3337    if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3338      && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3339    ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3340      && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3341    {
3342       return JB_ERR_OK;
3343    }
3344
3345    log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3346
3347    return enlist(csp->headers, "Connection: close");
3348 }
3349
3350
3351 /*********************************************************************
3352  *
3353  * Function    :  server_http
3354  *
3355  * Description :  - Save the HTTP Status into csp->http->status
3356  *                - Set CT_TABOO to prevent filtering if the answer
3357  *                  is a partial range (HTTP status 206)
3358  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3359  *                  action applies.
3360  *
3361  * Parameters  :
3362  *          1  :  csp = Current client state (buffers, headers, etc...)
3363  *          2  :  header = On input, pointer to header to modify.
3364  *                On output, pointer to the modified header, or NULL
3365  *                to remove the header.  This function frees the
3366  *                original string if necessary.
3367  *
3368  * Returns     :  JB_ERR_OK on success, or
3369  *                JB_ERR_MEMORY on out-of-memory error.
3370  *
3371  *********************************************************************/
3372 jb_err server_http(struct client_state *csp, char **header)
3373 {
3374    /* Signal that were now parsing server headers. */
3375    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
3376
3377    sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3378    if (csp->http->status == 206)
3379    {
3380       csp->content_type = CT_TABOO;
3381    }
3382
3383    if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3384    {
3385       (*header)[7] = '0';
3386       log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3387    }
3388
3389    return JB_ERR_OK;
3390 }
3391
3392
3393 /*********************************************************************
3394  *
3395  * Function    :  server_set_cookie
3396  *
3397  * Description :  Handle the server "cookie" header properly.
3398  *                Log cookie to the jar file.  Then "crunch",
3399  *                accept or rewrite it to a session cookie.
3400  *                Called from `sed'.
3401  *
3402  *                TODO: Allow the user to specify a new expiration
3403  *                time to cause the cookie to expire even before the
3404  *                browser is closed.
3405  *
3406  * Parameters  :
3407  *          1  :  csp = Current client state (buffers, headers, etc...)
3408  *          2  :  header = On input, pointer to header to modify.
3409  *                On output, pointer to the modified header, or NULL
3410  *                to remove the header.  This function frees the
3411  *                original string if necessary.
3412  *
3413  * Returns     :  JB_ERR_OK on success, or
3414  *                JB_ERR_MEMORY on out-of-memory error.
3415  *
3416  *********************************************************************/
3417 jb_err server_set_cookie(struct client_state *csp, char **header)
3418 {
3419    time_t now;
3420    time_t cookie_time; 
3421    struct tm tm_now; 
3422    struct tm tm_cookie;
3423    time(&now);
3424
3425 #ifdef FEATURE_COOKIE_JAR
3426    if (csp->config->jar)
3427    {
3428       /*
3429        * Write timestamp into outbuf.
3430        *
3431        * Complex because not all OSs have tm_gmtoff or
3432        * the %z field in strftime()
3433        */
3434       char tempbuf[ BUFFER_SIZE ];
3435  
3436 #ifdef HAVE_LOCALTIME_R
3437       tm_now = *localtime_r(&now, &tm_now);
3438 #elif FEATURE_PTHREAD
3439       pthread_mutex_lock(&localtime_mutex);
3440       tm_now = *localtime (&now);
3441       pthread_mutex_unlock(&localtime_mutex);
3442 #else
3443       tm_now = *localtime (&now);
3444 #endif
3445       strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now); 
3446
3447       /* strlen("set-cookie: ") = 12 */
3448       fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3449    }
3450 #endif /* def FEATURE_COOKIE_JAR */
3451
3452    if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3453    {
3454       log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
3455       return crumble(csp, header);
3456    }
3457    else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3458    {
3459       /* Flag whether or not to log a message */
3460       int changed = 0;
3461
3462       /* A variable to store the tag we're working on */
3463       char *cur_tag;
3464
3465       /* Skip "Set-Cookie:" (11 characters) in header */
3466       cur_tag = *header + 11;
3467
3468       /* skip whitespace between "Set-Cookie:" and value */
3469       while (*cur_tag && ijb_isspace(*cur_tag))
3470       {
3471          cur_tag++;
3472       }
3473
3474       /* Loop through each tag in the cookie */
3475       while (*cur_tag)
3476       {
3477          /* Find next tag */
3478          char *next_tag = strchr(cur_tag, ';');
3479          if (next_tag != NULL)
3480          {
3481             /* Skip the ';' character itself */
3482             next_tag++;
3483
3484             /* skip whitespace ";" and start of tag */
3485             while (*next_tag && ijb_isspace(*next_tag))
3486             {
3487                next_tag++;
3488             }
3489          }
3490          else
3491          {
3492             /* "Next tag" is the end of the string */
3493             next_tag = cur_tag + strlen(cur_tag);
3494          }
3495
3496          /*
3497           * Check the expiration date to see
3498           * if the cookie is still valid, if yes,
3499           * rewrite it to a session cookie.
3500           */
3501          if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3502          {
3503             char *match;
3504             const char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3505             memset(&tm_cookie, 0, sizeof(tm_cookie));
3506             /*
3507              * Try the valid time formats we know about.
3508              *
3509              * XXX: This should be moved to parse_header_time().
3510              *
3511              * XXX: Maybe the log messages should be removed
3512              * for the next stable release. They just exist to
3513              * see which time format gets the most hits and
3514              * should be checked for first.
3515              */
3516             if (NULL != (match = strptime(expiration_date, "%a, %e-%b-%y %H:%M:%S ", &tm_cookie)))
3517             {
3518                /* 22-Feb-2008 12:01:18 GMT */
3519                log_error(LOG_LEVEL_HEADER,
3520                   "cookie \'%s\' send by %s appears to be using time format 1.",
3521                   *header, csp->http->url);
3522             }
3523             else if (NULL != (match = strptime(expiration_date, "%A, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3524             {
3525                /* Tue, 02-Jun-2037 20:00:00 GMT */
3526                log_error(LOG_LEVEL_HEADER,
3527                   "cookie \'%s\' send by %s appears to be using time format 2.",
3528                   *header, csp->http->url);
3529             }
3530             else if (NULL != (match = strptime(expiration_date, "%a, %e-%b-%Y %H:%M:%S ", &tm_cookie)))
3531             {
3532                /* Tuesday, 02-Jun-2037 20:00:00 GMT */
3533                /*
3534                 * On FreeBSD this is never reached because it's handled
3535                 * by "format 2" as well. I am, however, not sure if all
3536                 * strptime() implementations behave that way.
3537                 */
3538                log_error(LOG_LEVEL_HEADER,
3539                   "cookie \'%s\' send by %s appears to be using time format 3.",
3540                    *header, csp->http->url);
3541             }
3542             else if (NULL != (match = strptime(expiration_date, "%a, %e %b %Y %H:%M:%S ", &tm_cookie)))
3543             {
3544                /* Fri, 22 Feb 2008 19:20:05 GMT */
3545                log_error(LOG_LEVEL_HEADER,
3546                   "cookie \'%s\' send by %s appears to be using time format 4.",
3547                    *header, csp->http->url);
3548             }
3549             else if (NULL != (match = strptime(expiration_date, "%A %b %e %H:%M:%S %Y", &tm_cookie)))
3550             {
3551                /* Thu Mar 08 23:00:00 2007 GMT */
3552                log_error(LOG_LEVEL_HEADER,
3553                   "cookie \'%s\' send by %s appears to be using time format 5.",
3554                    *header, csp->http->url);
3555             }
3556
3557             /* Did any of them match? */
3558             if (NULL == match)
3559             {
3560                /*
3561                 * Nope, treat it as if it was still valid.
3562                 *
3563                 * XXX: Should we remove the whole cookie instead?
3564                 */
3565                log_error(LOG_LEVEL_ERROR,
3566                   "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3567                memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3568                changed = 1;
3569             }
3570             else
3571             {
3572                /*
3573                 * Yes. Check if the cookie is still valid.
3574                 *
3575                 * If the cookie is already expired it's probably
3576                 * a delete cookie and even if it isn't, the browser
3577                 * will discard it anyway.
3578                 */
3579
3580                /*
3581                 * XXX: timegm() isn't available on some AmigaOS
3582                 * versions and our replacement doesn't work.
3583                 *
3584                 * Our options are to either:
3585                 *
3586                 * - disable session-cookies-only completely if timegm
3587                 *   is missing,
3588                 *
3589                 * - to simply remove all expired tags, like it has
3590                 *   been done until Privoxy 3.0.6 and to live with
3591                 *    the consequence that it can cause login/logout
3592                 *   problems on servers that don't validate their
3593                 *   input properly, or
3594                 *
3595                 * - to replace it with mktime in which
3596                 *   case there is a slight chance of valid cookies
3597                 *   passing as already expired.
3598                 *
3599                 *   This is the way it's currently done and it's not
3600                 *   as bad as it sounds. If the missing GMT offset is
3601                 *   enough to change the result of the expiration check
3602                 *   the cookie will be only valid for a few hours
3603                 *   anyway, which in many cases will be shorter
3604                 *   than a browser session.
3605                 */
3606                cookie_time = timegm(&tm_cookie);
3607                if (cookie_time - now < 0)
3608                {
3609                   log_error(LOG_LEVEL_HEADER,
3610                      "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3611                   /* Just in case some clown sets more then one expiration date */
3612                   cur_tag = next_tag;
3613                }
3614                else
3615                {
3616                   /*
3617                    * Still valid, delete expiration date by copying
3618                    * the rest of the string over it.
3619                    *
3620                    * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3621                    * since the behaviour of strcpy is undefined for overlapping
3622                    * strings.)
3623                    */
3624                   memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3625
3626                   /* That changed the header, need to issue a log message */
3627                   changed = 1;
3628
3629                   /*
3630                    * Note that the next tag has now been moved to *cur_tag,
3631                    * so we do not need to update the cur_tag pointer.
3632                    */
3633                }
3634             }
3635
3636          }
3637          else
3638          {
3639             /* Move on to next cookie tag */
3640             cur_tag = next_tag;
3641          }
3642       }
3643
3644       if (changed)
3645       {
3646          assert(NULL != *header);
3647          log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3648             *header);
3649       }
3650    }
3651
3652    return JB_ERR_OK;
3653 }
3654
3655
3656 #ifdef FEATURE_FORCE_LOAD
3657 /*********************************************************************
3658  *
3659  * Function    :  strclean
3660  *
3661  * Description :  In-Situ-Eliminate all occurances of substring in
3662  *                string
3663  *
3664  * Parameters  :
3665  *          1  :  string = string to clean
3666  *          2  :  substring = substring to eliminate
3667  *
3668  * Returns     :  Number of eliminations
3669  *
3670  *********************************************************************/
3671 int strclean(const char *string, const char *substring)
3672 {
3673    int hits = 0;
3674    size_t len;
3675    char *pos, *p;
3676
3677    len = strlen(substring);
3678
3679    while((pos = strstr(string, substring)) != NULL)
3680    {
3681       p = pos + len;
3682       do
3683       {
3684          *(p - len) = *p;
3685       }
3686       while (*p++ != '\0');
3687
3688       hits++;
3689    }
3690
3691    return(hits);
3692 }
3693 #endif /* def FEATURE_FORCE_LOAD */
3694
3695 /*********************************************************************
3696  *
3697  * Function    :  parse_header_time
3698  *
3699  * Description :  Transforms time inside a HTTP header into
3700  *                the usual time format.
3701  *
3702  * Parameters  :
3703  *          1  :  header = header to parse
3704  *          2  :  tm = storage for the resulting time in seconds 
3705  *
3706  * Returns     :  Time struct containing the header time, or
3707  *                NULL in case of a parsing problems.
3708  *
3709  *********************************************************************/
3710 struct tm *parse_header_time(char *header, time_t *tm) {
3711
3712    char * timestring;
3713    struct tm gmt;
3714    struct tm * timeptr;
3715
3716    /*
3717     * Initializing gmt to prevent time zone offsets.
3718     *
3719     * While this is only necessary on some platforms
3720     * (mingw32 for example), I don't know how to
3721     * detect these automatically and doing it everywhere
3722     * shouldn't hurt.
3723     */
3724    time(tm); 
3725 #ifdef HAVE_LOCALTIME_R
3726    gmt = *localtime_r(tm, &gmt);
3727 #elif FEATURE_PTHREAD
3728    pthread_mutex_lock(&localtime_mutex);
3729    gmt = *localtime(tm); 
3730    pthread_mutex_unlock(&localtime_mutex);
3731 #else
3732    gmt = *localtime(tm); 
3733 #endif
3734
3735    /* Skipping header name */
3736    timestring = strstr(header, ": ");
3737    if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)
3738    {
3739       timeptr = NULL;
3740    }
3741    else
3742    {
3743       *tm = timegm(&gmt);
3744       timeptr = &gmt;
3745    }
3746    return(timeptr);
3747
3748 }
3749
3750 /*********************************************************************
3751  *
3752  * Function    :  get_destination_from_headers
3753  *
3754  * Description :  Parse the "Host:" header to get the request's destination.
3755  *                Only needed if the client's request was forcefully
3756  *                redirected into Privoxy.
3757  *
3758  *                Code mainly copied from client_host() which is currently
3759  *                run too late for this purpose.
3760  *
3761  * Parameters  :
3762  *          1  :  headers = List of headers (one of them hopefully being
3763  *                the "Host:" header)
3764  *          2  :  http = storage for the result (host, port and hostport). 
3765  *
3766  * Returns     :  JB_ERR_MEMORY in case of memory problems,
3767  *                JB_ERR_PARSE if the host header couldn't be found,
3768  *                JB_ERR_OK otherwise.
3769  *
3770  *********************************************************************/
3771 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3772 {
3773    char *q;
3774    char *p;
3775    char *host;
3776
3777    host = get_header_value(headers, "Host:");
3778
3779    if (NULL == host)
3780    {
3781       log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3782       return JB_ERR_PARSE;
3783    }
3784
3785    if (NULL == (p = strdup((host))))
3786    {
3787       log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3788       return JB_ERR_MEMORY;
3789    }
3790    chomp(p);
3791    if (NULL == (q = strdup(p)))
3792    {
3793       freez(p);
3794       log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3795       return JB_ERR_MEMORY;
3796    }
3797
3798    freez(http->hostport);
3799    http->hostport = p;
3800    freez(http->host);
3801    http->host = q;
3802    q = strchr(http->host, ':');
3803    if (q != NULL)
3804    {
3805       /* Terminate hostname and evaluate port string */
3806       *q++ = '\0';
3807       http->port = atoi(q);
3808    }
3809    else
3810    {
3811       http->port = http->ssl ? 443 : 80;
3812    }
3813
3814    /* Rebuild request URL */
3815    freez(http->url);
3816    http->url = strdup(http->ssl ? "https://" : "http://");
3817    string_append(&http->url, http->hostport);
3818    string_append(&http->url, http->path);
3819    if (http->url == NULL)
3820    {
3821       return JB_ERR_MEMORY;
3822    }
3823
3824    log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3825       http->url);
3826
3827    return JB_ERR_OK;
3828
3829 }
3830
3831
3832 /*
3833   Local Variables:
3834   tab-width: 3
3835   end:
3836 */