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