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