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