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