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