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