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