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