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