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