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