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