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