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