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