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