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