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