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