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