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