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