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