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