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