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