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