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