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