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