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