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