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