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