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