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