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