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