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