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