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