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