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