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