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