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