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