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