Remove redundant log message in client_save_content_length().
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.206 2009/08/19 15:57:13 fabiankeil 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', `filter_header'
14  *                   `server_content_encoding', `server_content_disposition',
15  *                   `server_last_modified', `client_accept_language',
16  *                   `crunch_client_header', `client_if_modified_since',
17  *                   `client_if_none_match', `get_destination_from_headers',
18  *                   `parse_header_time', `decompress_iob' and `server_set_cookie'.
19  *
20  * Copyright   :  Written by and Copyright (C) 2001-2009 the
21  *                Privoxy team. http://www.privoxy.org/
22  *
23  *                Based on the Internet Junkbuster originally written
24  *                by and Copyright (C) 1997 Anonymous Coders and
25  *                Junkbusters Corporation.  http://www.junkbusters.com
26  *
27  *                This program is free software; you can redistribute it
28  *                and/or modify it under the terms of the GNU General
29  *                Public License as published by the Free Software
30  *                Foundation; either version 2 of the License, or (at
31  *                your option) any later version.
32  *
33  *                This program is distributed in the hope that it will
34  *                be useful, but WITHOUT ANY WARRANTY; without even the
35  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
36  *                PARTICULAR PURPOSE.  See the GNU General Public
37  *                License for more details.
38  *
39  *                The GNU General Public License should be included with
40  *                this file.  If not, you can view it at
41  *                http://www.gnu.org/copyleft/gpl.html
42  *                or write to the Free Software Foundation, Inc., 59
43  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
44  *
45  *********************************************************************/
46
47
48 #include "config.h"
49
50 #ifndef _WIN32
51 #include <stdio.h>
52 #include <sys/types.h>
53 #endif
54
55 #include <stdlib.h>
56 #include <ctype.h>
57 #include <assert.h>
58 #include <string.h>
59
60 #ifdef __GLIBC__
61 /*
62  * Convince GNU's libc to provide a strptime prototype.
63  */
64 #define __USE_XOPEN
65 #endif /*__GLIBC__ */
66 #include <time.h>
67
68 #ifdef FEATURE_ZLIB
69 #include <zlib.h>
70
71 #define GZIP_IDENTIFIER_1       0x1f
72 #define GZIP_IDENTIFIER_2       0x8b
73
74 #define GZIP_FLAG_CHECKSUM      0x02
75 #define GZIP_FLAG_EXTRA_FIELDS  0x04
76 #define GZIP_FLAG_FILE_NAME     0x08
77 #define GZIP_FLAG_COMMENT       0x10
78 #define GZIP_FLAG_RESERVED_BITS 0xe0
79 #endif
80
81 #if !defined(_WIN32) && !defined(__OS2__)
82 #include <unistd.h>
83 #endif
84
85 #include "project.h"
86
87 #ifdef FEATURE_PTHREAD
88 #include "jcc.h"
89 /* jcc.h is for mutex semapores only */
90 #endif /* def FEATURE_PTHREAD */
91 #include "list.h"
92 #include "parsers.h"
93 #include "ssplit.h"
94 #include "errlog.h"
95 #include "jbsockets.h"
96 #include "miscutil.h"
97 #include "list.h"
98 #include "actions.h"
99 #include "filters.h"
100
101 #ifndef HAVE_STRPTIME
102 #include "strptime.h"
103 #endif
104
105 const char parsers_h_rcs[] = PARSERS_H_VERSION;
106
107 /* Fix a problem with Solaris.  There should be no effect on other
108  * platforms.
109  * Solaris's isspace() is a macro which uses its argument directly
110  * as an array index.  Therefore we need to make sure that high-bit
111  * characters generate +ve values, and ideally we also want to make
112  * the argument match the declared parameter type of "int".
113  *
114  * Why did they write a character function that can't take a simple
115  * "char" argument?  Doh!
116  */
117 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
118 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
119
120 static char *get_header_line(struct iob *iob);
121 static jb_err scan_headers(struct client_state *csp);
122 static jb_err header_tagger(struct client_state *csp, char *header);
123 static jb_err parse_header_time(const char *header_time, time_t *result);
124
125 static jb_err crumble                   (struct client_state *csp, char **header);
126 static jb_err filter_header             (struct client_state *csp, char **header);
127 static jb_err client_connection         (struct client_state *csp, char **header);
128 static jb_err client_referrer           (struct client_state *csp, char **header);
129 static jb_err client_uagent             (struct client_state *csp, char **header);
130 static jb_err client_ua                 (struct client_state *csp, char **header);
131 static jb_err client_from               (struct client_state *csp, char **header);
132 static jb_err client_send_cookie        (struct client_state *csp, char **header);
133 static jb_err client_x_forwarded        (struct client_state *csp, char **header);
134 static jb_err client_accept_encoding    (struct client_state *csp, char **header);
135 static jb_err client_te                 (struct client_state *csp, char **header);
136 static jb_err client_max_forwards       (struct client_state *csp, char **header);
137 static jb_err client_host               (struct client_state *csp, char **header);
138 static jb_err client_if_modified_since  (struct client_state *csp, char **header);
139 static jb_err client_accept_language    (struct client_state *csp, char **header);
140 static jb_err client_if_none_match      (struct client_state *csp, char **header);
141 static jb_err crunch_client_header      (struct client_state *csp, char **header);
142 static jb_err client_x_filter           (struct client_state *csp, char **header);
143 static jb_err client_range              (struct client_state *csp, char **header);
144 static jb_err server_set_cookie         (struct client_state *csp, char **header);
145 static jb_err server_connection         (struct client_state *csp, char **header);
146 static jb_err server_content_type       (struct client_state *csp, char **header);
147 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
148 static jb_err server_content_md5        (struct client_state *csp, char **header);
149 static jb_err server_content_encoding   (struct client_state *csp, char **header);
150 static jb_err server_transfer_coding    (struct client_state *csp, char **header);
151 static jb_err server_http               (struct client_state *csp, char **header);
152 static jb_err crunch_server_header      (struct client_state *csp, char **header);
153 static jb_err server_last_modified      (struct client_state *csp, char **header);
154 static jb_err server_content_disposition(struct client_state *csp, char **header);
155
156 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
157 static jb_err server_save_content_length(struct client_state *csp, char **header);
158 static jb_err server_keep_alive(struct client_state *csp, char **header);
159 static jb_err server_proxy_connection(struct client_state *csp, char **header);
160 static jb_err client_keep_alive(struct client_state *csp, char **header);
161 static jb_err client_save_content_length(struct client_state *csp, char **header);
162 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
163
164 static jb_err client_host_adder       (struct client_state *csp);
165 static jb_err client_xtra_adder       (struct client_state *csp);
166 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
167 static jb_err client_connection_header_adder(struct client_state *csp);
168 static jb_err server_connection_adder(struct client_state *csp);
169 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
170 static jb_err server_proxy_connection_adder(struct client_state *csp);
171 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
172
173 static jb_err create_forged_referrer(char **header, const char *hostport);
174 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
175 static jb_err handle_conditional_hide_referrer_parameter(char **header,
176    const char *host, const int parameter_conditional_block);
177 static void create_content_length_header(unsigned long long content_length,
178                                          char *header, size_t buffer_length);
179
180 /*
181  * List of functions to run on a list of headers.
182  */
183 struct parsers
184 {
185    /** The header prefix to match */
186    const char *str;
187    
188    /** The length of the prefix to match */
189    const size_t len;
190    
191    /** The function to apply to this line */
192    const parser_func_ptr parser;
193 };
194
195 static const struct parsers client_patterns[] = {
196    { "referer:",                  8,   client_referrer },
197    { "user-agent:",              11,   client_uagent },
198    { "ua-",                       3,   client_ua },
199    { "from:",                     5,   client_from },
200    { "cookie:",                   7,   client_send_cookie },
201    { "x-forwarded-for:",         16,   client_x_forwarded },
202    { "Accept-Encoding:",         16,   client_accept_encoding },
203    { "TE:",                       3,   client_te },
204    { "Host:",                     5,   client_host },
205    { "if-modified-since:",       18,   client_if_modified_since },
206 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
207    { "Keep-Alive:",              11,   client_keep_alive },
208    { "Content-Length:",          15,   client_save_content_length },
209 #else
210    { "Keep-Alive:",              11,   crumble },
211 #endif
212    { "connection:",              11,   client_connection },
213    { "proxy-connection:",        17,   crumble },
214    { "max-forwards:",            13,   client_max_forwards },
215    { "Accept-Language:",         16,   client_accept_language },
216    { "if-none-match:",           14,   client_if_none_match },
217    { "Range:",                    6,   client_range },
218    { "Request-Range:",           14,   client_range },
219    { "If-Range:",                 9,   client_range },
220    { "X-Filter:",                 9,   client_x_filter },
221    { "*",                         0,   crunch_client_header },
222    { "*",                         0,   filter_header },
223    { NULL,                        0,   NULL }
224 };
225
226 static const struct parsers server_patterns[] = {
227    { "HTTP/",                     5, server_http },
228    { "set-cookie:",              11, server_set_cookie },
229    { "connection:",              11, server_connection },
230    { "Content-Type:",            13, server_content_type },
231    { "Content-MD5:",             12, server_content_md5 },
232    { "Content-Encoding:",        17, server_content_encoding },
233 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
234    { "Content-Length:",          15, server_save_content_length },
235    { "Keep-Alive:",              11, server_keep_alive },
236    { "Proxy-Connection:",        17, server_proxy_connection },
237 #else
238    { "Keep-Alive:",              11, crumble },
239 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
240    { "Transfer-Encoding:",       18, server_transfer_coding },
241    { "content-disposition:",     20, server_content_disposition },
242    { "Last-Modified:",           14, server_last_modified },
243    { "*",                         0, crunch_server_header },
244    { "*",                         0, filter_header },
245    { NULL,                        0, NULL }
246 };
247
248 static const add_header_func_ptr add_client_headers[] = {
249    client_host_adder,
250    client_x_forwarded_for_adder,
251    client_xtra_adder,
252    /* Temporarily disabled:    client_accept_encoding_adder, */
253    client_connection_header_adder,
254    NULL
255 };
256
257 static const add_header_func_ptr add_server_headers[] = {
258    server_connection_adder,
259 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
260    server_proxy_connection_adder,
261 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
262    NULL
263 };
264
265 /*********************************************************************
266  *
267  * Function    :  flush_socket
268  *
269  * Description :  Write any pending "buffered" content.
270  *
271  * Parameters  :
272  *          1  :  fd = file descriptor of the socket to read
273  *          2  :  iob = The I/O buffer to flush, usually csp->iob.
274  *
275  * Returns     :  On success, the number of bytes written are returned (zero
276  *                indicates nothing was written).  On error, -1 is returned,
277  *                and errno is set appropriately.  If count is zero and the
278  *                file descriptor refers to a regular file, 0 will be
279  *                returned without causing any other effect.  For a special
280  *                file, the results are not portable.
281  *
282  *********************************************************************/
283 long flush_socket(jb_socket fd, struct iob *iob)
284 {
285    long len = iob->eod - iob->cur;
286
287    if (len <= 0)
288    {
289       return(0);
290    }
291
292    if (write_socket(fd, iob->cur, (size_t)len))
293    {
294       return(-1);
295    }
296    iob->eod = iob->cur = iob->buf;
297    return(len);
298
299 }
300
301
302 /*********************************************************************
303  *
304  * Function    :  add_to_iob
305  *
306  * Description :  Add content to the buffered page, expanding the
307  *                buffer if necessary.
308  *
309  * Parameters  :
310  *          1  :  csp = Current client state (buffers, headers, etc...)
311  *          2  :  buf = holds the content to be added to the page
312  *          3  :  n = number of bytes to be added
313  *
314  * Returns     :  JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
315  *                or buffer limit reached.
316  *
317  *********************************************************************/
318 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
319 {
320    struct iob *iob = csp->iob;
321    size_t used, offset, need, want;
322    char *p;
323
324    if (n <= 0) return JB_ERR_OK;
325
326    used   = (size_t)(iob->eod - iob->buf);
327    offset = (size_t)(iob->cur - iob->buf);
328    need   = used + (size_t)n + 1;
329
330    /*
331     * If the buffer can't hold the new data, extend it first.
332     * Use the next power of two if possible, else use the actual need.
333     */
334    if (need > csp->config->buffer_limit)
335    {
336       log_error(LOG_LEVEL_INFO,
337          "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
338          need, csp->config->buffer_limit);
339       return JB_ERR_MEMORY;
340    }
341
342    if (need > iob->size)
343    {
344       for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
345       
346       if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
347       {
348          iob->size = want;
349       }
350       else if (NULL != (p = (char *)realloc(iob->buf, need)))
351       {
352          iob->size = need;
353       }
354       else
355       {
356          log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
357          return JB_ERR_MEMORY;
358       }
359
360       /* Update the iob pointers */
361       iob->cur = p + offset;
362       iob->eod = p + used;
363       iob->buf = p;
364    }
365
366    /* copy the new data into the iob buffer */
367    memcpy(iob->eod, buf, (size_t)n);
368
369    /* point to the end of the data */
370    iob->eod += n;
371
372    /* null terminate == cheap insurance */
373    *iob->eod = '\0';
374
375    return JB_ERR_OK;
376
377 }
378
379
380 #ifdef FEATURE_ZLIB
381 /*********************************************************************
382  *
383  * Function    :  decompress_iob
384  *
385  * Description :  Decompress buffered page, expanding the
386  *                buffer as necessary.  csp->iob->cur
387  *                should point to the the beginning of the
388  *                compressed data block.
389  *
390  * Parameters  :
391  *          1  :  csp = Current client state (buffers, headers, etc...)
392  *
393  * Returns     :  JB_ERR_OK on success,
394  *                JB_ERR_MEMORY if out-of-memory limit reached, and
395  *                JB_ERR_COMPRESS if error decompressing buffer.
396  *
397  *********************************************************************/
398 jb_err decompress_iob(struct client_state *csp)
399 {
400    char  *buf;       /* new, uncompressed buffer */
401    char  *cur;       /* Current iob position (to keep the original 
402                       * iob->cur unmodified if we return early) */
403    size_t bufsize;   /* allocated size of the new buffer */
404    size_t old_size;  /* Content size before decompression */
405    size_t skip_size; /* Number of bytes at the beginning of the iob
406                         that we should NOT decompress. */
407    int status;       /* return status of the inflate() call */
408    z_stream zstr;    /* used by calls to zlib */
409
410    assert(csp->iob->cur - csp->iob->buf > 0);
411    assert(csp->iob->eod - csp->iob->cur > 0);
412
413    bufsize = csp->iob->size;
414    skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
415    old_size = (size_t)(csp->iob->eod - csp->iob->cur);
416
417    cur = csp->iob->cur;
418
419    if (bufsize < (size_t)10)
420    {
421       /*
422        * This is to protect the parsing of gzipped data,
423        * but it should(?) be valid for deflated data also.
424        */
425       log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
426       return JB_ERR_COMPRESS;
427    }
428
429    if (csp->content_type & CT_GZIP)
430    {
431       /*
432        * Our task is slightly complicated by the facts that data
433        * compressed by gzip does not include a zlib header, and
434        * that there is no easily accessible interface in zlib to
435        * handle a gzip header. We strip off the gzip header by
436        * hand, and later inform zlib not to expect a header.
437        */
438
439       /*
440        * Strip off the gzip header. Please see RFC 1952 for more
441        * explanation of the appropriate fields.
442        */
443       if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
444        || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
445        || (*cur++ != Z_DEFLATED))
446       {
447          log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
448          return JB_ERR_COMPRESS;
449       }
450       else
451       {
452          int flags = *cur++;
453          if (flags & GZIP_FLAG_RESERVED_BITS)
454          {
455             /* The gzip header has reserved bits set; bail out. */
456             log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
457             return JB_ERR_COMPRESS;
458          }
459
460          /*
461           * Skip mtime (4 bytes), extra flags (1 byte)
462           * and OS type (1 byte).
463           */
464          cur += 6;
465
466          /* Skip extra fields if necessary. */
467          if (flags & GZIP_FLAG_EXTRA_FIELDS)
468          {
469             /*
470              * Skip a given number of bytes, specified
471              * as a 16-bit little-endian value.
472              *
473              * XXX: this code is untested and should probably be removed.
474              */
475             int skip_bytes;
476             skip_bytes = *cur++;
477             skip_bytes += *cur++ << 8;
478
479             /*
480              * The number of bytes to skip should be positive
481              * and we'd like to stay in the buffer.
482              */
483             if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
484             {
485                log_error(LOG_LEVEL_ERROR,
486                   "Unreasonable amount of bytes to skip (%d). Stopping decompression",
487                   skip_bytes);
488                return JB_ERR_COMPRESS;
489             }
490             log_error(LOG_LEVEL_INFO,
491                "Skipping %d bytes for gzip compression. Does this sound right?",
492                skip_bytes);
493             cur += skip_bytes;
494          }
495
496          /* Skip the filename if necessary. */
497          if (flags & GZIP_FLAG_FILE_NAME)
498          {
499             /* A null-terminated string is supposed to follow. */
500             while (*cur++ && (cur < csp->iob->eod));
501          }
502
503          /* Skip the comment if necessary. */
504          if (flags & GZIP_FLAG_COMMENT)
505          {
506             /* A null-terminated string is supposed to follow. */
507             while (*cur++ && (cur < csp->iob->eod));
508          }
509
510          /* Skip the CRC if necessary. */
511          if (flags & GZIP_FLAG_CHECKSUM)
512          {
513             cur += 2;
514          }
515
516          if (cur >= csp->iob->eod)
517          {
518             /*
519              * If the current position pointer reached or passed
520              * the buffer end, we were obviously tricked to skip
521              * too much.
522              */
523             log_error(LOG_LEVEL_ERROR,
524                "Malformed gzip header detected. Aborting decompression.");
525             return JB_ERR_COMPRESS;
526          }
527       }
528    }
529    else if (csp->content_type & CT_DEFLATE)
530    {
531       /*
532        * XXX: The debug level should be lowered
533        * before the next stable release.
534        */
535       log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
536       /*
537        * In theory (that is, according to RFC 1950), deflate-compressed
538        * data should begin with a two-byte zlib header and have an
539        * adler32 checksum at the end. It seems that in practice only
540        * the raw compressed data is sent. Note that this means that
541        * we are not RFC 1950-compliant here, but the advantage is that
542        * this actually works. :)
543        *
544        * We add a dummy null byte to tell zlib where the data ends,
545        * and later inform it not to expect a header.
546        *
547        * Fortunately, add_to_iob() has thoughtfully null-terminated
548        * the buffer; we can just increment the end pointer to include
549        * the dummy byte.  
550        */
551       csp->iob->eod++;
552    }
553    else
554    {
555       log_error(LOG_LEVEL_ERROR,
556          "Unable to determine compression format for decompression");
557       return JB_ERR_COMPRESS;
558    }
559
560    /* Set up the fields required by zlib. */
561    zstr.next_in  = (Bytef *)cur;
562    zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
563    zstr.zalloc   = Z_NULL;
564    zstr.zfree    = Z_NULL;
565    zstr.opaque   = Z_NULL;
566
567    /*
568     * Passing -MAX_WBITS to inflateInit2 tells the library
569     * that there is no zlib header.
570     */
571    if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
572    {
573       log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
574       return JB_ERR_COMPRESS;
575    }
576
577    /*
578     * Next, we allocate new storage for the inflated data.
579     * We don't modify the existing iob yet, so in case there
580     * is error in decompression we can recover gracefully.
581     */
582    buf = zalloc(bufsize);
583    if (NULL == buf)
584    {
585       log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
586       return JB_ERR_MEMORY;
587    }
588
589    assert(bufsize >= skip_size);
590    memcpy(buf, csp->iob->buf, skip_size);
591    zstr.avail_out = (uInt)(bufsize - skip_size);
592    zstr.next_out  = (Bytef *)buf + skip_size;
593
594    /* Try to decompress the whole stream in one shot. */
595    while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
596    {
597       /* We need to allocate more memory for the output buffer. */
598
599       char *tmpbuf;                /* used for realloc'ing the buffer */
600       size_t oldbufsize = bufsize; /* keep track of the old bufsize */
601
602       if (0 == zstr.avail_in)
603       {
604          /*
605           * If zlib wants more data then there's a problem, because
606           * the complete compressed file should have been buffered.
607           */
608          log_error(LOG_LEVEL_ERROR,
609             "Unexpected end of compressed iob. Using what we got so far.");
610          break;
611       }
612
613       /*
614        * If we tried the limit and still didn't have enough
615        * memory, just give up.
616        */
617       if (bufsize == csp->config->buffer_limit)
618       {
619          log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
620          return JB_ERR_MEMORY;
621       }
622
623       /* Try doubling the buffer size each time. */
624       bufsize *= 2;
625
626       /* Don't exceed the buffer limit. */
627       if (bufsize > csp->config->buffer_limit)
628       {
629          bufsize = csp->config->buffer_limit;
630       }
631     
632       /* Try to allocate the new buffer. */
633       tmpbuf = realloc(buf, bufsize);
634       if (NULL == tmpbuf)
635       {
636          log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
637          freez(buf);
638          return JB_ERR_MEMORY;
639       }
640       else
641       {
642          char *oldnext_out = (char *)zstr.next_out;
643
644          /*
645           * Update the fields for inflate() to use the new
646           * buffer, which may be in a location different from
647           * the old one.
648           */
649          zstr.avail_out += (uInt)(bufsize - oldbufsize);
650          zstr.next_out   = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
651
652          /*
653           * Compare with an uglier method of calculating these values
654           * that doesn't require the extra oldbufsize variable.
655           */
656          assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
657          assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
658
659          buf = tmpbuf;
660       }
661    }
662
663    if (Z_STREAM_ERROR == inflateEnd(&zstr))
664    {
665       log_error(LOG_LEVEL_ERROR,
666          "Inconsistent stream state after decompression: %s", zstr.msg);
667       /*
668        * XXX: Intentionally no return.
669        *
670        * According to zlib.h, Z_STREAM_ERROR is returned
671        * "if the stream state was inconsistent".
672        *
673        * I assume in this case inflate()'s status
674        * would also be something different than Z_STREAM_END
675        * so this check should be redundant, but lets see.
676        */
677    }
678
679    if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
680    {
681       /*
682        * We failed to decompress the stream and it's
683        * not simply because of missing data.
684        */
685       log_error(LOG_LEVEL_ERROR,
686          "Unexpected error while decompressing to the buffer (iob): %s",
687          zstr.msg);
688       return JB_ERR_COMPRESS;
689    }
690
691    /*
692     * Finally, we can actually update the iob, since the
693     * decompression was successful. First, free the old
694     * buffer.
695     */
696    freez(csp->iob->buf);
697
698    /* Now, update the iob to use the new buffer. */
699    csp->iob->buf  = buf;
700    csp->iob->cur  = csp->iob->buf + skip_size;
701    csp->iob->eod  = (char *)zstr.next_out;
702    csp->iob->size = bufsize;
703   
704    /*
705     * Make sure the new uncompressed iob obeys some minimal
706     * consistency conditions.
707     */
708    if ((csp->iob->buf <  csp->iob->cur)
709     && (csp->iob->cur <= csp->iob->eod)
710     && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
711    {
712       const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
713       if (new_size > (size_t)0)
714       {
715          log_error(LOG_LEVEL_RE_FILTER,
716             "Decompression successful. Old size: %d, new size: %d.",
717             old_size, new_size);
718       }
719       else
720       {
721          /* zlib thinks this is OK, so lets do the same. */
722          log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
723       }
724    }
725    else
726    {
727       /* It seems that zlib did something weird. */
728       log_error(LOG_LEVEL_ERROR,
729          "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
730          csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
731          csp->iob->eod, csp->iob->buf + csp->iob->size);
732       return JB_ERR_COMPRESS;
733    }
734
735    return JB_ERR_OK;
736
737 }
738 #endif /* defined(FEATURE_ZLIB) */
739
740
741 /*********************************************************************
742  *
743  * Function    :  string_move
744  *
745  * Description :  memmove wrapper to move the last part of a string
746  *                towards the beginning, overwriting the part in
747  *                the middle. strlcpy() can't be used here as the
748  *                strings overlap.
749  *
750  * Parameters  :
751  *          1  :  dst = Destination to overwrite
752  *          2  :  src = Source to move.
753  *
754  * Returns     :  N/A
755  *
756  *********************************************************************/
757 static void string_move(char *dst, char *src)
758 {
759    assert(dst < src);
760
761    /* +1 to copy the terminating nul as well. */
762    memmove(dst, src, strlen(src)+1);
763 }
764
765
766 /*********************************************************************
767  *
768  * Function    :  normalize_lws
769  *
770  * Description :  Reduces unquoted linear white space in headers
771  *                to a single space in accordance with RFC 2616 2.2.
772  *                This simplifies parsing and filtering later on.
773  *
774  *                XXX: Remove log messages before
775  *                     the next stable release?
776  *
777  * Parameters  :
778  *          1  :  header = A header with linear white space to reduce.
779  *
780  * Returns     :  N/A
781  *
782  *********************************************************************/
783 static void normalize_lws(char *header)
784 {
785    char *p = header;
786
787    while (*p != '\0')
788    {
789       if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
790       {
791          char *q = p+1;
792
793          while (ijb_isspace(*q))
794          {
795             q++;
796          }
797          log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
798          string_move(p+1, q);
799       }
800
801       if (*p == '\t')
802       {
803          log_error(LOG_LEVEL_HEADER,
804             "Converting tab to space in '%s'", header);
805          *p = ' ';
806       }
807       else if (*p == '"')
808       {
809          char *end_of_token = strstr(p+1, "\"");
810
811          if (NULL != end_of_token)
812          {
813             /* Don't mess with quoted text. */
814             p = end_of_token;
815          }
816          else
817          {
818             log_error(LOG_LEVEL_HEADER,
819                "Ignoring single quote in '%s'", header);
820          }
821       }
822       p++;
823    }
824
825    p = strchr(header, ':');
826    if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
827    {
828       /*
829        * There's still space before the colon.
830        * We don't want it.
831        */
832       string_move(p-1, p);
833    }
834 }
835
836
837 /*********************************************************************
838  *
839  * Function    :  get_header
840  *
841  * Description :  This (odd) routine will parse the csp->iob
842  *                to get the next complete header.
843  *
844  * Parameters  :
845  *          1  :  iob = The I/O buffer to parse, usually csp->iob.
846  *
847  * Returns     :  Any one of the following:
848  *
849  * 1) a pointer to a dynamically allocated string that contains a header line
850  * 2) NULL  indicating that the end of the header was reached
851  * 3) ""    indicating that the end of the iob was reached before finding
852  *          a complete header line.
853  *
854  *********************************************************************/
855 char *get_header(struct iob *iob)
856 {
857    char *header;
858
859    header = get_header_line(iob);
860
861    if ((header == NULL) || (*header == '\0'))
862    {
863       /*
864        * No complete header read yet, tell the client.
865        */
866       return header;
867    }
868
869    while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
870    {
871       /*
872        * Header spans multiple lines, append the next one.
873        */
874       char *continued_header;
875       
876       continued_header = get_header_line(iob);
877       if ((continued_header == NULL) || (*continued_header == '\0'))
878       {
879          /*
880           * No complete header read yet, return what we got.
881           * XXX: Should "unread" header instead.
882           */
883          log_error(LOG_LEVEL_INFO,
884             "Failed to read a multi-line header properly: '%s'",
885             header);
886          break;
887       }
888
889       if (JB_ERR_OK != string_join(&header, continued_header))
890       {
891          log_error(LOG_LEVEL_FATAL,
892             "Out of memory while appending multiple headers.");
893       }
894       else
895       {
896          /* XXX: remove before next stable release. */
897          log_error(LOG_LEVEL_HEADER,
898             "Merged multiple header lines to: '%s'",
899             header);
900       }
901    }
902
903    normalize_lws(header);
904
905    return header;
906
907 }
908
909
910 /*********************************************************************
911  *
912  * Function    :  get_header_line
913  *
914  * Description :  This (odd) routine will parse the csp->iob
915  *                to get the next header line.
916  *
917  * Parameters  :
918  *          1  :  iob = The I/O buffer to parse, usually csp->iob.
919  *
920  * Returns     :  Any one of the following:
921  *
922  * 1) a pointer to a dynamically allocated string that contains a header line
923  * 2) NULL  indicating that the end of the header was reached
924  * 3) ""    indicating that the end of the iob was reached before finding
925  *          a complete header line.
926  *
927  *********************************************************************/
928 static char *get_header_line(struct iob *iob)
929 {
930    char *p, *q, *ret;
931
932    if ((iob->cur == NULL)
933       || ((p = strchr(iob->cur, '\n')) == NULL))
934    {
935       return(""); /* couldn't find a complete header */
936    }
937
938    *p = '\0';
939
940    ret = strdup(iob->cur);
941    if (ret == NULL)
942    {
943       /* FIXME No way to handle error properly */
944       log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
945    }
946    assert(ret != NULL);
947
948    iob->cur = p+1;
949
950    if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
951
952    /* is this a blank line (i.e. the end of the header) ? */
953    if (*ret == '\0')
954    {
955       freez(ret);
956       return NULL;
957    }
958
959    return ret;
960
961 }
962
963
964 /*********************************************************************
965  *
966  * Function    :  get_header_value
967  *
968  * Description :  Get the value of a given header from a chained list
969  *                of header lines or return NULL if no such header is
970  *                present in the list.
971  *
972  * Parameters  :
973  *          1  :  header_list = pointer to list
974  *          2  :  header_name = string with name of header to look for.
975  *                              Trailing colon required, capitalization
976  *                              doesn't matter.
977  *
978  * Returns     :  NULL if not found, else value of header
979  *
980  *********************************************************************/
981 char *get_header_value(const struct list *header_list, const char *header_name)
982 {
983    struct list_entry *cur_entry;
984    char *ret = NULL;
985    size_t length = 0;
986
987    assert(header_list);
988    assert(header_name);
989    length = strlen(header_name);
990
991    for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
992    {
993       if (cur_entry->str)
994       {
995          if (!strncmpic(cur_entry->str, header_name, length))
996          {
997             /*
998              * Found: return pointer to start of value
999              */
1000             ret = cur_entry->str + length;
1001             while (*ret && ijb_isspace(*ret)) ret++;
1002             return ret;
1003          }
1004       }
1005    }
1006
1007    /* 
1008     * Not found
1009     */
1010    return NULL;
1011
1012 }
1013
1014
1015 /*********************************************************************
1016  *
1017  * Function    :  scan_headers
1018  *
1019  * Description :  Scans headers, applies tags and updates action bits. 
1020  *
1021  * Parameters  :
1022  *          1  :  csp = Current client state (buffers, headers, etc...)
1023  *
1024  * Returns     :  JB_ERR_OK
1025  *
1026  *********************************************************************/
1027 static jb_err scan_headers(struct client_state *csp)
1028 {
1029    struct list_entry *h; /* Header */
1030    jb_err err = JB_ERR_OK;
1031
1032    for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1033    {
1034       /* Header crunch()ed in previous run? -> ignore */
1035       if (h->str == NULL) continue;
1036       log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1037       err = header_tagger(csp, h->str);
1038    }
1039
1040    return err;
1041 }
1042
1043
1044 /*********************************************************************
1045  *
1046  * Function    :  sed
1047  *
1048  * Description :  add, delete or modify lines in the HTTP header streams.
1049  *                On entry, it receives a linked list of headers space
1050  *                that was allocated dynamically (both the list nodes
1051  *                and the header contents).
1052  *
1053  *                As a side effect it frees the space used by the original
1054  *                header lines.
1055  *
1056  * Parameters  :
1057  *          1  :  csp = Current client state (buffers, headers, etc...)
1058  *          2  :  filter_server_headers = Boolean to switch between
1059  *                                        server and header filtering.
1060  *
1061  * Returns     :  JB_ERR_OK in case off success, or
1062  *                JB_ERR_MEMORY on out-of-memory error.
1063  *
1064  *********************************************************************/
1065 jb_err sed(struct client_state *csp, int filter_server_headers)
1066 {
1067    /* XXX: use more descriptive names. */
1068    struct list_entry *p;
1069    const struct parsers *v;
1070    const add_header_func_ptr *f;
1071    jb_err err = JB_ERR_OK;
1072
1073    if (filter_server_headers)
1074    {
1075       v = server_patterns;
1076       f = add_server_headers;
1077    }
1078    else
1079    {
1080       v = client_patterns;
1081       f = add_client_headers;
1082    }
1083
1084    scan_headers(csp);
1085
1086    while ((err == JB_ERR_OK) && (v->str != NULL))
1087    {
1088       for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1089       {
1090          /* Header crunch()ed in previous run? -> ignore */
1091          if (p->str == NULL) continue;
1092
1093          /* Does the current parser handle this header? */
1094          if ((strncmpic(p->str, v->str, v->len) == 0) ||
1095              (v->len == CHECK_EVERY_HEADER_REMAINING))
1096          {
1097             err = v->parser(csp, &(p->str));
1098          }
1099       }
1100       v++;
1101    }
1102
1103    /* place additional headers on the csp->headers list */
1104    while ((err == JB_ERR_OK) && (*f))
1105    {
1106       err = (*f)(csp);
1107       f++;
1108    }
1109
1110    return err;
1111 }
1112
1113
1114 /*********************************************************************
1115  *
1116  * Function    :  update_server_headers
1117  *
1118  * Description :  Updates server headers after the body has been modified.
1119  *
1120  * Parameters  :
1121  *          1  :  csp = Current client state (buffers, headers, etc...)
1122  *
1123  * Returns     :  JB_ERR_OK in case off success, or
1124  *                JB_ERR_MEMORY on out-of-memory error.
1125  *
1126  *********************************************************************/
1127 jb_err update_server_headers(struct client_state *csp)
1128 {
1129    jb_err err = JB_ERR_OK;
1130
1131    static const struct parsers server_patterns_light[] = {
1132       { "Content-Length:",    15, server_adjust_content_length },
1133       { "Transfer-Encoding:", 18, server_transfer_coding },
1134 #ifdef FEATURE_ZLIB
1135       { "Content-Encoding:",  17, server_content_encoding },
1136 #endif /* def FEATURE_ZLIB */
1137       { NULL,                  0, NULL }
1138    };
1139
1140    if (strncmpic(csp->http->cmd, "HEAD", 4))
1141    {
1142       const struct parsers *v;
1143       struct list_entry *p;
1144
1145       for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1146       {
1147          for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1148          {
1149             /* Header crunch()ed in previous run? -> ignore */
1150             if (p->str == NULL) continue;
1151
1152             /* Does the current parser handle this header? */
1153             if (strncmpic(p->str, v->str, v->len) == 0)
1154             {
1155                err = v->parser(csp, (char **)&(p->str));
1156             }
1157          }
1158       }
1159    }
1160
1161 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1162    if ((JB_ERR_OK == err)
1163     && (csp->flags & CSP_FLAG_MODIFIED)
1164     && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1165     && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1166    {
1167       char header[50];
1168
1169       create_content_length_header(csp->content_length, header, sizeof(header));
1170       err = enlist(csp->headers, header);
1171       if (JB_ERR_OK == err)
1172       {
1173          log_error(LOG_LEVEL_HEADER,
1174             "Content modified with no Content-Length header set. "
1175             "Created: %s.", header);
1176       }
1177    }
1178 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1179
1180    return err;
1181 }
1182
1183
1184 /*********************************************************************
1185  *
1186  * Function    :  header_tagger
1187  *
1188  * Description :  Executes all text substitutions from applying
1189  *                tag actions and saves the result as tag.
1190  *
1191  *                XXX: Shares enough code with filter_header() and
1192  *                pcrs_filter_response() to warrant some helper functions.
1193  *
1194  * Parameters  :
1195  *          1  :  csp = Current client state (buffers, headers, etc...)
1196  *          2  :  header = Header that is used as tagger input
1197  *
1198  * Returns     :  JB_ERR_OK on success and always succeeds
1199  *
1200  *********************************************************************/
1201 static jb_err header_tagger(struct client_state *csp, char *header)
1202 {
1203    int wanted_filter_type;
1204    int multi_action_index;
1205    int i;
1206    pcrs_job *job;
1207
1208    struct file_list *fl;
1209    struct re_filterfile_spec *b;
1210    struct list_entry *tag_name;
1211
1212    int found_filters = 0;
1213    const size_t header_length = strlen(header);
1214
1215    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1216    {
1217       wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1218       multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1219    }
1220    else
1221    {
1222       wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1223       multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1224    }
1225
1226    /* Check if there are any filters */
1227    for (i = 0; i < MAX_AF_FILES; i++)
1228    {
1229       fl = csp->rlist[i];
1230       if (NULL != fl)
1231       {
1232          if (NULL != fl->f)
1233          {
1234            found_filters = 1;
1235            break;
1236          }
1237       }
1238    }
1239
1240    if (0 == found_filters)
1241    {
1242       log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1243          "tagging enabled, but no taggers available.");
1244       return JB_ERR_OK;
1245    }
1246
1247    for (i = 0; i < MAX_AF_FILES; i++)
1248    {
1249       fl = csp->rlist[i];
1250       if ((NULL == fl) || (NULL == fl->f))
1251       {
1252          /*
1253           * Either there are no filter files
1254           * left, or this filter file just
1255           * contains no valid filters.
1256           *
1257           * Continue to be sure we don't miss
1258           * valid filter files that are chained
1259           * after empty or invalid ones.
1260           */
1261          continue;
1262       }
1263
1264       /* For all filters, */
1265       for (b = fl->f; b; b = b->next)
1266       {
1267          if (b->type != wanted_filter_type)
1268          {
1269             /* skip the ones we don't care about, */
1270             continue;
1271          }
1272          /* leaving only taggers that could apply, of which we use the ones, */
1273          for (tag_name = csp->action->multi[multi_action_index]->first;
1274               NULL != tag_name; tag_name = tag_name->next)
1275          {
1276             /* that do apply, and */
1277             if (strcmp(b->name, tag_name->str) == 0)
1278             {
1279                char *modified_tag = NULL;
1280                char *tag = header;
1281                size_t size = header_length;
1282                pcrs_job *joblist = b->joblist;
1283
1284                if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1285
1286                if (NULL == joblist)
1287                {
1288                   log_error(LOG_LEVEL_RE_FILTER,
1289                      "Tagger %s has empty joblist. Nothing to do.", b->name);
1290                   continue;
1291                }
1292
1293                /* execute their pcrs_joblist on the header. */
1294                for (job = joblist; NULL != job; job = job->next)
1295                {
1296                   const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1297
1298                   if (0 < hits)
1299                   {
1300                      /* Success, continue with the modified version. */
1301                      if (tag != header)
1302                      {
1303                         freez(tag);
1304                      }
1305                      tag = modified_tag;
1306                   }
1307                   else
1308                   {
1309                      /* Tagger doesn't match */
1310                      if (0 > hits)
1311                      {
1312                         /* Regex failure, log it but continue anyway. */
1313                         assert(NULL != header);
1314                         log_error(LOG_LEVEL_ERROR,
1315                            "Problems with tagger \'%s\' and header \'%s\': %s",
1316                            b->name, *header, pcrs_strerror(hits));
1317                      }
1318                      freez(modified_tag);
1319                   }
1320                }
1321
1322                if (b->dynamic) pcrs_free_joblist(joblist);
1323
1324                /* If this tagger matched */
1325                if (tag != header)
1326                {
1327                   if (0 == size)
1328                   {
1329                      /*
1330                       * There is to technical limitation which makes
1331                       * it impossible to use empty tags, but I assume
1332                       * no one would do it intentionally.
1333                       */
1334                      freez(tag);
1335                      log_error(LOG_LEVEL_INFO,
1336                         "Tagger \'%s\' created an empty tag. Ignored.",
1337                         b->name);
1338                      continue;
1339                   }
1340  
1341                   if (!list_contains_item(csp->tags, tag))
1342                   {
1343                      if (JB_ERR_OK != enlist(csp->tags, tag))
1344                      {
1345                         log_error(LOG_LEVEL_ERROR,
1346                            "Insufficient memory to add tag \'%s\', "
1347                            "based on tagger \'%s\' and header \'%s\'",
1348                            tag, b->name, *header);
1349                      }
1350                      else
1351                      {
1352                         char *action_message;
1353                         /*
1354                          * update the action bits right away, to make
1355                          * tagging based on tags set by earlier taggers
1356                          * of the same kind possible.
1357                          */
1358                         if (update_action_bits_for_tag(csp, tag))
1359                         {
1360                            action_message = "Action bits updated accordingly.";
1361                         }
1362                         else
1363                         {
1364                            action_message = "No action bits update necessary.";
1365                         }
1366
1367                         log_error(LOG_LEVEL_HEADER,
1368                            "Tagger \'%s\' added tag \'%s\'. %s",
1369                            b->name, tag, action_message);
1370                      }
1371                   }
1372                   else
1373                   {
1374                      /* XXX: Is this log-worthy? */
1375                      log_error(LOG_LEVEL_HEADER,
1376                         "Tagger \'%s\' didn't add tag \'%s\'. "
1377                         "Tag already present", b->name, tag);
1378                   }
1379                   freez(tag);
1380                } /* if the tagger matched */
1381             } /* if the tagger applies */
1382          } /* for every tagger that could apply */
1383       } /* for all filters */
1384    } /* for all filter files */
1385
1386    return JB_ERR_OK;
1387 }
1388
1389 /* here begins the family of parser functions that reformat header lines */
1390
1391 /*********************************************************************
1392  *
1393  * Function    :  filter_header
1394  *
1395  * Description :  Executes all text substitutions from all applying
1396  *                +(server|client)-header-filter actions on the header.
1397  *                Most of the code was copied from pcrs_filter_response,
1398  *                including the rather short variable names
1399  *
1400  * Parameters  :
1401  *          1  :  csp = Current client state (buffers, headers, etc...)
1402  *          2  :  header = On input, pointer to header to modify.
1403  *                On output, pointer to the modified header, or NULL
1404  *                to remove the header.  This function frees the
1405  *                original string if necessary.
1406  *
1407  * Returns     :  JB_ERR_OK on success and always succeeds
1408  *
1409  *********************************************************************/
1410 static jb_err filter_header(struct client_state *csp, char **header)
1411 {
1412    int hits=0;
1413    int matches;
1414    size_t size = strlen(*header);
1415
1416    char *newheader = NULL;
1417    pcrs_job *job;
1418
1419    struct file_list *fl;
1420    struct re_filterfile_spec *b;
1421    struct list_entry *filtername;
1422
1423    int i, found_filters = 0;
1424    int wanted_filter_type;
1425    int multi_action_index;
1426
1427    if (csp->flags & CSP_FLAG_NO_FILTERING)
1428    {
1429       return JB_ERR_OK;
1430    }
1431
1432    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1433    {
1434       wanted_filter_type = FT_SERVER_HEADER_FILTER;
1435       multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1436    }
1437    else
1438    {
1439       wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1440       multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1441    }
1442
1443    /*
1444     * Need to check the set of re_filterfiles...
1445     */
1446    for (i = 0; i < MAX_AF_FILES; i++)
1447    {
1448       fl = csp->rlist[i];
1449       if (NULL != fl)
1450       {
1451          if (NULL != fl->f)
1452          {
1453            found_filters = 1;
1454            break;
1455          }
1456       }
1457    }
1458
1459    if (0 == found_filters)
1460    {
1461       log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1462          "header filtering enabled, but no matching filters available.");
1463       return JB_ERR_OK;
1464    }
1465
1466    for (i = 0; i < MAX_AF_FILES; i++)
1467    {
1468       fl = csp->rlist[i];
1469       if ((NULL == fl) || (NULL == fl->f))
1470       {
1471          /*
1472           * Either there are no filter files
1473           * left, or this filter file just
1474           * contains no valid filters.
1475           *
1476           * Continue to be sure we don't miss
1477           * valid filter files that are chained
1478           * after empty or invalid ones.
1479           */
1480          continue;
1481       }
1482       /*
1483        * For all applying +filter actions, look if a filter by that
1484        * name exists and if yes, execute its pcrs_joblist on the
1485        * buffer.
1486        */
1487       for (b = fl->f; b; b = b->next)
1488       {
1489          if (b->type != wanted_filter_type)
1490          {
1491             /* Skip other filter types */
1492             continue;
1493          }
1494
1495          for (filtername = csp->action->multi[multi_action_index]->first;
1496               filtername ; filtername = filtername->next)
1497          {
1498             if (strcmp(b->name, filtername->str) == 0)
1499             {
1500                int current_hits = 0;
1501                pcrs_job *joblist = b->joblist;
1502
1503                if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1504
1505                if (NULL == joblist)
1506                {
1507                   log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1508                   continue;
1509                }
1510
1511                log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1512                          *header, size, b->name);
1513
1514                /* Apply all jobs from the joblist */
1515                for (job = joblist; NULL != job; job = job->next)
1516                {
1517                   matches = pcrs_execute(job, *header, size, &newheader, &size);
1518                   if ( 0 < matches )
1519                   {
1520                      current_hits += matches; 
1521                      log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1522                      freez(*header);
1523                      *header = newheader;
1524                   }
1525                   else if ( 0 == matches )
1526                   {
1527                      /* Filter doesn't change header */
1528                      freez(newheader);
1529                   }
1530                   else
1531                   {
1532                      /* RegEx failure */
1533                      log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1534                         *header, b->name, pcrs_strerror(matches));
1535                      if (newheader != NULL)
1536                      {
1537                         log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1538                         freez(newheader);
1539                      }
1540                   }
1541                }
1542
1543                if (b->dynamic) pcrs_free_joblist(joblist);
1544
1545                log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1546                hits += current_hits;
1547             }
1548          }
1549       }
1550    }
1551
1552    /*
1553     * Additionally checking for hits is important because if
1554     * the continue hack is triggered, server headers can
1555     * arrive empty to separate multiple heads from each other.
1556     */
1557    if ((0 == size) && hits)
1558    {
1559       log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1560       freez(*header);
1561    }
1562
1563    return JB_ERR_OK;
1564 }
1565
1566
1567 /*********************************************************************
1568  *
1569  * Function    :  server_connection
1570  *
1571  * Description :  Makes sure a proper "Connection:" header is
1572  *                set and signals connection_header_adder to
1573  *                do nothing.
1574  *
1575  * Parameters  :
1576  *          1  :  csp = Current client state (buffers, headers, etc...)
1577  *          2  :  header = On input, pointer to header to modify.
1578  *                On output, pointer to the modified header, or NULL
1579  *                to remove the header.  This function frees the
1580  *                original string if necessary.
1581  *
1582  * Returns     :  JB_ERR_OK on success, or
1583  *                JB_ERR_MEMORY on out-of-memory error.
1584  *
1585  *********************************************************************/
1586 static jb_err server_connection(struct client_state *csp, char **header)
1587 {
1588    if (!strcmpic(*header, "Connection: keep-alive")
1589 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1590     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1591 #endif
1592       )
1593    {
1594 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1595       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1596       {
1597          csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1598       }
1599
1600       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1601       {
1602          log_error(LOG_LEVEL_HEADER,
1603             "Keeping the server header '%s' around.", *header);
1604       }
1605       else
1606 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1607       {
1608          char *old_header = *header;
1609
1610          *header = strdup("Connection: close");
1611          if (header == NULL)
1612          {
1613             return JB_ERR_MEMORY;
1614          }
1615          log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1616          freez(old_header);
1617       }
1618    }
1619
1620    /* Signal server_connection_adder() to return early. */
1621    csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1622
1623    return JB_ERR_OK;
1624 }
1625
1626
1627 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1628 /*********************************************************************
1629  *
1630  * Function    :  server_keep_alive
1631  *
1632  * Description :  Stores the server's keep alive timeout.
1633  *
1634  * Parameters  :
1635  *          1  :  csp = Current client state (buffers, headers, etc...)
1636  *          2  :  header = On input, pointer to header to modify.
1637  *                On output, pointer to the modified header, or NULL
1638  *                to remove the header.  This function frees the
1639  *                original string if necessary.
1640  *
1641  * Returns     :  JB_ERR_OK.
1642  *
1643  *********************************************************************/
1644 static jb_err server_keep_alive(struct client_state *csp, char **header)
1645 {
1646    unsigned int keep_alive_timeout;
1647    const char *timeout_position = strstr(*header, "timeout=");
1648
1649    if ((NULL == timeout_position)
1650     || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1651    {
1652       log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1653    }
1654    else
1655    {
1656       if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1657       {
1658          log_error(LOG_LEVEL_HEADER,
1659             "Reducing keep-alive timeout from %u to %u.",
1660             csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1661          csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1662       }
1663       else
1664       {
1665          /* XXX: Is this log worthy? */
1666          log_error(LOG_LEVEL_HEADER,
1667             "Server keep-alive timeout is %u. Sticking with %u.",
1668             keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1669       }
1670       csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1671    }
1672
1673    return JB_ERR_OK;
1674 }
1675
1676
1677 /*********************************************************************
1678  *
1679  * Function    :  server_proxy_connection
1680  *
1681  * Description :  Figures out whether or not we should add a
1682  *                Proxy-Connection header.
1683  *
1684  * Parameters  :
1685  *          1  :  csp = Current client state (buffers, headers, etc...)
1686  *          2  :  header = On input, pointer to header to modify.
1687  *                On output, pointer to the modified header, or NULL
1688  *                to remove the header.  This function frees the
1689  *                original string if necessary.
1690  *
1691  * Returns     :  JB_ERR_OK.
1692  *
1693  *********************************************************************/
1694 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1695 {
1696    csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1697    return JB_ERR_OK;
1698 }
1699
1700
1701 /*********************************************************************
1702  *
1703  * Function    :  client_keep_alive
1704  *
1705  * Description :  Stores the client's keep alive timeout.
1706  *
1707  * Parameters  :
1708  *          1  :  csp = Current client state (buffers, headers, etc...)
1709  *          2  :  header = On input, pointer to header to modify.
1710  *                On output, pointer to the modified header, or NULL
1711  *                to remove the header.  This function frees the
1712  *                original string if necessary.
1713  *
1714  * Returns     :  JB_ERR_OK.
1715  *
1716  *********************************************************************/
1717 static jb_err client_keep_alive(struct client_state *csp, char **header)
1718 {
1719    unsigned int keep_alive_timeout;
1720    const char *timeout_position = strstr(*header, ": ");
1721
1722    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1723    {
1724       log_error(LOG_LEVEL_HEADER,
1725          "keep-alive support is disabled. Crunching: %s.", *header);
1726       freez(*header);
1727       return JB_ERR_OK;
1728    }
1729
1730    if ((NULL == timeout_position)
1731     || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1732    {
1733       log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1734    }
1735    else
1736    {
1737       if (keep_alive_timeout < csp->config->keep_alive_timeout)
1738       {
1739          log_error(LOG_LEVEL_HEADER,
1740             "Reducing keep-alive timeout from %u to %u.",
1741             csp->config->keep_alive_timeout, keep_alive_timeout);
1742          csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1743       }
1744       else
1745       {
1746          /* XXX: Is this log worthy? */
1747          log_error(LOG_LEVEL_HEADER,
1748             "Client keep-alive timeout is %u. Sticking with %u.",
1749             keep_alive_timeout, csp->config->keep_alive_timeout);
1750       }
1751    }
1752
1753    return JB_ERR_OK;
1754 }
1755
1756
1757 /*********************************************************************
1758  *
1759  * Function    :  client_save_content_length
1760  *
1761  * Description :  Save the Content-Length sent by the client.
1762  *
1763  *                XXX: Shares code with the server version
1764  *                     that should be factored out.
1765  *
1766  * Parameters  :
1767  *          1  :  csp = Current client state (buffers, headers, etc...)
1768  *          2  :  header = On input, pointer to header to modify.
1769  *                On output, pointer to the modified header, or NULL
1770  *                to remove the header.  This function frees the
1771  *                original string if necessary.
1772  *
1773  * Returns     :  JB_ERR_OK on success, or
1774  *                JB_ERR_MEMORY on out-of-memory error.
1775  *
1776  *********************************************************************/
1777 static jb_err client_save_content_length(struct client_state *csp, char **header)
1778 {
1779    unsigned long long content_length = 0;
1780
1781    assert(*(*header+14) == ':');
1782
1783 #ifdef _WIN32
1784    if (1 != sscanf(*header+14, ": %I64u", &content_length))
1785 #else
1786    if (1 != sscanf(*header+14, ": %llu", &content_length))
1787 #endif
1788    {
1789       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1790       freez(*header);
1791    }
1792    else
1793    {
1794       csp->expected_client_content_length = content_length;
1795    }
1796
1797    return JB_ERR_OK;
1798 }
1799 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1800
1801
1802
1803 /*********************************************************************
1804  *
1805  * Function    :  client_connection
1806  *
1807  * Description :  Makes sure a proper "Connection:" header is
1808  *                set and signals connection_header_adder 
1809  *                to do nothing.
1810  *
1811  * Parameters  :
1812  *          1  :  csp = Current client state (buffers, headers, etc...)
1813  *          2  :  header = On input, pointer to header to modify.
1814  *                On output, pointer to the modified header, or NULL
1815  *                to remove the header.  This function frees the
1816  *                original string if necessary.
1817  *
1818  * Returns     :  JB_ERR_OK on success, or
1819  *                JB_ERR_MEMORY on out-of-memory error.
1820  *
1821  *********************************************************************/
1822 static jb_err client_connection(struct client_state *csp, char **header)
1823 {
1824    static const char connection_close[] = "Connection: close";
1825
1826    if (!strcmpic(*header, connection_close))
1827    {
1828 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1829       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1830       {
1831           if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1832           {
1833              log_error(LOG_LEVEL_HEADER,
1834                 "Removing \'%s\' to imply keep-alive.", *header);
1835              freez(*header);
1836           }
1837           else
1838           {
1839              char *old_header = *header;
1840
1841              *header = strdup("Connection: keep-alive");
1842              if (header == NULL)
1843              {
1844                 return JB_ERR_MEMORY;
1845              }
1846              log_error(LOG_LEVEL_HEADER,
1847                 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1848              freez(old_header);
1849           }
1850       }
1851       else
1852       {
1853          log_error(LOG_LEVEL_HEADER,
1854             "Keeping the client header '%s' around. "
1855             "The connection will not be kept alive.",
1856             *header);
1857          csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1858       }
1859    }
1860    else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1861    {
1862       log_error(LOG_LEVEL_HEADER,
1863          "Keeping the client header '%s' around. "
1864          "The server connection will be kept alive if possible.",
1865          *header);
1866       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1867 #endif  /* def FEATURE_CONNECTION_KEEP_ALIVE */
1868    }
1869    else
1870    {
1871       char *old_header = *header;
1872
1873       *header = strdup(connection_close);
1874       if (header == NULL)
1875       {
1876          return JB_ERR_MEMORY;
1877       }
1878       log_error(LOG_LEVEL_HEADER,
1879          "Replaced: \'%s\' with \'%s\'", old_header, *header);
1880       freez(old_header);
1881    }
1882
1883    /* Signal client_connection_adder() to return early. */
1884    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1885
1886    return JB_ERR_OK;
1887 }
1888
1889
1890 /*********************************************************************
1891  *
1892  * Function    :  crumble
1893  *
1894  * Description :  This is called if a header matches a pattern to "crunch"
1895  *
1896  * Parameters  :
1897  *          1  :  csp = Current client state (buffers, headers, etc...)
1898  *          2  :  header = On input, pointer to header to modify.
1899  *                On output, pointer to the modified header, or NULL
1900  *                to remove the header.  This function frees the
1901  *                original string if necessary.
1902  *
1903  * Returns     :  JB_ERR_OK on success, or
1904  *                JB_ERR_MEMORY on out-of-memory error.
1905  *
1906  *********************************************************************/
1907 static jb_err crumble(struct client_state *csp, char **header)
1908 {
1909    (void)csp;
1910    log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1911    freez(*header);
1912    return JB_ERR_OK;
1913 }
1914
1915
1916 /*********************************************************************
1917  *
1918  * Function    :  crunch_server_header
1919  *
1920  * Description :  Crunch server header if it matches a string supplied by the
1921  *                user. Called from `sed'.
1922  *
1923  * Parameters  :
1924  *          1  :  csp = Current client state (buffers, headers, etc...)
1925  *          2  :  header = On input, pointer to header to modify.
1926  *                On output, pointer to the modified header, or NULL
1927  *                to remove the header.  This function frees the
1928  *                original string if necessary.
1929  *
1930  * Returns     :  JB_ERR_OK on success and always succeeds
1931  *
1932  *********************************************************************/
1933 static jb_err crunch_server_header(struct client_state *csp, char **header)
1934 {
1935    const char *crunch_pattern;
1936
1937    /* Do we feel like crunching? */
1938    if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1939    {
1940       crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1941
1942       /* Is the current header the lucky one? */
1943       if (strstr(*header, crunch_pattern))
1944       {
1945          log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);  
1946          freez(*header);
1947       }
1948    }
1949
1950    return JB_ERR_OK;
1951 }
1952
1953
1954 /*********************************************************************
1955  *
1956  * Function    :  server_content_type
1957  *
1958  * Description :  Set the content-type for filterable types (text/.*,
1959  *                .*xml.*, javascript and image/gif) unless filtering has been
1960  *                forbidden (CT_TABOO) while parsing earlier headers.
1961  *                NOTE: Since text/plain is commonly used by web servers
1962  *                      for files whose correct type is unknown, we don't
1963  *                      set CT_TEXT for it.
1964  *
1965  * Parameters  :
1966  *          1  :  csp = Current client state (buffers, headers, etc...)
1967  *          2  :  header = On input, pointer to header to modify.
1968  *                On output, pointer to the modified header, or NULL
1969  *                to remove the header.  This function frees the
1970  *                original string if necessary.
1971  *
1972  * Returns     :  JB_ERR_OK on success, or
1973  *                JB_ERR_MEMORY on out-of-memory error.
1974  *
1975  *********************************************************************/
1976 static jb_err server_content_type(struct client_state *csp, char **header)
1977 {
1978    /* Remove header if it isn't the first Content-Type header */
1979    if ((csp->content_type & CT_DECLARED))
1980    {
1981      /*
1982       * Another, slightly slower, way to see if
1983       * we already parsed another Content-Type header.
1984       */
1985       assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1986
1987       log_error(LOG_LEVEL_ERROR,
1988          "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1989          *header);
1990       freez(*header);
1991
1992       return JB_ERR_OK;
1993    }
1994
1995    /*
1996     * Signal that the Content-Type has been set.
1997     */
1998    csp->content_type |= CT_DECLARED;
1999
2000    if (!(csp->content_type & CT_TABOO))
2001    {
2002       /*
2003        * XXX: The assumption that text/plain is a sign of
2004        * binary data seems to be somewhat unreasonable nowadays
2005        * and should be dropped after 3.0.8 is out.
2006        */
2007       if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2008         || strstr(*header, "xml")
2009         || strstr(*header, "application/x-javascript"))
2010       {
2011          csp->content_type |= CT_TEXT;
2012       }
2013       else if (strstr(*header, "image/gif"))
2014       {
2015          csp->content_type |= CT_GIF;
2016       }
2017    }
2018
2019    /*
2020     * Are we messing with the content type?
2021     */
2022    if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2023    {
2024       /*
2025        * Make sure the user doesn't accidently
2026        * change the content type of binary documents. 
2027        */
2028       if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2029       {
2030          freez(*header);
2031          *header = strdup("Content-Type: ");
2032          string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2033
2034          if (header == NULL)
2035          {
2036             log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2037             return JB_ERR_MEMORY;
2038          }
2039          log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2040       }
2041       else
2042       {
2043          log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2044             "It doesn't look like a content type that should be filtered. "
2045             "Enable force-text-mode if you know what you're doing.", *header);
2046       }
2047    }
2048
2049    return JB_ERR_OK;
2050 }
2051
2052
2053 /*********************************************************************
2054  *
2055  * Function    :  server_transfer_coding
2056  *
2057  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
2058  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2059  *                - Remove header if body was chunked but has been
2060  *                  de-chunked for filtering.
2061  *
2062  * Parameters  :
2063  *          1  :  csp = Current client state (buffers, headers, etc...)
2064  *          2  :  header = On input, pointer to header to modify.
2065  *                On output, pointer to the modified header, or NULL
2066  *                to remove the header.  This function frees the
2067  *                original string if necessary.
2068  *
2069  * Returns     :  JB_ERR_OK on success, or
2070  *                JB_ERR_MEMORY on out-of-memory error.
2071  *
2072  *********************************************************************/
2073 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2074 {
2075    /*
2076     * Turn off pcrs and gif filtering if body compressed
2077     */
2078    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2079    {
2080 #ifdef FEATURE_ZLIB
2081       /*
2082        * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2083        */
2084       log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2085          csp->http->cmd, *header);
2086 #endif /* def FEATURE_ZLIB */
2087       csp->content_type = CT_TABOO;
2088    }
2089
2090    /*
2091     * Raise flag if body chunked
2092     */
2093    if (strstr(*header, "chunked"))
2094    {
2095       csp->flags |= CSP_FLAG_CHUNKED;
2096
2097       /*
2098        * If the body was modified, it has been de-chunked first
2099        * and the header must be removed.
2100        *
2101        * FIXME: If there is more than one transfer encoding,
2102        * only the "chunked" part should be removed here.
2103        */
2104       if (csp->flags & CSP_FLAG_MODIFIED)
2105       {
2106          log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2107          freez(*header);
2108       }
2109    }
2110
2111    return JB_ERR_OK;
2112 }
2113
2114
2115 /*********************************************************************
2116  *
2117  * Function    :  server_content_encoding
2118  *
2119  * Description :  This function is run twice for each request,
2120  *                unless FEATURE_ZLIB and filtering are disabled.
2121  *
2122  *                The first run is used to check if the content
2123  *                is compressed, if FEATURE_ZLIB is disabled
2124  *                filtering is then disabled as well, if FEATURE_ZLIB
2125  *                is enabled the content is marked for decompression.
2126  *                
2127  *                The second run is used to remove the Content-Encoding
2128  *                header if the decompression was successful.
2129  *
2130  * Parameters  :
2131  *          1  :  csp = Current client state (buffers, headers, etc...)
2132  *          2  :  header = On input, pointer to header to modify.
2133  *                On output, pointer to the modified header, or NULL
2134  *                to remove the header.  This function frees the
2135  *                original string if necessary.
2136  *
2137  * Returns     :  JB_ERR_OK on success, or
2138  *                JB_ERR_MEMORY on out-of-memory error.
2139  *
2140  *********************************************************************/
2141 static jb_err server_content_encoding(struct client_state *csp, char **header)
2142 {
2143 #ifdef FEATURE_ZLIB
2144    if ((csp->flags & CSP_FLAG_MODIFIED)
2145     && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2146    {
2147       /*
2148        * We successfully decompressed the content,
2149        * and have to clean the header now, so the
2150        * client no longer expects compressed data..
2151        *
2152        * XXX: There is a difference between cleaning
2153        * and removing it completely.
2154        */
2155       log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2156       freez(*header);
2157    }
2158    else if (strstr(*header, "gzip"))
2159    {
2160       /* Mark for gzip decompression */
2161       csp->content_type |= CT_GZIP;
2162    }
2163    else if (strstr(*header, "deflate"))
2164    {
2165       /* Mark for zlib decompression */
2166       csp->content_type |= CT_DEFLATE;
2167    }
2168    else if (strstr(*header, "compress"))
2169    {
2170       /*
2171        * We can't decompress this; therefore we can't filter
2172        * it either.
2173        */
2174       csp->content_type |= CT_TABOO;
2175    }
2176 #else /* !defined(FEATURE_ZLIB) */
2177    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2178    {
2179       /*
2180        * Body is compressed, turn off pcrs and gif filtering.
2181        */
2182       csp->content_type |= CT_TABOO;
2183
2184       /*
2185        * Log a warning if the user expects the content to be filtered.
2186        */
2187       if ((csp->rlist != NULL) &&
2188          (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2189       {
2190          log_error(LOG_LEVEL_INFO,
2191             "Compressed content detected, content filtering disabled. "
2192             "Consider recompiling Privoxy with zlib support or "
2193             "enable the prevent-compression action.");
2194       }
2195    }
2196 #endif /* defined(FEATURE_ZLIB) */
2197
2198    return JB_ERR_OK;
2199
2200 }
2201
2202
2203 /*********************************************************************
2204  *
2205  * Function    :  server_adjust_content_length
2206  *
2207  * Description :  Adjust Content-Length header if we modified
2208  *                the body.
2209  *
2210  * Parameters  :
2211  *          1  :  csp = Current client state (buffers, headers, etc...)
2212  *          2  :  header = On input, pointer to header to modify.
2213  *                On output, pointer to the modified header, or NULL
2214  *                to remove the header.  This function frees the
2215  *                original string if necessary.
2216  *
2217  * Returns     :  JB_ERR_OK on success, or
2218  *                JB_ERR_MEMORY on out-of-memory error.
2219  *
2220  *********************************************************************/
2221 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2222 {
2223    /* Regenerate header if the content was modified. */
2224    if (csp->flags & CSP_FLAG_MODIFIED)
2225    {
2226       const size_t header_length = 50;
2227       freez(*header);
2228       *header = malloc(header_length);
2229       if (*header == NULL)
2230       {
2231          return JB_ERR_MEMORY;
2232       }
2233       create_content_length_header(csp->content_length, *header, header_length);
2234       log_error(LOG_LEVEL_HEADER,
2235          "Adjusted Content-Length to %llu", csp->content_length);
2236    }
2237
2238    return JB_ERR_OK;
2239 }
2240
2241
2242 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2243 /*********************************************************************
2244  *
2245  * Function    :  server_save_content_length
2246  *
2247  * Description :  Save the Content-Length sent by the server.
2248  *
2249  * Parameters  :
2250  *          1  :  csp = Current client state (buffers, headers, etc...)
2251  *          2  :  header = On input, pointer to header to modify.
2252  *                On output, pointer to the modified header, or NULL
2253  *                to remove the header.  This function frees the
2254  *                original string if necessary.
2255  *
2256  * Returns     :  JB_ERR_OK on success, or
2257  *                JB_ERR_MEMORY on out-of-memory error.
2258  *
2259  *********************************************************************/
2260 static jb_err server_save_content_length(struct client_state *csp, char **header)
2261 {
2262    unsigned long long content_length = 0;
2263
2264    assert(*(*header+14) == ':');
2265
2266 #ifdef _WIN32
2267    if (1 != sscanf(*header+14, ": %I64u", &content_length))
2268 #else
2269    if (1 != sscanf(*header+14, ": %llu", &content_length))
2270 #endif
2271    {
2272       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2273       freez(*header);
2274    }
2275    else
2276    {
2277       csp->expected_content_length = content_length;
2278       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2279       csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2280    }
2281
2282    return JB_ERR_OK;
2283 }
2284 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2285
2286
2287 /*********************************************************************
2288  *
2289  * Function    :  server_content_md5
2290  *
2291  * Description :  Crumble any Content-MD5 headers if the document was
2292  *                modified. FIXME: Should we re-compute instead?
2293  *
2294  * Parameters  :
2295  *          1  :  csp = Current client state (buffers, headers, etc...)
2296  *          2  :  header = On input, pointer to header to modify.
2297  *                On output, pointer to the modified header, or NULL
2298  *                to remove the header.  This function frees the
2299  *                original string if necessary.
2300  *
2301  * Returns     :  JB_ERR_OK on success, or
2302  *                JB_ERR_MEMORY on out-of-memory error.
2303  *
2304  *********************************************************************/
2305 static jb_err server_content_md5(struct client_state *csp, char **header)
2306 {
2307    if (csp->flags & CSP_FLAG_MODIFIED)
2308    {
2309       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2310       freez(*header);
2311    }
2312
2313    return JB_ERR_OK;
2314 }
2315
2316
2317 /*********************************************************************
2318  *
2319  * Function    :  server_content_disposition
2320  *
2321  * Description :  If enabled, blocks or modifies the "Content-Disposition" header.
2322  *                Called from `sed'.
2323  *
2324  * Parameters  :
2325  *          1  :  csp = Current client state (buffers, headers, etc...)
2326  *          2  :  header = On input, pointer to header to modify.
2327  *                On output, pointer to the modified header, or NULL
2328  *                to remove the header.  This function frees the
2329  *                original string if necessary.
2330  *
2331  * Returns     :  JB_ERR_OK on success, or
2332  *                JB_ERR_MEMORY on out-of-memory error.
2333  *
2334  *********************************************************************/
2335 static jb_err server_content_disposition(struct client_state *csp, char **header)
2336 {
2337    const char *newval;
2338
2339    /*
2340     * Are we messing with the Content-Disposition header?
2341     */
2342    if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2343    {
2344       /* Me tinks not */
2345       return JB_ERR_OK;
2346    }
2347
2348    newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2349
2350    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2351    {
2352       /*
2353        * Blocking content-disposition header
2354        */
2355       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2356       freez(*header);
2357       return JB_ERR_OK;
2358    }
2359    else
2360    {  
2361       /*
2362        * Replacing Content-Disposition header
2363        */
2364       freez(*header);
2365       *header = strdup("Content-Disposition: ");
2366       string_append(header, newval);
2367
2368       if (*header != NULL)
2369       {
2370          log_error(LOG_LEVEL_HEADER,
2371             "Content-Disposition header crunched and replaced with: %s", *header);
2372       }
2373    }
2374    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2375 }
2376
2377
2378 /*********************************************************************
2379  *
2380  * Function    :  server_last_modified
2381  *
2382  * Description :  Changes Last-Modified header to the actual date
2383  *                to help hide-if-modified-since.
2384  *                Called from `sed'.
2385  *
2386  * Parameters  :
2387  *          1  :  csp = Current client state (buffers, headers, etc...)
2388  *          2  :  header = On input, pointer to header to modify.
2389  *                On output, pointer to the modified header, or NULL
2390  *                to remove the header.  This function frees the
2391  *                original string if necessary.
2392  *
2393  * Returns     :  JB_ERR_OK on success, or
2394  *                JB_ERR_MEMORY on out-of-memory error.
2395  *
2396  *********************************************************************/
2397 static jb_err server_last_modified(struct client_state *csp, char **header)
2398 {
2399    const char *newval;
2400    char buf[BUFFER_SIZE];
2401
2402    char newheader[50];
2403 #ifdef HAVE_GMTIME_R
2404    struct tm gmt;
2405 #endif
2406    struct tm *timeptr = NULL;
2407    time_t now, last_modified;                  
2408    long int days, hours, minutes, seconds;
2409    
2410    /*
2411     * Are we messing with the Last-Modified header?
2412     */
2413    if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2414    {
2415       /*Nope*/
2416       return JB_ERR_OK;
2417    }
2418
2419    newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2420
2421    if (0 == strcmpic(newval, "block") )
2422    {
2423       /*
2424        * Blocking Last-Modified header. Useless but why not.
2425        */
2426       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2427       freez(*header);
2428       return JB_ERR_OK;
2429    }
2430    else if (0 == strcmpic(newval, "reset-to-request-time"))
2431    {  
2432       /*
2433        * Setting Last-Modified Header to now.
2434        */
2435       get_http_time(0, buf, sizeof(buf));
2436       freez(*header);
2437       *header = strdup("Last-Modified: ");
2438       string_append(header, buf);   
2439
2440       if (*header == NULL)
2441       {
2442          log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");  
2443       }
2444       else
2445       {
2446          log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2447       }
2448    }
2449    else if (0 == strcmpic(newval, "randomize"))
2450    {
2451       const char *header_time = *header + sizeof("Last-Modified:");
2452
2453       log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2454       now = time(NULL);
2455 #ifdef HAVE_GMTIME_R
2456       gmtime_r(&now, &gmt);
2457 #elif defined(MUTEX_LOCKS_AVAILABLE)
2458       privoxy_mutex_lock(&gmtime_mutex);
2459       gmtime(&now);
2460       privoxy_mutex_unlock(&gmtime_mutex);
2461 #else
2462       gmtime(&now);
2463 #endif
2464       if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2465       {
2466          log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2467          freez(*header);
2468       }
2469       else
2470       {
2471          long int rtime = (long int)difftime(now, last_modified);
2472          if (rtime)
2473          {
2474             const int negative_delta = (rtime < 0);
2475
2476             if (negative_delta)
2477             {
2478                rtime *= -1; 
2479                log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2480             }
2481             rtime = pick_from_range(rtime);
2482             if (negative_delta)
2483             {
2484                rtime *= -1;
2485             }
2486             last_modified += rtime;
2487 #ifdef HAVE_GMTIME_R
2488             timeptr = gmtime_r(&last_modified, &gmt);
2489 #elif defined(MUTEX_LOCKS_AVAILABLE)
2490             privoxy_mutex_lock(&gmtime_mutex);
2491             timeptr = gmtime(&last_modified);
2492             privoxy_mutex_unlock(&gmtime_mutex);
2493 #else
2494             timeptr = gmtime(&last_modified);
2495 #endif
2496             if ((NULL == timeptr) || !strftime(newheader,
2497                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2498             {
2499                log_error(LOG_LEVEL_ERROR,
2500                   "Randomizing '%s' failed. Crunching the header without replacement.",
2501                   *header);
2502                freez(*header);
2503                return JB_ERR_OK;
2504             }
2505
2506             freez(*header);
2507             *header = strdup("Last-Modified: ");
2508             string_append(header, newheader);
2509
2510             if (*header == NULL)
2511             {
2512                log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2513                return JB_ERR_MEMORY;  
2514             }
2515
2516             days    = rtime / (3600 * 24);
2517             hours   = rtime / 3600 % 24;
2518             minutes = rtime / 60 % 60;
2519             seconds = rtime % 60;
2520
2521             log_error(LOG_LEVEL_HEADER,
2522                "Randomized:  %s (added %d da%s %d hou%s %d minut%s %d second%s",
2523                *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2524                minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2525          }
2526          else
2527          {
2528             log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2529          }
2530       }
2531    }
2532
2533    return JB_ERR_OK;
2534 }
2535
2536
2537 /*********************************************************************
2538  *
2539  * Function    :  client_accept_encoding
2540  *
2541  * Description :  Rewrite the client's Accept-Encoding header so that
2542  *                if doesn't allow compression, if the action applies.
2543  *                Note: For HTTP/1.0 the absence of the header is enough.
2544  *
2545  * Parameters  :
2546  *          1  :  csp = Current client state (buffers, headers, etc...)
2547  *          2  :  header = On input, pointer to header to modify.
2548  *                On output, pointer to the modified header, or NULL
2549  *                to remove the header.  This function frees the
2550  *                original string if necessary.
2551  *
2552  * Returns     :  JB_ERR_OK on success, or
2553  *                JB_ERR_MEMORY on out-of-memory error.
2554  *
2555  *********************************************************************/
2556 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2557 {
2558    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2559    {
2560       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2561
2562       freez(*header);
2563
2564       /* Temporarily disable the correct behaviour to
2565        * work around a PHP bug. 
2566        *
2567        * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2568        * {
2569        *    *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2570        *    if (*header == NULL)
2571        *    {
2572        *       return JB_ERR_MEMORY;
2573        *    }
2574        * }
2575        * 
2576        */
2577    }
2578
2579    return JB_ERR_OK;
2580 }
2581
2582
2583 /*********************************************************************
2584  *
2585  * Function    :  client_te
2586  *
2587  * Description :  Rewrite the client's TE header so that
2588  *                if doesn't allow compression, if the action applies.
2589  *
2590  * Parameters  :
2591  *          1  :  csp = Current client state (buffers, headers, etc...)
2592  *          2  :  header = On input, pointer to header to modify.
2593  *                On output, pointer to the modified header, or NULL
2594  *                to remove the header.  This function frees the
2595  *                original string if necessary.
2596  *
2597  * Returns     :  JB_ERR_OK on success, or
2598  *                JB_ERR_MEMORY on out-of-memory error.
2599  *
2600  *********************************************************************/
2601 static jb_err client_te(struct client_state *csp, char **header)
2602 {
2603    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2604    {
2605       freez(*header);
2606       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2607    }
2608
2609    return JB_ERR_OK;
2610 }
2611
2612
2613 /*********************************************************************
2614  *
2615  * Function    :  client_referrer
2616  *
2617  * Description :  Handle the "referer" config setting properly.
2618  *                Called from `sed'.
2619  *
2620  * Parameters  :
2621  *          1  :  csp = Current client state (buffers, headers, etc...)
2622  *          2  :  header = On input, pointer to header to modify.
2623  *                On output, pointer to the modified header, or NULL
2624  *                to remove the header.  This function frees the
2625  *                original string if necessary.
2626  *
2627  * Returns     :  JB_ERR_OK on success, or
2628  *                JB_ERR_MEMORY on out-of-memory error.
2629  *
2630  *********************************************************************/
2631 static jb_err client_referrer(struct client_state *csp, char **header)
2632 {
2633    const char *parameter;
2634    /* booleans for parameters we have to check multiple times */
2635    int parameter_conditional_block;
2636    int parameter_conditional_forge;
2637  
2638 #ifdef FEATURE_FORCE_LOAD
2639    /*
2640     * Since the referrer can include the prefix even
2641     * if the request itself is non-forced, we must
2642     * clean it unconditionally.
2643     *
2644     * XXX: strclean is too broad
2645     */
2646    strclean(*header, FORCE_PREFIX);
2647 #endif /* def FEATURE_FORCE_LOAD */
2648
2649    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2650    {
2651       /* Nothing left to do */
2652       return JB_ERR_OK;
2653    }
2654
2655    parameter = csp->action->string[ACTION_STRING_REFERER];
2656    assert(parameter != NULL);
2657    parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2658    parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2659
2660    if (!parameter_conditional_block && !parameter_conditional_forge)
2661    {
2662       /*
2663        * As conditional-block and conditional-forge are the only
2664        * parameters that rely on the original referrer, we can
2665        * remove it now for all the others.
2666        */
2667       freez(*header);
2668    }
2669
2670    if (0 == strcmpic(parameter, "block"))
2671    {
2672       log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2673       return JB_ERR_OK;
2674    }
2675    else if (parameter_conditional_block || parameter_conditional_forge)
2676    {
2677       return handle_conditional_hide_referrer_parameter(header,
2678          csp->http->hostport, parameter_conditional_block);
2679    }
2680    else if (0 == strcmpic(parameter, "forge"))
2681    {
2682       return create_forged_referrer(header, csp->http->hostport);
2683    }
2684    else
2685    {
2686       /* interpret parameter as user-supplied referer to fake */
2687       return create_fake_referrer(header, parameter);
2688    }
2689 }
2690
2691
2692 /*********************************************************************
2693  *
2694  * Function    :  client_accept_language
2695  *
2696  * Description :  Handle the "Accept-Language" config setting properly.
2697  *                Called from `sed'.
2698  *
2699  * Parameters  :
2700  *          1  :  csp = Current client state (buffers, headers, etc...)
2701  *          2  :  header = On input, pointer to header to modify.
2702  *                On output, pointer to the modified header, or NULL
2703  *                to remove the header.  This function frees the
2704  *                original string if necessary.
2705  *
2706  * Returns     :  JB_ERR_OK on success, or
2707  *                JB_ERR_MEMORY on out-of-memory error.
2708  *
2709  *********************************************************************/
2710 static jb_err client_accept_language(struct client_state *csp, char **header)
2711 {
2712    const char *newval;
2713
2714    /*
2715     * Are we messing with the Accept-Language?
2716     */
2717    if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2718    {
2719       /*I don't think so*/
2720       return JB_ERR_OK;
2721    }
2722
2723    newval = csp->action->string[ACTION_STRING_LANGUAGE];
2724
2725    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2726    {
2727       /*
2728        * Blocking Accept-Language header
2729        */
2730       log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2731       freez(*header);
2732       return JB_ERR_OK;
2733    }
2734    else
2735    {  
2736       /*
2737        * Replacing Accept-Language header
2738        */
2739       freez(*header);
2740       *header = strdup("Accept-Language: ");
2741       string_append(header, newval);   
2742
2743       if (*header == NULL)
2744       {
2745          log_error(LOG_LEVEL_ERROR,
2746             "Insufficient memory. Accept-Language header crunched without replacement.");  
2747       }
2748       else
2749       {
2750          log_error(LOG_LEVEL_HEADER,
2751             "Accept-Language header crunched and replaced with: %s", *header);
2752       }
2753    }
2754    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2755 }
2756
2757
2758 /*********************************************************************
2759  *
2760  * Function    :  crunch_client_header
2761  *
2762  * Description :  Crunch client header if it matches a string supplied by the
2763  *                user. Called from `sed'.
2764  *
2765  * Parameters  :
2766  *          1  :  csp = Current client state (buffers, headers, etc...)
2767  *          2  :  header = On input, pointer to header to modify.
2768  *                On output, pointer to the modified header, or NULL
2769  *                to remove the header.  This function frees the
2770  *                original string if necessary.
2771  *
2772  * Returns     :  JB_ERR_OK on success and always succeeds
2773  *
2774  *********************************************************************/
2775 static jb_err crunch_client_header(struct client_state *csp, char **header)
2776 {
2777    const char *crunch_pattern;
2778
2779    /* Do we feel like crunching? */
2780    if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2781    {
2782       crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2783
2784       /* Is the current header the lucky one? */
2785       if (strstr(*header, crunch_pattern))
2786       {
2787          log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);  
2788          freez(*header);
2789       }
2790    }
2791    return JB_ERR_OK;
2792 }
2793
2794
2795 /*********************************************************************
2796  *
2797  * Function    :  client_uagent
2798  *
2799  * Description :  Handle the "user-agent" config setting properly
2800  *                and remember its original value to enable browser
2801  *                bug workarounds. Called from `sed'.
2802  *
2803  * Parameters  :
2804  *          1  :  csp = Current client state (buffers, headers, etc...)
2805  *          2  :  header = On input, pointer to header to modify.
2806  *                On output, pointer to the modified header, or NULL
2807  *                to remove the header.  This function frees the
2808  *                original string if necessary.
2809  *
2810  * Returns     :  JB_ERR_OK on success, or
2811  *                JB_ERR_MEMORY on out-of-memory error.
2812  *
2813  *********************************************************************/
2814 static jb_err client_uagent(struct client_state *csp, char **header)
2815 {
2816    const char *newval;
2817
2818    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2819    {
2820       return JB_ERR_OK;
2821    }
2822
2823    newval = csp->action->string[ACTION_STRING_USER_AGENT];
2824    if (newval == NULL)
2825    {
2826       return JB_ERR_OK;
2827    }
2828
2829    freez(*header);
2830    *header = strdup("User-Agent: ");
2831    string_append(header, newval);
2832
2833    log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2834
2835    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2836 }
2837
2838
2839 /*********************************************************************
2840  *
2841  * Function    :  client_ua
2842  *
2843  * Description :  Handle "ua-" headers properly.  Called from `sed'.
2844  *
2845  * Parameters  :
2846  *          1  :  csp = Current client state (buffers, headers, etc...)
2847  *          2  :  header = On input, pointer to header to modify.
2848  *                On output, pointer to the modified header, or NULL
2849  *                to remove the header.  This function frees the
2850  *                original string if necessary.
2851  *
2852  * Returns     :  JB_ERR_OK on success, or
2853  *                JB_ERR_MEMORY on out-of-memory error.
2854  *
2855  *********************************************************************/
2856 static jb_err client_ua(struct client_state *csp, char **header)
2857 {
2858    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2859    {
2860       log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2861       freez(*header);
2862    }
2863
2864    return JB_ERR_OK;
2865 }
2866
2867
2868 /*********************************************************************
2869  *
2870  * Function    :  client_from
2871  *
2872  * Description :  Handle the "from" config setting properly.
2873  *                Called from `sed'.
2874  *
2875  * Parameters  :
2876  *          1  :  csp = Current client state (buffers, headers, etc...)
2877  *          2  :  header = On input, pointer to header to modify.
2878  *                On output, pointer to the modified header, or NULL
2879  *                to remove the header.  This function frees the
2880  *                original string if necessary.
2881  *
2882  * Returns     :  JB_ERR_OK on success, or
2883  *                JB_ERR_MEMORY on out-of-memory error.
2884  *
2885  *********************************************************************/
2886 static jb_err client_from(struct client_state *csp, char **header)
2887 {
2888    const char *newval;
2889
2890    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2891    {
2892       return JB_ERR_OK;
2893    }
2894
2895    freez(*header);
2896
2897    newval = csp->action->string[ACTION_STRING_FROM];
2898
2899    /*
2900     * Are we blocking the e-mail address?
2901     */
2902    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2903    {
2904       log_error(LOG_LEVEL_HEADER, "crunched From!");
2905       return JB_ERR_OK;
2906    }
2907
2908    log_error(LOG_LEVEL_HEADER, " modified");
2909
2910    *header = strdup("From: ");
2911    string_append(header, newval);
2912
2913    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2914 }
2915
2916
2917 /*********************************************************************
2918  *
2919  * Function    :  client_send_cookie
2920  *
2921  * Description :  Crunches the "cookie" header if necessary.
2922  *                Called from `sed'.
2923  *
2924  *                XXX: Stupid name, doesn't send squat.
2925  *
2926  * Parameters  :
2927  *          1  :  csp = Current client state (buffers, headers, etc...)
2928  *          2  :  header = On input, pointer to header to modify.
2929  *                On output, pointer to the modified header, or NULL
2930  *                to remove the header.  This function frees the
2931  *                original string if necessary.
2932  *
2933  * Returns     :  JB_ERR_OK on success, or
2934  *                JB_ERR_MEMORY on out-of-memory error.
2935  *
2936  *********************************************************************/
2937 static jb_err client_send_cookie(struct client_state *csp, char **header)
2938 {
2939    if (csp->action->flags & ACTION_NO_COOKIE_READ)
2940    {
2941       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2942       freez(*header);
2943    }
2944
2945    return JB_ERR_OK;
2946 }
2947
2948
2949 /*********************************************************************
2950  *
2951  * Function    :  client_x_forwarded
2952  *
2953  * Description :  Handle the "x-forwarded-for" config setting properly,
2954  *                also used in the add_client_headers list.  Called from `sed'.
2955  *
2956  * Parameters  :
2957  *          1  :  csp = Current client state (buffers, headers, etc...)
2958  *          2  :  header = On input, pointer to header to modify.
2959  *                On output, pointer to the modified header, or NULL
2960  *                to remove the header.  This function frees the
2961  *                original string if necessary.
2962  *
2963  * Returns     :  JB_ERR_OK on success, or
2964  *                JB_ERR_MEMORY on out-of-memory error.
2965  *
2966  *********************************************************************/
2967 jb_err client_x_forwarded(struct client_state *csp, char **header)
2968 {
2969    if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2970    {
2971       const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2972
2973       if (0 == strcmpic(parameter, "block"))
2974       {
2975          freez(*header);
2976          log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2977       }
2978       else if (0 == strcmpic(parameter, "add"))
2979       {
2980          string_append(header, ", ");
2981          string_append(header, csp->ip_addr_str);
2982
2983          if (*header == NULL)
2984          {
2985             return JB_ERR_MEMORY;
2986          }
2987          log_error(LOG_LEVEL_HEADER,
2988             "Appended client IP address to %s", *header);
2989          csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2990       }
2991       else
2992       {
2993          log_error(LOG_LEVEL_FATAL,
2994             "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2995       }
2996    }
2997
2998    return JB_ERR_OK;
2999 }
3000
3001
3002 /*********************************************************************
3003  *
3004  * Function    :  client_max_forwards
3005  *
3006  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
3007  *                from the value of the Max-Forwards header field.
3008  *
3009  * Parameters  :
3010  *          1  :  csp = Current client state (buffers, headers, etc...)
3011  *          2  :  header = On input, pointer to header to modify.
3012  *                On output, pointer to the modified header, or NULL
3013  *                to remove the header.  This function frees the
3014  *                original string if necessary.
3015  *
3016  * Returns     :  JB_ERR_OK on success, or
3017  *                JB_ERR_MEMORY on out-of-memory error.
3018  *
3019  *********************************************************************/
3020 static jb_err client_max_forwards(struct client_state *csp, char **header)
3021 {
3022    int max_forwards;
3023
3024    if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3025        (0 == strcmpic(csp->http->gpc, "options")))
3026    {
3027       assert(*(*header+12) == ':');
3028       if (1 == sscanf(*header+12, ": %d", &max_forwards))
3029       {
3030          if (max_forwards > 0)
3031          {
3032             snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3033             log_error(LOG_LEVEL_HEADER,
3034                "Max-Forwards value for %s request reduced to %d.",
3035                csp->http->gpc, max_forwards);
3036          }
3037          else if (max_forwards < 0)
3038          {
3039             log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3040             freez(*header);
3041          }
3042       }
3043       else
3044       {
3045          log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3046          freez(*header);
3047       }
3048    }
3049
3050    return JB_ERR_OK;
3051 }
3052
3053
3054 /*********************************************************************
3055  *
3056  * Function    :  client_host
3057  *
3058  * Description :  If the request URI did not contain host and
3059  *                port information, parse and evaluate the Host
3060  *                header field.
3061  *
3062  *                Also, kill ill-formed HOST: headers as sent by
3063  *                Apple's iTunes software when used with a proxy.
3064  *
3065  * Parameters  :
3066  *          1  :  csp = Current client state (buffers, headers, etc...)
3067  *          2  :  header = On input, pointer to header to modify.
3068  *                On output, pointer to the modified header, or NULL
3069  *                to remove the header.  This function frees the
3070  *                original string if necessary.
3071  *
3072  * Returns     :  JB_ERR_OK on success, or
3073  *                JB_ERR_MEMORY on out-of-memory error.
3074  *
3075  *********************************************************************/
3076 static jb_err client_host(struct client_state *csp, char **header)
3077 {
3078    char *p, *q;
3079
3080    /*
3081     * If the header field name is all upper-case, chances are that it's
3082     * an ill-formed one from iTunes. BTW, killing innocent headers here is
3083     * not a problem -- they are regenerated later.
3084     */
3085    if ((*header)[1] == 'O')
3086    {
3087       log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3088       freez(*header);
3089       return JB_ERR_OK;
3090    }
3091
3092    if (!csp->http->hostport || (*csp->http->hostport == '*') ||  
3093        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3094    {
3095       
3096       if (NULL == (p = strdup((*header)+6)))
3097       {
3098          return JB_ERR_MEMORY;
3099       }
3100       chomp(p);
3101       if (NULL == (q = strdup(p)))
3102       {
3103          freez(p);
3104          return JB_ERR_MEMORY;
3105       }
3106
3107       freez(csp->http->hostport);
3108       csp->http->hostport = p;
3109       freez(csp->http->host);
3110       csp->http->host = q;
3111       q = strchr(csp->http->host, ':');
3112       if (q != NULL)
3113       {
3114          /* Terminate hostname and evaluate port string */
3115          *q++ = '\0';
3116          csp->http->port = atoi(q);
3117       }
3118       else
3119       {
3120          csp->http->port = csp->http->ssl ? 443 : 80;
3121       }
3122
3123       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3124                 csp->http->hostport, csp->http->host, csp->http->port);
3125    }
3126
3127    /* Signal client_host_adder() to return right away */
3128    csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3129
3130    return JB_ERR_OK;
3131 }
3132
3133
3134 /*********************************************************************
3135  *
3136  * Function    :  client_if_modified_since
3137  *
3138  * Description :  Remove or modify the If-Modified-Since header.
3139  *
3140  * Parameters  :
3141  *          1  :  csp = Current client state (buffers, headers, etc...)
3142  *          2  :  header = On input, pointer to header to modify.
3143  *                On output, pointer to the modified header, or NULL
3144  *                to remove the header.  This function frees the
3145  *                original string if necessary.
3146  *
3147  * Returns     :  JB_ERR_OK on success, or
3148  *                JB_ERR_MEMORY on out-of-memory error.
3149  *
3150  *********************************************************************/
3151 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3152 {
3153    char newheader[50];
3154 #ifdef HAVE_GMTIME_R
3155    struct tm gmt;
3156 #endif
3157    struct tm *timeptr = NULL;
3158    time_t tm = 0;                  
3159    const char *newval;
3160    long int hours, minutes, seconds;
3161    char * endptr;
3162    
3163    if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3164    {
3165       /* 
3166        * The client got an error message because of a temporary problem,
3167        * the problem is gone and the client now tries to revalidate our
3168        * error message on the real server. The revalidation would always
3169        * end with the transmission of the whole document and there is
3170        * no need to expose the bogus If-Modified-Since header.
3171        */
3172       log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3173       freez(*header);
3174    }
3175    else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3176    {
3177       newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3178
3179       if ((0 == strcmpic(newval, "block")))
3180       {
3181          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3182          freez(*header);
3183       }
3184       else /* add random value */
3185       {
3186          const char *header_time = *header + sizeof("If-Modified-Since:");
3187
3188          if (JB_ERR_OK != parse_header_time(header_time, &tm))
3189          {
3190             log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3191             freez(*header);
3192          }
3193          else
3194          {
3195             long int rtime = strtol(newval, &endptr, 0);
3196             const int negative_range = (rtime < 0);
3197
3198             if (rtime)
3199             {
3200                log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3201                   *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3202                if (negative_range)
3203                {
3204                   rtime *= -1; 
3205                }
3206                rtime *= 60;
3207                rtime = pick_from_range(rtime);
3208             }
3209             else
3210             {
3211                log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3212                   *header);
3213             }
3214             tm += rtime * (negative_range ? -1 : 1);
3215 #ifdef HAVE_GMTIME_R
3216             timeptr = gmtime_r(&tm, &gmt);
3217 #elif defined(MUTEX_LOCKS_AVAILABLE)
3218             privoxy_mutex_lock(&gmtime_mutex);
3219             timeptr = gmtime(&tm);
3220             privoxy_mutex_unlock(&gmtime_mutex);
3221 #else
3222             timeptr = gmtime(&tm);
3223 #endif
3224             if ((NULL == timeptr) || !strftime(newheader,
3225                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3226             {
3227                log_error(LOG_LEVEL_ERROR,
3228                   "Randomizing '%s' failed. Crunching the header without replacement.",
3229                   *header);
3230                freez(*header);
3231                return JB_ERR_OK;
3232             }
3233
3234             freez(*header);
3235             *header = strdup("If-Modified-Since: ");
3236             string_append(header, newheader);
3237
3238             if (*header == NULL)
3239             {
3240                log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3241                return JB_ERR_MEMORY;  
3242             }
3243
3244             hours   = rtime / 3600;
3245             minutes = rtime / 60 % 60;
3246             seconds = rtime % 60;
3247
3248             log_error(LOG_LEVEL_HEADER,
3249                "Randomized:  %s (%s %d hou%s %d minut%s %d second%s",
3250                *header, (negative_range) ? "subtracted" : "added", hours,
3251                (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3252                seconds, (seconds == 1) ? ")" : "s)");
3253          }
3254       }
3255    }
3256
3257    return JB_ERR_OK;
3258 }
3259
3260
3261 /*********************************************************************
3262  *
3263  * Function    :  client_if_none_match
3264  *
3265  * Description :  Remove the If-None-Match header.
3266  *
3267  * Parameters  :
3268  *          1  :  csp = Current client state (buffers, headers, etc...)
3269  *          2  :  header = On input, pointer to header to modify.
3270  *                On output, pointer to the modified header, or NULL
3271  *                to remove the header.  This function frees the
3272  *                original string if necessary.
3273  *
3274  * Returns     :  JB_ERR_OK on success, or
3275  *                JB_ERR_MEMORY on out-of-memory error.
3276  *
3277  *********************************************************************/
3278 static jb_err client_if_none_match(struct client_state *csp, char **header)
3279 {
3280    if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3281    {  
3282       log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3283       freez(*header);
3284    }
3285
3286    return JB_ERR_OK;
3287 }
3288
3289
3290 /*********************************************************************
3291  *
3292  * Function    :  client_x_filter
3293  *
3294  * Description :  Disables filtering if the client set "X-Filter: No".
3295  *                Called from `sed'.
3296  *
3297  * Parameters  :
3298  *          1  :  csp = Current client state (buffers, headers, etc...)
3299  *          2  :  header = On input, pointer to header to modify.
3300  *                On output, pointer to the modified header, or NULL
3301  *                to remove the header.  This function frees the
3302  *                original string if necessary.
3303  *
3304  * Returns     :  JB_ERR_OK on success
3305  *
3306  *********************************************************************/
3307 jb_err client_x_filter(struct client_state *csp, char **header)
3308 {
3309    if ( 0 == strcmpic(*header, "X-Filter: No"))
3310    {
3311       if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3312       {
3313          log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3314       }
3315       else
3316       {
3317          if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3318          {
3319             log_error(LOG_LEVEL_HEADER,
3320                "force-text-mode overruled the client's request to fetch without filtering!");
3321          }
3322          else
3323          {  
3324             csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3325             csp->flags |= CSP_FLAG_NO_FILTERING;
3326             log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3327          }
3328          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3329          freez(*header);
3330       }
3331    }
3332    return JB_ERR_OK; 
3333 }
3334
3335
3336 /*********************************************************************
3337  *
3338  * Function    :  client_range
3339  *
3340  * Description :  Removes Range, Request-Range and If-Range headers if
3341  *                content filtering is enabled. If the client's version
3342  *                of the document has been altered by Privoxy, the server
3343  *                could interpret the range differently than the client
3344  *                intended in which case the user could end up with
3345  *                corrupted content.
3346  *
3347  * Parameters  :
3348  *          1  :  csp = Current client state (buffers, headers, etc...)
3349  *          2  :  header = On input, pointer to header to modify.
3350  *                On output, pointer to the modified header, or NULL
3351  *                to remove the header.  This function frees the
3352  *                original string if necessary.
3353  *
3354  * Returns     :  JB_ERR_OK
3355  *
3356  *********************************************************************/
3357 static jb_err client_range(struct client_state *csp, char **header)
3358 {
3359    if (content_filters_enabled(csp->action))
3360    {
3361       log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3362          " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3363       freez(*header);
3364    }
3365
3366    return JB_ERR_OK; 
3367 }
3368
3369 /* the following functions add headers directly to the header list */
3370
3371 /*********************************************************************
3372  *
3373  * Function    :  client_host_adder
3374  *
3375  * Description :  Adds the Host: header field if it is missing.
3376  *                Called from `sed'.
3377  *
3378  * Parameters  :
3379  *          1  :  csp = Current client state (buffers, headers, etc...)
3380  *
3381  * Returns     :  JB_ERR_OK on success, or
3382  *                JB_ERR_MEMORY on out-of-memory error.
3383  *
3384  *********************************************************************/
3385 static jb_err client_host_adder(struct client_state *csp)
3386 {
3387    char *p;
3388    jb_err err;
3389
3390    if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3391    {
3392       /* Header already set by the client, nothing to do. */
3393       return JB_ERR_OK;
3394    }
3395
3396    if ( !csp->http->hostport || !*(csp->http->hostport))
3397    {
3398       /* XXX: When does this happen and why is it OK? */
3399       log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3400       return JB_ERR_OK;
3401    }
3402
3403    /*
3404     * remove 'user:pass@' from 'proto://user:pass@host'
3405     */
3406    if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3407    {
3408       p++;
3409    }
3410    else
3411    {
3412       p = csp->http->hostport;
3413    }
3414
3415    /* XXX: Just add it, we already made sure that it will be unique */
3416    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3417    err = enlist_unique_header(csp->headers, "Host", p);
3418    return err;
3419
3420 }
3421
3422
3423 #if 0
3424 /*********************************************************************
3425  *
3426  * Function    :  client_accept_encoding_adder
3427  *
3428  * Description :  Add an Accept-Encoding header to the client's request
3429  *                that disables compression if the action applies, and
3430  *                the header is not already there. Called from `sed'.
3431  *                Note: For HTTP/1.0, the absence of the header is enough.
3432  *
3433  * Parameters  :
3434  *          1  :  csp = Current client state (buffers, headers, etc...)
3435  *
3436  * Returns     :  JB_ERR_OK on success, or
3437  *                JB_ERR_MEMORY on out-of-memory error.
3438  *
3439  *********************************************************************/
3440 static jb_err client_accept_encoding_adder(struct client_state *csp)
3441 {
3442    if (   ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3443        && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3444    {
3445       return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3446    }
3447
3448    return JB_ERR_OK;
3449 }
3450 #endif
3451
3452
3453 /*********************************************************************
3454  *
3455  * Function    :  client_xtra_adder
3456  *
3457  * Description :  Used in the add_client_headers list.  Called from `sed'.
3458  *
3459  * Parameters  :
3460  *          1  :  csp = Current client state (buffers, headers, etc...)
3461  *
3462  * Returns     :  JB_ERR_OK on success, or
3463  *                JB_ERR_MEMORY on out-of-memory error.
3464  *
3465  *********************************************************************/
3466 static jb_err client_xtra_adder(struct client_state *csp)
3467 {
3468    struct list_entry *lst;
3469    jb_err err;
3470
3471    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3472         lst ; lst = lst->next)
3473    {
3474       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3475       err = enlist(csp->headers, lst->str);
3476       if (err)
3477       {
3478          return err;
3479       }
3480
3481    }
3482
3483    return JB_ERR_OK;
3484 }
3485
3486
3487 /*********************************************************************
3488  *
3489  * Function    :  client_x_forwarded_for_adder
3490  *
3491  * Description :  Used in the add_client_headers list.  Called from `sed'.
3492  *
3493  * Parameters  :
3494  *          1  :  csp = Current client state (buffers, headers, etc...)
3495  *
3496  * Returns     :  JB_ERR_OK on success, or
3497  *                JB_ERR_MEMORY on out-of-memory error.
3498  *
3499  *********************************************************************/
3500 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3501 {
3502    char *header = NULL;
3503    jb_err err;
3504
3505    if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3506          && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3507       || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3508    {
3509       /*
3510        * If we aren't adding X-Forwarded-For headers,
3511        * or we already appended an existing X-Forwarded-For
3512        * header, there's nothing left to do here.
3513        */
3514       return JB_ERR_OK;
3515    }
3516
3517    header = strdup("X-Forwarded-For: ");
3518    string_append(&header, csp->ip_addr_str);
3519
3520    if (header == NULL)
3521    {
3522       return JB_ERR_MEMORY;
3523    }
3524
3525    log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3526    err = enlist(csp->headers, header);
3527    freez(header);
3528
3529    return err;
3530 }
3531
3532
3533 /*********************************************************************
3534  *
3535  * Function    :  server_connection_adder
3536  *
3537  * Description :  Adds an appropiate "Connection:" header to csp->headers
3538  *                unless the header was already present. Called from `sed'.
3539  *
3540  * Parameters  :
3541  *          1  :  csp = Current client state (buffers, headers, etc...)
3542  *
3543  * Returns     :  JB_ERR_OK on success, or
3544  *                JB_ERR_MEMORY on out-of-memory error.
3545  *
3546  *********************************************************************/
3547 static jb_err server_connection_adder(struct client_state *csp)
3548 {
3549    const unsigned int flags = csp->flags;
3550    const char *response_status_line = csp->headers->first->str;
3551    static const char connection_close[] = "Connection: close";
3552
3553    if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3554     && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3555    {
3556       return JB_ERR_OK;
3557    }
3558
3559    /*
3560     * XXX: if we downgraded the response, this check will fail.
3561     */
3562    if ((csp->config->feature_flags &
3563         RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3564     && (NULL != response_status_line)
3565     && !strncmpic(response_status_line, "HTTP/1.1", 8)
3566 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3567     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3568 #endif
3569        )
3570    {
3571       log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3572          "without Connection header implies keep-alive.");
3573       csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3574       return JB_ERR_OK;
3575    }
3576
3577    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3578
3579    return enlist(csp->headers, connection_close);
3580 }
3581
3582
3583 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3584 /*********************************************************************
3585  *
3586  * Function    :  server_proxy_connection_adder
3587  *
3588  * Description :  Adds a "Proxy-Connection: keep-alive" header to
3589  *                csp->headers if the client asked for keep-alive.
3590  *                XXX: We should reuse existant ones.
3591  *
3592  * Parameters  :
3593  *          1  :  csp = Current client state (buffers, headers, etc...)
3594  *
3595  * Returns     :  JB_ERR_OK on success, or
3596  *                JB_ERR_MEMORY on out-of-memory error.
3597  *
3598  *********************************************************************/
3599 static jb_err server_proxy_connection_adder(struct client_state *csp)
3600 {
3601    static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3602    jb_err err = JB_ERR_OK;
3603
3604    if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3605     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3606     && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3607    {
3608       log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3609       err = enlist(csp->headers, proxy_connection_header);
3610    }
3611
3612    return err;
3613 }
3614 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3615
3616
3617 /*********************************************************************
3618  *
3619  * Function    :  client_connection_header_adder
3620  *
3621  * Description :  Adds a proper "Connection:" header to csp->headers
3622  *                unless the header was already present. Called from `sed'.
3623  *
3624  * Parameters  :
3625  *          1  :  csp = Current client state (buffers, headers, etc...)
3626  *
3627  * Returns     :  JB_ERR_OK on success, or
3628  *                JB_ERR_MEMORY on out-of-memory error.
3629  *
3630  *********************************************************************/
3631 static jb_err client_connection_header_adder(struct client_state *csp)
3632 {
3633    static const char connection_close[] = "Connection: close";
3634
3635    if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3636      && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3637    {
3638       return JB_ERR_OK;
3639    }
3640
3641 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3642    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3643       && (csp->http->ssl == 0)
3644       && !strcmpic(csp->http->ver, "HTTP/1.1"))
3645    {
3646       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3647       return JB_ERR_OK;
3648    }
3649 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3650
3651    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3652
3653    return enlist(csp->headers, connection_close);
3654 }
3655
3656
3657 /*********************************************************************
3658  *
3659  * Function    :  server_http
3660  *
3661  * Description :  - Save the HTTP Status into csp->http->status
3662  *                - Set CT_TABOO to prevent filtering if the answer
3663  *                  is a partial range (HTTP status 206)
3664  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3665  *                  action applies.
3666  *
3667  * Parameters  :
3668  *          1  :  csp = Current client state (buffers, headers, etc...)
3669  *          2  :  header = On input, pointer to header to modify.
3670  *                On output, pointer to the modified header, or NULL
3671  *                to remove the header.  This function frees the
3672  *                original string if necessary.
3673  *
3674  * Returns     :  JB_ERR_OK on success, or
3675  *                JB_ERR_MEMORY on out-of-memory error.
3676  *
3677  *********************************************************************/
3678 static jb_err server_http(struct client_state *csp, char **header)
3679 {
3680    sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3681    if (csp->http->status == 206)
3682    {
3683       csp->content_type = CT_TABOO;
3684    }
3685
3686    if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3687    {
3688       /* XXX: Should we do a real validity check here? */
3689       if (strlen(*header) > 8)
3690       {
3691          (*header)[7] = '0';
3692          log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3693       }
3694       else
3695       {
3696          /*
3697           * XXX: Should we block the request or
3698           * enlist a valid status code line here?
3699           */
3700          log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3701             "Downgrading to HTTP/1.0 impossible.");
3702       }
3703    }
3704
3705    return JB_ERR_OK;
3706 }
3707
3708
3709 /*********************************************************************
3710  *
3711  * Function    :  server_set_cookie
3712  *
3713  * Description :  Handle the server "cookie" header properly.
3714  *                Crunch, accept or rewrite it to a session cookie.
3715  *                Called from `sed'.
3716  *
3717  *                TODO: Allow the user to specify a new expiration
3718  *                time to cause the cookie to expire even before the
3719  *                browser is closed.
3720  *
3721  * Parameters  :
3722  *          1  :  csp = Current client state (buffers, headers, etc...)
3723  *          2  :  header = On input, pointer to header to modify.
3724  *                On output, pointer to the modified header, or NULL
3725  *                to remove the header.  This function frees the
3726  *                original string if necessary.
3727  *
3728  * Returns     :  JB_ERR_OK on success, or
3729  *                JB_ERR_MEMORY on out-of-memory error.
3730  *
3731  *********************************************************************/
3732 static jb_err server_set_cookie(struct client_state *csp, char **header)
3733 {
3734    time_t now;
3735    time_t cookie_time; 
3736
3737    time(&now);
3738
3739    if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3740    {
3741       log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3742       freez(*header);
3743    }
3744    else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3745    {
3746       /* Flag whether or not to log a message */
3747       int changed = 0;
3748
3749       /* A variable to store the tag we're working on */
3750       char *cur_tag;
3751
3752       /* Skip "Set-Cookie:" (11 characters) in header */
3753       cur_tag = *header + 11;
3754
3755       /* skip whitespace between "Set-Cookie:" and value */
3756       while (*cur_tag && ijb_isspace(*cur_tag))
3757       {
3758          cur_tag++;
3759       }
3760
3761       /* Loop through each tag in the cookie */
3762       while (*cur_tag)
3763       {
3764          /* Find next tag */
3765          char *next_tag = strchr(cur_tag, ';');
3766          if (next_tag != NULL)
3767          {
3768             /* Skip the ';' character itself */
3769             next_tag++;
3770
3771             /* skip whitespace ";" and start of tag */
3772             while (*next_tag && ijb_isspace(*next_tag))
3773             {
3774                next_tag++;
3775             }
3776          }
3777          else
3778          {
3779             /* "Next tag" is the end of the string */
3780             next_tag = cur_tag + strlen(cur_tag);
3781          }
3782
3783          /*
3784           * Check the expiration date to see
3785           * if the cookie is still valid, if yes,
3786           * rewrite it to a session cookie.
3787           */
3788          if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3789          {
3790             char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3791
3792             /* Did we detect the date properly? */
3793             if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3794             {
3795                /*
3796                 * Nope, treat it as if it was still valid.
3797                 *
3798                 * XXX: Should we remove the whole cookie instead?
3799                 */
3800                log_error(LOG_LEVEL_ERROR,
3801                   "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3802                string_move(cur_tag, next_tag);
3803                changed = 1;
3804             }
3805             else
3806             {
3807                /*
3808                 * Yes. Check if the cookie is still valid.
3809                 *
3810                 * If the cookie is already expired it's probably
3811                 * a delete cookie and even if it isn't, the browser
3812                 * will discard it anyway.
3813                 */
3814
3815                /*
3816                 * XXX: timegm() isn't available on some AmigaOS
3817                 * versions and our replacement doesn't work.
3818                 *
3819                 * Our options are to either:
3820                 *
3821                 * - disable session-cookies-only completely if timegm
3822                 *   is missing,
3823                 *
3824                 * - to simply remove all expired tags, like it has
3825                 *   been done until Privoxy 3.0.6 and to live with
3826                 *    the consequence that it can cause login/logout
3827                 *   problems on servers that don't validate their
3828                 *   input properly, or
3829                 *
3830                 * - to replace it with mktime in which
3831                 *   case there is a slight chance of valid cookies
3832                 *   passing as already expired.
3833                 *
3834                 *   This is the way it's currently done and it's not
3835                 *   as bad as it sounds. If the missing GMT offset is
3836                 *   enough to change the result of the expiration check
3837                 *   the cookie will be only valid for a few hours
3838                 *   anyway, which in many cases will be shorter
3839                 *   than a browser session.
3840                 */
3841                if (cookie_time - now < 0)
3842                {
3843                   log_error(LOG_LEVEL_HEADER,
3844                      "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3845                   /* Just in case some clown sets more then one expiration date */
3846                   cur_tag = next_tag;
3847                }
3848                else
3849                {
3850                   /*
3851                    * Still valid, delete expiration date by copying
3852                    * the rest of the string over it.
3853                    */
3854                   string_move(cur_tag, next_tag);
3855
3856                   /* That changed the header, need to issue a log message */
3857                   changed = 1;
3858
3859                   /*
3860                    * Note that the next tag has now been moved to *cur_tag,
3861                    * so we do not need to update the cur_tag pointer.
3862                    */
3863                }
3864             }
3865
3866          }
3867          else
3868          {
3869             /* Move on to next cookie tag */
3870             cur_tag = next_tag;
3871          }
3872       }
3873
3874       if (changed)
3875       {
3876          assert(NULL != *header);
3877          log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3878             *header);
3879       }
3880    }
3881
3882    return JB_ERR_OK;
3883 }
3884
3885
3886 #ifdef FEATURE_FORCE_LOAD
3887 /*********************************************************************
3888  *
3889  * Function    :  strclean
3890  *
3891  * Description :  In-Situ-Eliminate all occurances of substring in
3892  *                string
3893  *
3894  * Parameters  :
3895  *          1  :  string = string to clean
3896  *          2  :  substring = substring to eliminate
3897  *
3898  * Returns     :  Number of eliminations
3899  *
3900  *********************************************************************/
3901 int strclean(char *string, const char *substring)
3902 {
3903    int hits = 0;
3904    size_t len;
3905    char *pos, *p;
3906
3907    len = strlen(substring);
3908
3909    while((pos = strstr(string, substring)) != NULL)
3910    {
3911       p = pos + len;
3912       do
3913       {
3914          *(p - len) = *p;
3915       }
3916       while (*p++ != '\0');
3917
3918       hits++;
3919    }
3920
3921    return(hits);
3922 }
3923 #endif /* def FEATURE_FORCE_LOAD */
3924
3925
3926 /*********************************************************************
3927  *
3928  * Function    :  parse_header_time
3929  *
3930  * Description :  Parses time formats used in HTTP header strings
3931  *                to get the numerical respresentation.
3932  *
3933  * Parameters  :
3934  *          1  :  header_time = HTTP header time as string. 
3935  *          2  :  result = storage for header_time in seconds
3936  *
3937  * Returns     :  JB_ERR_OK if the time format was recognized, or
3938  *                JB_ERR_PARSE otherwise.
3939  *
3940  *********************************************************************/
3941 static jb_err parse_header_time(const char *header_time, time_t *result)
3942 {
3943    struct tm gmt;
3944
3945    /*
3946     * Zero out gmt to prevent time zone offsets.
3947     *
3948     * While this is only necessary on some platforms
3949     * (mingw32 for example), I don't know how to
3950     * detect these automatically and doing it everywhere
3951     * shouldn't hurt.
3952     */
3953    memset(&gmt, 0, sizeof(gmt));
3954
3955                             /* Tue, 02 Jun 2037 20:00:00 */
3956    if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3957                             /* Tue, 02-Jun-2037 20:00:00 */
3958     && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3959                             /* Tue, 02-Jun-37 20:00:00 */
3960     && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3961                         /* Tuesday, 02-Jun-2037 20:00:00 */
3962     && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3963                         /* Tuesday Jun 02 20:00:00 2037 */
3964     && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3965    {
3966       return JB_ERR_PARSE;
3967    }
3968
3969    *result = timegm(&gmt);
3970
3971    return JB_ERR_OK;
3972
3973 }
3974
3975
3976 /*********************************************************************
3977  *
3978  * Function    :  get_destination_from_headers
3979  *
3980  * Description :  Parse the "Host:" header to get the request's destination.
3981  *                Only needed if the client's request was forcefully
3982  *                redirected into Privoxy.
3983  *
3984  *                Code mainly copied from client_host() which is currently
3985  *                run too late for this purpose.
3986  *
3987  * Parameters  :
3988  *          1  :  headers = List of headers (one of them hopefully being
3989  *                the "Host:" header)
3990  *          2  :  http = storage for the result (host, port and hostport). 
3991  *
3992  * Returns     :  JB_ERR_MEMORY in case of memory problems,
3993  *                JB_ERR_PARSE if the host header couldn't be found,
3994  *                JB_ERR_OK otherwise.
3995  *
3996  *********************************************************************/
3997 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3998 {
3999    char *q;
4000    char *p;
4001    char *host;
4002
4003    host = get_header_value(headers, "Host:");
4004
4005    if (NULL == host)
4006    {
4007       log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4008       return JB_ERR_PARSE;
4009    }
4010
4011    if (NULL == (p = strdup((host))))
4012    {
4013       log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4014       return JB_ERR_MEMORY;
4015    }
4016    chomp(p);
4017    if (NULL == (q = strdup(p)))
4018    {
4019       freez(p);
4020       log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4021       return JB_ERR_MEMORY;
4022    }
4023
4024    freez(http->hostport);
4025    http->hostport = p;
4026    freez(http->host);
4027    http->host = q;
4028    q = strchr(http->host, ':');
4029    if (q != NULL)
4030    {
4031       /* Terminate hostname and evaluate port string */
4032       *q++ = '\0';
4033       http->port = atoi(q);
4034    }
4035    else
4036    {
4037       http->port = http->ssl ? 443 : 80;
4038    }
4039
4040    /* Rebuild request URL */
4041    freez(http->url);
4042    http->url = strdup(http->ssl ? "https://" : "http://");
4043    string_append(&http->url, http->hostport);
4044    string_append(&http->url, http->path);
4045    if (http->url == NULL)
4046    {
4047       return JB_ERR_MEMORY;
4048    }
4049
4050    log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4051       http->url);
4052
4053    return JB_ERR_OK;
4054
4055 }
4056
4057
4058 /*********************************************************************
4059  *
4060  * Function    :  create_forged_referrer
4061  *
4062  * Description :  Helper for client_referrer to forge a referer as
4063  *                'http://[hostname:port/' to fool stupid
4064  *                checks for in-site links 
4065  *
4066  * Parameters  :
4067  *          1  :  header   = Pointer to header pointer
4068  *          2  :  hostport = Host and optionally port as string
4069  *
4070  * Returns     :  JB_ERR_OK in case of success, or
4071  *                JB_ERR_MEMORY in case of memory problems.
4072  *
4073  *********************************************************************/
4074 static jb_err create_forged_referrer(char **header, const char *hostport)
4075 {
4076     assert(NULL == *header);
4077
4078     *header = strdup("Referer: http://");
4079     string_append(header, hostport);
4080     string_append(header, "/");
4081
4082     if (NULL == *header)
4083     {
4084        return JB_ERR_MEMORY;
4085     }
4086
4087     log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4088
4089     return JB_ERR_OK;
4090
4091 }
4092
4093
4094 /*********************************************************************
4095  *
4096  * Function    :  create_fake_referrer
4097  *
4098  * Description :  Helper for client_referrer to create a fake referrer
4099  *                based on a string supplied by the user.
4100  *
4101  * Parameters  :
4102  *          1  :  header   = Pointer to header pointer
4103  *          2  :  hosthost = Referrer to fake
4104  *
4105  * Returns     :  JB_ERR_OK in case of success, or
4106  *                JB_ERR_MEMORY in case of memory problems.
4107  *
4108  *********************************************************************/
4109 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4110 {
4111    assert(NULL == *header);
4112
4113    if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4114    {
4115       log_error(LOG_LEVEL_HEADER,
4116          "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4117    }
4118    *header = strdup("Referer: ");
4119    string_append(header, fake_referrer);
4120
4121    if (NULL == *header)
4122    {
4123       return JB_ERR_MEMORY;
4124    }
4125
4126    log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4127
4128    return JB_ERR_OK;
4129
4130 }
4131
4132
4133 /*********************************************************************
4134  *
4135  * Function    :  handle_conditional_hide_referrer_parameter
4136  *
4137  * Description :  Helper for client_referrer to crunch or forge
4138  *                the referrer header if the host has changed.
4139  *
4140  * Parameters  :
4141  *          1  :  header = Pointer to header pointer
4142  *          2  :  host   = The target host (may include the port)
4143  *          3  :  parameter_conditional_block = Boolean to signal
4144  *                if we're in conditional-block mode. If not set,
4145  *                we're in conditional-forge mode.
4146  *
4147  * Returns     :  JB_ERR_OK in case of success, or
4148  *                JB_ERR_MEMORY in case of memory problems.
4149  *
4150  *********************************************************************/
4151 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4152    const char *host, const int parameter_conditional_block)
4153 {
4154    char *referer = strdup(*header);
4155    const size_t hostlenght = strlen(host);
4156    const char *referer_url = NULL;
4157
4158    if (NULL == referer)
4159    {
4160       freez(*header);
4161       return JB_ERR_MEMORY;
4162    }
4163
4164    /* referer begins with 'Referer: http[s]://' */
4165    if ((hostlenght+17) < strlen(referer))
4166    {
4167       /*
4168        * Shorten referer to make sure the referer is blocked
4169        * if www.example.org/www.example.com-shall-see-the-referer/
4170        * links to www.example.com/
4171        */
4172       referer[hostlenght+17] = '\0';
4173    }
4174    referer_url = strstr(referer, "http://");
4175    if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4176    {
4177       /* Host has changed, Referer is invalid or a https URL. */
4178       if (parameter_conditional_block)
4179       {
4180          log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4181          freez(*header);
4182       }
4183       else
4184       {
4185          freez(*header);
4186          freez(referer);
4187          return create_forged_referrer(header, host);
4188       }
4189    }
4190    freez(referer);
4191
4192    return JB_ERR_OK;
4193
4194 }
4195
4196
4197 /*********************************************************************
4198  *
4199  * Function    :  create_content_length_header
4200  *
4201  * Description :  Creates a Content-Length header.
4202  *
4203  * Parameters  :
4204  *          1  :  content_length = The content length to be used in the header.
4205  *          2  :  header = Allocated space to safe the header.
4206  *          3  :  buffer_length = The length of the allocated space.
4207  *
4208  * Returns     :  void
4209  *
4210  *********************************************************************/
4211 static void create_content_length_header(unsigned long long content_length,
4212                                          char *header, size_t buffer_length)
4213 {
4214    snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4215 }
4216
4217
4218 /*
4219   Local Variables:
4220   tab-width: 3
4221   end:
4222 */