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