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