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