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