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