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