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