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