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