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