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