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