Document the 6 mysterious bytes we skip in decompress_iob().
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.174 2009/06/05 16:54:27 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    return err;
1155 }
1156
1157
1158 /*********************************************************************
1159  *
1160  * Function    :  header_tagger
1161  *
1162  * Description :  Executes all text substitutions from applying
1163  *                tag actions and saves the result as tag.
1164  *
1165  *                XXX: Shares enough code with filter_header() and
1166  *                pcrs_filter_response() to warrant some helper functions.
1167  *
1168  * Parameters  :
1169  *          1  :  csp = Current client state (buffers, headers, etc...)
1170  *          2  :  header = Header that is used as tagger input
1171  *
1172  * Returns     :  JB_ERR_OK on success and always succeeds
1173  *
1174  *********************************************************************/
1175 static jb_err header_tagger(struct client_state *csp, char *header)
1176 {
1177    int wanted_filter_type;
1178    int multi_action_index;
1179    int i;
1180    pcrs_job *job;
1181
1182    struct file_list *fl;
1183    struct re_filterfile_spec *b;
1184    struct list_entry *tag_name;
1185
1186    int found_filters = 0;
1187    const size_t header_length = strlen(header);
1188
1189    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1190    {
1191       wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1192       multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1193    }
1194    else
1195    {
1196       wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1197       multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1198    }
1199
1200    /* Check if there are any filters */
1201    for (i = 0; i < MAX_AF_FILES; i++)
1202    {
1203       fl = csp->rlist[i];
1204       if (NULL != fl)
1205       {
1206          if (NULL != fl->f)
1207          {
1208            found_filters = 1;
1209            break;
1210          }
1211       }
1212    }
1213
1214    if (0 == found_filters)
1215    {
1216       log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1217          "tagging enabled, but no taggers available.");
1218       return JB_ERR_OK;
1219    }
1220
1221    for (i = 0; i < MAX_AF_FILES; i++)
1222    {
1223       fl = csp->rlist[i];
1224       if ((NULL == fl) || (NULL == fl->f))
1225       {
1226          /*
1227           * Either there are no filter files
1228           * left, or this filter file just
1229           * contains no valid filters.
1230           *
1231           * Continue to be sure we don't miss
1232           * valid filter files that are chained
1233           * after empty or invalid ones.
1234           */
1235          continue;
1236       }
1237
1238       /* For all filters, */
1239       for (b = fl->f; b; b = b->next)
1240       {
1241          if (b->type != wanted_filter_type)
1242          {
1243             /* skip the ones we don't care about, */
1244             continue;
1245          }
1246          /* leaving only taggers that could apply, of which we use the ones, */
1247          for (tag_name = csp->action->multi[multi_action_index]->first;
1248               NULL != tag_name; tag_name = tag_name->next)
1249          {
1250             /* that do apply, and */
1251             if (strcmp(b->name, tag_name->str) == 0)
1252             {
1253                char *modified_tag = NULL;
1254                char *tag = header;
1255                size_t size = header_length;
1256                pcrs_job *joblist = b->joblist;
1257
1258                if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1259
1260                if (NULL == joblist)
1261                {
1262                   log_error(LOG_LEVEL_RE_FILTER,
1263                      "Tagger %s has empty joblist. Nothing to do.", b->name);
1264                   continue;
1265                }
1266
1267                /* execute their pcrs_joblist on the header. */
1268                for (job = joblist; NULL != job; job = job->next)
1269                {
1270                   const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1271
1272                   if (0 < hits)
1273                   {
1274                      /* Success, continue with the modified version. */
1275                      if (tag != header)
1276                      {
1277                         freez(tag);
1278                      }
1279                      tag = modified_tag;
1280                   }
1281                   else
1282                   {
1283                      /* Tagger doesn't match */
1284                      if (0 > hits)
1285                      {
1286                         /* Regex failure, log it but continue anyway. */
1287                         assert(NULL != header);
1288                         log_error(LOG_LEVEL_ERROR,
1289                            "Problems with tagger \'%s\' and header \'%s\': %s",
1290                            b->name, *header, pcrs_strerror(hits));
1291                      }
1292                      freez(modified_tag);
1293                   }
1294                }
1295
1296                if (b->dynamic) pcrs_free_joblist(joblist);
1297
1298                /* If this tagger matched */
1299                if (tag != header)
1300                {
1301                   if (0 == size)
1302                   {
1303                      /*
1304                       * There is to technical limitation which makes
1305                       * it impossible to use empty tags, but I assume
1306                       * no one would do it intentionally.
1307                       */
1308                      freez(tag);
1309                      log_error(LOG_LEVEL_INFO,
1310                         "Tagger \'%s\' created an empty tag. Ignored.",
1311                         b->name);
1312                      continue;
1313                   }
1314  
1315                   if (!list_contains_item(csp->tags, tag))
1316                   {
1317                      if (JB_ERR_OK != enlist(csp->tags, tag))
1318                      {
1319                         log_error(LOG_LEVEL_ERROR,
1320                            "Insufficient memory to add tag \'%s\', "
1321                            "based on tagger \'%s\' and header \'%s\'",
1322                            tag, b->name, *header);
1323                      }
1324                      else
1325                      {
1326                         char *action_message;
1327                         /*
1328                          * update the action bits right away, to make
1329                          * tagging based on tags set by earlier taggers
1330                          * of the same kind possible.
1331                          */
1332                         if (update_action_bits_for_tag(csp, tag))
1333                         {
1334                            action_message = "Action bits updated accordingly.";
1335                         }
1336                         else
1337                         {
1338                            action_message = "No action bits update necessary.";
1339                         }
1340
1341                         log_error(LOG_LEVEL_HEADER,
1342                            "Tagger \'%s\' added tag \'%s\'. %s",
1343                            b->name, tag, action_message);
1344                      }
1345                   }
1346                   else
1347                   {
1348                      /* XXX: Is this log-worthy? */
1349                      log_error(LOG_LEVEL_HEADER,
1350                         "Tagger \'%s\' didn't add tag \'%s\'. "
1351                         "Tag already present", b->name, tag);
1352                   }
1353                   freez(tag);
1354                } /* if the tagger matched */
1355             } /* if the tagger applies */
1356          } /* for every tagger that could apply */
1357       } /* for all filters */
1358    } /* for all filter files */
1359
1360    return JB_ERR_OK;
1361 }
1362
1363 /* here begins the family of parser functions that reformat header lines */
1364
1365 /*********************************************************************
1366  *
1367  * Function    :  filter_header
1368  *
1369  * Description :  Executes all text substitutions from all applying
1370  *                +(server|client)-header-filter actions on the header.
1371  *                Most of the code was copied from pcrs_filter_response,
1372  *                including the rather short variable names
1373  *
1374  * Parameters  :
1375  *          1  :  csp = Current client state (buffers, headers, etc...)
1376  *          2  :  header = On input, pointer to header to modify.
1377  *                On output, pointer to the modified header, or NULL
1378  *                to remove the header.  This function frees the
1379  *                original string if necessary.
1380  *
1381  * Returns     :  JB_ERR_OK on success and always succeeds
1382  *
1383  *********************************************************************/
1384 static jb_err filter_header(struct client_state *csp, char **header)
1385 {
1386    int hits=0;
1387    int matches;
1388    size_t size = strlen(*header);
1389
1390    char *newheader = NULL;
1391    pcrs_job *job;
1392
1393    struct file_list *fl;
1394    struct re_filterfile_spec *b;
1395    struct list_entry *filtername;
1396
1397    int i, found_filters = 0;
1398    int wanted_filter_type;
1399    int multi_action_index;
1400
1401    if (csp->flags & CSP_FLAG_NO_FILTERING)
1402    {
1403       return JB_ERR_OK;
1404    }
1405
1406    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1407    {
1408       wanted_filter_type = FT_SERVER_HEADER_FILTER;
1409       multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1410    }
1411    else
1412    {
1413       wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1414       multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1415    }
1416
1417    /*
1418     * Need to check the set of re_filterfiles...
1419     */
1420    for (i = 0; i < MAX_AF_FILES; i++)
1421    {
1422       fl = csp->rlist[i];
1423       if (NULL != fl)
1424       {
1425          if (NULL != fl->f)
1426          {
1427            found_filters = 1;
1428            break;
1429          }
1430       }
1431    }
1432
1433    if (0 == found_filters)
1434    {
1435       log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1436          "header filtering enabled, but no matching filters available.");
1437       return JB_ERR_OK;
1438    }
1439
1440    for (i = 0; i < MAX_AF_FILES; i++)
1441    {
1442       fl = csp->rlist[i];
1443       if ((NULL == fl) || (NULL == fl->f))
1444       {
1445          /*
1446           * Either there are no filter files
1447           * left, or this filter file just
1448           * contains no valid filters.
1449           *
1450           * Continue to be sure we don't miss
1451           * valid filter files that are chained
1452           * after empty or invalid ones.
1453           */
1454          continue;
1455       }
1456       /*
1457        * For all applying +filter actions, look if a filter by that
1458        * name exists and if yes, execute its pcrs_joblist on the
1459        * buffer.
1460        */
1461       for (b = fl->f; b; b = b->next)
1462       {
1463          if (b->type != wanted_filter_type)
1464          {
1465             /* Skip other filter types */
1466             continue;
1467          }
1468
1469          for (filtername = csp->action->multi[multi_action_index]->first;
1470               filtername ; filtername = filtername->next)
1471          {
1472             if (strcmp(b->name, filtername->str) == 0)
1473             {
1474                int current_hits = 0;
1475                pcrs_job *joblist = b->joblist;
1476
1477                if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1478
1479                if (NULL == joblist)
1480                {
1481                   log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1482                   continue;
1483                }
1484
1485                log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1486                          *header, size, b->name);
1487
1488                /* Apply all jobs from the joblist */
1489                for (job = joblist; NULL != job; job = job->next)
1490                {
1491                   matches = pcrs_execute(job, *header, size, &newheader, &size);
1492                   if ( 0 < matches )
1493                   {
1494                      current_hits += matches; 
1495                      log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1496                      freez(*header);
1497                      *header = newheader;
1498                   }
1499                   else if ( 0 == matches )
1500                   {
1501                      /* Filter doesn't change header */
1502                      freez(newheader);
1503                   }
1504                   else
1505                   {
1506                      /* RegEx failure */
1507                      log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1508                         *header, b->name, pcrs_strerror(matches));
1509                      if (newheader != NULL)
1510                      {
1511                         log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1512                         freez(newheader);
1513                      }
1514                   }
1515                }
1516
1517                if (b->dynamic) pcrs_free_joblist(joblist);
1518
1519                log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1520                hits += current_hits;
1521             }
1522          }
1523       }
1524    }
1525
1526    /*
1527     * Additionally checking for hits is important because if
1528     * the continue hack is triggered, server headers can
1529     * arrive empty to separate multiple heads from each other.
1530     */
1531    if ((0 == size) && hits)
1532    {
1533       log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1534       freez(*header);
1535    }
1536
1537    return JB_ERR_OK;
1538 }
1539
1540
1541 /*********************************************************************
1542  *
1543  * Function    :  server_connection
1544  *
1545  * Description :  Makes sure a proper "Connection:" header is
1546  *                set and signals connection_header_adder to
1547  *                do nothing.
1548  *
1549  * Parameters  :
1550  *          1  :  csp = Current client state (buffers, headers, etc...)
1551  *          2  :  header = On input, pointer to header to modify.
1552  *                On output, pointer to the modified header, or NULL
1553  *                to remove the header.  This function frees the
1554  *                original string if necessary.
1555  *
1556  * Returns     :  JB_ERR_OK on success, or
1557  *                JB_ERR_MEMORY on out-of-memory error.
1558  *
1559  *********************************************************************/
1560 static jb_err server_connection(struct client_state *csp, char **header)
1561 {
1562    if (!strcmpic(*header, "Connection: keep-alive"))
1563    {
1564 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1565       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1566       {
1567          csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1568       }
1569
1570       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1571       {
1572          log_error(LOG_LEVEL_HEADER,
1573             "Keeping the server header '%s' around.", *header);
1574       }
1575       else
1576 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1577       {
1578          char *old_header = *header;
1579
1580          *header = strdup("Connection: close");
1581          if (header == NULL)
1582          {
1583             return JB_ERR_MEMORY;
1584          }
1585          log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1586          freez(old_header);
1587       }
1588    }
1589
1590    /* Signal server_connection_adder() to return early. */
1591    csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1592
1593    return JB_ERR_OK;
1594 }
1595
1596
1597 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1598 /*********************************************************************
1599  *
1600  * Function    :  server_keep_alive
1601  *
1602  * Description :  Stores the servers keep alive timeout.
1603  *
1604  * Parameters  :
1605  *          1  :  csp = Current client state (buffers, headers, etc...)
1606  *          2  :  header = On input, pointer to header to modify.
1607  *                On output, pointer to the modified header, or NULL
1608  *                to remove the header.  This function frees the
1609  *                original string if necessary.
1610  *
1611  * Returns     :  JB_ERR_OK.
1612  *
1613  *********************************************************************/
1614 static jb_err server_keep_alive(struct client_state *csp, char **header)
1615 {
1616    unsigned int keep_alive_timeout;
1617    const char *timeout_position = strstr(*header, "timeout=");
1618
1619    if ((NULL == timeout_position)
1620     || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1621    {
1622       log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1623    }
1624    else
1625    {
1626       if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1627       {
1628          log_error(LOG_LEVEL_HEADER,
1629             "Reducing keep-alive timeout from %u to %u.",
1630             csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1631          csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1632       }
1633       else
1634       {
1635          /* XXX: Is this log worthy? */
1636          log_error(LOG_LEVEL_HEADER,
1637             "Server keep-alive timeout is %u. Sticking with %u.",
1638             keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1639       }
1640    }
1641
1642    return JB_ERR_OK;
1643 }
1644 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1645
1646
1647
1648 /*********************************************************************
1649  *
1650  * Function    :  client_connection
1651  *
1652  * Description :  Makes sure a proper "Connection:" header is
1653  *                set and signals connection_header_adder 
1654  *                to do nothing.
1655  *
1656  * Parameters  :
1657  *          1  :  csp = Current client state (buffers, headers, etc...)
1658  *          2  :  header = On input, pointer to header to modify.
1659  *                On output, pointer to the modified header, or NULL
1660  *                to remove the header.  This function frees the
1661  *                original string if necessary.
1662  *
1663  * Returns     :  JB_ERR_OK on success, or
1664  *                JB_ERR_MEMORY on out-of-memory error.
1665  *
1666  *********************************************************************/
1667 static jb_err client_connection(struct client_state *csp, char **header)
1668 {
1669    const char *wanted_header = get_appropiate_connection_header(csp);
1670
1671    if (strcmpic(*header, wanted_header))
1672    {
1673 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1674       if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1675       {
1676          log_error(LOG_LEVEL_HEADER,
1677             "Keeping the client header '%s' around. "
1678             "The connection will not be kept alive.",
1679             *header);
1680       }
1681       else
1682 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1683       {
1684          char *old_header = *header;
1685
1686          *header = strdup(wanted_header);
1687          if (header == NULL)
1688          {
1689             return JB_ERR_MEMORY;
1690          }
1691          log_error(LOG_LEVEL_HEADER,
1692             "Replaced: \'%s\' with \'%s\'", old_header, *header);
1693          freez(old_header);
1694       }
1695    }
1696 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1697    else
1698    {
1699       log_error(LOG_LEVEL_HEADER,
1700          "Keeping the client header '%s' around. "
1701          "The server connection will be kept alive if possible.",
1702          *header);
1703       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1704    }
1705 #endif  /* def FEATURE_CONNECTION_KEEP_ALIVE */
1706
1707    /* Signal client_connection_adder() to return early. */
1708    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1709
1710    return JB_ERR_OK;
1711 }
1712
1713
1714 /*********************************************************************
1715  *
1716  * Function    :  crumble
1717  *
1718  * Description :  This is called if a header matches a pattern to "crunch"
1719  *
1720  * Parameters  :
1721  *          1  :  csp = Current client state (buffers, headers, etc...)
1722  *          2  :  header = On input, pointer to header to modify.
1723  *                On output, pointer to the modified header, or NULL
1724  *                to remove the header.  This function frees the
1725  *                original string if necessary.
1726  *
1727  * Returns     :  JB_ERR_OK on success, or
1728  *                JB_ERR_MEMORY on out-of-memory error.
1729  *
1730  *********************************************************************/
1731 static jb_err crumble(struct client_state *csp, char **header)
1732 {
1733    (void)csp;
1734    log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1735    freez(*header);
1736    return JB_ERR_OK;
1737 }
1738
1739
1740 /*********************************************************************
1741  *
1742  * Function    :  crunch_server_header
1743  *
1744  * Description :  Crunch server header if it matches a string supplied by the
1745  *                user. Called from `sed'.
1746  *
1747  * Parameters  :
1748  *          1  :  csp = Current client state (buffers, headers, etc...)
1749  *          2  :  header = On input, pointer to header to modify.
1750  *                On output, pointer to the modified header, or NULL
1751  *                to remove the header.  This function frees the
1752  *                original string if necessary.
1753  *
1754  * Returns     :  JB_ERR_OK on success and always succeeds
1755  *
1756  *********************************************************************/
1757 static jb_err crunch_server_header(struct client_state *csp, char **header)
1758 {
1759    const char *crunch_pattern;
1760
1761    /* Do we feel like crunching? */
1762    if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1763    {
1764       crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1765
1766       /* Is the current header the lucky one? */
1767       if (strstr(*header, crunch_pattern))
1768       {
1769          log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);  
1770          freez(*header);
1771       }
1772    }
1773
1774    return JB_ERR_OK;
1775 }
1776
1777
1778 /*********************************************************************
1779  *
1780  * Function    :  server_content_type
1781  *
1782  * Description :  Set the content-type for filterable types (text/.*,
1783  *                .*xml.*, javascript and image/gif) unless filtering has been
1784  *                forbidden (CT_TABOO) while parsing earlier headers.
1785  *                NOTE: Since text/plain is commonly used by web servers
1786  *                      for files whose correct type is unknown, we don't
1787  *                      set CT_TEXT for it.
1788  *
1789  * Parameters  :
1790  *          1  :  csp = Current client state (buffers, headers, etc...)
1791  *          2  :  header = On input, pointer to header to modify.
1792  *                On output, pointer to the modified header, or NULL
1793  *                to remove the header.  This function frees the
1794  *                original string if necessary.
1795  *
1796  * Returns     :  JB_ERR_OK on success, or
1797  *                JB_ERR_MEMORY on out-of-memory error.
1798  *
1799  *********************************************************************/
1800 static jb_err server_content_type(struct client_state *csp, char **header)
1801 {
1802    /* Remove header if it isn't the first Content-Type header */
1803    if ((csp->content_type & CT_DECLARED))
1804    {
1805      /*
1806       * Another, slightly slower, way to see if
1807       * we already parsed another Content-Type header.
1808       */
1809       assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1810
1811       log_error(LOG_LEVEL_ERROR,
1812          "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1813          *header);
1814       freez(*header);
1815
1816       return JB_ERR_OK;
1817    }
1818
1819    /*
1820     * Signal that the Content-Type has been set.
1821     */
1822    csp->content_type |= CT_DECLARED;
1823
1824    if (!(csp->content_type & CT_TABOO))
1825    {
1826       /*
1827        * XXX: The assumption that text/plain is a sign of
1828        * binary data seems to be somewhat unreasonable nowadays
1829        * and should be dropped after 3.0.8 is out.
1830        */
1831       if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1832         || strstr(*header, "xml")
1833         || strstr(*header, "application/x-javascript"))
1834       {
1835          csp->content_type |= CT_TEXT;
1836       }
1837       else if (strstr(*header, "image/gif"))
1838       {
1839          csp->content_type |= CT_GIF;
1840       }
1841    }
1842
1843    /*
1844     * Are we messing with the content type?
1845     */
1846    if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1847    {
1848       /*
1849        * Make sure the user doesn't accidently
1850        * change the content type of binary documents. 
1851        */
1852       if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1853       {
1854          freez(*header);
1855          *header = strdup("Content-Type: ");
1856          string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1857
1858          if (header == NULL)
1859          {
1860             log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1861             return JB_ERR_MEMORY;
1862          }
1863          log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1864       }
1865       else
1866       {
1867          log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1868             "It doesn't look like a content type that should be filtered. "
1869             "Enable force-text-mode if you know what you're doing.", *header);
1870       }
1871    }
1872
1873    return JB_ERR_OK;
1874 }
1875
1876
1877 /*********************************************************************
1878  *
1879  * Function    :  server_transfer_coding
1880  *
1881  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
1882  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1883  *                - Remove header if body was chunked but has been
1884  *                  de-chunked for filtering.
1885  *
1886  * Parameters  :
1887  *          1  :  csp = Current client state (buffers, headers, etc...)
1888  *          2  :  header = On input, pointer to header to modify.
1889  *                On output, pointer to the modified header, or NULL
1890  *                to remove the header.  This function frees the
1891  *                original string if necessary.
1892  *
1893  * Returns     :  JB_ERR_OK on success, or
1894  *                JB_ERR_MEMORY on out-of-memory error.
1895  *
1896  *********************************************************************/
1897 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1898 {
1899    /*
1900     * Turn off pcrs and gif filtering if body compressed
1901     */
1902    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1903    {
1904 #ifdef FEATURE_ZLIB
1905       /*
1906        * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1907        */
1908       log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1909          csp->http->cmd, *header);
1910 #endif /* def FEATURE_ZLIB */
1911       csp->content_type = CT_TABOO;
1912    }
1913
1914    /*
1915     * Raise flag if body chunked
1916     */
1917    if (strstr(*header, "chunked"))
1918    {
1919       csp->flags |= CSP_FLAG_CHUNKED;
1920
1921       /*
1922        * If the body was modified, it has been de-chunked first
1923        * and the header must be removed.
1924        *
1925        * FIXME: If there is more than one transfer encoding,
1926        * only the "chunked" part should be removed here.
1927        */
1928       if (csp->flags & CSP_FLAG_MODIFIED)
1929       {
1930          log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1931          freez(*header);
1932       }
1933    }
1934
1935    return JB_ERR_OK;
1936 }
1937
1938
1939 /*********************************************************************
1940  *
1941  * Function    :  server_content_encoding
1942  *
1943  * Description :  This function is run twice for each request,
1944  *                unless FEATURE_ZLIB and filtering are disabled.
1945  *
1946  *                The first run is used to check if the content
1947  *                is compressed, if FEATURE_ZLIB is disabled
1948  *                filtering is then disabled as well, if FEATURE_ZLIB
1949  *                is enabled the content is marked for decompression.
1950  *                
1951  *                The second run is used to remove the Content-Encoding
1952  *                header if the decompression was successful.
1953  *
1954  * Parameters  :
1955  *          1  :  csp = Current client state (buffers, headers, etc...)
1956  *          2  :  header = On input, pointer to header to modify.
1957  *                On output, pointer to the modified header, or NULL
1958  *                to remove the header.  This function frees the
1959  *                original string if necessary.
1960  *
1961  * Returns     :  JB_ERR_OK on success, or
1962  *                JB_ERR_MEMORY on out-of-memory error.
1963  *
1964  *********************************************************************/
1965 static jb_err server_content_encoding(struct client_state *csp, char **header)
1966 {
1967 #ifdef FEATURE_ZLIB
1968    if ((csp->flags & CSP_FLAG_MODIFIED)
1969     && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1970    {
1971       /*
1972        * We successfully decompressed the content,
1973        * and have to clean the header now, so the
1974        * client no longer expects compressed data..
1975        *
1976        * XXX: There is a difference between cleaning
1977        * and removing it completely.
1978        */
1979       log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1980       freez(*header);
1981    }
1982    else if (strstr(*header, "gzip"))
1983    {
1984       /* Mark for gzip decompression */
1985       csp->content_type |= CT_GZIP;
1986    }
1987    else if (strstr(*header, "deflate"))
1988    {
1989       /* Mark for zlib decompression */
1990       csp->content_type |= CT_DEFLATE;
1991    }
1992    else if (strstr(*header, "compress"))
1993    {
1994       /*
1995        * We can't decompress this; therefore we can't filter
1996        * it either.
1997        */
1998       csp->content_type |= CT_TABOO;
1999    }
2000 #else /* !defined(FEATURE_ZLIB) */
2001    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2002    {
2003       /*
2004        * Body is compressed, turn off pcrs and gif filtering.
2005        */
2006       csp->content_type |= CT_TABOO;
2007
2008       /*
2009        * Log a warning if the user expects the content to be filtered.
2010        */
2011       if ((csp->rlist != NULL) &&
2012          (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2013       {
2014          log_error(LOG_LEVEL_INFO,
2015             "Compressed content detected, content filtering disabled. "
2016             "Consider recompiling Privoxy with zlib support or "
2017             "enable the prevent-compression action.");
2018       }
2019    }
2020 #endif /* defined(FEATURE_ZLIB) */
2021
2022    return JB_ERR_OK;
2023
2024 }
2025
2026
2027 /*********************************************************************
2028  *
2029  * Function    :  server_adjust_content_length
2030  *
2031  * Description :  Adjust Content-Length header if we modified
2032  *                the body.
2033  *
2034  * Parameters  :
2035  *          1  :  csp = Current client state (buffers, headers, etc...)
2036  *          2  :  header = On input, pointer to header to modify.
2037  *                On output, pointer to the modified header, or NULL
2038  *                to remove the header.  This function frees the
2039  *                original string if necessary.
2040  *
2041  * Returns     :  JB_ERR_OK on success, or
2042  *                JB_ERR_MEMORY on out-of-memory error.
2043  *
2044  *********************************************************************/
2045 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2046 {
2047    const size_t max_header_length = 80;
2048
2049    /* Regenerate header if the content was modified. */
2050    if (csp->flags & CSP_FLAG_MODIFIED)
2051    {
2052       freez(*header);
2053       *header = (char *) zalloc(max_header_length);
2054       if (*header == NULL)
2055       {
2056          return JB_ERR_MEMORY;
2057       }
2058
2059       snprintf(*header, max_header_length, "Content-Length: %d",
2060          (int)csp->content_length);
2061       log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2062          (int)csp->content_length);
2063    }
2064
2065    return JB_ERR_OK;
2066 }
2067
2068
2069 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2070 /*********************************************************************
2071  *
2072  * Function    :  server_save_content_length
2073  *
2074  * Description :  Save the Content-Length sent by the server.
2075  *
2076  * Parameters  :
2077  *          1  :  csp = Current client state (buffers, headers, etc...)
2078  *          2  :  header = On input, pointer to header to modify.
2079  *                On output, pointer to the modified header, or NULL
2080  *                to remove the header.  This function frees the
2081  *                original string if necessary.
2082  *
2083  * Returns     :  JB_ERR_OK on success, or
2084  *                JB_ERR_MEMORY on out-of-memory error.
2085  *
2086  *********************************************************************/
2087 static jb_err server_save_content_length(struct client_state *csp, char **header)
2088 {
2089    unsigned long long content_length = 0;
2090
2091    assert(*(*header+14) == ':');
2092
2093    if (1 != sscanf(*header+14, ": %llu", &content_length))
2094    {
2095       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2096       freez(*header);
2097    }
2098    else
2099    {
2100       csp->expected_content_length = content_length;
2101       csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2102    }
2103
2104    return JB_ERR_OK;
2105 }
2106 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2107
2108
2109 /*********************************************************************
2110  *
2111  * Function    :  server_content_md5
2112  *
2113  * Description :  Crumble any Content-MD5 headers if the document was
2114  *                modified. FIXME: Should we re-compute instead?
2115  *
2116  * Parameters  :
2117  *          1  :  csp = Current client state (buffers, headers, etc...)
2118  *          2  :  header = On input, pointer to header to modify.
2119  *                On output, pointer to the modified header, or NULL
2120  *                to remove the header.  This function frees the
2121  *                original string if necessary.
2122  *
2123  * Returns     :  JB_ERR_OK on success, or
2124  *                JB_ERR_MEMORY on out-of-memory error.
2125  *
2126  *********************************************************************/
2127 static jb_err server_content_md5(struct client_state *csp, char **header)
2128 {
2129    if (csp->flags & CSP_FLAG_MODIFIED)
2130    {
2131       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2132       freez(*header);
2133    }
2134
2135    return JB_ERR_OK;
2136 }
2137
2138
2139 /*********************************************************************
2140  *
2141  * Function    :  server_content_disposition
2142  *
2143  * Description :  If enabled, blocks or modifies the "Content-Disposition" header.
2144  *                Called from `sed'.
2145  *
2146  * Parameters  :
2147  *          1  :  csp = Current client state (buffers, headers, etc...)
2148  *          2  :  header = On input, pointer to header to modify.
2149  *                On output, pointer to the modified header, or NULL
2150  *                to remove the header.  This function frees the
2151  *                original string if necessary.
2152  *
2153  * Returns     :  JB_ERR_OK on success, or
2154  *                JB_ERR_MEMORY on out-of-memory error.
2155  *
2156  *********************************************************************/
2157 static jb_err server_content_disposition(struct client_state *csp, char **header)
2158 {
2159    const char *newval;
2160
2161    /*
2162     * Are we messing with the Content-Disposition header?
2163     */
2164    if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2165    {
2166       /* Me tinks not */
2167       return JB_ERR_OK;
2168    }
2169
2170    newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2171
2172    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2173    {
2174       /*
2175        * Blocking content-disposition header
2176        */
2177       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2178       freez(*header);
2179       return JB_ERR_OK;
2180    }
2181    else
2182    {  
2183       /*
2184        * Replacing Content-Disposition header
2185        */
2186       freez(*header);
2187       *header = strdup("Content-Disposition: ");
2188       string_append(header, newval);
2189
2190       if (*header != NULL)
2191       {
2192          log_error(LOG_LEVEL_HEADER,
2193             "Content-Disposition header crunched and replaced with: %s", *header);
2194       }
2195    }
2196    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2197 }
2198
2199
2200 /*********************************************************************
2201  *
2202  * Function    :  server_last_modified
2203  *
2204  * Description :  Changes Last-Modified header to the actual date
2205  *                to help hide-if-modified-since.
2206  *                Called from `sed'.
2207  *
2208  * Parameters  :
2209  *          1  :  csp = Current client state (buffers, headers, etc...)
2210  *          2  :  header = On input, pointer to header to modify.
2211  *                On output, pointer to the modified header, or NULL
2212  *                to remove the header.  This function frees the
2213  *                original string if necessary.
2214  *
2215  * Returns     :  JB_ERR_OK on success, or
2216  *                JB_ERR_MEMORY on out-of-memory error.
2217  *
2218  *********************************************************************/
2219 static jb_err server_last_modified(struct client_state *csp, char **header)
2220 {
2221    const char *newval;
2222    char buf[BUFFER_SIZE];
2223
2224    char newheader[50];
2225 #ifdef HAVE_GMTIME_R
2226    struct tm gmt;
2227 #endif
2228    struct tm *timeptr = NULL;
2229    time_t now, last_modified;                  
2230    long int days, hours, minutes, seconds;
2231    
2232    /*
2233     * Are we messing with the Last-Modified header?
2234     */
2235    if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2236    {
2237       /*Nope*/
2238       return JB_ERR_OK;
2239    }
2240
2241    newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2242
2243    if (0 == strcmpic(newval, "block") )
2244    {
2245       /*
2246        * Blocking Last-Modified header. Useless but why not.
2247        */
2248       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2249       freez(*header);
2250       return JB_ERR_OK;
2251    }
2252    else if (0 == strcmpic(newval, "reset-to-request-time"))
2253    {  
2254       /*
2255        * Setting Last-Modified Header to now.
2256        */
2257       get_http_time(0, buf, sizeof(buf));
2258       freez(*header);
2259       *header = strdup("Last-Modified: ");
2260       string_append(header, buf);   
2261
2262       if (*header == NULL)
2263       {
2264          log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");  
2265       }
2266       else
2267       {
2268          log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2269       }
2270    }
2271    else if (0 == strcmpic(newval, "randomize"))
2272    {
2273       const char *header_time = *header + sizeof("Last-Modified:");
2274
2275       log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2276       now = time(NULL);
2277 #ifdef HAVE_GMTIME_R
2278       gmtime_r(&now, &gmt);
2279 #elif defined(MUTEX_LOCKS_AVAILABLE)
2280       privoxy_mutex_lock(&gmtime_mutex);
2281       gmtime(&now);
2282       privoxy_mutex_unlock(&gmtime_mutex);
2283 #else
2284       gmtime(&now);
2285 #endif
2286       if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2287       {
2288          log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2289          freez(*header);
2290       }
2291       else
2292       {
2293          long int rtime = (long int)difftime(now, last_modified);
2294          if (rtime)
2295          {
2296             const int negative_delta = (rtime < 0);
2297
2298             if (negative_delta)
2299             {
2300                rtime *= -1; 
2301                log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2302             }
2303             rtime = pick_from_range(rtime);
2304             if (negative_delta)
2305             {
2306                rtime *= -1;
2307             }
2308             last_modified += rtime;
2309 #ifdef HAVE_GMTIME_R
2310             timeptr = gmtime_r(&last_modified, &gmt);
2311 #elif defined(MUTEX_LOCKS_AVAILABLE)
2312             privoxy_mutex_lock(&gmtime_mutex);
2313             timeptr = gmtime(&last_modified);
2314             privoxy_mutex_unlock(&gmtime_mutex);
2315 #else
2316             timeptr = gmtime(&last_modified);
2317 #endif
2318             strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2319             freez(*header);
2320             *header = strdup("Last-Modified: ");
2321             string_append(header, newheader);
2322
2323             if (*header == NULL)
2324             {
2325                log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2326                return JB_ERR_MEMORY;  
2327             }
2328
2329             days    = rtime / (3600 * 24);
2330             hours   = rtime / 3600 % 24;
2331             minutes = rtime / 60 % 60;
2332             seconds = rtime % 60;
2333
2334             log_error(LOG_LEVEL_HEADER,
2335                "Randomized:  %s (added %d da%s %d hou%s %d minut%s %d second%s",
2336                *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2337                minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2338          }
2339          else
2340          {
2341             log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2342          }
2343       }
2344    }
2345
2346    return JB_ERR_OK;
2347 }
2348
2349
2350 /*********************************************************************
2351  *
2352  * Function    :  client_accept_encoding
2353  *
2354  * Description :  Rewrite the client's Accept-Encoding header so that
2355  *                if doesn't allow compression, if the action applies.
2356  *                Note: For HTTP/1.0 the absence of the header is enough.
2357  *
2358  * Parameters  :
2359  *          1  :  csp = Current client state (buffers, headers, etc...)
2360  *          2  :  header = On input, pointer to header to modify.
2361  *                On output, pointer to the modified header, or NULL
2362  *                to remove the header.  This function frees the
2363  *                original string if necessary.
2364  *
2365  * Returns     :  JB_ERR_OK on success, or
2366  *                JB_ERR_MEMORY on out-of-memory error.
2367  *
2368  *********************************************************************/
2369 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2370 {
2371    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2372    {
2373       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2374
2375       freez(*header);
2376
2377       /* Temporarily disable the correct behaviour to
2378        * work around a PHP bug. 
2379        *
2380        * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2381        * {
2382        *    *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2383        *    if (*header == NULL)
2384        *    {
2385        *       return JB_ERR_MEMORY;
2386        *    }
2387        * }
2388        * 
2389        */
2390    }
2391
2392    return JB_ERR_OK;
2393 }
2394
2395
2396 /*********************************************************************
2397  *
2398  * Function    :  client_te
2399  *
2400  * Description :  Rewrite the client's TE header so that
2401  *                if doesn't allow compression, if the action applies.
2402  *
2403  * Parameters  :
2404  *          1  :  csp = Current client state (buffers, headers, etc...)
2405  *          2  :  header = On input, pointer to header to modify.
2406  *                On output, pointer to the modified header, or NULL
2407  *                to remove the header.  This function frees the
2408  *                original string if necessary.
2409  *
2410  * Returns     :  JB_ERR_OK on success, or
2411  *                JB_ERR_MEMORY on out-of-memory error.
2412  *
2413  *********************************************************************/
2414 static jb_err client_te(struct client_state *csp, char **header)
2415 {
2416    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2417    {
2418       freez(*header);
2419       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2420    }
2421
2422    return JB_ERR_OK;
2423 }
2424
2425
2426 /*********************************************************************
2427  *
2428  * Function    :  client_referrer
2429  *
2430  * Description :  Handle the "referer" config setting properly.
2431  *                Called from `sed'.
2432  *
2433  * Parameters  :
2434  *          1  :  csp = Current client state (buffers, headers, etc...)
2435  *          2  :  header = On input, pointer to header to modify.
2436  *                On output, pointer to the modified header, or NULL
2437  *                to remove the header.  This function frees the
2438  *                original string if necessary.
2439  *
2440  * Returns     :  JB_ERR_OK on success, or
2441  *                JB_ERR_MEMORY on out-of-memory error.
2442  *
2443  *********************************************************************/
2444 static jb_err client_referrer(struct client_state *csp, char **header)
2445 {
2446    const char *parameter;
2447    /* booleans for parameters we have to check multiple times */
2448    int parameter_conditional_block;
2449    int parameter_conditional_forge;
2450  
2451 #ifdef FEATURE_FORCE_LOAD
2452    /*
2453     * Since the referrer can include the prefix even
2454     * if the request itself is non-forced, we must
2455     * clean it unconditionally.
2456     *
2457     * XXX: strclean is too broad
2458     */
2459    strclean(*header, FORCE_PREFIX);
2460 #endif /* def FEATURE_FORCE_LOAD */
2461
2462    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2463    {
2464       /* Nothing left to do */
2465       return JB_ERR_OK;
2466    }
2467
2468    parameter = csp->action->string[ACTION_STRING_REFERER];
2469    assert(parameter != NULL);
2470    parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2471    parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2472
2473    if (!parameter_conditional_block && !parameter_conditional_forge)
2474    {
2475       /*
2476        * As conditional-block and conditional-forge are the only
2477        * parameters that rely on the original referrer, we can
2478        * remove it now for all the others.
2479        */
2480       freez(*header);
2481    }
2482
2483    if (0 == strcmpic(parameter, "block"))
2484    {
2485       log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2486       return JB_ERR_OK;
2487    }
2488    else if (parameter_conditional_block || parameter_conditional_forge)
2489    {
2490       return handle_conditional_hide_referrer_parameter(header,
2491          csp->http->hostport, parameter_conditional_block);
2492    }
2493    else if (0 == strcmpic(parameter, "forge"))
2494    {
2495       return create_forged_referrer(header, csp->http->hostport);
2496    }
2497    else
2498    {
2499       /* interpret parameter as user-supplied referer to fake */
2500       return create_fake_referrer(header, parameter);
2501    }
2502 }
2503
2504
2505 /*********************************************************************
2506  *
2507  * Function    :  client_accept_language
2508  *
2509  * Description :  Handle the "Accept-Language" config setting properly.
2510  *                Called from `sed'.
2511  *
2512  * Parameters  :
2513  *          1  :  csp = Current client state (buffers, headers, etc...)
2514  *          2  :  header = On input, pointer to header to modify.
2515  *                On output, pointer to the modified header, or NULL
2516  *                to remove the header.  This function frees the
2517  *                original string if necessary.
2518  *
2519  * Returns     :  JB_ERR_OK on success, or
2520  *                JB_ERR_MEMORY on out-of-memory error.
2521  *
2522  *********************************************************************/
2523 static jb_err client_accept_language(struct client_state *csp, char **header)
2524 {
2525    const char *newval;
2526
2527    /*
2528     * Are we messing with the Accept-Language?
2529     */
2530    if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2531    {
2532       /*I don't think so*/
2533       return JB_ERR_OK;
2534    }
2535
2536    newval = csp->action->string[ACTION_STRING_LANGUAGE];
2537
2538    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2539    {
2540       /*
2541        * Blocking Accept-Language header
2542        */
2543       log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2544       freez(*header);
2545       return JB_ERR_OK;
2546    }
2547    else
2548    {  
2549       /*
2550        * Replacing Accept-Language header
2551        */
2552       freez(*header);
2553       *header = strdup("Accept-Language: ");
2554       string_append(header, newval);   
2555
2556       if (*header == NULL)
2557       {
2558          log_error(LOG_LEVEL_ERROR,
2559             "Insufficient memory. Accept-Language header crunched without replacement.");  
2560       }
2561       else
2562       {
2563          log_error(LOG_LEVEL_HEADER,
2564             "Accept-Language header crunched and replaced with: %s", *header);
2565       }
2566    }
2567    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2568 }
2569
2570
2571 /*********************************************************************
2572  *
2573  * Function    :  crunch_client_header
2574  *
2575  * Description :  Crunch client header if it matches a string supplied by the
2576  *                user. Called from `sed'.
2577  *
2578  * Parameters  :
2579  *          1  :  csp = Current client state (buffers, headers, etc...)
2580  *          2  :  header = On input, pointer to header to modify.
2581  *                On output, pointer to the modified header, or NULL
2582  *                to remove the header.  This function frees the
2583  *                original string if necessary.
2584  *
2585  * Returns     :  JB_ERR_OK on success and always succeeds
2586  *
2587  *********************************************************************/
2588 static jb_err crunch_client_header(struct client_state *csp, char **header)
2589 {
2590    const char *crunch_pattern;
2591
2592    /* Do we feel like crunching? */
2593    if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2594    {
2595       crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2596
2597       /* Is the current header the lucky one? */
2598       if (strstr(*header, crunch_pattern))
2599       {
2600          log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);  
2601          freez(*header);
2602       }
2603    }
2604    return JB_ERR_OK;
2605 }
2606
2607
2608 /*********************************************************************
2609  *
2610  * Function    :  client_uagent
2611  *
2612  * Description :  Handle the "user-agent" config setting properly
2613  *                and remember its original value to enable browser
2614  *                bug workarounds. Called from `sed'.
2615  *
2616  * Parameters  :
2617  *          1  :  csp = Current client state (buffers, headers, etc...)
2618  *          2  :  header = On input, pointer to header to modify.
2619  *                On output, pointer to the modified header, or NULL
2620  *                to remove the header.  This function frees the
2621  *                original string if necessary.
2622  *
2623  * Returns     :  JB_ERR_OK on success, or
2624  *                JB_ERR_MEMORY on out-of-memory error.
2625  *
2626  *********************************************************************/
2627 static jb_err client_uagent(struct client_state *csp, char **header)
2628 {
2629    const char *newval;
2630
2631    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2632    {
2633       return JB_ERR_OK;
2634    }
2635
2636    newval = csp->action->string[ACTION_STRING_USER_AGENT];
2637    if (newval == NULL)
2638    {
2639       return JB_ERR_OK;
2640    }
2641
2642    freez(*header);
2643    *header = strdup("User-Agent: ");
2644    string_append(header, newval);
2645
2646    log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2647
2648    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2649 }
2650
2651
2652 /*********************************************************************
2653  *
2654  * Function    :  client_ua
2655  *
2656  * Description :  Handle "ua-" headers properly.  Called from `sed'.
2657  *
2658  * Parameters  :
2659  *          1  :  csp = Current client state (buffers, headers, etc...)
2660  *          2  :  header = On input, pointer to header to modify.
2661  *                On output, pointer to the modified header, or NULL
2662  *                to remove the header.  This function frees the
2663  *                original string if necessary.
2664  *
2665  * Returns     :  JB_ERR_OK on success, or
2666  *                JB_ERR_MEMORY on out-of-memory error.
2667  *
2668  *********************************************************************/
2669 static jb_err client_ua(struct client_state *csp, char **header)
2670 {
2671    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2672    {
2673       log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2674       freez(*header);
2675    }
2676
2677    return JB_ERR_OK;
2678 }
2679
2680
2681 /*********************************************************************
2682  *
2683  * Function    :  client_from
2684  *
2685  * Description :  Handle the "from" config setting properly.
2686  *                Called from `sed'.
2687  *
2688  * Parameters  :
2689  *          1  :  csp = Current client state (buffers, headers, etc...)
2690  *          2  :  header = On input, pointer to header to modify.
2691  *                On output, pointer to the modified header, or NULL
2692  *                to remove the header.  This function frees the
2693  *                original string if necessary.
2694  *
2695  * Returns     :  JB_ERR_OK on success, or
2696  *                JB_ERR_MEMORY on out-of-memory error.
2697  *
2698  *********************************************************************/
2699 static jb_err client_from(struct client_state *csp, char **header)
2700 {
2701    const char *newval;
2702
2703    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2704    {
2705       return JB_ERR_OK;
2706    }
2707
2708    freez(*header);
2709
2710    newval = csp->action->string[ACTION_STRING_FROM];
2711
2712    /*
2713     * Are we blocking the e-mail address?
2714     */
2715    if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2716    {
2717       log_error(LOG_LEVEL_HEADER, "crunched From!");
2718       return JB_ERR_OK;
2719    }
2720
2721    log_error(LOG_LEVEL_HEADER, " modified");
2722
2723    *header = strdup("From: ");
2724    string_append(header, newval);
2725
2726    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2727 }
2728
2729
2730 /*********************************************************************
2731  *
2732  * Function    :  client_send_cookie
2733  *
2734  * Description :  Crunches the "cookie" header if necessary.
2735  *                Called from `sed'.
2736  *
2737  *                XXX: Stupid name, doesn't send squat.
2738  *
2739  * Parameters  :
2740  *          1  :  csp = Current client state (buffers, headers, etc...)
2741  *          2  :  header = On input, pointer to header to modify.
2742  *                On output, pointer to the modified header, or NULL
2743  *                to remove the header.  This function frees the
2744  *                original string if necessary.
2745  *
2746  * Returns     :  JB_ERR_OK on success, or
2747  *                JB_ERR_MEMORY on out-of-memory error.
2748  *
2749  *********************************************************************/
2750 static jb_err client_send_cookie(struct client_state *csp, char **header)
2751 {
2752    if (csp->action->flags & ACTION_NO_COOKIE_READ)
2753    {
2754       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2755       freez(*header);
2756    }
2757
2758    return JB_ERR_OK;
2759 }
2760
2761
2762 /*********************************************************************
2763  *
2764  * Function    :  client_x_forwarded
2765  *
2766  * Description :  Handle the "x-forwarded-for" config setting properly,
2767  *                also used in the add_client_headers list.  Called from `sed'.
2768  *
2769  * Parameters  :
2770  *          1  :  csp = Current client state (buffers, headers, etc...)
2771  *          2  :  header = On input, pointer to header to modify.
2772  *                On output, pointer to the modified header, or NULL
2773  *                to remove the header.  This function frees the
2774  *                original string if necessary.
2775  *
2776  * Returns     :  JB_ERR_OK on success, or
2777  *                JB_ERR_MEMORY on out-of-memory error.
2778  *
2779  *********************************************************************/
2780 jb_err client_x_forwarded(struct client_state *csp, char **header)
2781 {
2782    if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2783    {
2784       const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2785
2786       if (0 == strcmpic(parameter, "block"))
2787       {
2788          freez(*header);
2789          log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2790       }
2791       else if (0 == strcmpic(parameter, "add"))
2792       {
2793          string_append(header, ", ");
2794          string_append(header, csp->ip_addr_str);
2795
2796          if (*header == NULL)
2797          {
2798             return JB_ERR_MEMORY;
2799          }
2800          log_error(LOG_LEVEL_HEADER,
2801             "Appended client IP address to %s", *header);
2802          csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2803       }
2804       else
2805       {
2806          log_error(LOG_LEVEL_FATAL,
2807             "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2808       }
2809    }
2810
2811    return JB_ERR_OK;
2812 }
2813
2814
2815 /*********************************************************************
2816  *
2817  * Function    :  client_max_forwards
2818  *
2819  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
2820  *                from the value of the Max-Forwards header field.
2821  *
2822  * Parameters  :
2823  *          1  :  csp = Current client state (buffers, headers, etc...)
2824  *          2  :  header = On input, pointer to header to modify.
2825  *                On output, pointer to the modified header, or NULL
2826  *                to remove the header.  This function frees the
2827  *                original string if necessary.
2828  *
2829  * Returns     :  JB_ERR_OK on success, or
2830  *                JB_ERR_MEMORY on out-of-memory error.
2831  *
2832  *********************************************************************/
2833 static jb_err client_max_forwards(struct client_state *csp, char **header)
2834 {
2835    int max_forwards;
2836
2837    if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2838        (0 == strcmpic(csp->http->gpc, "options")))
2839    {
2840       assert(*(*header+12) == ':');
2841       if (1 == sscanf(*header+12, ": %d", &max_forwards))
2842       {
2843          if (max_forwards > 0)
2844          {
2845             snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2846             log_error(LOG_LEVEL_HEADER,
2847                "Max-Forwards value for %s request reduced to %d.",
2848                csp->http->gpc, max_forwards);
2849          }
2850          else if (max_forwards < 0)
2851          {
2852             log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2853             freez(*header);
2854          }
2855       }
2856       else
2857       {
2858          log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2859          freez(*header);
2860       }
2861    }
2862
2863    return JB_ERR_OK;
2864 }
2865
2866
2867 /*********************************************************************
2868  *
2869  * Function    :  client_host
2870  *
2871  * Description :  If the request URI did not contain host and
2872  *                port information, parse and evaluate the Host
2873  *                header field.
2874  *
2875  *                Also, kill ill-formed HOST: headers as sent by
2876  *                Apple's iTunes software when used with a proxy.
2877  *
2878  * Parameters  :
2879  *          1  :  csp = Current client state (buffers, headers, etc...)
2880  *          2  :  header = On input, pointer to header to modify.
2881  *                On output, pointer to the modified header, or NULL
2882  *                to remove the header.  This function frees the
2883  *                original string if necessary.
2884  *
2885  * Returns     :  JB_ERR_OK on success, or
2886  *                JB_ERR_MEMORY on out-of-memory error.
2887  *
2888  *********************************************************************/
2889 static jb_err client_host(struct client_state *csp, char **header)
2890 {
2891    char *p, *q;
2892
2893    /*
2894     * If the header field name is all upper-case, chances are that it's
2895     * an ill-formed one from iTunes. BTW, killing innocent headers here is
2896     * not a problem -- they are regenerated later.
2897     */
2898    if ((*header)[1] == 'O')
2899    {
2900       log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2901       freez(*header);
2902       return JB_ERR_OK;
2903    }
2904
2905    if (!csp->http->hostport || (*csp->http->hostport == '*') ||  
2906        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2907    {
2908       
2909       if (NULL == (p = strdup((*header)+6)))
2910       {
2911          return JB_ERR_MEMORY;
2912       }
2913       chomp(p);
2914       if (NULL == (q = strdup(p)))
2915       {
2916          freez(p);
2917          return JB_ERR_MEMORY;
2918       }
2919
2920       freez(csp->http->hostport);
2921       csp->http->hostport = p;
2922       freez(csp->http->host);
2923       csp->http->host = q;
2924       q = strchr(csp->http->host, ':');
2925       if (q != NULL)
2926       {
2927          /* Terminate hostname and evaluate port string */
2928          *q++ = '\0';
2929          csp->http->port = atoi(q);
2930       }
2931       else
2932       {
2933          csp->http->port = csp->http->ssl ? 443 : 80;
2934       }
2935
2936       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2937                 csp->http->hostport, csp->http->host, csp->http->port);
2938    }
2939
2940    /* Signal client_host_adder() to return right away */
2941    csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2942
2943    return JB_ERR_OK;
2944 }
2945
2946
2947 /*********************************************************************
2948  *
2949  * Function    :  client_if_modified_since
2950  *
2951  * Description :  Remove or modify the If-Modified-Since header.
2952  *
2953  * Parameters  :
2954  *          1  :  csp = Current client state (buffers, headers, etc...)
2955  *          2  :  header = On input, pointer to header to modify.
2956  *                On output, pointer to the modified header, or NULL
2957  *                to remove the header.  This function frees the
2958  *                original string if necessary.
2959  *
2960  * Returns     :  JB_ERR_OK on success, or
2961  *                JB_ERR_MEMORY on out-of-memory error.
2962  *
2963  *********************************************************************/
2964 static jb_err client_if_modified_since(struct client_state *csp, char **header)
2965 {
2966    char newheader[50];
2967 #ifdef HAVE_GMTIME_R
2968    struct tm gmt;
2969 #endif
2970    struct tm *timeptr = NULL;
2971    time_t tm = 0;                  
2972    const char *newval;
2973    long int hours, minutes, seconds;
2974    char * endptr;
2975    
2976    if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2977    {
2978       /* 
2979        * The client got an error message because of a temporary problem,
2980        * the problem is gone and the client now tries to revalidate our
2981        * error message on the real server. The revalidation would always
2982        * end with the transmission of the whole document and there is
2983        * no need to expose the bogus If-Modified-Since header.
2984        */
2985       log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2986       freez(*header);
2987    }
2988    else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2989    {
2990       newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2991
2992       if ((0 == strcmpic(newval, "block")))
2993       {
2994          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2995          freez(*header);
2996       }
2997       else /* add random value */
2998       {
2999          const char *header_time = *header + sizeof("If-Modified-Since:");
3000
3001          if (JB_ERR_OK != parse_header_time(header_time, &tm))
3002          {
3003             log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3004             freez(*header);
3005          }
3006          else
3007          {
3008             long int rtime = strtol(newval, &endptr, 0);
3009             const int negative_range = (rtime < 0);
3010
3011             if (rtime)
3012             {
3013                log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3014                   *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3015                if (negative_range)
3016                {
3017                   rtime *= -1; 
3018                }
3019                rtime *= 60;
3020                rtime = pick_from_range(rtime);
3021             }
3022             else
3023             {
3024                log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3025                   *header);
3026             }
3027             tm += rtime * (negative_range ? -1 : 1);
3028 #ifdef HAVE_GMTIME_R
3029             timeptr = gmtime_r(&tm, &gmt);
3030 #elif defined(MUTEX_LOCKS_AVAILABLE)
3031             privoxy_mutex_lock(&gmtime_mutex);
3032             timeptr = gmtime(&tm);
3033             privoxy_mutex_unlock(&gmtime_mutex);
3034 #else
3035             timeptr = gmtime(&tm);
3036 #endif
3037             strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3038
3039             freez(*header);
3040             *header = strdup("If-Modified-Since: ");
3041             string_append(header, newheader);
3042
3043             if (*header == NULL)
3044             {
3045                log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3046                return JB_ERR_MEMORY;  
3047             }
3048
3049             hours   = rtime / 3600;
3050             minutes = rtime / 60 % 60;
3051             seconds = rtime % 60;
3052
3053             log_error(LOG_LEVEL_HEADER,
3054                "Randomized:  %s (%s %d hou%s %d minut%s %d second%s",
3055                *header, (negative_range) ? "subtracted" : "added", hours,
3056                (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3057                seconds, (seconds == 1) ? ")" : "s)");
3058          }
3059       }
3060    }
3061
3062    return JB_ERR_OK;
3063 }
3064
3065
3066 /*********************************************************************
3067  *
3068  * Function    :  client_if_none_match
3069  *
3070  * Description :  Remove the If-None-Match header.
3071  *
3072  * Parameters  :
3073  *          1  :  csp = Current client state (buffers, headers, etc...)
3074  *          2  :  header = On input, pointer to header to modify.
3075  *                On output, pointer to the modified header, or NULL
3076  *                to remove the header.  This function frees the
3077  *                original string if necessary.
3078  *
3079  * Returns     :  JB_ERR_OK on success, or
3080  *                JB_ERR_MEMORY on out-of-memory error.
3081  *
3082  *********************************************************************/
3083 static jb_err client_if_none_match(struct client_state *csp, char **header)
3084 {
3085    if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3086    {  
3087       log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3088       freez(*header);
3089    }
3090
3091    return JB_ERR_OK;
3092 }
3093
3094
3095 /*********************************************************************
3096  *
3097  * Function    :  client_x_filter
3098  *
3099  * Description :  Disables filtering if the client set "X-Filter: No".
3100  *                Called from `sed'.
3101  *
3102  * Parameters  :
3103  *          1  :  csp = Current client state (buffers, headers, etc...)
3104  *          2  :  header = On input, pointer to header to modify.
3105  *                On output, pointer to the modified header, or NULL
3106  *                to remove the header.  This function frees the
3107  *                original string if necessary.
3108  *
3109  * Returns     :  JB_ERR_OK on success
3110  *
3111  *********************************************************************/
3112 jb_err client_x_filter(struct client_state *csp, char **header)
3113 {
3114    if ( 0 == strcmpic(*header, "X-Filter: No"))
3115    {
3116       if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3117       {
3118          log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3119       }
3120       else
3121       {
3122          if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3123          {
3124             log_error(LOG_LEVEL_HEADER,
3125                "force-text-mode overruled the client's request to fetch without filtering!");
3126          }
3127          else
3128          {  
3129             csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3130             csp->flags |= CSP_FLAG_NO_FILTERING;
3131             log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3132          }
3133          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3134          freez(*header);
3135       }
3136    }
3137    return JB_ERR_OK; 
3138 }
3139
3140
3141 /*********************************************************************
3142  *
3143  * Function    :  client_range
3144  *
3145  * Description :  Removes Range, Request-Range and If-Range headers if
3146  *                content filtering is enabled. If the client's version
3147  *                of the document has been altered by Privoxy, the server
3148  *                could interpret the range differently than the client
3149  *                intended in which case the user could end up with
3150  *                corrupted content.
3151  *
3152  * Parameters  :
3153  *          1  :  csp = Current client state (buffers, headers, etc...)
3154  *          2  :  header = On input, pointer to header to modify.
3155  *                On output, pointer to the modified header, or NULL
3156  *                to remove the header.  This function frees the
3157  *                original string if necessary.
3158  *
3159  * Returns     :  JB_ERR_OK
3160  *
3161  *********************************************************************/
3162 static jb_err client_range(struct client_state *csp, char **header)
3163 {
3164    if (content_filters_enabled(csp->action))
3165    {
3166       log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3167          " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3168       freez(*header);
3169    }
3170
3171    return JB_ERR_OK; 
3172 }
3173
3174 /* the following functions add headers directly to the header list */
3175
3176 /*********************************************************************
3177  *
3178  * Function    :  client_host_adder
3179  *
3180  * Description :  Adds the Host: header field if it is missing.
3181  *                Called from `sed'.
3182  *
3183  * Parameters  :
3184  *          1  :  csp = Current client state (buffers, headers, etc...)
3185  *
3186  * Returns     :  JB_ERR_OK on success, or
3187  *                JB_ERR_MEMORY on out-of-memory error.
3188  *
3189  *********************************************************************/
3190 static jb_err client_host_adder(struct client_state *csp)
3191 {
3192    char *p;
3193    jb_err err;
3194
3195    if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3196    {
3197       /* Header already set by the client, nothing to do. */
3198       return JB_ERR_OK;
3199    }
3200
3201    if ( !csp->http->hostport || !*(csp->http->hostport))
3202    {
3203       /* XXX: When does this happen and why is it OK? */
3204       log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3205       return JB_ERR_OK;
3206    }
3207
3208    /*
3209     * remove 'user:pass@' from 'proto://user:pass@host'
3210     */
3211    if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3212    {
3213       p++;
3214    }
3215    else
3216    {
3217       p = csp->http->hostport;
3218    }
3219
3220    /* XXX: Just add it, we already made sure that it will be unique */
3221    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3222    err = enlist_unique_header(csp->headers, "Host", p);
3223    return err;
3224
3225 }
3226
3227
3228 #if 0
3229 /*********************************************************************
3230  *
3231  * Function    :  client_accept_encoding_adder
3232  *
3233  * Description :  Add an Accept-Encoding header to the client's request
3234  *                that disables compression if the action applies, and
3235  *                the header is not already there. Called from `sed'.
3236  *                Note: For HTTP/1.0, the absence of the header is enough.
3237  *
3238  * Parameters  :
3239  *          1  :  csp = Current client state (buffers, headers, etc...)
3240  *
3241  * Returns     :  JB_ERR_OK on success, or
3242  *                JB_ERR_MEMORY on out-of-memory error.
3243  *
3244  *********************************************************************/
3245 static jb_err client_accept_encoding_adder(struct client_state *csp)
3246 {
3247    if (   ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3248        && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3249    {
3250       return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3251    }
3252
3253    return JB_ERR_OK;
3254 }
3255 #endif
3256
3257
3258 /*********************************************************************
3259  *
3260  * Function    :  client_xtra_adder
3261  *
3262  * Description :  Used in the add_client_headers list.  Called from `sed'.
3263  *
3264  * Parameters  :
3265  *          1  :  csp = Current client state (buffers, headers, etc...)
3266  *
3267  * Returns     :  JB_ERR_OK on success, or
3268  *                JB_ERR_MEMORY on out-of-memory error.
3269  *
3270  *********************************************************************/
3271 static jb_err client_xtra_adder(struct client_state *csp)
3272 {
3273    struct list_entry *lst;
3274    jb_err err;
3275
3276    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3277         lst ; lst = lst->next)
3278    {
3279       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3280       err = enlist(csp->headers, lst->str);
3281       if (err)
3282       {
3283          return err;
3284       }
3285
3286    }
3287
3288    return JB_ERR_OK;
3289 }
3290
3291
3292 /*********************************************************************
3293  *
3294  * Function    :  client_x_forwarded_for_adder
3295  *
3296  * Description :  Used in the add_client_headers list.  Called from `sed'.
3297  *
3298  * Parameters  :
3299  *          1  :  csp = Current client state (buffers, headers, etc...)
3300  *
3301  * Returns     :  JB_ERR_OK on success, or
3302  *                JB_ERR_MEMORY on out-of-memory error.
3303  *
3304  *********************************************************************/
3305 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3306 {
3307    char *header = NULL;
3308    jb_err err;
3309
3310    if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3311          && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3312       || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3313    {
3314       /*
3315        * If we aren't adding X-Forwarded-For headers,
3316        * or we already appended an existing X-Forwarded-For
3317        * header, there's nothing left to do here.
3318        */
3319       return JB_ERR_OK;
3320    }
3321
3322    header = strdup("X-Forwarded-For: ");
3323    string_append(&header, csp->ip_addr_str);
3324
3325    if (header == NULL)
3326    {
3327       return JB_ERR_MEMORY;
3328    }
3329
3330    log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3331    err = enlist(csp->headers, header);
3332    freez(header);
3333
3334    return err;
3335 }
3336
3337
3338 /*********************************************************************
3339  *
3340  * Function    :  server_connection_adder
3341  *
3342  * Description :  Adds an appropiate "Connection:" header to csp->headers
3343  *                unless the header was already present. Called from `sed'.
3344  *
3345  * Parameters  :
3346  *          1  :  csp = Current client state (buffers, headers, etc...)
3347  *
3348  * Returns     :  JB_ERR_OK on success, or
3349  *                JB_ERR_MEMORY on out-of-memory error.
3350  *
3351  *********************************************************************/
3352 static jb_err server_connection_adder(struct client_state *csp)
3353 {
3354    const unsigned int flags = csp->flags;
3355    const char *response_status_line = csp->headers->first->str;
3356    const char *wanted_header = get_appropiate_connection_header(csp);
3357
3358    if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3359     && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3360    {
3361       return JB_ERR_OK;
3362    }
3363
3364    /*
3365     * XXX: if we downgraded the response, this check will fail.
3366     */
3367    if ((csp->config->feature_flags &
3368         RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3369     && (NULL != response_status_line)
3370     && !strncmpic(response_status_line, "HTTP/1.1", 8))
3371    {
3372       log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3373          "without Connection header implies keep-alive.");
3374       csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3375    }
3376
3377    log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3378
3379    return enlist(csp->headers, wanted_header);
3380 }
3381
3382
3383 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3384 /*********************************************************************
3385  *
3386  * Function    :  server_proxy_connection_adder
3387  *
3388  * Description :  Adds a "Proxy-Connection: keep-alive" header to
3389  *                csp->headers if the client asked for keep-alive.
3390  *                XXX: We should reuse existant ones.
3391  *
3392  * Parameters  :
3393  *          1  :  csp = Current client state (buffers, headers, etc...)
3394  *
3395  * Returns     :  JB_ERR_OK on success, or
3396  *                JB_ERR_MEMORY on out-of-memory error.
3397  *
3398  *********************************************************************/
3399 static jb_err server_proxy_connection_adder(struct client_state *csp)
3400 {
3401    static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3402    jb_err err = JB_ERR_OK;
3403
3404    if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3405    {
3406       log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3407       err = enlist(csp->headers, proxy_connection_header);
3408    }
3409
3410    return err;
3411 }
3412 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3413
3414
3415 /*********************************************************************
3416  *
3417  * Function    :  client_connection_header_adder
3418  *
3419  * Description :  Adds a proper "Connection:" header to csp->headers
3420  *                unless the header was already present. Called from `sed'.
3421  *
3422  * Parameters  :
3423  *          1  :  csp = Current client state (buffers, headers, etc...)
3424  *
3425  * Returns     :  JB_ERR_OK on success, or
3426  *                JB_ERR_MEMORY on out-of-memory error.
3427  *
3428  *********************************************************************/
3429 static jb_err client_connection_header_adder(struct client_state *csp)
3430 {
3431    const char *wanted_header = get_appropiate_connection_header(csp);
3432
3433    if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3434      && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3435    {
3436       return JB_ERR_OK;
3437    }
3438
3439    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3440       && (csp->http->ssl == 0))
3441    {
3442       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3443    }
3444
3445    log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3446
3447    return enlist(csp->headers, wanted_header);
3448 }
3449
3450
3451 /*********************************************************************
3452  *
3453  * Function    :  server_http
3454  *
3455  * Description :  - Save the HTTP Status into csp->http->status
3456  *                - Set CT_TABOO to prevent filtering if the answer
3457  *                  is a partial range (HTTP status 206)
3458  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3459  *                  action applies.
3460  *
3461  * Parameters  :
3462  *          1  :  csp = Current client state (buffers, headers, etc...)
3463  *          2  :  header = On input, pointer to header to modify.
3464  *                On output, pointer to the modified header, or NULL
3465  *                to remove the header.  This function frees the
3466  *                original string if necessary.
3467  *
3468  * Returns     :  JB_ERR_OK on success, or
3469  *                JB_ERR_MEMORY on out-of-memory error.
3470  *
3471  *********************************************************************/
3472 static jb_err server_http(struct client_state *csp, char **header)
3473 {
3474    sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3475    if (csp->http->status == 206)
3476    {
3477       csp->content_type = CT_TABOO;
3478    }
3479
3480    if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3481    {
3482       /* XXX: Should we do a real validity check here? */
3483       if (strlen(*header) > 8)
3484       {
3485          (*header)[7] = '0';
3486          log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3487       }
3488       else
3489       {
3490          /*
3491           * XXX: Should we block the request or
3492           * enlist a valid status code line here?
3493           */
3494          log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3495             "Downgrading to HTTP/1.0 impossible.");
3496       }
3497    }
3498
3499    return JB_ERR_OK;
3500 }
3501
3502
3503 /*********************************************************************
3504  *
3505  * Function    :  server_set_cookie
3506  *
3507  * Description :  Handle the server "cookie" header properly.
3508  *                Log cookie to the jar file.  Then "crunch",
3509  *                accept or rewrite it to a session cookie.
3510  *                Called from `sed'.
3511  *
3512  *                TODO: Allow the user to specify a new expiration
3513  *                time to cause the cookie to expire even before the
3514  *                browser is closed.
3515  *
3516  * Parameters  :
3517  *          1  :  csp = Current client state (buffers, headers, etc...)
3518  *          2  :  header = On input, pointer to header to modify.
3519  *                On output, pointer to the modified header, or NULL
3520  *                to remove the header.  This function frees the
3521  *                original string if necessary.
3522  *
3523  * Returns     :  JB_ERR_OK on success, or
3524  *                JB_ERR_MEMORY on out-of-memory error.
3525  *
3526  *********************************************************************/
3527 static jb_err server_set_cookie(struct client_state *csp, char **header)
3528 {
3529    time_t now;
3530    time_t cookie_time; 
3531
3532    time(&now);
3533
3534    if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3535    {
3536       log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3537       freez(*header);
3538    }
3539    else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3540    {
3541       /* Flag whether or not to log a message */
3542       int changed = 0;
3543
3544       /* A variable to store the tag we're working on */
3545       char *cur_tag;
3546
3547       /* Skip "Set-Cookie:" (11 characters) in header */
3548       cur_tag = *header + 11;
3549
3550       /* skip whitespace between "Set-Cookie:" and value */
3551       while (*cur_tag && ijb_isspace(*cur_tag))
3552       {
3553          cur_tag++;
3554       }
3555
3556       /* Loop through each tag in the cookie */
3557       while (*cur_tag)
3558       {
3559          /* Find next tag */
3560          char *next_tag = strchr(cur_tag, ';');
3561          if (next_tag != NULL)
3562          {
3563             /* Skip the ';' character itself */
3564             next_tag++;
3565
3566             /* skip whitespace ";" and start of tag */
3567             while (*next_tag && ijb_isspace(*next_tag))
3568             {
3569                next_tag++;
3570             }
3571          }
3572          else
3573          {
3574             /* "Next tag" is the end of the string */
3575             next_tag = cur_tag + strlen(cur_tag);
3576          }
3577
3578          /*
3579           * Check the expiration date to see
3580           * if the cookie is still valid, if yes,
3581           * rewrite it to a session cookie.
3582           */
3583          if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3584          {
3585             char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3586
3587             /* Did we detect the date properly? */
3588             if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3589             {
3590                /*
3591                 * Nope, treat it as if it was still valid.
3592                 *
3593                 * XXX: Should we remove the whole cookie instead?
3594                 */
3595                log_error(LOG_LEVEL_ERROR,
3596                   "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3597                string_move(cur_tag, next_tag);
3598                changed = 1;
3599             }
3600             else
3601             {
3602                /*
3603                 * Yes. Check if the cookie is still valid.
3604                 *
3605                 * If the cookie is already expired it's probably
3606                 * a delete cookie and even if it isn't, the browser
3607                 * will discard it anyway.
3608                 */
3609
3610                /*
3611                 * XXX: timegm() isn't available on some AmigaOS
3612                 * versions and our replacement doesn't work.
3613                 *
3614                 * Our options are to either:
3615                 *
3616                 * - disable session-cookies-only completely if timegm
3617                 *   is missing,
3618                 *
3619                 * - to simply remove all expired tags, like it has
3620                 *   been done until Privoxy 3.0.6 and to live with
3621                 *    the consequence that it can cause login/logout
3622                 *   problems on servers that don't validate their
3623                 *   input properly, or
3624                 *
3625                 * - to replace it with mktime in which
3626                 *   case there is a slight chance of valid cookies
3627                 *   passing as already expired.
3628                 *
3629                 *   This is the way it's currently done and it's not
3630                 *   as bad as it sounds. If the missing GMT offset is
3631                 *   enough to change the result of the expiration check
3632                 *   the cookie will be only valid for a few hours
3633                 *   anyway, which in many cases will be shorter
3634                 *   than a browser session.
3635                 */
3636                if (cookie_time - now < 0)
3637                {
3638                   log_error(LOG_LEVEL_HEADER,
3639                      "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3640                   /* Just in case some clown sets more then one expiration date */
3641                   cur_tag = next_tag;
3642                }
3643                else
3644                {
3645                   /*
3646                    * Still valid, delete expiration date by copying
3647                    * the rest of the string over it.
3648                    */
3649                   string_move(cur_tag, next_tag);
3650
3651                   /* That changed the header, need to issue a log message */
3652                   changed = 1;
3653
3654                   /*
3655                    * Note that the next tag has now been moved to *cur_tag,
3656                    * so we do not need to update the cur_tag pointer.
3657                    */
3658                }
3659             }
3660
3661          }
3662          else
3663          {
3664             /* Move on to next cookie tag */
3665             cur_tag = next_tag;
3666          }
3667       }
3668
3669       if (changed)
3670       {
3671          assert(NULL != *header);
3672          log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3673             *header);
3674       }
3675    }
3676
3677    return JB_ERR_OK;
3678 }
3679
3680
3681 #ifdef FEATURE_FORCE_LOAD
3682 /*********************************************************************
3683  *
3684  * Function    :  strclean
3685  *
3686  * Description :  In-Situ-Eliminate all occurances of substring in
3687  *                string
3688  *
3689  * Parameters  :
3690  *          1  :  string = string to clean
3691  *          2  :  substring = substring to eliminate
3692  *
3693  * Returns     :  Number of eliminations
3694  *
3695  *********************************************************************/
3696 int strclean(char *string, const char *substring)
3697 {
3698    int hits = 0;
3699    size_t len;
3700    char *pos, *p;
3701
3702    len = strlen(substring);
3703
3704    while((pos = strstr(string, substring)) != NULL)
3705    {
3706       p = pos + len;
3707       do
3708       {
3709          *(p - len) = *p;
3710       }
3711       while (*p++ != '\0');
3712
3713       hits++;
3714    }
3715
3716    return(hits);
3717 }
3718 #endif /* def FEATURE_FORCE_LOAD */
3719
3720
3721 /*********************************************************************
3722  *
3723  * Function    :  parse_header_time
3724  *
3725  * Description :  Parses time formats used in HTTP header strings
3726  *                to get the numerical respresentation.
3727  *
3728  * Parameters  :
3729  *          1  :  header_time = HTTP header time as string. 
3730  *          2  :  result = storage for header_time in seconds
3731  *
3732  * Returns     :  JB_ERR_OK if the time format was recognized, or
3733  *                JB_ERR_PARSE otherwise.
3734  *
3735  *********************************************************************/
3736 static jb_err parse_header_time(const char *header_time, time_t *result)
3737 {
3738    struct tm gmt;
3739
3740    /*
3741     * Zero out gmt to prevent time zone offsets.
3742     *
3743     * While this is only necessary on some platforms
3744     * (mingw32 for example), I don't know how to
3745     * detect these automatically and doing it everywhere
3746     * shouldn't hurt.
3747     */
3748    memset(&gmt, 0, sizeof(gmt));
3749
3750                             /* Tue, 02 Jun 2037 20:00:00 */
3751    if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3752                             /* Tue, 02-Jun-2037 20:00:00 */
3753     && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3754                             /* Tue, 02-Jun-37 20:00:00 */
3755     && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3756                         /* Tuesday, 02-Jun-2037 20:00:00 */
3757     && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3758                         /* Tuesday Jun 02 20:00:00 2037 */
3759     && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3760    {
3761       return JB_ERR_PARSE;
3762    }
3763
3764    *result = timegm(&gmt);
3765
3766    return JB_ERR_OK;
3767
3768 }
3769
3770
3771 /*********************************************************************
3772  *
3773  * Function    :  get_destination_from_headers
3774  *
3775  * Description :  Parse the "Host:" header to get the request's destination.
3776  *                Only needed if the client's request was forcefully
3777  *                redirected into Privoxy.
3778  *
3779  *                Code mainly copied from client_host() which is currently
3780  *                run too late for this purpose.
3781  *
3782  * Parameters  :
3783  *          1  :  headers = List of headers (one of them hopefully being
3784  *                the "Host:" header)
3785  *          2  :  http = storage for the result (host, port and hostport). 
3786  *
3787  * Returns     :  JB_ERR_MEMORY in case of memory problems,
3788  *                JB_ERR_PARSE if the host header couldn't be found,
3789  *                JB_ERR_OK otherwise.
3790  *
3791  *********************************************************************/
3792 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3793 {
3794    char *q;
3795    char *p;
3796    char *host;
3797
3798    host = get_header_value(headers, "Host:");
3799
3800    if (NULL == host)
3801    {
3802       log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3803       return JB_ERR_PARSE;
3804    }
3805
3806    if (NULL == (p = strdup((host))))
3807    {
3808       log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3809       return JB_ERR_MEMORY;
3810    }
3811    chomp(p);
3812    if (NULL == (q = strdup(p)))
3813    {
3814       freez(p);
3815       log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3816       return JB_ERR_MEMORY;
3817    }
3818
3819    freez(http->hostport);
3820    http->hostport = p;
3821    freez(http->host);
3822    http->host = q;
3823    q = strchr(http->host, ':');
3824    if (q != NULL)
3825    {
3826       /* Terminate hostname and evaluate port string */
3827       *q++ = '\0';
3828       http->port = atoi(q);
3829    }
3830    else
3831    {
3832       http->port = http->ssl ? 443 : 80;
3833    }
3834
3835    /* Rebuild request URL */
3836    freez(http->url);
3837    http->url = strdup(http->ssl ? "https://" : "http://");
3838    string_append(&http->url, http->hostport);
3839    string_append(&http->url, http->path);
3840    if (http->url == NULL)
3841    {
3842       return JB_ERR_MEMORY;
3843    }
3844
3845    log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3846       http->url);
3847
3848    return JB_ERR_OK;
3849
3850 }
3851
3852
3853 /*********************************************************************
3854  *
3855  * Function    :  create_forged_referrer
3856  *
3857  * Description :  Helper for client_referrer to forge a referer as
3858  *                'http://[hostname:port/' to fool stupid
3859  *                checks for in-site links 
3860  *
3861  * Parameters  :
3862  *          1  :  header   = Pointer to header pointer
3863  *          2  :  hostport = Host and optionally port as string
3864  *
3865  * Returns     :  JB_ERR_OK in case of success, or
3866  *                JB_ERR_MEMORY in case of memory problems.
3867  *
3868  *********************************************************************/
3869 static jb_err create_forged_referrer(char **header, const char *hostport)
3870 {
3871     assert(NULL == *header);
3872
3873     *header = strdup("Referer: http://");
3874     string_append(header, hostport);
3875     string_append(header, "/");
3876
3877     if (NULL == *header)
3878     {
3879        return JB_ERR_MEMORY;
3880     }
3881
3882     log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
3883
3884     return JB_ERR_OK;
3885
3886 }
3887
3888
3889 /*********************************************************************
3890  *
3891  * Function    :  create_fake_referrer
3892  *
3893  * Description :  Helper for client_referrer to create a fake referrer
3894  *                based on a string supplied by the user.
3895  *
3896  * Parameters  :
3897  *          1  :  header   = Pointer to header pointer
3898  *          2  :  hosthost = Referrer to fake
3899  *
3900  * Returns     :  JB_ERR_OK in case of success, or
3901  *                JB_ERR_MEMORY in case of memory problems.
3902  *
3903  *********************************************************************/
3904 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
3905 {
3906    assert(NULL == *header);
3907
3908    if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
3909    {
3910       log_error(LOG_LEVEL_HEADER,
3911          "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
3912    }
3913    *header = strdup("Referer: ");
3914    string_append(header, fake_referrer);
3915
3916    if (NULL == *header)
3917    {
3918       return JB_ERR_MEMORY;
3919    }
3920
3921    log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
3922
3923    return JB_ERR_OK;
3924
3925 }
3926
3927
3928 /*********************************************************************
3929  *
3930  * Function    :  handle_conditional_hide_referrer_parameter
3931  *
3932  * Description :  Helper for client_referrer to crunch or forge
3933  *                the referrer header if the host has changed.
3934  *
3935  * Parameters  :
3936  *          1  :  header = Pointer to header pointer
3937  *          2  :  host   = The target host (may include the port)
3938  *          3  :  parameter_conditional_block = Boolean to signal
3939  *                if we're in conditional-block mode. If not set,
3940  *                we're in conditional-forge mode.
3941  *
3942  * Returns     :  JB_ERR_OK in case of success, or
3943  *                JB_ERR_MEMORY in case of memory problems.
3944  *
3945  *********************************************************************/
3946 static jb_err handle_conditional_hide_referrer_parameter(char **header,
3947    const char *host, const int parameter_conditional_block)
3948 {
3949    char *referer = strdup(*header);
3950    const size_t hostlenght = strlen(host);
3951    const char *referer_url = NULL;
3952
3953    if (NULL == referer)
3954    {
3955       freez(*header);
3956       return JB_ERR_MEMORY;
3957    }
3958
3959    /* referer begins with 'Referer: http[s]://' */
3960    if ((hostlenght+17) < strlen(referer))
3961    {
3962       /*
3963        * Shorten referer to make sure the referer is blocked
3964        * if www.example.org/www.example.com-shall-see-the-referer/
3965        * links to www.example.com/
3966        */
3967       referer[hostlenght+17] = '\0';
3968    }
3969    referer_url = strstr(referer, "http://");
3970    if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
3971    {
3972       /* Host has changed, Referer is invalid or a https URL. */
3973       if (parameter_conditional_block)
3974       {
3975          log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
3976          freez(*header);
3977       }
3978       else
3979       {
3980          freez(*header);
3981          freez(referer);
3982          return create_forged_referrer(header, host);
3983       }
3984    }
3985    freez(referer);
3986
3987    return JB_ERR_OK;
3988
3989 }
3990
3991
3992 /*********************************************************************
3993  *
3994  * Function    :  get_appropiate_connection_header
3995  *
3996  * Description :  Returns an appropiate Connection header
3997  *                depending on whether or not we try to keep
3998  *                the connection to the server alive.
3999  *
4000  * Parameters  :
4001  *          1  :  csp = Current client state (buffers, headers, etc...)
4002  *
4003  * Returns     :  Pointer to statically allocated header buffer.
4004  *
4005  *********************************************************************/
4006 static const char *get_appropiate_connection_header(const struct client_state *csp)
4007 {
4008    static const char connection_keep_alive[] = "Connection: keep-alive";
4009    static const char connection_close[] = "Connection: close";
4010
4011    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4012     && (csp->http->ssl == 0))
4013    {
4014       return connection_keep_alive;
4015    }
4016    return connection_close;
4017 }
4018 /*
4019   Local Variables:
4020   tab-width: 3
4021   end:
4022 */