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