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