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