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