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