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