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