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