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