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