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