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