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