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