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