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