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