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