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