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