Added temporary workaround for bug in PHP < 4.2.3
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.56.2.4 2003/03/07 03:41:05 david__schmidt Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/Attic/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.56.2.4  2003/03/07 03:41:05  david__schmidt
44  *    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.
45  *
46  *    Revision 1.56.2.3  2002/11/10 04:20:02  hal9
47  *    Fix typo: supressed -> suppressed
48  *
49  *    Revision 1.56.2.2  2002/09/25 14:59:53  oes
50  *    Improved cookie logging
51  *
52  *    Revision 1.56.2.1  2002/09/25 14:52:45  oes
53  *    Added basic support for OPTIONS and TRACE HTTP methods:
54  *     - New parser function client_max_forwards which decrements
55  *       the Max-Forwards HTTP header field of OPTIONS and TRACE
56  *       requests by one before forwarding
57  *     - New parser function client_host which extracts the host
58  *       and port information from the HTTP header field if the
59  *       request URI was not absolute
60  *     - Don't crumble and re-add the Host: header, but only generate
61  *       and append if missing
62  *
63  *    Revision 1.56  2002/05/12 15:34:22  jongfoster
64  *    Fixing typo in a comment
65  *
66  *    Revision 1.55  2002/05/08 16:01:07  oes
67  *    Optimized add_to_iob:
68  *     - Use realloc instead of malloc(), memcpy(), free()
69  *     - Expand to powers of two if possible, to get
70  *       O(log n) reallocs instead of O(n).
71  *     - Moved check for buffer limit here from chat
72  *     - Report failure via returncode
73  *
74  *    Revision 1.54  2002/04/02 15:03:16  oes
75  *    Tiny code cosmetics
76  *
77  *    Revision 1.53  2002/03/26 22:29:55  swa
78  *    we have a new homepage!
79  *
80  *    Revision 1.52  2002/03/24 13:25:43  swa
81  *    name change related issues
82  *
83  *    Revision 1.51  2002/03/13 00:27:05  jongfoster
84  *    Killing warnings
85  *
86  *    Revision 1.50  2002/03/12 01:45:35  oes
87  *    More verbose logging
88  *
89  *    Revision 1.49  2002/03/09 20:03:52  jongfoster
90  *    - Making various functions return int rather than size_t.
91  *      (Undoing a recent change).  Since size_t is unsigned on
92  *      Windows, functions like read_socket that return -1 on
93  *      error cannot return a size_t.
94  *
95  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
96  *      crashes, and also frequently caused JB to jump to 100%
97  *      CPU and stay there.  (Because it thought it had just
98  *      read ((unsigned)-1) == 4Gb of data...)
99  *
100  *    - The signature of write_socket has changed, it now simply
101  *      returns success=0/failure=nonzero.
102  *
103  *    - Trying to get rid of a few warnings --with-debug on
104  *      Windows, I've introduced a new type "jb_socket".  This is
105  *      used for the socket file descriptors.  On Windows, this
106  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
107  *      an int.  The error value can't be -1 any more, so it's
108  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
109  *      Windows it maps to the #define INVALID_SOCKET.)
110  *
111  *    - The signature of bind_port has changed.
112  *
113  *    Revision 1.48  2002/03/07 03:46:53  oes
114  *    Fixed compiler warnings etc
115  *
116  *    Revision 1.47  2002/02/20 23:15:13  jongfoster
117  *    Parsing functions now handle out-of-memory gracefully by returning
118  *    an error code.
119  *
120  *    Revision 1.46  2002/01/17 21:03:47  jongfoster
121  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
122  *
123  *    Revision 1.45  2002/01/09 14:33:03  oes
124  *    Added support for localtime_r.
125  *
126  *    Revision 1.44  2001/12/14 01:22:54  steudten
127  *    Remove 'user:pass@' from 'proto://user:pass@host' for the
128  *    new added header 'Host: ..'. (See Req ID 491818)
129  *
130  *    Revision 1.43  2001/11/23 00:26:38  jongfoster
131  *    Fixing two really stupid errors in my previous commit
132  *
133  *    Revision 1.42  2001/11/22 21:59:30  jongfoster
134  *    Adding code to handle +no-cookies-keep
135  *
136  *    Revision 1.41  2001/11/05 23:43:05  steudten
137  *    Add time+date to log files.
138  *
139  *    Revision 1.40  2001/10/26 20:13:09  jongfoster
140  *    ctype.h is needed in Windows, too.
141  *
142  *    Revision 1.39  2001/10/26 17:40:04  oes
143  *    Introduced get_header_value()
144  *    Removed http->user_agent, csp->referrer and csp->accept_types
145  *    Removed client_accept()
146  *
147  *    Revision 1.38  2001/10/25 03:40:48  david__schmidt
148  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
149  *    threads to call select() simultaneously.  So, it's time to do a real, live,
150  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
151  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
152  *
153  *    Revision 1.37  2001/10/23 21:36:02  jongfoster
154  *    Documenting sed()'s error behaviou (doc change only)
155  *
156  *    Revision 1.36  2001/10/13 12:51:51  joergs
157  *    Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
158  *    force-load), instead crumble Host: and add it (again) in client_host_adder
159  *    (in case we get a HTTP/1.0 request without Host: header and forward it to
160  *    a HTTP/1.1 server/proxy).
161  *
162  *    Revision 1.35  2001/10/09 22:39:21  jongfoster
163  *    assert.h is also required under Win32, so moving out of #ifndef _WIN32
164  *    block.
165  *
166  *    Revision 1.34  2001/10/07 18:50:55  oes
167  *    Added server_content_encoding, renamed server_transfer_encoding
168  *
169  *    Revision 1.33  2001/10/07 18:04:49  oes
170  *    Changed server_http11 to server_http and its pattern to "HTTP".
171  *      Additional functionality: it now saves the HTTP status into
172  *      csp->http->status and sets CT_TABOO for Status 206 (partial range)
173  *
174  *    Revision 1.32  2001/10/07 15:43:28  oes
175  *    Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
176  *       client_te and client_accept_encoding_adder, triggered by the new
177  *       +no-compression action. For HTTP/1.1 the Accept-Encoding header is
178  *       changed to allow only identity and chunked, and the TE header is
179  *       crunched. For HTTP/1.0, Accept-Encoding is crunched.
180  *
181  *    parse_http_request no longer does anything than parsing. The rewriting
182  *      of http->cmd and version mangling are gone. It now also recognizes
183  *      the put and delete methods and saves the url in http->url. Removed
184  *      unused variable.
185  *
186  *    renamed content_type and content_length to have the server_ prefix
187  *
188  *    server_content_type now only works if csp->content_type != CT_TABOO
189  *
190  *    added server_transfer_encoding, which
191  *      - Sets CT_TABOO to prohibit filtering if encoding compresses
192  *      - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
193  *      - Change from "chunked" to "identity" if body was chunked
194  *        but has been de-chunked for filtering.
195  *
196  *    added server_content_md5 which crunches any Content-MD5 headers
197  *      if the body was modified.
198  *
199  *    made server_http11 conditional on +downgrade action
200  *
201  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
202  *
203  *    Revision 1.31  2001/10/05 14:25:02  oes
204  *    Crumble Keep-Alive from Server
205  *
206  *    Revision 1.30  2001/09/29 12:56:03  joergs
207  *    IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
208  *
209  *    Revision 1.29  2001/09/24 21:09:24  jongfoster
210  *    Fixing 2 memory leaks that Guy spotted, where the paramater to
211  *    enlist() was not being free()d.
212  *
213  *    Revision 1.28  2001/09/22 16:32:28  jongfoster
214  *    Removing unused #includes.
215  *
216  *    Revision 1.27  2001/09/20 15:45:25  steudten
217  *
218  *    add casting from size_t to int for printf()
219  *    remove local variable shadow s2
220  *
221  *    Revision 1.26  2001/09/16 17:05:14  jongfoster
222  *    Removing unused #include showarg.h
223  *
224  *    Revision 1.25  2001/09/16 13:21:27  jongfoster
225  *    Changes to use new list functions.
226  *
227  *    Revision 1.24  2001/09/13 23:05:50  jongfoster
228  *    Changing the string paramater to the header parsers a "const".
229  *
230  *    Revision 1.23  2001/09/12 18:08:19  steudten
231  *
232  *    In parse_http_request() header rewriting miss the host value, so
233  *    from http://www.mydomain.com the result was just " / " not
234  *    http://www.mydomain.com/ in case we forward.
235  *
236  *    Revision 1.22  2001/09/10 10:58:53  oes
237  *    Silenced compiler warnings
238  *
239  *    Revision 1.21  2001/07/31 14:46:00  oes
240  *     - Persistant connections now suppressed
241  *     - sed() no longer appends empty header to csp->headers
242  *
243  *    Revision 1.20  2001/07/30 22:08:36  jongfoster
244  *    Tidying up #defines:
245  *    - All feature #defines are now of the form FEATURE_xxx
246  *    - Permanently turned off WIN_GUI_EDIT
247  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
248  *
249  *    Revision 1.19  2001/07/25 17:21:54  oes
250  *    client_uagent now saves copy of User-Agent: header value
251  *
252  *    Revision 1.18  2001/07/13 14:02:46  oes
253  *     - Included fix to repair broken HTTP requests that
254  *       don't contain a path, not even '/'.
255  *     - Removed all #ifdef PCRS
256  *     - content_type now always inspected and classified as
257  *       text, gif or other.
258  *     - formatting / comments
259  *
260  *    Revision 1.17  2001/06/29 21:45:41  oes
261  *    Indentation, CRLF->LF, Tab-> Space
262  *
263  *    Revision 1.16  2001/06/29 13:32:42  oes
264  *    - Fixed a comment
265  *    - Adapted free_http_request
266  *    - Removed logentry from cancelled commit
267  *
268  *    Revision 1.15  2001/06/03 19:12:38  oes
269  *    deleted const struct interceptors
270  *
271  *    Revision 1.14  2001/06/01 18:49:17  jongfoster
272  *    Replaced "list_share" with "list" - the tiny memory gain was not
273  *    worth the extra complexity.
274  *
275  *    Revision 1.13  2001/05/31 21:30:33  jongfoster
276  *    Removed list code - it's now in list.[ch]
277  *    Renamed "permission" to "action", and changed many features
278  *    to use the actions file rather than the global config.
279  *
280  *    Revision 1.12  2001/05/31 17:33:13  oes
281  *
282  *    CRLF -> LF
283  *
284  *    Revision 1.11  2001/05/29 20:11:19  joergs
285  *    '/ * inside comment' warning removed.
286  *
287  *    Revision 1.10  2001/05/29 09:50:24  jongfoster
288  *    Unified blocklist/imagelist/permissionslist.
289  *    File format is still under discussion, but the internal changes
290  *    are (mostly) done.
291  *
292  *    Also modified interceptor behaviour:
293  *    - We now intercept all URLs beginning with one of the following
294  *      prefixes (and *only* these prefixes):
295  *        * http://i.j.b/
296  *        * http://ijbswa.sf.net/config/
297  *        * http://ijbswa.sourceforge.net/config/
298  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
299  *    - Internal changes so that intercepted and fast redirect pages
300  *      are not replaced with an image.
301  *    - Interceptors now have the option to send a binary page direct
302  *      to the client. (i.e. ijb-send-banner uses this)
303  *    - Implemented show-url-info interceptor.  (Which is why I needed
304  *      the above interceptors changes - a typical URL is
305  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
306  *      The previous mechanism would not have intercepted that, and
307  *      if it had been intercepted then it then it would have replaced
308  *      it with an image.)
309  *
310  *    Revision 1.9  2001/05/28 17:26:33  jongfoster
311  *    Fixing segfault if last header was crunched.
312  *    Fixing Windows build (snprintf() is _snprintf() under Win32, but we
313  *    can use the cross-platform sprintf() instead.)
314  *
315  *    Revision 1.8  2001/05/27 22:17:04  oes
316  *
317  *    - re_process_buffer no longer writes the modified buffer
318  *      to the client, which was very ugly. It now returns the
319  *      buffer, which it is then written by chat.
320  *
321  *    - content_length now adjusts the Content-Length: header
322  *      for modified documents rather than crunch()ing it.
323  *      (Length info in csp->content_length, which is 0 for
324  *      unmodified documents)
325  *
326  *    - For this to work, sed() is called twice when filtering.
327  *
328  *    Revision 1.7  2001/05/27 13:19:06  oes
329  *    Patched Joergs solution for the content-length in.
330  *
331  *    Revision 1.6  2001/05/26 13:39:32  jongfoster
332  *    Only crunches Content-Length header if applying RE filtering.
333  *    Without this fix, Microsoft Windows Update wouldn't work.
334  *
335  *    Revision 1.5  2001/05/26 00:28:36  jongfoster
336  *    Automatic reloading of config file.
337  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
338  *    Most of the global variables have been moved to a new
339  *    struct configuration_spec, accessed through csp->config->globalname
340  *    Most of the globals remaining are used by the Win32 GUI.
341  *
342  *    Revision 1.4  2001/05/22 18:46:04  oes
343  *
344  *    - Enabled filtering banners by size rather than URL
345  *      by adding patterns that replace all standard banner
346  *      sizes with the "Junkbuster" gif to the re_filterfile
347  *
348  *    - Enabled filtering WebBugs by providing a pattern
349  *      which kills all 1x1 images
350  *
351  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
352  *      which is selected by the (nonstandard and therefore
353  *      capital) letter 'U' in the option string.
354  *      It causes the quantifiers to be ungreedy by default.
355  *      Appending a ? turns back to greedy (!).
356  *
357  *    - Added a new interceptor ijb-send-banner, which
358  *      sends back the "Junkbuster" gif. Without imagelist or
359  *      MSIE detection support, or if tinygif = 1, or the
360  *      URL isn't recognized as an imageurl, a lame HTML
361  *      explanation is sent instead.
362  *
363  *    - Added new feature, which permits blocking remote
364  *      script redirects and firing back a local redirect
365  *      to the browser.
366  *      The feature is conditionally compiled, i.e. it
367  *      can be disabled with --disable-fast-redirects,
368  *      plus it must be activated by a "fast-redirects"
369  *      line in the config file, has its own log level
370  *      and of course wants to be displayed by show-proxy-args
371  *      Note: Boy, all the #ifdefs in 1001 locations and
372  *      all the fumbling with configure.in and acconfig.h
373  *      were *way* more work than the feature itself :-(
374  *
375  *    - Because a generic redirect template was needed for
376  *      this, tinygif = 3 now uses the same.
377  *
378  *    - Moved GIFs, and other static HTTP response templates
379  *      to project.h
380  *
381  *    - Some minor fixes
382  *
383  *    - Removed some >400 CRs again (Jon, you really worked
384  *      a lot! ;-)
385  *
386  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
387  *    Version 2.9.4 checkin.
388  *    - Merged popupfile and cookiefile, and added control over PCRS
389  *      filtering, in new "permissionsfile".
390  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
391  *      file error you now get a message box (in the Win32 GUI) rather
392  *      than the program exiting with no explanation.
393  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
394  *      skipping.
395  *    - Removed tabs from "config"
396  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
397  *    - Bumped up version number.
398  *
399  *    Revision 1.2  2001/05/17 23:02:36  oes
400  *     - Made referrer option accept 'L' as a substitute for '§'
401  *
402  *    Revision 1.1.1.1  2001/05/15 13:59:01  oes
403  *    Initial import of version 2.9.3 source tree
404  *
405  *
406  *********************************************************************/
407 \f
408
409 #include "config.h"
410
411 #ifndef _WIN32
412 #include <stdio.h>
413 #include <sys/types.h>
414 #endif
415
416 #include <stdlib.h>
417 #include <ctype.h>
418 #include <assert.h>
419 #include <string.h>
420
421 #if !defined(_WIN32) && !defined(__OS2__)
422 #include <unistd.h>
423 #endif
424
425 #ifdef OSX_DARWIN
426 #include <pthread.h>
427 #include "jcc.h"
428 /* jcc.h is for mutex semapores only */
429 #endif /* def OSX_DARWIN */
430 #include "project.h"
431 #include "list.h"
432 #include "parsers.h"
433 #include "encode.h"
434 #include "ssplit.h"
435 #include "errlog.h"
436 #include "jbsockets.h"
437 #include "miscutil.h"
438 #include "list.h"
439
440 const char parsers_h_rcs[] = PARSERS_H_VERSION;
441
442 /* Fix a problem with Solaris.  There should be no effect on other
443  * platforms.
444  * Solaris's isspace() is a macro which uses it's argument directly
445  * as an array index.  Therefore we need to make sure that high-bit
446  * characters generate +ve values, and ideally we also want to make
447  * the argument match the declared parameter type of "int".
448  *
449  * Why did they write a character function that can't take a simple
450  * "char" argument?  Doh!
451  */
452 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
453 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
454
455
456 const struct parsers client_patterns[] = {
457    { "referer:",                 8,    client_referrer },
458    { "user-agent:",              11,   client_uagent },
459    { "ua-",                      3,    client_ua },
460    { "from:",                    5,    client_from },
461    { "cookie:",                  7,    client_send_cookie },
462    { "x-forwarded-for:",         16,   client_x_forwarded },
463    { "Accept-Encoding:",         16,   client_accept_encoding },
464    { "TE:",                       3,   client_te },
465    { "Host:",                     5,   client_host },
466 /* { "if-modified-since:",       18,   crumble }, */
467    { "Keep-Alive:",              11,   crumble },
468    { "connection:",              11,   crumble },
469    { "proxy-connection:",        17,   crumble },
470    { "max-forwards:",            13,   client_max_forwards },
471    { NULL,                       0,    NULL }
472 };
473
474
475 const struct parsers server_patterns[] = {
476    { "HTTP",                4, server_http },
477    { "set-cookie:",        11, server_set_cookie },
478    { "connection:",        11, crumble },
479    { "Content-Type:",      13, server_content_type },
480    { "Content-Length:",    15, server_content_length },
481    { "Content-MD5:",       12, server_content_md5 },
482    { "Content-Encoding:",  17, server_content_encoding },
483    { "Transfer-Encoding:", 18, server_transfer_coding },
484    { "Keep-Alive:",        11, crumble },
485    { NULL, 0, NULL }
486 };
487
488
489 const add_header_func_ptr add_client_headers[] = {
490    client_host_adder,
491    client_cookie_adder,
492    client_x_forwarded_adder,
493    client_xtra_adder,
494    client_accept_encoding_adder,
495    connection_close_adder,
496    NULL
497 };
498
499
500 const add_header_func_ptr add_server_headers[] = {
501    connection_close_adder,
502    NULL
503 };
504
505
506 /*********************************************************************
507  *
508  * Function    :  flush_socket
509  *
510  * Description :  Write any pending "buffered" content.
511  *
512  * Parameters  :
513  *          1  :  fd = file descriptor of the socket to read
514  *          2  :  csp = Current client state (buffers, headers, etc...)
515  *
516  * Returns     :  On success, the number of bytes written are returned (zero
517  *                indicates nothing was written).  On error, -1 is returned,
518  *                and errno is set appropriately.  If count is zero and the
519  *                file descriptor refers to a regular file, 0 will be
520  *                returned without causing any other effect.  For a special
521  *                file, the results are not portable.
522  *
523  *********************************************************************/
524 int flush_socket(jb_socket fd, struct client_state *csp)
525 {
526    struct iob *iob = csp->iob;
527    int len = iob->eod - iob->cur;
528
529    if (len <= 0)
530    {
531       return(0);
532    }
533
534    if (write_socket(fd, iob->cur, (size_t)len))
535    {
536       return(-1);
537    }
538    iob->eod = iob->cur = iob->buf;
539    return(len);
540
541 }
542
543
544 /*********************************************************************
545  *
546  * Function    :  add_to_iob
547  *
548  * Description :  Add content to the buffered page, expanding the
549  *                buffer if necessary.
550  *
551  * Parameters  :
552  *          1  :  csp = Current client state (buffers, headers, etc...)
553  *          2  :  buf = holds the content to be added to the page
554  *          3  :  n = number of bytes to be added
555  *
556  * Returns     :  JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
557  *                or buffer limit reached.
558  *
559  *********************************************************************/
560 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
561 {
562    struct iob *iob = csp->iob;
563    size_t used, offset, need, want;
564    char *p;
565
566    if (n <= 0) return JB_ERR_OK;
567
568    used   = iob->eod - iob->buf;
569    offset = iob->cur - iob->buf;
570    need   = used + n + 1;
571
572    /*
573     * If the buffer can't hold the new data, extend it first.
574     * Use the next power of two if possible, else use the actual need.
575     */
576    if (need > csp->config->buffer_limit)
577    {
578       log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
579       return JB_ERR_MEMORY;
580    }
581
582    if (need > iob->size)
583    {
584       for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
585       
586       if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
587       {
588          iob->size = want;
589       }
590       else if (NULL != (p = (char *)realloc(iob->buf, need)))
591       {
592          iob->size = need;
593       }
594       else
595       {
596          log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
597          return JB_ERR_MEMORY;
598       }
599
600       /* Update the iob pointers */
601       iob->cur = p + offset;
602       iob->eod = p + used;
603       iob->buf = p;
604    }
605
606    /* copy the new data into the iob buffer */
607    memcpy(iob->eod, buf, (size_t)n);
608
609    /* point to the end of the data */
610    iob->eod += n;
611
612    /* null terminate == cheap insurance */
613    *iob->eod = '\0';
614
615    return JB_ERR_OK;
616
617 }
618
619
620 /*********************************************************************
621  *
622  * Function    :  get_header
623  *
624  * Description :  This (odd) routine will parse the csp->iob
625  *
626  * Parameters  :
627  *          1  :  csp = Current client state (buffers, headers, etc...)
628  *
629  * Returns     :  Any one of the following:
630  *
631  * 1) a pointer to a dynamically allocated string that contains a header line
632  * 2) NULL  indicating that the end of the header was reached
633  * 3) ""    indicating that the end of the iob was reached before finding
634  *          a complete header line.
635  *
636  *********************************************************************/
637 char *get_header(struct client_state *csp)
638 {
639    struct iob *iob;
640    char *p, *q, *ret;
641    iob = csp->iob;
642
643    if ((iob->cur == NULL)
644       || ((p = strchr(iob->cur, '\n')) == NULL))
645    {
646       return(""); /* couldn't find a complete header */
647    }
648
649    *p = '\0';
650
651    ret = strdup(iob->cur);
652    if (ret == NULL)
653    {
654       /* FIXME No way to handle error properly */
655       log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
656    }
657
658    iob->cur = p+1;
659
660    if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
661
662    /* is this a blank line (i.e. the end of the header) ? */
663    if (*ret == '\0')
664    {
665       freez(ret);
666       return(NULL);
667    }
668
669    return(ret);
670
671 }
672
673
674 /*********************************************************************
675  *
676  * Function    :  get_header_value
677  *
678  * Description :  Get the value of a given header from a chained list
679  *                of header lines or return NULL if no such header is
680  *                present in the list.
681  *
682  * Parameters  :
683  *          1  :  header_list = pointer to list
684  *          2  :  header_name = string with name of header to look for.
685  *                              Trailing colon required, capitalization
686  *                              doesn't matter.
687  *
688  * Returns     :  NULL if not found, else value of header
689  *
690  *********************************************************************/
691 char *get_header_value(const struct list *header_list, const char *header_name)
692 {
693    struct list_entry *cur_entry;
694    char *ret = NULL;
695    size_t length = 0;
696
697    assert(header_list);
698    assert(header_name);
699    length = strlen(header_name);
700
701    for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
702    {
703       if (cur_entry->str)
704       {
705          if (!strncmpic(cur_entry->str, header_name, length))
706          {
707             /*
708              * Found: return pointer to start of value
709              */
710             ret = (char *) (cur_entry->str + length);
711             while (*ret && ijb_isspace(*ret)) ret++;
712             return(ret);
713          }
714       }
715    }
716
717    /* 
718     * Not found
719     */
720    return NULL;
721
722 }
723
724 /*********************************************************************
725  *
726  * Function    :  sed
727  *
728  * Description :  add, delete or modify lines in the HTTP header streams.
729  *                On entry, it receives a linked list of headers space
730  *                that was allocated dynamically (both the list nodes
731  *                and the header contents).
732  *
733  *                As a side effect it frees the space used by the original
734  *                header lines.
735  *
736  * Parameters  :
737  *          1  :  pats = list of patterns to match against headers
738  *          2  :  more_headers = list of functions to add more
739  *                headers (client or server)
740  *          3  :  csp = Current client state (buffers, headers, etc...)
741  *
742  * Returns     :  Single pointer to a fully formed header, or NULL
743  *                on out-of-memory error.
744  *
745  *********************************************************************/
746 char *sed(const struct parsers pats[],
747           const add_header_func_ptr more_headers[],
748           struct client_state *csp)
749 {
750    struct list_entry *p;
751    const struct parsers *v;
752    const add_header_func_ptr *f;
753    jb_err err = JB_ERR_OK;
754
755    for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
756    {
757       for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
758       {
759          /* Header crunch()ed in previous run? -> ignore */
760          if (p->str == NULL) continue;
761
762          if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
763
764          if (strncmpic(p->str, v->str, v->len) == 0)
765          {
766             err = v->parser(csp, (char **)&(p->str));
767          }
768       }
769    }
770
771    /* place any additional headers on the csp->headers list */
772    for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
773    {
774       err = (*f)(csp);
775    }
776
777    if (err != JB_ERR_OK)
778    {
779       return NULL;
780    }
781
782    return list_to_text(csp->headers);
783 }
784
785
786 /* here begins the family of parser functions that reformat header lines */
787
788
789 /*********************************************************************
790  *
791  * Function    :  crumble
792  *
793  * Description :  This is called if a header matches a pattern to "crunch"
794  *
795  * Parameters  :
796  *          1  :  csp = Current client state (buffers, headers, etc...)
797  *          2  :  header = On input, pointer to header to modify.
798  *                On output, pointer to the modified header, or NULL
799  *                to remove the header.  This function frees the
800  *                original string if necessary.
801  *
802  * Returns     :  JB_ERR_OK on success, or
803  *                JB_ERR_MEMORY on out-of-memory error.
804  *
805  *********************************************************************/
806 jb_err crumble(struct client_state *csp, char **header)
807 {
808    log_error(LOG_LEVEL_HEADER, "crunch!");
809    freez(*header);
810    return JB_ERR_OK;
811 }
812
813
814 /*********************************************************************
815  *
816  * Function    :  server_content_type
817  *
818  * Description :  Set the content-type for filterable types (text/.*,
819  *                javascript and image/gif) unless filtering has been
820  *                forbidden (CT_TABOO) while parsing earlier headers.
821  *
822  * Parameters  :
823  *          1  :  csp = Current client state (buffers, headers, etc...)
824  *          2  :  header = On input, pointer to header to modify.
825  *                On output, pointer to the modified header, or NULL
826  *                to remove the header.  This function frees the
827  *                original string if necessary.
828  *
829  * Returns     :  JB_ERR_OK on success, or
830  *                JB_ERR_MEMORY on out-of-memory error.
831  *
832  *********************************************************************/
833 jb_err server_content_type(struct client_state *csp, char **header)
834 {
835    if (csp->content_type != CT_TABOO)
836    {
837       if (strstr(*header, " text/")
838        || strstr(*header, "application/x-javascript"))
839          csp->content_type = CT_TEXT;
840       else if (strstr(*header, " image/gif"))
841          csp->content_type = CT_GIF;
842       else
843          csp->content_type = 0;
844    }
845
846    return JB_ERR_OK;
847 }
848
849
850 /*********************************************************************
851  *
852  * Function    :  server_transfer_coding
853  *
854  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
855  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
856  *                - Change from "chunked" to "identity" if body was chunked
857  *                  but has been de-chunked for filtering.
858  *
859  * Parameters  :
860  *          1  :  csp = Current client state (buffers, headers, etc...)
861  *          2  :  header = On input, pointer to header to modify.
862  *                On output, pointer to the modified header, or NULL
863  *                to remove the header.  This function frees the
864  *                original string if necessary.
865  *
866  * Returns     :  JB_ERR_OK on success, or
867  *                JB_ERR_MEMORY on out-of-memory error.
868  *
869  *********************************************************************/
870 jb_err server_transfer_coding(struct client_state *csp, char **header)
871 {
872    /*
873     * Turn off pcrs and gif filtering if body compressed
874     */
875    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
876    {
877       csp->content_type = CT_TABOO;
878    }
879
880    /*
881     * Raise flag if body chunked
882     */
883    if (strstr(*header, "chunked"))
884    {
885       csp->flags |= CSP_FLAG_CHUNKED;
886
887       /*
888        * If the body was modified, it has been
889        * de-chunked first, so adjust the header:
890        */
891       if (csp->flags & CSP_FLAG_MODIFIED)
892       {
893          freez(*header);
894          *header = strdup("Transfer-Encoding: identity");
895          return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
896       }
897    }
898
899    return JB_ERR_OK;
900 }
901
902
903 /*********************************************************************
904  *
905  * Function    :  server_content_encoding
906  *
907  * Description :  Prohibit filtering (CT_TABOO) if content encoding compresses
908  *
909  * Parameters  :
910  *          1  :  csp = Current client state (buffers, headers, etc...)
911  *          2  :  header = On input, pointer to header to modify.
912  *                On output, pointer to the modified header, or NULL
913  *                to remove the header.  This function frees the
914  *                original string if necessary.
915  *
916  * Returns     :  JB_ERR_OK on success, or
917  *                JB_ERR_MEMORY on out-of-memory error.
918  *
919  *********************************************************************/
920 jb_err server_content_encoding(struct client_state *csp, char **header)
921 {
922    /*
923     * Turn off pcrs and gif filtering if body compressed
924     */
925    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
926    {
927       csp->content_type = CT_TABOO;
928    }
929
930    return JB_ERR_OK;
931
932 }
933
934
935 /*********************************************************************
936  *
937  * Function    :  server_content_length
938  *
939  * Description :  Adjust Content-Length header if we modified
940  *                the body.
941  *
942  * Parameters  :
943  *          1  :  csp = Current client state (buffers, headers, etc...)
944  *          2  :  header = On input, pointer to header to modify.
945  *                On output, pointer to the modified header, or NULL
946  *                to remove the header.  This function frees the
947  *                original string if necessary.
948  *
949  * Returns     :  JB_ERR_OK on success, or
950  *                JB_ERR_MEMORY on out-of-memory error.
951  *
952  *********************************************************************/
953 jb_err server_content_length(struct client_state *csp, char **header)
954 {
955    if (csp->content_length != 0) /* Content length has been modified */
956    {
957       freez(*header);
958       *header = (char *) zalloc(100);
959       if (*header == NULL)
960       {
961          return JB_ERR_MEMORY;
962       }
963
964       sprintf(*header, "Content-Length: %d", (int) csp->content_length);
965
966       log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
967    }
968
969    return JB_ERR_OK;
970 }
971
972
973 /*********************************************************************
974  *
975  * Function    :  server_content_md5
976  *
977  * Description :  Crumble any Content-MD5 headers if the document was
978  *                modified. FIXME: Should we re-compute instead?
979  *
980  * Parameters  :
981  *          1  :  csp = Current client state (buffers, headers, etc...)
982  *          2  :  header = On input, pointer to header to modify.
983  *                On output, pointer to the modified header, or NULL
984  *                to remove the header.  This function frees the
985  *                original string if necessary.
986  *
987  * Returns     :  JB_ERR_OK on success, or
988  *                JB_ERR_MEMORY on out-of-memory error.
989  *
990  *********************************************************************/
991 jb_err server_content_md5(struct client_state *csp, char **header)
992 {
993    if (csp->flags & CSP_FLAG_MODIFIED)
994    {
995       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
996       freez(*header);
997    }
998
999    return JB_ERR_OK;
1000 }
1001
1002
1003 /*********************************************************************
1004  *
1005  * Function    :  client_accept_encoding
1006  *
1007  * Description :  Rewrite the client's Accept-Encoding header so that
1008  *                if doesn't allow compression, if the action applies.
1009  *                Note: For HTTP/1.0 the absence of the header is enough.
1010  *
1011  * Parameters  :
1012  *          1  :  csp = Current client state (buffers, headers, etc...)
1013  *          2  :  header = On input, pointer to header to modify.
1014  *                On output, pointer to the modified header, or NULL
1015  *                to remove the header.  This function frees the
1016  *                original string if necessary.
1017  *
1018  * Returns     :  JB_ERR_OK on success, or
1019  *                JB_ERR_MEMORY on out-of-memory error.
1020  *
1021  *********************************************************************/
1022 jb_err client_accept_encoding(struct client_state *csp, char **header)
1023 {
1024    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1025    {
1026       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1027
1028       freez(*header);
1029
1030       /* Temporarily disable the correct behaviour to
1031        * work around a PHP bug. 
1032        *
1033        * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1034        * {
1035        *    *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1036        *    if (*header == NULL)
1037        *    {
1038        *       return JB_ERR_MEMORY;
1039        *    }
1040        * }
1041        * 
1042        */
1043    }
1044
1045    return JB_ERR_OK;
1046 }
1047
1048
1049 /*********************************************************************
1050  *
1051  * Function    :  client_te
1052  *
1053  * Description :  Rewrite the client's TE header so that
1054  *                if doesn't allow compression, if the action applies.
1055  *
1056  * Parameters  :
1057  *          1  :  csp = Current client state (buffers, headers, etc...)
1058  *          2  :  header = On input, pointer to header to modify.
1059  *                On output, pointer to the modified header, or NULL
1060  *                to remove the header.  This function frees the
1061  *                original string if necessary.
1062  *
1063  * Returns     :  JB_ERR_OK on success, or
1064  *                JB_ERR_MEMORY on out-of-memory error.
1065  *
1066  *********************************************************************/
1067 jb_err client_te(struct client_state *csp, char **header)
1068 {
1069    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1070    {
1071       freez(*header);
1072       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1073    }
1074
1075    return JB_ERR_OK;
1076 }
1077
1078 /*********************************************************************
1079  *
1080  * Function    :  client_referrer
1081  *
1082  * Description :  Handle the "referer" config setting properly.
1083  *                Called from `sed'.
1084  *
1085  * Parameters  :
1086  *          1  :  csp = Current client state (buffers, headers, etc...)
1087  *          2  :  header = On input, pointer to header to modify.
1088  *                On output, pointer to the modified header, or NULL
1089  *                to remove the header.  This function frees the
1090  *                original string if necessary.
1091  *
1092  * Returns     :  JB_ERR_OK on success, or
1093  *                JB_ERR_MEMORY on out-of-memory error.
1094  *
1095  *********************************************************************/
1096 jb_err client_referrer(struct client_state *csp, char **header)
1097 {
1098    const char *newval;
1099
1100 #ifdef FEATURE_FORCE_LOAD
1101    /* Since the referrer can include the prefix even
1102     * even if the request itself is non-forced, we must
1103     * clean it unconditionally
1104     */
1105    strclean(*header, FORCE_PREFIX);
1106 #endif /* def FEATURE_FORCE_LOAD */
1107
1108    /*
1109     * Are we sending referer?
1110     */
1111    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1112    {
1113       return JB_ERR_OK;
1114    }
1115
1116    freez(*header);
1117
1118    newval = csp->action->string[ACTION_STRING_REFERER];
1119
1120    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1121    {
1122       /*
1123        * Blocking referer
1124        */
1125       log_error(LOG_LEVEL_HEADER, "crunch!");
1126       return JB_ERR_OK;
1127    }
1128    else if (0 == strncmpic(newval, "http://", 7))
1129    {
1130       /*
1131        * We have a specific (fixed) referer we want to send.
1132        */
1133       log_error(LOG_LEVEL_HEADER, "modified");
1134
1135       *header = strdup("Referer: ");
1136       string_append(header, newval);
1137
1138       return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1139    }
1140    else
1141    {
1142       /*
1143        * Forge a referer as http://[hostname:port of REQUEST]/
1144        * to fool stupid checks for in-site links
1145        */
1146       if (0 != strcmpic(newval, "forge"))
1147       {
1148          /*
1149           * Invalid choice - but forge is probably the best default.
1150           */
1151          log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1152       }
1153
1154       *header = strdup("Referer: http://");
1155       string_append(header, csp->http->hostport);
1156       string_append(header, "/");
1157       log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1158       
1159       return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1160    }
1161 }
1162
1163
1164 /*********************************************************************
1165  *
1166  * Function    :  client_uagent
1167  *
1168  * Description :  Handle the "user-agent" config setting properly
1169  *                and remember its original value to enable browser
1170  *                bug workarounds. Called from `sed'.
1171  *
1172  * Parameters  :
1173  *          1  :  csp = Current client state (buffers, headers, etc...)
1174  *          2  :  header = On input, pointer to header to modify.
1175  *                On output, pointer to the modified header, or NULL
1176  *                to remove the header.  This function frees the
1177  *                original string if necessary.
1178  *
1179  * Returns     :  JB_ERR_OK on success, or
1180  *                JB_ERR_MEMORY on out-of-memory error.
1181  *
1182  *********************************************************************/
1183 jb_err client_uagent(struct client_state *csp, char **header)
1184 {
1185    const char *newval;
1186
1187    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1188    {
1189       return JB_ERR_OK;
1190    }
1191
1192    newval = csp->action->string[ACTION_STRING_USER_AGENT];
1193    if (newval == NULL)
1194    {
1195       return JB_ERR_OK;
1196    }
1197
1198    log_error(LOG_LEVEL_HEADER, "modified");
1199
1200    freez(*header);
1201    *header = strdup("User-Agent: ");
1202    string_append(header, newval);
1203
1204    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1205 }
1206
1207
1208 /*********************************************************************
1209  *
1210  * Function    :  client_ua
1211  *
1212  * Description :  Handle "ua-" headers properly.  Called from `sed'.
1213  *
1214  * Parameters  :
1215  *          1  :  csp = Current client state (buffers, headers, etc...)
1216  *          2  :  header = On input, pointer to header to modify.
1217  *                On output, pointer to the modified header, or NULL
1218  *                to remove the header.  This function frees the
1219  *                original string if necessary.
1220  *
1221  * Returns     :  JB_ERR_OK on success, or
1222  *                JB_ERR_MEMORY on out-of-memory error.
1223  *
1224  *********************************************************************/
1225 jb_err client_ua(struct client_state *csp, char **header)
1226 {
1227    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1228    {
1229       log_error(LOG_LEVEL_HEADER, "crunch!");
1230       freez(*header);
1231    }
1232
1233    return JB_ERR_OK;
1234 }
1235
1236
1237 /*********************************************************************
1238  *
1239  * Function    :  client_from
1240  *
1241  * Description :  Handle the "from" config setting properly.
1242  *                Called from `sed'.
1243  *
1244  * Parameters  :
1245  *          1  :  csp = Current client state (buffers, headers, etc...)
1246  *          2  :  header = On input, pointer to header to modify.
1247  *                On output, pointer to the modified header, or NULL
1248  *                to remove the header.  This function frees the
1249  *                original string if necessary.
1250  *
1251  * Returns     :  JB_ERR_OK on success, or
1252  *                JB_ERR_MEMORY on out-of-memory error.
1253  *
1254  *********************************************************************/
1255 jb_err client_from(struct client_state *csp, char **header)
1256 {
1257    const char *newval;
1258
1259    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1260    {
1261       return JB_ERR_OK;
1262    }
1263
1264    freez(*header);
1265
1266    newval = csp->action->string[ACTION_STRING_FROM];
1267
1268    /*
1269     * Are we blocking the e-mail address?
1270     */
1271    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1272    {
1273       log_error(LOG_LEVEL_HEADER, "crunch!");
1274       return JB_ERR_OK;
1275    }
1276
1277    log_error(LOG_LEVEL_HEADER, " modified");
1278
1279    *header = strdup("From: ");
1280    string_append(header, newval);
1281
1282    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1283 }
1284
1285
1286 /*********************************************************************
1287  *
1288  * Function    :  client_send_cookie
1289  *
1290  * Description :  Handle the "cookie" header properly.  Called from `sed'.
1291  *                If cookie is accepted, add it to the cookie_list,
1292  *                else we crunch it.  Mmmmmmmmmmm ... cookie ......
1293  *
1294  * Parameters  :
1295  *          1  :  csp = Current client state (buffers, headers, etc...)
1296  *          2  :  header = On input, pointer to header to modify.
1297  *                On output, pointer to the modified header, or NULL
1298  *                to remove the header.  This function frees the
1299  *                original string if necessary.
1300  *
1301  * Returns     :  JB_ERR_OK on success, or
1302  *                JB_ERR_MEMORY on out-of-memory error.
1303  *
1304  *********************************************************************/
1305 jb_err client_send_cookie(struct client_state *csp, char **header)
1306 {
1307    jb_err result = JB_ERR_OK;
1308
1309    if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1310    {
1311       /* strlen("cookie: ") == 8 */
1312       result = enlist(csp->cookie_list, *header + 8);
1313    }
1314    else
1315    {
1316       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
1317    }
1318
1319    /*
1320     * Always remove the cookie here.  The cookie header
1321     * will be sent at the end of the header.
1322     */
1323    freez(*header);
1324
1325    return result;
1326 }
1327
1328
1329 /*********************************************************************
1330  *
1331  * Function    :  client_x_forwarded
1332  *
1333  * Description :  Handle the "x-forwarded-for" config setting properly,
1334  *                also used in the add_client_headers list.  Called from `sed'.
1335  *
1336  * Parameters  :
1337  *          1  :  csp = Current client state (buffers, headers, etc...)
1338  *          2  :  header = On input, pointer to header to modify.
1339  *                On output, pointer to the modified header, or NULL
1340  *                to remove the header.  This function frees the
1341  *                original string if necessary.
1342  *
1343  * Returns     :  JB_ERR_OK on success, or
1344  *                JB_ERR_MEMORY on out-of-memory error.
1345  *
1346  *********************************************************************/
1347 jb_err client_x_forwarded(struct client_state *csp, char **header)
1348 {
1349    if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1350    {
1351       /* Save it so we can re-add it later */
1352       freez(csp->x_forwarded);
1353       csp->x_forwarded = *header;
1354
1355       /*
1356        * Always set *header = NULL, since this information
1357        * will be sent at the end of the header.
1358        */
1359       *header = NULL;
1360    }
1361    else
1362    {
1363       freez(*header);
1364       log_error(LOG_LEVEL_HEADER, " crunch!");
1365    }
1366
1367    return JB_ERR_OK;
1368 }
1369
1370
1371 /*********************************************************************
1372  *
1373  * Function    :  client_max_forwards
1374  *
1375  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
1376  *                from the value of the Max-Forwards header field.
1377  *
1378  * Parameters  :
1379  *          1  :  csp = Current client state (buffers, headers, etc...)
1380  *          2  :  header = On input, pointer to header to modify.
1381  *                On output, pointer to the modified header, or NULL
1382  *                to remove the header.  This function frees the
1383  *                original string if necessary.
1384  *
1385  * Returns     :  JB_ERR_OK on success, or
1386  *                JB_ERR_MEMORY on out-of-memory error.
1387  *
1388  *********************************************************************/
1389 jb_err client_max_forwards(struct client_state *csp, char **header)
1390 {
1391    unsigned int max_forwards;
1392
1393    if ((0 == strcmpic(csp->http->gpc, "trace"))
1394       || (0 == strcmpic(csp->http->gpc, "options")))
1395    {
1396       if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
1397       {
1398          if (max_forwards-- >= 1)
1399          {
1400             sprintf(*header, "Max-Forwards: %u", max_forwards);
1401             log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
1402          }
1403          else
1404          {
1405             log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
1406          }
1407       }
1408    }
1409
1410    return JB_ERR_OK;
1411 }
1412
1413
1414 /*********************************************************************
1415  *
1416  * Function    :  client_host
1417  *
1418  * Description :  If the request URI did not contain host and
1419  *                port information, parse and evaluate the Host
1420  *                header field.
1421  *
1422  * Parameters  :
1423  *          1  :  csp = Current client state (buffers, headers, etc...)
1424  *          2  :  header = On input, pointer to header to modify.
1425  *                On output, pointer to the modified header, or NULL
1426  *                to remove the header.  This function frees the
1427  *                original string if necessary.
1428  *
1429  * Returns     :  JB_ERR_OK on success, or
1430  *                JB_ERR_MEMORY on out-of-memory error.
1431  *
1432  *********************************************************************/
1433 jb_err client_host(struct client_state *csp, char **header)
1434 {
1435    char *p, *q;
1436
1437    if (!csp->http->hostport || (*csp->http->hostport == '*') ||  
1438        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
1439    {
1440       
1441       if (NULL == (p = strdup((*header)+6)))
1442       {
1443          return JB_ERR_MEMORY;
1444       }
1445       chomp(p);
1446       if (NULL == (q = strdup(p)))
1447       {
1448          freez(p);
1449          return JB_ERR_MEMORY;
1450       }
1451
1452       freez(csp->http->hostport);
1453       csp->http->hostport = p;
1454       freez(csp->http->host);
1455       csp->http->host = q;
1456       q = strchr(csp->http->host, ':');
1457       if (q != NULL)
1458       {
1459          /* Terminate hostname and evaluate port string */
1460          *q++ = '\0';
1461          csp->http->port = atoi(q);
1462       }
1463       else
1464       {
1465          csp->http->port = csp->http->ssl ? 443 : 80;
1466       }
1467
1468       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
1469                 csp->http->hostport, csp->http->host, csp->http->port);
1470    }
1471
1472    return JB_ERR_OK;
1473 }
1474
1475
1476 /* the following functions add headers directly to the header list */
1477
1478 /*********************************************************************
1479  *
1480  * Function    :  client_host_adder
1481  *
1482  * Description :  Adds the Host: header field if it is missing.
1483  *                Called from `sed'.
1484  *
1485  * Parameters  :
1486  *          1  :  csp = Current client state (buffers, headers, etc...)
1487  *
1488  * Returns     :  JB_ERR_OK on success, or
1489  *                JB_ERR_MEMORY on out-of-memory error.
1490  *
1491  *********************************************************************/
1492 jb_err client_host_adder(struct client_state *csp)
1493 {
1494    char *p;
1495    jb_err err;
1496
1497    if ( !csp->http->hostport || !*(csp->http->hostport))
1498    {
1499       return JB_ERR_OK;
1500    }
1501
1502    /*
1503     * remove 'user:pass@' from 'proto://user:pass@host'
1504     */
1505    if ( (p = strchr( csp->http->hostport, '@')) != NULL )
1506    {
1507       p++;
1508    }
1509    else
1510    {
1511       p = csp->http->hostport;
1512    }
1513
1514    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
1515    err = enlist_unique_header(csp->headers, "Host", p);
1516    return err;
1517
1518 }
1519
1520
1521 /*********************************************************************
1522  *
1523  * Function    :  client_cookie_adder
1524  *
1525  * Description :  Used in the add_client_headers list.  Called from `sed'.
1526  *
1527  * Parameters  :
1528  *          1  :  csp = Current client state (buffers, headers, etc...)
1529  *
1530  * Returns     :  JB_ERR_OK on success, or
1531  *                JB_ERR_MEMORY on out-of-memory error.
1532  *
1533  *********************************************************************/
1534 jb_err client_cookie_adder(struct client_state *csp)
1535 {
1536    struct list_entry *lst;
1537    char *tmp;
1538    struct list_entry *list1 = csp->cookie_list->first;
1539    struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1540    int first_cookie = 1;
1541    jb_err err;
1542
1543    if ((list1 == NULL) && (list2 == NULL))
1544    {
1545       /* Nothing to do */
1546       return JB_ERR_OK;
1547    }
1548
1549    tmp = strdup("Cookie: ");
1550
1551    for (lst = list1; lst ; lst = lst->next)
1552    {
1553       if (first_cookie)
1554       {
1555          first_cookie = 0;
1556       }
1557       else
1558       {
1559          string_append(&tmp, "; ");
1560       }
1561       string_append(&tmp, lst->str);
1562    }
1563
1564    for (lst = list2;  lst ; lst = lst->next)
1565    {
1566       if (first_cookie)
1567       {
1568          first_cookie = 0;
1569       }
1570       else
1571       {
1572          string_append(&tmp, "; ");
1573       }
1574       string_join(&tmp, cookie_encode(lst->str));
1575    }
1576
1577    if (tmp == NULL)
1578    {
1579       return JB_ERR_MEMORY;
1580    }
1581
1582    log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1583    err = enlist(csp->headers, tmp);
1584    free(tmp);
1585    return err;
1586 }
1587
1588
1589 /*********************************************************************
1590  *
1591  * Function    :  client_accept_encoding_adder
1592  *
1593  * Description :  Add an Accept-Encoding header to the client's request
1594  *                that disables compression if the action applies, and
1595  *                the header is not already there. Called from `sed'.
1596  *                Note: For HTTP/1.0, the absence of the header is enough.
1597  *
1598  * Parameters  :
1599  *          1  :  csp = Current client state (buffers, headers, etc...)
1600  *
1601  * Returns     :  JB_ERR_OK on success, or
1602  *                JB_ERR_MEMORY on out-of-memory error.
1603  *
1604  *********************************************************************/
1605 jb_err client_accept_encoding_adder(struct client_state *csp)
1606 {
1607    if (   ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1608        && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1609    {
1610       return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1611    }
1612
1613    return JB_ERR_OK;
1614 }
1615
1616
1617 /*********************************************************************
1618  *
1619  * Function    :  client_xtra_adder
1620  *
1621  * Description :  Used in the add_client_headers list.  Called from `sed'.
1622  *
1623  * Parameters  :
1624  *          1  :  csp = Current client state (buffers, headers, etc...)
1625  *
1626  * Returns     :  JB_ERR_OK on success, or
1627  *                JB_ERR_MEMORY on out-of-memory error.
1628  *
1629  *********************************************************************/
1630 jb_err client_xtra_adder(struct client_state *csp)
1631 {
1632    struct list_entry *lst;
1633    jb_err err;
1634
1635    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1636         lst ; lst = lst->next)
1637    {
1638       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1639       err = enlist(csp->headers, lst->str);
1640       if (err)
1641       {
1642          return err;
1643       }
1644
1645    }
1646
1647    return JB_ERR_OK;
1648 }
1649
1650
1651 /*********************************************************************
1652  *
1653  * Function    :  client_x_forwarded_adder
1654  *
1655  * Description :  Used in the add_client_headers list.  Called from `sed'.
1656  *
1657  * Parameters  :
1658  *          1  :  csp = Current client state (buffers, headers, etc...)
1659  *
1660  * Returns     :  JB_ERR_OK on success, or
1661  *                JB_ERR_MEMORY on out-of-memory error.
1662  *
1663  *********************************************************************/
1664 jb_err client_x_forwarded_adder(struct client_state *csp)
1665 {
1666    char *p = NULL;
1667    jb_err err;
1668
1669    if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1670    {
1671       return JB_ERR_OK;
1672    }
1673
1674    if (csp->x_forwarded)
1675    {
1676       p = strdup(csp->x_forwarded);
1677       string_append(&p, ", ");
1678    }
1679    else
1680    {
1681       p = strdup("X-Forwarded-For: ");
1682    }
1683    string_append(&p, csp->ip_addr_str);
1684
1685    if (p == NULL)
1686    {
1687       return JB_ERR_MEMORY;
1688    }
1689
1690    log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1691    err = enlist(csp->headers, p);
1692    free(p);
1693
1694    return err;
1695 }
1696
1697
1698 /*********************************************************************
1699  *
1700  * Function    :  connection_close_adder
1701  *
1702  * Description :  Adds a "Connection: close" header to csp->headers
1703  *                as a temporary fix for the needed but missing HTTP/1.1
1704  *                support. Called from `sed'.
1705  *                FIXME: This whole function shouldn't be neccessary!
1706  *
1707  * Parameters  :
1708  *          1  :  csp = Current client state (buffers, headers, etc...)
1709  *
1710  * Returns     :  JB_ERR_OK on success, or
1711  *                JB_ERR_MEMORY on out-of-memory error.
1712  *
1713  *********************************************************************/
1714 jb_err connection_close_adder(struct client_state *csp)
1715 {
1716    return enlist(csp->headers, "Connection: close");
1717 }
1718
1719
1720 /*********************************************************************
1721  *
1722  * Function    :  server_http
1723  *
1724  * Description :  - Save the HTTP Status into csp->http->status
1725  *                - Set CT_TABOO to prevent filtering if the answer
1726  *                  is a partial range (HTTP status 206)
1727  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1728  *                  action applies.
1729  *
1730  * Parameters  :
1731  *          1  :  csp = Current client state (buffers, headers, etc...)
1732  *          2  :  header = On input, pointer to header to modify.
1733  *                On output, pointer to the modified header, or NULL
1734  *                to remove the header.  This function frees the
1735  *                original string if necessary.
1736  *
1737  * Returns     :  JB_ERR_OK on success, or
1738  *                JB_ERR_MEMORY on out-of-memory error.
1739  *
1740  *********************************************************************/
1741 jb_err server_http(struct client_state *csp, char **header)
1742 {
1743    sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1744    if (csp->http->status == 206)
1745    {
1746       csp->content_type = CT_TABOO;
1747    }
1748
1749    if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1750    {
1751       (*header)[7] = '0';
1752       log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1753    }
1754
1755    return JB_ERR_OK;
1756 }
1757
1758
1759 /*********************************************************************
1760  *
1761  * Function    :  server_set_cookie
1762  *
1763  * Description :  Handle the server "cookie" header properly.
1764  *                Log cookie to the jar file.  Then "crunch" it,
1765  *                or accept it.  Called from `sed'.
1766  *
1767  * Parameters  :
1768  *          1  :  csp = Current client state (buffers, headers, etc...)
1769  *          2  :  header = On input, pointer to header to modify.
1770  *                On output, pointer to the modified header, or NULL
1771  *                to remove the header.  This function frees the
1772  *                original string if necessary.
1773  *
1774  * Returns     :  JB_ERR_OK on success, or
1775  *                JB_ERR_MEMORY on out-of-memory error.
1776  *
1777  *********************************************************************/
1778 jb_err server_set_cookie(struct client_state *csp, char **header)
1779 {
1780 #ifdef FEATURE_COOKIE_JAR
1781    if (csp->config->jar)
1782    {
1783       /*
1784        * Write timestamp into outbuf.
1785        *
1786        * Complex because not all OSs have tm_gmtoff or
1787        * the %z field in strftime()
1788        */
1789       char tempbuf[ BUFFER_SIZE ];
1790       time_t now; 
1791       struct tm tm_now; 
1792       time (&now); 
1793 #ifdef HAVE_LOCALTIME_R
1794       tm_now = *localtime_r(&now, &tm_now);
1795 #elif OSX_DARWIN
1796       pthread_mutex_lock(&localtime_mutex);
1797       tm_now = *localtime (&now); 
1798       pthread_mutex_unlock(&localtime_mutex);
1799 #else
1800       tm_now = *localtime (&now); 
1801 #endif
1802       strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now); 
1803
1804       /* strlen("set-cookie: ") = 12 */
1805       fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1806    }
1807 #endif /* def FEATURE_COOKIE_JAR */
1808
1809    if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1810    {
1811       log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
1812       return crumble(csp, header);
1813    }
1814    else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1815    {
1816       /* Flag whether or not to log a message */
1817       int changed = 0;
1818
1819       /* A variable to store the tag we're working on */
1820       char *cur_tag;
1821
1822       /* Skip "Set-Cookie:" (11 characters) in header */
1823       cur_tag = *header + 11;
1824
1825       /* skip whitespace between "Set-Cookie:" and value */
1826       while (*cur_tag && ijb_isspace(*cur_tag))
1827       {
1828          cur_tag++;
1829       }
1830
1831       /* Loop through each tag in the cookie */
1832       while (*cur_tag)
1833       {
1834          /* Find next tag */
1835          char *next_tag = strchr(cur_tag, ';');
1836          if (next_tag != NULL)
1837          {
1838             /* Skip the ';' character itself */
1839             next_tag++;
1840
1841             /* skip whitespace ";" and start of tag */
1842             while (*next_tag && ijb_isspace(*next_tag))
1843             {
1844                next_tag++;
1845             }
1846          }
1847          else
1848          {
1849             /* "Next tag" is the end of the string */
1850             next_tag = cur_tag + strlen(cur_tag);
1851          }
1852
1853          /* Is this the "Expires" tag? */
1854          if (strncmpic(cur_tag, "expires=", 8) == 0)
1855          {
1856             /* Delete the tag by copying the rest of the string over it.
1857              * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1858              * since the behaviour of strcpy is undefined for overlapping
1859              * strings.)
1860              */
1861             memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1862
1863             /* That changed the header, need to issue a log message */
1864             changed = 1;
1865
1866             /* Note that the next tag has now been moved to *cur_tag,
1867              * so we do not need to update the cur_tag pointer.
1868              */
1869          }
1870          else
1871          {
1872             /* Move on to next cookie tag */
1873             cur_tag = next_tag;
1874          }
1875       }
1876
1877       if (changed)
1878       {
1879          log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1880       }
1881    }
1882
1883    return JB_ERR_OK;
1884 }
1885
1886
1887 #ifdef FEATURE_FORCE_LOAD
1888 /*********************************************************************
1889  *
1890  * Function    :  strclean
1891  *
1892  * Description :  In-Situ-Eliminate all occurances of substring in
1893  *                string
1894  *
1895  * Parameters  :
1896  *          1  :  string = string to clean
1897  *          2  :  substring = substring to eliminate
1898  *
1899  * Returns     :  Number of eliminations
1900  *
1901  *********************************************************************/
1902 int strclean(const char *string, const char *substring)
1903 {
1904    int hits = 0, len = strlen(substring);
1905    char *pos, *p;
1906
1907    while((pos = strstr(string, substring)) != NULL)
1908    {
1909       p = pos + len;
1910       do
1911       {
1912          *(p - len) = *p;
1913       }
1914       while (*p++ != '\0');
1915
1916       hits++;
1917    }
1918
1919    return(hits);
1920 }
1921 #endif /* def FEATURE_FORCE_LOAD */
1922
1923
1924 /*
1925   Local Variables:
1926   tab-width: 3
1927   end:
1928 */