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