Introduce negative tag patterns NO-REQUEST-TAG and NO-RESPONSE-TAG
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.279 2013/08/06 12:59:34 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/parsers.c,v $
5  *
6  * Purpose     :  Declares functions to parse/crunch headers and pages.
7  *
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  *
1103  * Function    :  sed
1104  *
1105  * Description :  add, delete or modify lines in the HTTP header streams.
1106  *                On entry, it receives a linked list of headers space
1107  *                that was allocated dynamically (both the list nodes
1108  *                and the header contents).
1109  *
1110  *                As a side effect it frees the space used by the original
1111  *                header lines.
1112  *
1113  * Parameters  :
1114  *          1  :  csp = Current client state (buffers, headers, etc...)
1115  *          2  :  filter_server_headers = Boolean to switch between
1116  *                                        server and header filtering.
1117  *
1118  * Returns     :  JB_ERR_OK in case off success, or
1119  *                JB_ERR_MEMORY on out-of-memory error.
1120  *
1121  *********************************************************************/
1122 jb_err sed(struct client_state *csp, int filter_server_headers)
1123 {
1124    /* XXX: use more descriptive names. */
1125    struct list_entry *p;
1126    const struct parsers *v;
1127    const add_header_func_ptr *f;
1128    jb_err err = JB_ERR_OK;
1129
1130    scan_headers(csp);
1131
1132    if (filter_server_headers)
1133    {
1134       v = server_patterns;
1135       f = add_server_headers;
1136       check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1137    }
1138    else
1139    {
1140       v = client_patterns;
1141       f = add_client_headers;
1142       check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1143    }
1144
1145    while ((err == JB_ERR_OK) && (v->str != NULL))
1146    {
1147       for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1148       {
1149          /* Header crunch()ed in previous run? -> ignore */
1150          if (p->str == NULL) continue;
1151
1152          /* Does the current parser handle this header? */
1153          if ((strncmpic(p->str, v->str, v->len) == 0) ||
1154              (v->len == CHECK_EVERY_HEADER_REMAINING))
1155          {
1156             err = v->parser(csp, &(p->str));
1157          }
1158       }
1159       v++;
1160    }
1161
1162    /* place additional headers on the csp->headers list */
1163    while ((err == JB_ERR_OK) && (*f))
1164    {
1165       err = (*f)(csp);
1166       f++;
1167    }
1168
1169    if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1170    {
1171       enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1172    }
1173
1174    return err;
1175 }
1176
1177
1178 /*********************************************************************
1179  *
1180  * Function    :  update_server_headers
1181  *
1182  * Description :  Updates server headers after the body has been modified.
1183  *
1184  * Parameters  :
1185  *          1  :  csp = Current client state (buffers, headers, etc...)
1186  *
1187  * Returns     :  JB_ERR_OK in case off success, or
1188  *                JB_ERR_MEMORY on out-of-memory error.
1189  *
1190  *********************************************************************/
1191 jb_err update_server_headers(struct client_state *csp)
1192 {
1193    jb_err err = JB_ERR_OK;
1194
1195    static const struct parsers server_patterns_light[] = {
1196       { "Content-Length:",    15, server_adjust_content_length },
1197       { "Transfer-Encoding:", 18, server_transfer_coding },
1198 #ifdef FEATURE_ZLIB
1199       { "Content-Encoding:",  17, server_adjust_content_encoding },
1200 #endif /* def FEATURE_ZLIB */
1201       { NULL,                  0, NULL }
1202    };
1203
1204    if (strncmpic(csp->http->cmd, "HEAD", 4))
1205    {
1206       const struct parsers *v;
1207       struct list_entry *p;
1208
1209       for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1210       {
1211          for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1212          {
1213             /* Header crunch()ed in previous run? -> ignore */
1214             if (p->str == NULL) continue;
1215
1216             /* Does the current parser handle this header? */
1217             if (strncmpic(p->str, v->str, v->len) == 0)
1218             {
1219                err = v->parser(csp, (char **)&(p->str));
1220             }
1221          }
1222       }
1223    }
1224
1225 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1226    if ((JB_ERR_OK == err)
1227     && (csp->flags & CSP_FLAG_MODIFIED)
1228     && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1229     && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1230    {
1231       char header[50];
1232
1233       create_content_length_header(csp->content_length, header, sizeof(header));
1234       err = enlist(csp->headers, header);
1235       if (JB_ERR_OK == err)
1236       {
1237          log_error(LOG_LEVEL_HEADER,
1238             "Content modified with no Content-Length header set. "
1239             "Created: %s.", header);
1240          csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1241       }
1242    }
1243 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1244
1245 #ifdef FEATURE_COMPRESSION
1246    if ((JB_ERR_OK == err)
1247       && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1248    {
1249       err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1250       if (JB_ERR_OK == err)
1251       {
1252          log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1253       }
1254    }
1255 #endif
1256
1257    return err;
1258 }
1259
1260
1261 /*********************************************************************
1262  *
1263  * Function    :  header_tagger
1264  *
1265  * Description :  Executes all text substitutions from applying
1266  *                tag actions and saves the result as tag.
1267  *
1268  *                XXX: Shares enough code with filter_header() and
1269  *                pcrs_filter_response() to warrant some helper functions.
1270  *
1271  * Parameters  :
1272  *          1  :  csp = Current client state (buffers, headers, etc...)
1273  *          2  :  header = Header that is used as tagger input
1274  *
1275  * Returns     :  JB_ERR_OK on success and always succeeds
1276  *
1277  *********************************************************************/
1278 static jb_err header_tagger(struct client_state *csp, char *header)
1279 {
1280    int wanted_filter_type;
1281    int multi_action_index;
1282    int i;
1283    pcrs_job *job;
1284
1285    struct file_list *fl;
1286    struct re_filterfile_spec *b;
1287    struct list_entry *tag_name;
1288
1289    const size_t header_length = strlen(header);
1290
1291    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1292    {
1293       wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1294       multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1295    }
1296    else
1297    {
1298       wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1299       multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1300    }
1301
1302    if (list_is_empty(csp->action->multi[multi_action_index])
1303       || filters_available(csp) == FALSE)
1304    {
1305       /* Return early if no taggers apply or if none are available. */
1306       return JB_ERR_OK;
1307    }
1308
1309    for (i = 0; i < MAX_AF_FILES; i++)
1310    {
1311       fl = csp->rlist[i];
1312       if ((NULL == fl) || (NULL == fl->f))
1313       {
1314          /*
1315           * Either there are no filter files
1316           * left, or this filter file just
1317           * contains no valid filters.
1318           *
1319           * Continue to be sure we don't miss
1320           * valid filter files that are chained
1321           * after empty or invalid ones.
1322           */
1323          continue;
1324       }
1325
1326       /* For all filters, */
1327       for (b = fl->f; b; b = b->next)
1328       {
1329          if (b->type != wanted_filter_type)
1330          {
1331             /* skip the ones we don't care about, */
1332             continue;
1333          }
1334          /* leaving only taggers that could apply, of which we use the ones, */
1335          for (tag_name = csp->action->multi[multi_action_index]->first;
1336               NULL != tag_name; tag_name = tag_name->next)
1337          {
1338             /* that do apply, and */
1339             if (strcmp(b->name, tag_name->str) == 0)
1340             {
1341                char *modified_tag = NULL;
1342                char *tag = header;
1343                size_t size = header_length;
1344                pcrs_job *joblist = b->joblist;
1345
1346                if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1347
1348                if (NULL == joblist)
1349                {
1350                   log_error(LOG_LEVEL_RE_FILTER,
1351                      "Tagger %s has empty joblist. Nothing to do.", b->name);
1352                   continue;
1353                }
1354
1355                /* execute their pcrs_joblist on the header. */
1356                for (job = joblist; NULL != job; job = job->next)
1357                {
1358                   const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1359
1360                   if (0 < hits)
1361                   {
1362                      /* Success, continue with the modified version. */
1363                      if (tag != header)
1364                      {
1365                         freez(tag);
1366                      }
1367                      tag = modified_tag;
1368                   }
1369                   else
1370                   {
1371                      /* Tagger doesn't match */
1372                      if (0 > hits)
1373                      {
1374                         /* Regex failure, log it but continue anyway. */
1375                         assert(NULL != header);
1376                         log_error(LOG_LEVEL_ERROR,
1377                            "Problems with tagger \'%s\' and header \'%s\': %s",
1378                            b->name, *header, pcrs_strerror(hits));
1379                      }
1380                      freez(modified_tag);
1381                   }
1382                }
1383
1384                if (b->dynamic) pcrs_free_joblist(joblist);
1385
1386                /* If this tagger matched */
1387                if (tag != header)
1388                {
1389                   if (0 == size)
1390                   {
1391                      /*
1392                       * There is no technical limitation which makes
1393                       * it impossible to use empty tags, but I assume
1394                       * no one would do it intentionally.
1395                       */
1396                      freez(tag);
1397                      log_error(LOG_LEVEL_INFO,
1398                         "Tagger \'%s\' created an empty tag. Ignored.",
1399                         b->name);
1400                      continue;
1401                   }
1402
1403                   if (!list_contains_item(csp->tags, tag))
1404                   {
1405                      if (JB_ERR_OK != enlist(csp->tags, tag))
1406                      {
1407                         log_error(LOG_LEVEL_ERROR,
1408                            "Insufficient memory to add tag \'%s\', "
1409                            "based on tagger \'%s\' and header \'%s\'",
1410                            tag, b->name, *header);
1411                      }
1412                      else
1413                      {
1414                         char *action_message;
1415                         /*
1416                          * update the action bits right away, to make
1417                          * tagging based on tags set by earlier taggers
1418                          * of the same kind possible.
1419                          */
1420                         if (update_action_bits_for_tag(csp, tag))
1421                         {
1422                            action_message = "Action bits updated accordingly.";
1423                         }
1424                         else
1425                         {
1426                            action_message = "No action bits update necessary.";
1427                         }
1428
1429                         log_error(LOG_LEVEL_HEADER,
1430                            "Tagger \'%s\' added tag \'%s\'. %s",
1431                            b->name, tag, action_message);
1432                      }
1433                   }
1434                   else
1435                   {
1436                      /* XXX: Is this log-worthy? */
1437                      log_error(LOG_LEVEL_HEADER,
1438                         "Tagger \'%s\' didn't add tag \'%s\'. "
1439                         "Tag already present", b->name, tag);
1440                   }
1441                   freez(tag);
1442                } /* if the tagger matched */
1443             } /* if the tagger applies */
1444          } /* for every tagger that could apply */
1445       } /* for all filters */
1446    } /* for all filter files */
1447
1448    return JB_ERR_OK;
1449 }
1450
1451 /* here begins the family of parser functions that reformat header lines */
1452
1453 /*********************************************************************
1454  *
1455  * Function    :  filter_header
1456  *
1457  * Description :  Executes all text substitutions from all applying
1458  *                +(server|client)-header-filter actions on the header.
1459  *                Most of the code was copied from pcrs_filter_response,
1460  *                including the rather short variable names
1461  *
1462  * Parameters  :
1463  *          1  :  csp = Current client state (buffers, headers, etc...)
1464  *          2  :  header = On input, pointer to header to modify.
1465  *                On output, pointer to the modified header, or NULL
1466  *                to remove the header.  This function frees the
1467  *                original string if necessary.
1468  *
1469  * Returns     :  JB_ERR_OK on success and always succeeds
1470  *
1471  *********************************************************************/
1472 static jb_err filter_header(struct client_state *csp, char **header)
1473 {
1474    int hits=0;
1475    int matches;
1476    size_t size = strlen(*header);
1477
1478    char *newheader = NULL;
1479    pcrs_job *job;
1480
1481    struct file_list *fl;
1482    struct re_filterfile_spec *b;
1483    struct list_entry *filtername;
1484
1485    int i;
1486    int wanted_filter_type;
1487    int multi_action_index;
1488
1489    if (csp->flags & CSP_FLAG_NO_FILTERING)
1490    {
1491       return JB_ERR_OK;
1492    }
1493
1494    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1495    {
1496       wanted_filter_type = FT_SERVER_HEADER_FILTER;
1497       multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1498    }
1499    else
1500    {
1501       wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1502       multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1503    }
1504
1505    if (list_is_empty(csp->action->multi[multi_action_index])
1506       || filters_available(csp) == FALSE)
1507    {
1508       /* Return early if no filters apply or if none are available. */
1509       return JB_ERR_OK;
1510    }
1511
1512    for (i = 0; i < MAX_AF_FILES; i++)
1513    {
1514       fl = csp->rlist[i];
1515       if ((NULL == fl) || (NULL == fl->f))
1516       {
1517          /*
1518           * Either there are no filter files
1519           * left, or this filter file just
1520           * contains no valid filters.
1521           *
1522           * Continue to be sure we don't miss
1523           * valid filter files that are chained
1524           * after empty or invalid ones.
1525           */
1526          continue;
1527       }
1528       /*
1529        * For all applying +filter actions, look if a filter by that
1530        * name exists and if yes, execute its pcrs_joblist on the
1531        * buffer.
1532        */
1533       for (b = fl->f; b; b = b->next)
1534       {
1535          if (b->type != wanted_filter_type)
1536          {
1537             /* Skip other filter types */
1538             continue;
1539          }
1540
1541          for (filtername = csp->action->multi[multi_action_index]->first;
1542               filtername ; filtername = filtername->next)
1543          {
1544             if (strcmp(b->name, filtername->str) == 0)
1545             {
1546                int current_hits = 0;
1547                pcrs_job *joblist = b->joblist;
1548
1549                if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1550
1551                if (NULL == joblist)
1552                {
1553                   log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1554                   continue;
1555                }
1556
1557                log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1558                          *header, size, b->name);
1559
1560                /* Apply all jobs from the joblist */
1561                for (job = joblist; NULL != job; job = job->next)
1562                {
1563                   matches = pcrs_execute(job, *header, size, &newheader, &size);
1564                   if (0 < matches)
1565                   {
1566                      current_hits += matches;
1567                      log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1568                      freez(*header);
1569                      *header = newheader;
1570                   }
1571                   else if (0 == matches)
1572                   {
1573                      /* Filter doesn't change header */
1574                      freez(newheader);
1575                   }
1576                   else
1577                   {
1578                      /* RegEx failure */
1579                      log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1580                         *header, b->name, pcrs_strerror(matches));
1581                      if (newheader != NULL)
1582                      {
1583                         log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1584                         freez(newheader);
1585                      }
1586                   }
1587                }
1588
1589                if (b->dynamic) pcrs_free_joblist(joblist);
1590
1591                log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1592                hits += current_hits;
1593             }
1594          }
1595       }
1596    }
1597
1598    /*
1599     * Additionally checking for hits is important because if
1600     * the continue hack is triggered, server headers can
1601     * arrive empty to separate multiple heads from each other.
1602     */
1603    if ((0 == size) && hits)
1604    {
1605       log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1606       freez(*header);
1607    }
1608
1609    return JB_ERR_OK;
1610 }
1611
1612
1613 /*********************************************************************
1614  *
1615  * Function    :  server_connection
1616  *
1617  * Description :  Makes sure a proper "Connection:" header is
1618  *                set and signals connection_header_adder to
1619  *                do nothing.
1620  *
1621  * Parameters  :
1622  *          1  :  csp = Current client state (buffers, headers, etc...)
1623  *          2  :  header = On input, pointer to header to modify.
1624  *                On output, pointer to the modified header, or NULL
1625  *                to remove the header.  This function frees the
1626  *                original string if necessary.
1627  *
1628  * Returns     :  JB_ERR_OK on success.
1629  *
1630  *********************************************************************/
1631 static jb_err server_connection(struct client_state *csp, char **header)
1632 {
1633    if (!strcmpic(*header, "Connection: keep-alive")
1634 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1635     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1636 #endif
1637      )
1638    {
1639 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1640       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1641       {
1642          csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1643       }
1644
1645       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1646       {
1647          log_error(LOG_LEVEL_HEADER,
1648             "Keeping the server header '%s' around.", *header);
1649       }
1650       else
1651 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1652       {
1653          char *old_header = *header;
1654
1655          *header = strdup_or_die("Connection: close");
1656          log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1657          freez(old_header);
1658       }
1659    }
1660
1661    /* Signal server_connection_adder() to return early. */
1662    csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1663
1664    return JB_ERR_OK;
1665 }
1666
1667
1668 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1669 /*********************************************************************
1670  *
1671  * Function    :  server_keep_alive
1672  *
1673  * Description :  Stores the server's keep alive timeout.
1674  *
1675  * Parameters  :
1676  *          1  :  csp = Current client state (buffers, headers, etc...)
1677  *          2  :  header = On input, pointer to header to modify.
1678  *                On output, pointer to the modified header, or NULL
1679  *                to remove the header.  This function frees the
1680  *                original string if necessary.
1681  *
1682  * Returns     :  JB_ERR_OK.
1683  *
1684  *********************************************************************/
1685 static jb_err server_keep_alive(struct client_state *csp, char **header)
1686 {
1687    unsigned int keep_alive_timeout;
1688    const char *timeout_position = strstr(*header, "timeout=");
1689
1690    if ((NULL == timeout_position)
1691     || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1692    {
1693       log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1694    }
1695    else
1696    {
1697       if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1698       {
1699          log_error(LOG_LEVEL_HEADER,
1700             "Reducing keep-alive timeout from %u to %u.",
1701             csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1702          csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1703       }
1704       else
1705       {
1706          /* XXX: Is this log worthy? */
1707          log_error(LOG_LEVEL_HEADER,
1708             "Server keep-alive timeout is %u. Sticking with %u.",
1709             keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1710       }
1711       csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1712    }
1713
1714    return JB_ERR_OK;
1715 }
1716
1717
1718 /*********************************************************************
1719  *
1720  * Function    :  server_proxy_connection
1721  *
1722  * Description :  Figures out whether or not we should add a
1723  *                Proxy-Connection header.
1724  *
1725  * Parameters  :
1726  *          1  :  csp = Current client state (buffers, headers, etc...)
1727  *          2  :  header = On input, pointer to header to modify.
1728  *                On output, pointer to the modified header, or NULL
1729  *                to remove the header.  This function frees the
1730  *                original string if necessary.
1731  *
1732  * Returns     :  JB_ERR_OK.
1733  *
1734  *********************************************************************/
1735 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1736 {
1737    csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1738    return JB_ERR_OK;
1739 }
1740
1741
1742 /*********************************************************************
1743  *
1744  * Function    :  proxy_authentication
1745  *
1746  * Description :  Removes headers that are relevant for proxy
1747  *                authentication unless forwarding them has
1748  *                been explicitly requested.
1749  *
1750  * Parameters  :
1751  *          1  :  csp = Current client state (buffers, headers, etc...)
1752  *          2  :  header = On input, pointer to header to modify.
1753  *                On output, pointer to the modified header, or NULL
1754  *                to remove the header.  This function frees the
1755  *                original string if necessary.
1756  *
1757  * Returns     :  JB_ERR_OK.
1758  *
1759  *********************************************************************/
1760 static jb_err proxy_authentication(struct client_state *csp, char **header)
1761 {
1762    if ((csp->config->feature_flags &
1763       RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1764       log_error(LOG_LEVEL_HEADER,
1765          "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1766       freez(*header);
1767    }
1768    return JB_ERR_OK;
1769 }
1770
1771
1772 /*********************************************************************
1773  *
1774  * Function    :  client_keep_alive
1775  *
1776  * Description :  Stores the client's keep alive timeout.
1777  *
1778  * Parameters  :
1779  *          1  :  csp = Current client state (buffers, headers, etc...)
1780  *          2  :  header = On input, pointer to header to modify.
1781  *                On output, pointer to the modified header, or NULL
1782  *                to remove the header.  This function frees the
1783  *                original string if necessary.
1784  *
1785  * Returns     :  JB_ERR_OK.
1786  *
1787  *********************************************************************/
1788 static jb_err client_keep_alive(struct client_state *csp, char **header)
1789 {
1790    unsigned int keep_alive_timeout;
1791    const char *timeout_position = strstr(*header, ": ");
1792
1793    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1794    {
1795       log_error(LOG_LEVEL_HEADER,
1796          "keep-alive support is disabled. Crunching: %s.", *header);
1797       freez(*header);
1798       return JB_ERR_OK;
1799    }
1800
1801    if ((NULL == timeout_position)
1802     || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1803    {
1804       log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1805    }
1806    else
1807    {
1808       if (keep_alive_timeout < csp->config->keep_alive_timeout)
1809       {
1810          log_error(LOG_LEVEL_HEADER,
1811             "Reducing keep-alive timeout from %u to %u.",
1812             csp->config->keep_alive_timeout, keep_alive_timeout);
1813          csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1814       }
1815       else
1816       {
1817          /* XXX: Is this log worthy? */
1818          log_error(LOG_LEVEL_HEADER,
1819             "Client keep-alive timeout is %u. Sticking with %u.",
1820             keep_alive_timeout, csp->config->keep_alive_timeout);
1821       }
1822    }
1823
1824    return JB_ERR_OK;
1825 }
1826
1827
1828 /*********************************************************************
1829  *
1830  * Function    :  get_content_length
1831  *
1832  * Description :  Gets the content length specified in a
1833  *                Content-Length header.
1834  *
1835  * Parameters  :
1836  *          1  :  header_value = The Content-Length header value.
1837  *          2  :  length = Storage to return the value.
1838  *
1839  * Returns     :  JB_ERR_OK on success, or
1840  *                JB_ERR_PARSE if no value is recognized.
1841  *
1842  *********************************************************************/
1843 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1844 {
1845 #ifdef _WIN32
1846    assert(sizeof(unsigned long long) > 4);
1847    if (1 != sscanf(header_value, "%I64u", length))
1848 #else
1849    if (1 != sscanf(header_value, "%llu", length))
1850 #endif
1851    {
1852       return JB_ERR_PARSE;
1853    }
1854
1855    return JB_ERR_OK;
1856 }
1857
1858
1859 /*********************************************************************
1860  *
1861  * Function    :  client_save_content_length
1862  *
1863  * Description :  Save the Content-Length sent by the client.
1864  *
1865  * Parameters  :
1866  *          1  :  csp = Current client state (buffers, headers, etc...)
1867  *          2  :  header = On input, pointer to header to modify.
1868  *                On output, pointer to the modified header, or NULL
1869  *                to remove the header.  This function frees the
1870  *                original string if necessary.
1871  *
1872  * Returns     :  JB_ERR_OK on success, or
1873  *                JB_ERR_MEMORY on out-of-memory error.
1874  *
1875  *********************************************************************/
1876 static jb_err client_save_content_length(struct client_state *csp, char **header)
1877 {
1878    unsigned long long content_length = 0;
1879    const char *header_value;
1880
1881    assert(*(*header+14) == ':');
1882
1883    header_value = *header + 15;
1884    if (JB_ERR_OK != get_content_length(header_value, &content_length))
1885    {
1886       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1887       freez(*header);
1888    }
1889    else
1890    {
1891       csp->expected_client_content_length = content_length;
1892    }
1893
1894    return JB_ERR_OK;
1895 }
1896 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1897
1898
1899
1900 /*********************************************************************
1901  *
1902  * Function    :  client_connection
1903  *
1904  * Description :  Makes sure a proper "Connection:" header is
1905  *                set and signals connection_header_adder
1906  *                to do nothing.
1907  *
1908  * Parameters  :
1909  *          1  :  csp = Current client state (buffers, headers, etc...)
1910  *          2  :  header = On input, pointer to header to modify.
1911  *                On output, pointer to the modified header, or NULL
1912  *                to remove the header.  This function frees the
1913  *                original string if necessary.
1914  *
1915  * Returns     :  JB_ERR_OK on success.
1916  *
1917  *********************************************************************/
1918 static jb_err client_connection(struct client_state *csp, char **header)
1919 {
1920    static const char connection_close[] = "Connection: close";
1921
1922    if (!strcmpic(*header, connection_close))
1923    {
1924 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1925       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1926         && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1927       {
1928           if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1929           {
1930              log_error(LOG_LEVEL_HEADER,
1931                 "Removing \'%s\' to imply keep-alive.", *header);
1932              freez(*header);
1933              /*
1934               * While we imply keep-alive to the server,
1935               * we have to remember that the client didn't.
1936               */
1937              csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1938           }
1939           else
1940           {
1941              char *old_header = *header;
1942
1943              *header = strdup_or_die("Connection: keep-alive");
1944              log_error(LOG_LEVEL_HEADER,
1945                 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1946              freez(old_header);
1947           }
1948       }
1949       else
1950       {
1951          log_error(LOG_LEVEL_HEADER,
1952             "Keeping the client header '%s' around. "
1953             "The connection will not be kept alive.",
1954             *header);
1955          csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1956       }
1957    }
1958    else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1959         && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1960    {
1961       log_error(LOG_LEVEL_HEADER,
1962          "Keeping the client header '%s' around. "
1963          "The server connection will be kept alive if possible.",
1964          *header);
1965       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1966 #endif  /* def FEATURE_CONNECTION_KEEP_ALIVE */
1967    }
1968    else
1969    {
1970       char *old_header = *header;
1971
1972       *header = strdup_or_die(connection_close);
1973       log_error(LOG_LEVEL_HEADER,
1974          "Replaced: \'%s\' with \'%s\'", old_header, *header);
1975       freez(old_header);
1976    }
1977
1978    /* Signal client_connection_header_adder() to return early. */
1979    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1980
1981    return JB_ERR_OK;
1982 }
1983
1984
1985 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1986 /*********************************************************************
1987  *
1988  * Function    :  client_proxy_connection
1989  *
1990  * Description :  Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1991  *                appropriate and removes the Proxy-Connection
1992  *                header.
1993  *
1994  * Parameters  :
1995  *          1  :  csp = Current client state (buffers, headers, etc...)
1996  *          2  :  header = On input, pointer to header to modify.
1997  *                On output, pointer to the modified header, or NULL
1998  *                to remove the header.  This function frees the
1999  *                original string if necessary.
2000  *
2001  * Returns     :  JB_ERR_OK
2002  *
2003  *********************************************************************/
2004 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2005 {
2006    if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2007       && (csp->http->ssl == 0)
2008       && (NULL == strstr(*header, "close")))
2009    {
2010       log_error(LOG_LEVEL_HEADER,
2011          "The client connection can be kept alive due to: %s", *header);
2012       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2013    }
2014    crumble(csp, header);
2015
2016    return JB_ERR_OK;
2017 }
2018 #endif  /* def FEATURE_CONNECTION_KEEP_ALIVE */
2019
2020
2021 /*********************************************************************
2022  *
2023  * Function    :  client_transfer_encoding
2024  *
2025  * Description :  Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2026  *                the request body is "chunked"
2027  *
2028  *                XXX: Currently not called through sed() as we
2029  *                     need the flag earlier on. Should be fixed.
2030  *
2031  * Parameters  :
2032  *          1  :  csp = Current client state (buffers, headers, etc...)
2033  *          2  :  header = On input, pointer to header to modify.
2034  *                On output, pointer to the modified header, or NULL
2035  *                to remove the header.  This function frees the
2036  *                original string if necessary.
2037  *
2038  * Returns     :  JB_ERR_OK on success, or
2039  *
2040  *********************************************************************/
2041 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2042 {
2043    if (strstr(*header, "chunked"))
2044    {
2045       csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2046       log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2047    }
2048
2049    return JB_ERR_OK;
2050 }
2051
2052
2053 /*********************************************************************
2054  *
2055  * Function    :  crumble
2056  *
2057  * Description :  This is called if a header matches a pattern to "crunch"
2058  *
2059  * Parameters  :
2060  *          1  :  csp = Current client state (buffers, headers, etc...)
2061  *          2  :  header = On input, pointer to header to modify.
2062  *                On output, pointer to the modified header, or NULL
2063  *                to remove the header.  This function frees the
2064  *                original string if necessary.
2065  *
2066  * Returns     :  JB_ERR_OK on success, or
2067  *                JB_ERR_MEMORY on out-of-memory error.
2068  *
2069  *********************************************************************/
2070 static jb_err crumble(struct client_state *csp, char **header)
2071 {
2072    (void)csp;
2073    log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2074    freez(*header);
2075    return JB_ERR_OK;
2076 }
2077
2078
2079 /*********************************************************************
2080  *
2081  * Function    :  crunch_server_header
2082  *
2083  * Description :  Crunch server header if it matches a string supplied by the
2084  *                user. Called from `sed'.
2085  *
2086  * Parameters  :
2087  *          1  :  csp = Current client state (buffers, headers, etc...)
2088  *          2  :  header = On input, pointer to header to modify.
2089  *                On output, pointer to the modified header, or NULL
2090  *                to remove the header.  This function frees the
2091  *                original string if necessary.
2092  *
2093  * Returns     :  JB_ERR_OK on success and always succeeds
2094  *
2095  *********************************************************************/
2096 static jb_err crunch_server_header(struct client_state *csp, char **header)
2097 {
2098    const char *crunch_pattern;
2099
2100    /* Do we feel like crunching? */
2101    if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2102    {
2103       crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2104
2105       /* Is the current header the lucky one? */
2106       if (strstr(*header, crunch_pattern))
2107       {
2108          log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2109          freez(*header);
2110       }
2111    }
2112
2113    return JB_ERR_OK;
2114 }
2115
2116
2117 /*********************************************************************
2118  *
2119  * Function    :  server_content_type
2120  *
2121  * Description :  Set the content-type for filterable types (text/.*,
2122  *                .*xml.*, .*script.* and image/gif) unless filtering has been
2123  *                forbidden (CT_TABOO) while parsing earlier headers.
2124  *                NOTE: Since text/plain is commonly used by web servers
2125  *                      for files whose correct type is unknown, we don't
2126  *                      set CT_TEXT for it.
2127  *
2128  * Parameters  :
2129  *          1  :  csp = Current client state (buffers, headers, etc...)
2130  *          2  :  header = On input, pointer to header to modify.
2131  *                On output, pointer to the modified header, or NULL
2132  *                to remove the header.  This function frees the
2133  *                original string if necessary.
2134  *
2135  * Returns     :  JB_ERR_OK on success, or
2136  *                JB_ERR_MEMORY on out-of-memory error.
2137  *
2138  *********************************************************************/
2139 static jb_err server_content_type(struct client_state *csp, char **header)
2140 {
2141    /* Remove header if it isn't the first Content-Type header */
2142    if ((csp->content_type & CT_DECLARED))
2143    {
2144       if (content_filters_enabled(csp->action))
2145       {
2146          /*
2147           * Making sure the client interprets the content the same way
2148           * Privoxy did is only relevant if Privoxy modified it.
2149           *
2150           * Checking for this is "hard" as it's not yet known when
2151           * this function is called, thus go shopping and and just
2152           * check if Privoxy could filter it.
2153           *
2154           * The main thing is that we don't mess with the headers
2155           * unless the user signalled that it's acceptable.
2156           */
2157          log_error(LOG_LEVEL_HEADER,
2158             "Multiple Content-Type headers detected. "
2159             "Removing and ignoring: %s",
2160             *header);
2161          freez(*header);
2162       }
2163       return JB_ERR_OK;
2164    }
2165
2166    /*
2167     * Signal that the Content-Type has been set.
2168     */
2169    csp->content_type |= CT_DECLARED;
2170
2171    if (!(csp->content_type & CT_TABOO))
2172    {
2173       /*
2174        * XXX: The assumption that text/plain is a sign of
2175        * binary data seems to be somewhat unreasonable nowadays
2176        * and should be dropped after 3.0.8 is out.
2177        */
2178       if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2179         || strstr(*header, "xml")
2180         || strstr(*header, "script"))
2181       {
2182          csp->content_type |= CT_TEXT;
2183       }
2184       else if (strstr(*header, "image/gif"))
2185       {
2186          csp->content_type |= CT_GIF;
2187       }
2188    }
2189
2190    /*
2191     * Are we messing with the content type?
2192     */
2193    if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2194    {
2195       /*
2196        * Make sure the user doesn't accidentally
2197        * change the content type of binary documents.
2198        */
2199       if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2200       {
2201          freez(*header);
2202          *header = strdup_or_die("Content-Type: ");
2203          string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2204
2205          if (header == NULL)
2206          {
2207             log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2208             return JB_ERR_MEMORY;
2209          }
2210          log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2211       }
2212       else
2213       {
2214          log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2215             "It doesn't look like a content type that should be filtered. "
2216             "Enable force-text-mode if you know what you're doing.", *header);
2217       }
2218    }
2219
2220    return JB_ERR_OK;
2221 }
2222
2223
2224 /*********************************************************************
2225  *
2226  * Function    :  server_transfer_coding
2227  *
2228  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
2229  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2230  *                - Remove header if body was chunked but has been
2231  *                  de-chunked for filtering.
2232  *
2233  * Parameters  :
2234  *          1  :  csp = Current client state (buffers, headers, etc...)
2235  *          2  :  header = On input, pointer to header to modify.
2236  *                On output, pointer to the modified header, or NULL
2237  *                to remove the header.  This function frees the
2238  *                original string if necessary.
2239  *
2240  * Returns     :  JB_ERR_OK on success, or
2241  *                JB_ERR_MEMORY on out-of-memory error.
2242  *
2243  *********************************************************************/
2244 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2245 {
2246    /*
2247     * Turn off pcrs and gif filtering if body compressed
2248     */
2249    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2250    {
2251 #ifdef FEATURE_ZLIB
2252       /*
2253        * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2254        */
2255       log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2256          csp->http->cmd, *header);
2257 #endif /* def FEATURE_ZLIB */
2258       csp->content_type = CT_TABOO;
2259    }
2260
2261    /*
2262     * Raise flag if body chunked
2263     */
2264    if (strstr(*header, "chunked"))
2265    {
2266       csp->flags |= CSP_FLAG_CHUNKED;
2267
2268       /*
2269        * If the body was modified, it has been de-chunked first
2270        * and the header must be removed.
2271        *
2272        * FIXME: If there is more than one transfer encoding,
2273        * only the "chunked" part should be removed here.
2274        */
2275       if (csp->flags & CSP_FLAG_MODIFIED)
2276       {
2277          log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2278          freez(*header);
2279       }
2280    }
2281
2282    return JB_ERR_OK;
2283 }
2284
2285
2286 /*********************************************************************
2287  *
2288  * Function    :  server_content_encoding
2289  *
2290  * Description :  Used to check if the content is compressed, and if
2291  *                FEATURE_ZLIB is disabled, filtering is disabled as
2292  *                well.
2293  *
2294  *                If FEATURE_ZLIB is enabled and the compression type
2295  *                supported, the content is marked for decompression.
2296  *
2297  *                XXX: Doesn't properly deal with multiple or with
2298  *                     unsupported but unknown encodings.
2299  *                     Is case-sensitive but shouldn't be.
2300  *
2301  * Parameters  :
2302  *          1  :  csp = Current client state (buffers, headers, etc...)
2303  *          2  :  header = On input, pointer to header to modify.
2304  *                On output, pointer to the modified header, or NULL
2305  *                to remove the header.  This function frees the
2306  *                original string if necessary.
2307  *
2308  * Returns     :  JB_ERR_OK on success, or
2309  *                JB_ERR_MEMORY on out-of-memory error.
2310  *
2311  *********************************************************************/
2312 static jb_err server_content_encoding(struct client_state *csp, char **header)
2313 {
2314 #ifdef FEATURE_ZLIB
2315    if (strstr(*header, "sdch"))
2316    {
2317       /*
2318        * Shared Dictionary Compression over HTTP isn't supported,
2319        * filtering it anyway is pretty much guaranteed to mess up
2320        * the encoding.
2321        */
2322       csp->content_type |= CT_TABOO;
2323
2324       /*
2325        * Log a warning if the user expects the content to be filtered.
2326        */
2327       if ((csp->rlist != NULL) &&
2328          (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2329       {
2330          log_error(LOG_LEVEL_INFO,
2331             "SDCH-compressed content detected, content filtering disabled. "
2332             "Consider suppressing SDCH offers made by the client.");
2333       }
2334    }
2335    else if (strstr(*header, "gzip"))
2336    {
2337       /* Mark for gzip decompression */
2338       csp->content_type |= CT_GZIP;
2339    }
2340    else if (strstr(*header, "deflate"))
2341    {
2342       /* Mark for zlib decompression */
2343       csp->content_type |= CT_DEFLATE;
2344    }
2345    else if (strstr(*header, "compress"))
2346    {
2347       /*
2348        * We can't decompress this; therefore we can't filter
2349        * it either.
2350        */
2351       csp->content_type |= CT_TABOO;
2352    }
2353 #else /* !defined(FEATURE_ZLIB) */
2354    /*
2355     * XXX: Using a black list here isn't the right approach.
2356     *
2357     *      In case of SDCH, building with zlib support isn't
2358     *      going to help.
2359     */
2360    if (strstr(*header, "gzip") ||
2361        strstr(*header, "compress") ||
2362        strstr(*header, "deflate") ||
2363        strstr(*header, "sdch"))
2364    {
2365       /*
2366        * Body is compressed, turn off pcrs and gif filtering.
2367        */
2368       csp->content_type |= CT_TABOO;
2369
2370       /*
2371        * Log a warning if the user expects the content to be filtered.
2372        */
2373       if ((csp->rlist != NULL) &&
2374          (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2375       {
2376          log_error(LOG_LEVEL_INFO,
2377             "Compressed content detected, content filtering disabled. "
2378             "Consider recompiling Privoxy with zlib support or "
2379             "enable the prevent-compression action.");
2380       }
2381    }
2382 #endif /* defined(FEATURE_ZLIB) */
2383
2384    return JB_ERR_OK;
2385
2386 }
2387
2388
2389 #ifdef FEATURE_ZLIB
2390 /*********************************************************************
2391  *
2392  * Function    :  server_adjust_content_encoding
2393  *
2394  * Description :  Remove the Content-Encoding header if the
2395  *                decompression was successful and the content
2396  *                has been modifed.
2397  *
2398  * Parameters  :
2399  *          1  :  csp = Current client state (buffers, headers, etc...)
2400  *          2  :  header = On input, pointer to header to modify.
2401  *                On output, pointer to the modified header, or NULL
2402  *                to remove the header.  This function frees the
2403  *                original string if necessary.
2404  *
2405  * Returns     :  JB_ERR_OK on success, or
2406  *                JB_ERR_MEMORY on out-of-memory error.
2407  *
2408  *********************************************************************/
2409 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2410 {
2411    if ((csp->flags & CSP_FLAG_MODIFIED)
2412     && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2413    {
2414       /*
2415        * We successfully decompressed the content,
2416        * and have to clean the header now, so the
2417        * client no longer expects compressed data.
2418        *
2419        * XXX: There is a difference between cleaning
2420        * and removing it completely.
2421        */
2422       log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2423       freez(*header);
2424    }
2425
2426    return JB_ERR_OK;
2427
2428 }
2429 #endif /* defined(FEATURE_ZLIB) */
2430
2431
2432 /*********************************************************************
2433  *
2434  * Function    :  server_adjust_content_length
2435  *
2436  * Description :  Adjust Content-Length header if we modified
2437  *                the body.
2438  *
2439  * Parameters  :
2440  *          1  :  csp = Current client state (buffers, headers, etc...)
2441  *          2  :  header = On input, pointer to header to modify.
2442  *                On output, pointer to the modified header, or NULL
2443  *                to remove the header.  This function frees the
2444  *                original string if necessary.
2445  *
2446  * Returns     :  JB_ERR_OK on success, or
2447  *                JB_ERR_MEMORY on out-of-memory error.
2448  *
2449  *********************************************************************/
2450 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2451 {
2452    /* Regenerate header if the content was modified. */
2453    if (csp->flags & CSP_FLAG_MODIFIED)
2454    {
2455       const size_t header_length = 50;
2456       freez(*header);
2457       *header = malloc(header_length);
2458       if (*header == NULL)
2459       {
2460          return JB_ERR_MEMORY;
2461       }
2462       create_content_length_header(csp->content_length, *header, header_length);
2463       log_error(LOG_LEVEL_HEADER,
2464          "Adjusted Content-Length to %llu", csp->content_length);
2465    }
2466
2467    return JB_ERR_OK;
2468 }
2469
2470
2471 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2472 /*********************************************************************
2473  *
2474  * Function    :  server_save_content_length
2475  *
2476  * Description :  Save the Content-Length sent by the server.
2477  *
2478  * Parameters  :
2479  *          1  :  csp = Current client state (buffers, headers, etc...)
2480  *          2  :  header = On input, pointer to header to modify.
2481  *                On output, pointer to the modified header, or NULL
2482  *                to remove the header.  This function frees the
2483  *                original string if necessary.
2484  *
2485  * Returns     :  JB_ERR_OK on success, or
2486  *                JB_ERR_MEMORY on out-of-memory error.
2487  *
2488  *********************************************************************/
2489 static jb_err server_save_content_length(struct client_state *csp, char **header)
2490 {
2491    unsigned long long content_length = 0;
2492    const char *header_value;
2493
2494    assert(*(*header+14) == ':');
2495
2496    header_value = *header + 15;
2497    if (JB_ERR_OK != get_content_length(header_value, &content_length))
2498    {
2499       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2500       freez(*header);
2501    }
2502    else
2503    {
2504       csp->expected_content_length = content_length;
2505       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2506       csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2507    }
2508
2509    return JB_ERR_OK;
2510 }
2511 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2512
2513
2514 /*********************************************************************
2515  *
2516  * Function    :  server_content_md5
2517  *
2518  * Description :  Crumble any Content-MD5 headers if the document was
2519  *                modified. FIXME: Should we re-compute instead?
2520  *
2521  * Parameters  :
2522  *          1  :  csp = Current client state (buffers, headers, etc...)
2523  *          2  :  header = On input, pointer to header to modify.
2524  *                On output, pointer to the modified header, or NULL
2525  *                to remove the header.  This function frees the
2526  *                original string if necessary.
2527  *
2528  * Returns     :  JB_ERR_OK on success, or
2529  *                JB_ERR_MEMORY on out-of-memory error.
2530  *
2531  *********************************************************************/
2532 static jb_err server_content_md5(struct client_state *csp, char **header)
2533 {
2534    if (csp->flags & CSP_FLAG_MODIFIED)
2535    {
2536       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2537       freez(*header);
2538    }
2539
2540    return JB_ERR_OK;
2541 }
2542
2543
2544 /*********************************************************************
2545  *
2546  * Function    :  server_content_disposition
2547  *
2548  * Description :  If enabled, blocks or modifies the "Content-Disposition" header.
2549  *                Called from `sed'.
2550  *
2551  * Parameters  :
2552  *          1  :  csp = Current client state (buffers, headers, etc...)
2553  *          2  :  header = On input, pointer to header to modify.
2554  *                On output, pointer to the modified header, or NULL
2555  *                to remove the header.  This function frees the
2556  *                original string if necessary.
2557  *
2558  * Returns     :  JB_ERR_OK on success, or
2559  *                JB_ERR_MEMORY on out-of-memory error.
2560  *
2561  *********************************************************************/
2562 static jb_err server_content_disposition(struct client_state *csp, char **header)
2563 {
2564    const char *newval;
2565
2566    /*
2567     * Are we messing with the Content-Disposition header?
2568     */
2569    if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2570    {
2571       /* Me tinks not */
2572       return JB_ERR_OK;
2573    }
2574
2575    newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2576
2577    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2578    {
2579       /*
2580        * Blocking content-disposition header
2581        */
2582       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2583       freez(*header);
2584       return JB_ERR_OK;
2585    }
2586    else
2587    {
2588       /*
2589        * Replacing Content-Disposition header
2590        */
2591       freez(*header);
2592       *header = strdup("Content-Disposition: ");
2593       string_append(header, newval);
2594
2595       if (*header != NULL)
2596       {
2597          log_error(LOG_LEVEL_HEADER,
2598             "Content-Disposition header crunched and replaced with: %s", *header);
2599       }
2600    }
2601    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2602 }
2603
2604
2605 /*********************************************************************
2606  *
2607  * Function    :  server_last_modified
2608  *
2609  * Description :  Changes Last-Modified header to the actual date
2610  *                to help hide-if-modified-since.
2611  *                Called from `sed'.
2612  *
2613  * Parameters  :
2614  *          1  :  csp = Current client state (buffers, headers, etc...)
2615  *          2  :  header = On input, pointer to header to modify.
2616  *                On output, pointer to the modified header, or NULL
2617  *                to remove the header.  This function frees the
2618  *                original string if necessary.
2619  *
2620  * Returns     :  JB_ERR_OK on success, or
2621  *                JB_ERR_MEMORY on out-of-memory error.
2622  *
2623  *********************************************************************/
2624 static jb_err server_last_modified(struct client_state *csp, char **header)
2625 {
2626    const char *newval;
2627    time_t last_modified;
2628    char newheader[50];
2629
2630    /*
2631     * Are we messing with the Last-Modified header?
2632     */
2633    if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2634    {
2635       /*Nope*/
2636       return JB_ERR_OK;
2637    }
2638
2639    newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2640
2641    if (0 == strcmpic(newval, "block"))
2642    {
2643       /*
2644        * Blocking Last-Modified header. Useless but why not.
2645        */
2646       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2647       freez(*header);
2648       return JB_ERR_OK;
2649    }
2650    else if (0 == strcmpic(newval, "reset-to-request-time"))
2651    {
2652       /*
2653        * Setting Last-Modified Header to now.
2654        */
2655       char buf[30];
2656       get_http_time(0, buf, sizeof(buf));
2657       freez(*header);
2658       *header = strdup("Last-Modified: ");
2659       string_append(header, buf);
2660
2661       if (*header == NULL)
2662       {
2663          log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2664       }
2665       else
2666       {
2667          log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2668       }
2669    }
2670    else if (0 == strcmpic(newval, "randomize"))
2671    {
2672       const char *header_time = *header + sizeof("Last-Modified:");
2673
2674       log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2675
2676       if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2677       {
2678          log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2679          freez(*header);
2680       }
2681       else
2682       {
2683          time_t now;
2684          struct tm *timeptr = NULL;
2685          long int rtime;
2686 #ifdef HAVE_GMTIME_R
2687          struct tm gmt;
2688 #endif
2689          now = time(NULL);
2690          rtime = (long int)difftime(now, last_modified);
2691          if (rtime)
2692          {
2693             long int days, hours, minutes, seconds;
2694             const int negative_delta = (rtime < 0);
2695
2696             if (negative_delta)
2697             {
2698                rtime *= -1;
2699                log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2700             }
2701             rtime = pick_from_range(rtime);
2702             if (negative_delta)
2703             {
2704                rtime *= -1;
2705             }
2706             last_modified += rtime;
2707 #ifdef HAVE_GMTIME_R
2708             timeptr = gmtime_r(&last_modified, &gmt);
2709 #elif defined(MUTEX_LOCKS_AVAILABLE)
2710             privoxy_mutex_lock(&gmtime_mutex);
2711             timeptr = gmtime(&last_modified);
2712             privoxy_mutex_unlock(&gmtime_mutex);
2713 #else
2714             timeptr = gmtime(&last_modified);
2715 #endif
2716             if ((NULL == timeptr) || !strftime(newheader,
2717                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2718             {
2719                log_error(LOG_LEVEL_ERROR,
2720                   "Randomizing '%s' failed. Crunching the header without replacement.",
2721                   *header);
2722                freez(*header);
2723                return JB_ERR_OK;
2724             }
2725
2726             freez(*header);
2727             *header = strdup("Last-Modified: ");
2728             string_append(header, newheader);
2729
2730             if (*header == NULL)
2731             {
2732                log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2733                return JB_ERR_MEMORY;
2734             }
2735
2736             days    = rtime / (3600 * 24);
2737             hours   = rtime / 3600 % 24;
2738             minutes = rtime / 60 % 60;
2739             seconds = rtime % 60;
2740
2741             log_error(LOG_LEVEL_HEADER,
2742                "Randomized:  %s (added %d da%s %d hou%s %d minut%s %d second%s",
2743                *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2744                minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2745          }
2746          else
2747          {
2748             log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2749          }
2750       }
2751    }
2752
2753    return JB_ERR_OK;
2754 }
2755
2756
2757 /*********************************************************************
2758  *
2759  * Function    :  client_accept_encoding
2760  *
2761  * Description :  Rewrite the client's Accept-Encoding header so that
2762  *                if doesn't allow compression, if the action applies.
2763  *                Note: For HTTP/1.0 the absence of the header is enough.
2764  *
2765  * Parameters  :
2766  *          1  :  csp = Current client state (buffers, headers, etc...)
2767  *          2  :  header = On input, pointer to header to modify.
2768  *                On output, pointer to the modified header, or NULL
2769  *                to remove the header.  This function frees the
2770  *                original string if necessary.
2771  *
2772  * Returns     :  JB_ERR_OK on success, or
2773  *                JB_ERR_MEMORY on out-of-memory error.
2774  *
2775  *********************************************************************/
2776 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2777 {
2778 #ifdef FEATURE_COMPRESSION
2779    if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2780       && strstr(*header, "deflate"))
2781    {
2782       csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2783    }
2784 #endif
2785    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2786    {
2787       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2788       freez(*header);
2789    }
2790
2791    return JB_ERR_OK;
2792 }
2793
2794
2795 /*********************************************************************
2796  *
2797  * Function    :  client_te
2798  *
2799  * Description :  Rewrite the client's TE header so that
2800  *                if doesn't allow compression, if the action applies.
2801  *
2802  * Parameters  :
2803  *          1  :  csp = Current client state (buffers, headers, etc...)
2804  *          2  :  header = On input, pointer to header to modify.
2805  *                On output, pointer to the modified header, or NULL
2806  *                to remove the header.  This function frees the
2807  *                original string if necessary.
2808  *
2809  * Returns     :  JB_ERR_OK on success, or
2810  *                JB_ERR_MEMORY on out-of-memory error.
2811  *
2812  *********************************************************************/
2813 static jb_err client_te(struct client_state *csp, char **header)
2814 {
2815    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2816    {
2817       freez(*header);
2818       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2819    }
2820
2821    return JB_ERR_OK;
2822 }
2823
2824
2825 /*********************************************************************
2826  *
2827  * Function    :  client_referrer
2828  *
2829  * Description :  Handle the "referer" config setting properly.
2830  *                Called from `sed'.
2831  *
2832  * Parameters  :
2833  *          1  :  csp = Current client state (buffers, headers, etc...)
2834  *          2  :  header = On input, pointer to header to modify.
2835  *                On output, pointer to the modified header, or NULL
2836  *                to remove the header.  This function frees the
2837  *                original string if necessary.
2838  *
2839  * Returns     :  JB_ERR_OK on success, or
2840  *                JB_ERR_MEMORY on out-of-memory error.
2841  *
2842  *********************************************************************/
2843 static jb_err client_referrer(struct client_state *csp, char **header)
2844 {
2845    const char *parameter;
2846    /* booleans for parameters we have to check multiple times */
2847    int parameter_conditional_block;
2848    int parameter_conditional_forge;
2849
2850 #ifdef FEATURE_FORCE_LOAD
2851    /*
2852     * Since the referrer can include the prefix even
2853     * if the request itself is non-forced, we must
2854     * clean it unconditionally.
2855     *
2856     * XXX: strclean is too broad
2857     */
2858    strclean(*header, FORCE_PREFIX);
2859 #endif /* def FEATURE_FORCE_LOAD */
2860
2861    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2862    {
2863       /* Nothing left to do */
2864       return JB_ERR_OK;
2865    }
2866
2867    parameter = csp->action->string[ACTION_STRING_REFERER];
2868    assert(parameter != NULL);
2869    parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2870    parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2871
2872    if (!parameter_conditional_block && !parameter_conditional_forge)
2873    {
2874       /*
2875        * As conditional-block and conditional-forge are the only
2876        * parameters that rely on the original referrer, we can
2877        * remove it now for all the others.
2878        */
2879       freez(*header);
2880    }
2881
2882    if (0 == strcmpic(parameter, "block"))
2883    {
2884       log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2885       return JB_ERR_OK;
2886    }
2887    else if (parameter_conditional_block || parameter_conditional_forge)
2888    {
2889       return handle_conditional_hide_referrer_parameter(header,
2890          csp->http->hostport, parameter_conditional_block);
2891    }
2892    else if (0 == strcmpic(parameter, "forge"))
2893    {
2894       return create_forged_referrer(header, csp->http->hostport);
2895    }
2896    else
2897    {
2898       /* interpret parameter as user-supplied referer to fake */
2899       return create_fake_referrer(header, parameter);
2900    }
2901 }
2902
2903
2904 /*********************************************************************
2905  *
2906  * Function    :  client_accept_language
2907  *
2908  * Description :  Handle the "Accept-Language" config setting properly.
2909  *                Called from `sed'.
2910  *
2911  * Parameters  :
2912  *          1  :  csp = Current client state (buffers, headers, etc...)
2913  *          2  :  header = On input, pointer to header to modify.
2914  *                On output, pointer to the modified header, or NULL
2915  *                to remove the header.  This function frees the
2916  *                original string if necessary.
2917  *
2918  * Returns     :  JB_ERR_OK on success, or
2919  *                JB_ERR_MEMORY on out-of-memory error.
2920  *
2921  *********************************************************************/
2922 static jb_err client_accept_language(struct client_state *csp, char **header)
2923 {
2924    const char *newval;
2925
2926    /*
2927     * Are we messing with the Accept-Language?
2928     */
2929    if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2930    {
2931       /*I don't think so*/
2932       return JB_ERR_OK;
2933    }
2934
2935    newval = csp->action->string[ACTION_STRING_LANGUAGE];
2936
2937    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2938    {
2939       /*
2940        * Blocking Accept-Language header
2941        */
2942       log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2943       freez(*header);
2944       return JB_ERR_OK;
2945    }
2946    else
2947    {
2948       /*
2949        * Replacing Accept-Language header
2950        */
2951       freez(*header);
2952       *header = strdup("Accept-Language: ");
2953       string_append(header, newval);
2954
2955       if (*header == NULL)
2956       {
2957          log_error(LOG_LEVEL_ERROR,
2958             "Insufficient memory. Accept-Language header crunched without replacement.");
2959       }
2960       else
2961       {
2962          log_error(LOG_LEVEL_HEADER,
2963             "Accept-Language header crunched and replaced with: %s", *header);
2964       }
2965    }
2966    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2967 }
2968
2969
2970 /*********************************************************************
2971  *
2972  * Function    :  crunch_client_header
2973  *
2974  * Description :  Crunch client header if it matches a string supplied by the
2975  *                user. Called from `sed'.
2976  *
2977  * Parameters  :
2978  *          1  :  csp = Current client state (buffers, headers, etc...)
2979  *          2  :  header = On input, pointer to header to modify.
2980  *                On output, pointer to the modified header, or NULL
2981  *                to remove the header.  This function frees the
2982  *                original string if necessary.
2983  *
2984  * Returns     :  JB_ERR_OK on success and always succeeds
2985  *
2986  *********************************************************************/
2987 static jb_err crunch_client_header(struct client_state *csp, char **header)
2988 {
2989    const char *crunch_pattern;
2990
2991    /* Do we feel like crunching? */
2992    if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2993    {
2994       crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2995
2996       /* Is the current header the lucky one? */
2997       if (strstr(*header, crunch_pattern))
2998       {
2999          log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3000          freez(*header);
3001       }
3002    }
3003    return JB_ERR_OK;
3004 }
3005
3006
3007 /*********************************************************************
3008  *
3009  * Function    :  client_uagent
3010  *
3011  * Description :  Handle the "user-agent" config setting properly
3012  *                and remember its original value to enable browser
3013  *                bug workarounds. Called from `sed'.
3014  *
3015  * Parameters  :
3016  *          1  :  csp = Current client state (buffers, headers, etc...)
3017  *          2  :  header = On input, pointer to header to modify.
3018  *                On output, pointer to the modified header, or NULL
3019  *                to remove the header.  This function frees the
3020  *                original string if necessary.
3021  *
3022  * Returns     :  JB_ERR_OK on success, or
3023  *                JB_ERR_MEMORY on out-of-memory error.
3024  *
3025  *********************************************************************/
3026 static jb_err client_uagent(struct client_state *csp, char **header)
3027 {
3028    const char *newval;
3029
3030    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3031    {
3032       return JB_ERR_OK;
3033    }
3034
3035    newval = csp->action->string[ACTION_STRING_USER_AGENT];
3036    if (newval == NULL)
3037    {
3038       return JB_ERR_OK;
3039    }
3040
3041    freez(*header);
3042    *header = strdup("User-Agent: ");
3043    string_append(header, newval);
3044
3045    log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3046
3047    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3048 }
3049
3050
3051 /*********************************************************************
3052  *
3053  * Function    :  client_ua
3054  *
3055  * Description :  Handle "ua-" headers properly.  Called from `sed'.
3056  *
3057  * Parameters  :
3058  *          1  :  csp = Current client state (buffers, headers, etc...)
3059  *          2  :  header = On input, pointer to header to modify.
3060  *                On output, pointer to the modified header, or NULL
3061  *                to remove the header.  This function frees the
3062  *                original string if necessary.
3063  *
3064  * Returns     :  JB_ERR_OK on success, or
3065  *                JB_ERR_MEMORY on out-of-memory error.
3066  *
3067  *********************************************************************/
3068 static jb_err client_ua(struct client_state *csp, char **header)
3069 {
3070    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3071    {
3072       log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3073       freez(*header);
3074    }
3075
3076    return JB_ERR_OK;
3077 }
3078
3079
3080 /*********************************************************************
3081  *
3082  * Function    :  client_from
3083  *
3084  * Description :  Handle the "from" config setting properly.
3085  *                Called from `sed'.
3086  *
3087  * Parameters  :
3088  *          1  :  csp = Current client state (buffers, headers, etc...)
3089  *          2  :  header = On input, pointer to header to modify.
3090  *                On output, pointer to the modified header, or NULL
3091  *                to remove the header.  This function frees the
3092  *                original string if necessary.
3093  *
3094  * Returns     :  JB_ERR_OK on success, or
3095  *                JB_ERR_MEMORY on out-of-memory error.
3096  *
3097  *********************************************************************/
3098 static jb_err client_from(struct client_state *csp, char **header)
3099 {
3100    const char *newval;
3101
3102    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3103    {
3104       return JB_ERR_OK;
3105    }
3106
3107    freez(*header);
3108
3109    newval = csp->action->string[ACTION_STRING_FROM];
3110
3111    /*
3112     * Are we blocking the e-mail address?
3113     */
3114    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3115    {
3116       log_error(LOG_LEVEL_HEADER, "crunched From!");
3117       return JB_ERR_OK;
3118    }
3119
3120    log_error(LOG_LEVEL_HEADER, " modified");
3121
3122    *header = strdup("From: ");
3123    string_append(header, newval);
3124
3125    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3126 }
3127
3128
3129 /*********************************************************************
3130  *
3131  * Function    :  client_send_cookie
3132  *
3133  * Description :  Crunches the "cookie" header if necessary.
3134  *                Called from `sed'.
3135  *
3136  *                XXX: Stupid name, doesn't send squat.
3137  *
3138  * Parameters  :
3139  *          1  :  csp = Current client state (buffers, headers, etc...)
3140  *          2  :  header = On input, pointer to header to modify.
3141  *                On output, pointer to the modified header, or NULL
3142  *                to remove the header.  This function frees the
3143  *                original string if necessary.
3144  *
3145  * Returns     :  JB_ERR_OK on success, or
3146  *                JB_ERR_MEMORY on out-of-memory error.
3147  *
3148  *********************************************************************/
3149 static jb_err client_send_cookie(struct client_state *csp, char **header)
3150 {
3151    if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3152    {
3153       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3154       freez(*header);
3155    }
3156
3157    return JB_ERR_OK;
3158 }
3159
3160
3161 /*********************************************************************
3162  *
3163  * Function    :  client_x_forwarded
3164  *
3165  * Description :  Handle the "x-forwarded-for" config setting properly,
3166  *                also used in the add_client_headers list.  Called from `sed'.
3167  *
3168  * Parameters  :
3169  *          1  :  csp = Current client state (buffers, headers, etc...)
3170  *          2  :  header = On input, pointer to header to modify.
3171  *                On output, pointer to the modified header, or NULL
3172  *                to remove the header.  This function frees the
3173  *                original string if necessary.
3174  *
3175  * Returns     :  JB_ERR_OK on success, or
3176  *                JB_ERR_MEMORY on out-of-memory error.
3177  *
3178  *********************************************************************/
3179 jb_err client_x_forwarded(struct client_state *csp, char **header)
3180 {
3181    if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3182    {
3183       const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3184
3185       if (0 == strcmpic(parameter, "block"))
3186       {
3187          freez(*header);
3188          log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3189       }
3190       else if (0 == strcmpic(parameter, "add"))
3191       {
3192          string_append(header, ", ");
3193          string_append(header, csp->ip_addr_str);
3194
3195          if (*header == NULL)
3196          {
3197             return JB_ERR_MEMORY;
3198          }
3199          log_error(LOG_LEVEL_HEADER,
3200             "Appended client IP address to %s", *header);
3201          csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3202       }
3203       else
3204       {
3205          log_error(LOG_LEVEL_FATAL,
3206             "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3207       }
3208    }
3209
3210    return JB_ERR_OK;
3211 }
3212
3213
3214 /*********************************************************************
3215  *
3216  * Function    :  client_max_forwards
3217  *
3218  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
3219  *                from the value of the Max-Forwards header field.
3220  *
3221  * Parameters  :
3222  *          1  :  csp = Current client state (buffers, headers, etc...)
3223  *          2  :  header = On input, pointer to header to modify.
3224  *                On output, pointer to the modified header, or NULL
3225  *                to remove the header.  This function frees the
3226  *                original string if necessary.
3227  *
3228  * Returns     :  JB_ERR_OK on success, or
3229  *                JB_ERR_MEMORY on out-of-memory error.
3230  *
3231  *********************************************************************/
3232 static jb_err client_max_forwards(struct client_state *csp, char **header)
3233 {
3234    int max_forwards;
3235
3236    if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3237        (0 == strcmpic(csp->http->gpc, "options")))
3238    {
3239       assert(*(*header+12) == ':');
3240       if (1 == sscanf(*header+12, ": %d", &max_forwards))
3241       {
3242          if (max_forwards > 0)
3243          {
3244             snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3245             log_error(LOG_LEVEL_HEADER,
3246                "Max-Forwards value for %s request reduced to %d.",
3247                csp->http->gpc, max_forwards);
3248          }
3249          else if (max_forwards < 0)
3250          {
3251             log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3252             freez(*header);
3253          }
3254       }
3255       else
3256       {
3257          log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3258          freez(*header);
3259       }
3260    }
3261
3262    return JB_ERR_OK;
3263 }
3264
3265
3266 /*********************************************************************
3267  *
3268  * Function    :  client_host
3269  *
3270  * Description :  If the request URI did not contain host and
3271  *                port information, parse and evaluate the Host
3272  *                header field.
3273  *
3274  * Parameters  :
3275  *          1  :  csp = Current client state (buffers, headers, etc...)
3276  *          2  :  header = On input, pointer to header to modify.
3277  *                On output, pointer to the modified header, or NULL
3278  *                to remove the header.  This function frees the
3279  *                original string if necessary.
3280  *
3281  * Returns     :  JB_ERR_OK on success, or
3282  *                JB_ERR_MEMORY on out-of-memory error.
3283  *
3284  *********************************************************************/
3285 static jb_err client_host(struct client_state *csp, char **header)
3286 {
3287    char *p, *q;
3288
3289    if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3290        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3291    {
3292
3293       p = strdup_or_die((*header)+6);
3294       chomp(p);
3295       q = strdup_or_die(p);
3296
3297       freez(csp->http->hostport);
3298       csp->http->hostport = p;
3299       freez(csp->http->host);
3300       csp->http->host = q;
3301       q = strchr(csp->http->host, ':');
3302       if (q != NULL)
3303       {
3304          /* Terminate hostname and evaluate port string */
3305          *q++ = '\0';
3306          csp->http->port = atoi(q);
3307       }
3308       else
3309       {
3310          csp->http->port = csp->http->ssl ? 443 : 80;
3311       }
3312
3313       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3314                 csp->http->hostport, csp->http->host, csp->http->port);
3315    }
3316
3317    /* Signal client_host_adder() to return right away */
3318    csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3319
3320    return JB_ERR_OK;
3321 }
3322
3323
3324 /*********************************************************************
3325  *
3326  * Function    :  client_if_modified_since
3327  *
3328  * Description :  Remove or modify the If-Modified-Since header.
3329  *
3330  * Parameters  :
3331  *          1  :  csp = Current client state (buffers, headers, etc...)
3332  *          2  :  header = On input, pointer to header to modify.
3333  *                On output, pointer to the modified header, or NULL
3334  *                to remove the header.  This function frees the
3335  *                original string if necessary.
3336  *
3337  * Returns     :  JB_ERR_OK on success, or
3338  *                JB_ERR_MEMORY on out-of-memory error.
3339  *
3340  *********************************************************************/
3341 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3342 {
3343    char newheader[50];
3344 #ifdef HAVE_GMTIME_R
3345    struct tm gmt;
3346 #endif
3347    struct tm *timeptr = NULL;
3348    time_t tm = 0;
3349    const char *newval;
3350    char * endptr;
3351
3352    if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3353    {
3354       /*
3355        * The client got an error message because of a temporary problem,
3356        * the problem is gone and the client now tries to revalidate our
3357        * error message on the real server. The revalidation would always
3358        * end with the transmission of the whole document and there is
3359        * no need to expose the bogus If-Modified-Since header.
3360        */
3361       log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3362       freez(*header);
3363    }
3364    else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3365    {
3366       newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3367
3368       if ((0 == strcmpic(newval, "block")))
3369       {
3370          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3371          freez(*header);
3372       }
3373       else /* add random value */
3374       {
3375          const char *header_time = *header + sizeof("If-Modified-Since:");
3376
3377          if (JB_ERR_OK != parse_header_time(header_time, &tm))
3378          {
3379             log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3380             freez(*header);
3381          }
3382          else
3383          {
3384             long int hours, minutes, seconds;
3385             long int rtime = strtol(newval, &endptr, 0);
3386             const int negative_range = (rtime < 0);
3387
3388             if (rtime)
3389             {
3390                log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3391                   *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3392                if (negative_range)
3393                {
3394                   rtime *= -1;
3395                }
3396                rtime *= 60;
3397                rtime = pick_from_range(rtime);
3398             }
3399             else
3400             {
3401                log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3402                   *header);
3403             }
3404             tm += rtime * (negative_range ? -1 : 1);
3405 #ifdef HAVE_GMTIME_R
3406             timeptr = gmtime_r(&tm, &gmt);
3407 #elif defined(MUTEX_LOCKS_AVAILABLE)
3408             privoxy_mutex_lock(&gmtime_mutex);
3409             timeptr = gmtime(&tm);
3410             privoxy_mutex_unlock(&gmtime_mutex);
3411 #else
3412             timeptr = gmtime(&tm);
3413 #endif
3414             if ((NULL == timeptr) || !strftime(newheader,
3415                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3416             {
3417                log_error(LOG_LEVEL_ERROR,
3418                   "Randomizing '%s' failed. Crunching the header without replacement.",
3419                   *header);
3420                freez(*header);
3421                return JB_ERR_OK;
3422             }
3423
3424             freez(*header);
3425             *header = strdup("If-Modified-Since: ");
3426             string_append(header, newheader);
3427
3428             if (*header == NULL)
3429             {
3430                log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3431                return JB_ERR_MEMORY;
3432             }
3433
3434             hours   = rtime / 3600;
3435             minutes = rtime / 60 % 60;
3436             seconds = rtime % 60;
3437
3438             log_error(LOG_LEVEL_HEADER,
3439                "Randomized:  %s (%s %d hou%s %d minut%s %d second%s",
3440                *header, (negative_range) ? "subtracted" : "added", hours,
3441                (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3442                seconds, (seconds == 1) ? ")" : "s)");
3443          }
3444       }
3445    }
3446
3447    return JB_ERR_OK;
3448 }
3449
3450
3451 /*********************************************************************
3452  *
3453  * Function    :  client_if_none_match
3454  *
3455  * Description :  Remove the If-None-Match header.
3456  *
3457  * Parameters  :
3458  *          1  :  csp = Current client state (buffers, headers, etc...)
3459  *          2  :  header = On input, pointer to header to modify.
3460  *                On output, pointer to the modified header, or NULL
3461  *                to remove the header.  This function frees the
3462  *                original string if necessary.
3463  *
3464  * Returns     :  JB_ERR_OK on success, or
3465  *                JB_ERR_MEMORY on out-of-memory error.
3466  *
3467  *********************************************************************/
3468 static jb_err client_if_none_match(struct client_state *csp, char **header)
3469 {
3470    if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3471    {
3472       log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3473       freez(*header);
3474    }
3475
3476    return JB_ERR_OK;
3477 }
3478
3479
3480 /*********************************************************************
3481  *
3482  * Function    :  client_x_filter
3483  *
3484  * Description :  Disables filtering if the client set "X-Filter: No".
3485  *                Called from `sed'.
3486  *
3487  * Parameters  :
3488  *          1  :  csp = Current client state (buffers, headers, etc...)
3489  *          2  :  header = On input, pointer to header to modify.
3490  *                On output, pointer to the modified header, or NULL
3491  *                to remove the header.  This function frees the
3492  *                original string if necessary.
3493  *
3494  * Returns     :  JB_ERR_OK on success
3495  *
3496  *********************************************************************/
3497 jb_err client_x_filter(struct client_state *csp, char **header)
3498 {
3499    if (0 == strcmpic(*header, "X-Filter: No"))
3500    {
3501       if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3502       {
3503          log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3504       }
3505       else
3506       {
3507          if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3508          {
3509             log_error(LOG_LEVEL_HEADER,
3510                "force-text-mode overruled the client's request to fetch without filtering!");
3511          }
3512          else
3513          {
3514             csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3515             csp->flags |= CSP_FLAG_NO_FILTERING;
3516             log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3517          }
3518          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3519          freez(*header);
3520       }
3521    }
3522    return JB_ERR_OK;
3523 }
3524
3525
3526 /*********************************************************************
3527  *
3528  * Function    :  client_range
3529  *
3530  * Description :  Removes Range, Request-Range and If-Range headers if
3531  *                content filtering is enabled and the range doesn't
3532  *                start at byte 0.
3533  *
3534  *                If the client's version of the document has been
3535  *                altered by Privoxy, the server could interpret the
3536  *                range differently than the client intended in which
3537  *                case the user could end up with corrupted content.
3538  *
3539  *                If the range starts at byte 0 this isn't an issue
3540  *                so the header can pass. Partial requests like this
3541  *                are used to render preview images for videos without
3542  *                downloading the whole video.
3543  *
3544  *                While HTTP doesn't require that range requests are
3545  *                honoured and the client could simply abort the download
3546  *                after receiving a sufficient amount of data, various
3547  *                clients don't handle complete responses to range
3548  *                requests gracefully and emit misleading error messages
3549  *                instead.
3550  *
3551  * Parameters  :
3552  *          1  :  csp = Current client state (buffers, headers, etc...)
3553  *          2  :  header = On input, pointer to header to modify.
3554  *                On output, pointer to the modified header, or NULL
3555  *                to remove the header.  This function frees the
3556  *                original string if necessary.
3557  *
3558  * Returns     :  JB_ERR_OK
3559  *
3560  *********************************************************************/
3561 static jb_err client_range(struct client_state *csp, char **header)
3562 {
3563    if (content_filters_enabled(csp->action)
3564       && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3565    {
3566       log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3567          " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3568       freez(*header);
3569    }
3570
3571    return JB_ERR_OK;
3572 }
3573
3574 /* the following functions add headers directly to the header list */
3575
3576 /*********************************************************************
3577  *
3578  * Function    :  client_host_adder
3579  *
3580  * Description :  Adds the Host: header field if it is missing.
3581  *                Called from `sed'.
3582  *
3583  * Parameters  :
3584  *          1  :  csp = Current client state (buffers, headers, etc...)
3585  *
3586  * Returns     :  JB_ERR_OK on success, or
3587  *                JB_ERR_MEMORY on out-of-memory error.
3588  *
3589  *********************************************************************/
3590 static jb_err client_host_adder(struct client_state *csp)
3591 {
3592    char *p;
3593    jb_err err;
3594
3595    if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3596    {
3597       /* Header already set by the client, nothing to do. */
3598       return JB_ERR_OK;
3599    }
3600
3601    if (!csp->http->hostport || !*(csp->http->hostport))
3602    {
3603       /* XXX: When does this happen and why is it OK? */
3604       log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3605       return JB_ERR_OK;
3606    }
3607
3608    /*
3609     * remove 'user:pass@' from 'proto://user:pass@host'
3610     */
3611    if ((p = strchr( csp->http->hostport, '@')) != NULL)
3612    {
3613       p++;
3614    }
3615    else
3616    {
3617       p = csp->http->hostport;
3618    }
3619
3620    /* XXX: Just add it, we already made sure that it will be unique */
3621    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3622    err = enlist_unique_header(csp->headers, "Host", p);
3623    return err;
3624
3625 }
3626
3627
3628 /*********************************************************************
3629  *
3630  * Function    :  client_xtra_adder
3631  *
3632  * Description :  Used in the add_client_headers list.  Called from `sed'.
3633  *
3634  * Parameters  :
3635  *          1  :  csp = Current client state (buffers, headers, etc...)
3636  *
3637  * Returns     :  JB_ERR_OK on success, or
3638  *                JB_ERR_MEMORY on out-of-memory error.
3639  *
3640  *********************************************************************/
3641 static jb_err client_xtra_adder(struct client_state *csp)
3642 {
3643    struct list_entry *lst;
3644    jb_err err;
3645
3646    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3647         lst ; lst = lst->next)
3648    {
3649       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3650       err = enlist(csp->headers, lst->str);
3651       if (err)
3652       {
3653          return err;
3654       }
3655
3656    }
3657
3658    return JB_ERR_OK;
3659 }
3660
3661
3662 /*********************************************************************
3663  *
3664  * Function    :  client_x_forwarded_for_adder
3665  *
3666  * Description :  Used in the add_client_headers list.  Called from `sed'.
3667  *
3668  * Parameters  :
3669  *          1  :  csp = Current client state (buffers, headers, etc...)
3670  *
3671  * Returns     :  JB_ERR_OK on success, or
3672  *                JB_ERR_MEMORY on out-of-memory error.
3673  *
3674  *********************************************************************/
3675 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3676 {
3677    char *header = NULL;
3678    jb_err err;
3679
3680    if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3681          && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3682       || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3683    {
3684       /*
3685        * If we aren't adding X-Forwarded-For headers,
3686        * or we already appended an existing X-Forwarded-For
3687        * header, there's nothing left to do here.
3688        */
3689       return JB_ERR_OK;
3690    }
3691
3692    header = strdup("X-Forwarded-For: ");
3693    string_append(&header, csp->ip_addr_str);
3694
3695    if (header == NULL)
3696    {
3697       return JB_ERR_MEMORY;
3698    }
3699
3700    log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3701    err = enlist(csp->headers, header);
3702    freez(header);
3703
3704    return err;
3705 }
3706
3707
3708 /*********************************************************************
3709  *
3710  * Function    :  server_connection_adder
3711  *
3712  * Description :  Adds an appropriate "Connection:" header to csp->headers
3713  *                unless the header was already present. Called from `sed'.
3714  *
3715  * Parameters  :
3716  *          1  :  csp = Current client state (buffers, headers, etc...)
3717  *
3718  * Returns     :  JB_ERR_OK on success, or
3719  *                JB_ERR_MEMORY on out-of-memory error.
3720  *
3721  *********************************************************************/
3722 static jb_err server_connection_adder(struct client_state *csp)
3723 {
3724    const unsigned int flags = csp->flags;
3725    const char *response_status_line = csp->headers->first->str;
3726    static const char connection_close[] = "Connection: close";
3727
3728    if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3729     && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3730    {
3731       return JB_ERR_OK;
3732    }
3733
3734    /*
3735     * XXX: if we downgraded the response, this check will fail.
3736     */
3737    if ((csp->config->feature_flags &
3738         RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3739     && (NULL != response_status_line)
3740     && !strncmpic(response_status_line, "HTTP/1.1", 8)
3741 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3742     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3743 #endif
3744       )
3745    {
3746       log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3747          "without Connection header implies keep-alive.");
3748       csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3749       return JB_ERR_OK;
3750    }
3751
3752    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3753
3754    return enlist(csp->headers, connection_close);
3755 }
3756
3757
3758 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3759 /*********************************************************************
3760  *
3761  * Function    :  server_proxy_connection_adder
3762  *
3763  * Description :  Adds a "Proxy-Connection: keep-alive" header to
3764  *                csp->headers when appropriate.
3765  *
3766  * Parameters  :
3767  *          1  :  csp = Current client state (buffers, headers, etc...)
3768  *
3769  * Returns     :  JB_ERR_OK on success, or
3770  *                JB_ERR_MEMORY on out-of-memory error.
3771  *
3772  *********************************************************************/
3773 static jb_err server_proxy_connection_adder(struct client_state *csp)
3774 {
3775    static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3776    jb_err err = JB_ERR_OK;
3777
3778    if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3779     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3780     && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3781     && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3782        || (csp->flags & CSP_FLAG_CHUNKED)))
3783    {
3784       log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3785       err = enlist(csp->headers, proxy_connection_header);
3786    }
3787
3788    return err;
3789 }
3790 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3791
3792
3793 /*********************************************************************
3794  *
3795  * Function    :  client_connection_header_adder
3796  *
3797  * Description :  Adds a proper "Connection:" header to csp->headers
3798  *                unless the header was already present. Called from `sed'.
3799  *
3800  * Parameters  :
3801  *          1  :  csp = Current client state (buffers, headers, etc...)
3802  *
3803  * Returns     :  JB_ERR_OK on success, or
3804  *                JB_ERR_MEMORY on out-of-memory error.
3805  *
3806  *********************************************************************/
3807 static jb_err client_connection_header_adder(struct client_state *csp)
3808 {
3809    static const char connection_close[] = "Connection: close";
3810
3811    if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3812      && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3813    {
3814       return JB_ERR_OK;
3815    }
3816
3817 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3818    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3819       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3820       && (csp->http->ssl == 0)
3821       && !strcmpic(csp->http->ver, "HTTP/1.1"))
3822    {
3823       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3824       return JB_ERR_OK;
3825    }
3826 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3827
3828    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3829
3830    return enlist(csp->headers, connection_close);
3831 }
3832
3833
3834 /*********************************************************************
3835  *
3836  * Function    :  server_http
3837  *
3838  * Description :  - Save the HTTP Status into csp->http->status
3839  *                - Set CT_TABOO to prevent filtering if the answer
3840  *                  is a partial range (HTTP status 206)
3841  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3842  *                  action applies.
3843  *
3844  * Parameters  :
3845  *          1  :  csp = Current client state (buffers, headers, etc...)
3846  *          2  :  header = On input, pointer to header to modify.
3847  *                On output, pointer to the modified header, or NULL
3848  *                to remove the header.  This function frees the
3849  *                original string if necessary.
3850  *
3851  * Returns     :  JB_ERR_OK on success, or
3852  *                JB_ERR_MEMORY on out-of-memory error.
3853  *
3854  *********************************************************************/
3855 static jb_err server_http(struct client_state *csp, char **header)
3856 {
3857    sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3858    if (csp->http->status == 206)
3859    {
3860       csp->content_type = CT_TABOO;
3861    }
3862
3863    if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3864    {
3865       /* XXX: Should we do a real validity check here? */
3866       if (strlen(*header) > 8)
3867       {
3868          (*header)[7] = '0';
3869          log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3870       }
3871       else
3872       {
3873          /*
3874           * XXX: Should we block the request or
3875           * enlist a valid status code line here?
3876           */
3877          log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3878             "Downgrading to HTTP/1.0 impossible.");
3879       }
3880    }
3881
3882    return JB_ERR_OK;
3883 }
3884
3885 /*********************************************************************
3886  *
3887  * Function    :  add_cooky_expiry_date
3888  *
3889  * Description :  Adds a cookie expiry date to a string.
3890  *
3891  * Parameters  :
3892  *          1  :  cookie = On input, pointer to cookie to modify.
3893  *                         On output, pointer to the modified header.
3894  *                         The original string is freed.
3895  *          2  :  lifetime = Seconds the cookie should be valid
3896  *
3897  * Returns     :  N/A
3898  *
3899  *********************************************************************/
3900 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3901 {
3902    char tmp[50];
3903    struct tm *timeptr = NULL;
3904    time_t expiry_date = time(NULL) + lifetime;
3905 #ifdef HAVE_GMTIME_R
3906    struct tm gmt;
3907
3908    timeptr = gmtime_r(&expiry_date, &gmt);
3909 #elif defined(MUTEX_LOCKS_AVAILABLE)
3910    privoxy_mutex_lock(&gmtime_mutex);
3911    timeptr = gmtime(&expiry_date);
3912    privoxy_mutex_unlock(&gmtime_mutex);
3913 #else
3914    timeptr = gmtime(&expiry_date);
3915 #endif
3916
3917    if (NULL == timeptr)
3918    {
3919       log_error(LOG_LEVEL_FATAL,
3920          "Failed to get the time in add_cooky_expiry_date()");
3921    }
3922    strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3923    if (JB_ERR_OK != string_append(cookie, tmp))
3924    {
3925       log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3926    }
3927 }
3928
3929
3930 /*********************************************************************
3931  *
3932  * Function    :  server_set_cookie
3933  *
3934  * Description :  Handle the server "cookie" header properly.
3935  *                Crunch, accept or rewrite it to a session cookie.
3936  *                Called from `sed'.
3937  *
3938  * Parameters  :
3939  *          1  :  csp = Current client state (buffers, headers, etc...)
3940  *          2  :  header = On input, pointer to header to modify.
3941  *                On output, pointer to the modified header, or NULL
3942  *                to remove the header.  This function frees the
3943  *                original string if necessary.
3944  *
3945  * Returns     :  JB_ERR_OK on success, or
3946  *                JB_ERR_MEMORY on out-of-memory error.
3947  *
3948  *********************************************************************/
3949 static jb_err server_set_cookie(struct client_state *csp, char **header)
3950 {
3951    if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
3952    {
3953       log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3954       freez(*header);
3955    }
3956    else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
3957          || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
3958    {
3959       time_t now;
3960       time_t cookie_time;
3961       long cookie_lifetime = 0;
3962       enum
3963       {
3964          NO_EXPIRY_DATE_SPECIFIED,
3965          EXPIRY_DATE_ACCEPTABLE,
3966          EXPIRY_DATE_UNACCEPTABLE
3967       } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
3968
3969       /* A variable to store the tag we're working on */
3970       char *cur_tag;
3971
3972       /* Skip "Set-Cookie:" (11 characters) in header */
3973       cur_tag = *header + 11;
3974
3975       /* skip whitespace between "Set-Cookie:" and value */
3976       while (*cur_tag && privoxy_isspace(*cur_tag))
3977       {
3978          cur_tag++;
3979       }
3980
3981       time(&now);
3982
3983       if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
3984       {
3985          const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
3986
3987          cookie_lifetime = strtol(param, NULL, 0);
3988          if (cookie_lifetime < 0)
3989          {
3990             log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
3991          }
3992          cookie_lifetime *= 60;
3993       }
3994
3995       /* Loop through each tag in the cookie */
3996       while (*cur_tag)
3997       {
3998          /* Find next tag */
3999          char *next_tag = strchr(cur_tag, ';');
4000          if (next_tag != NULL)
4001          {
4002             /* Skip the ';' character itself */
4003             next_tag++;
4004
4005             /* skip whitespace ";" and start of tag */
4006             while (*next_tag && privoxy_isspace(*next_tag))
4007             {
4008                next_tag++;
4009             }
4010          }
4011          else
4012          {
4013             /* "Next tag" is the end of the string */
4014             next_tag = cur_tag + strlen(cur_tag);
4015          }
4016
4017          /*
4018           * Check the expiration date to see
4019           * if the cookie is still valid, if yes,
4020           * rewrite it to a session cookie.
4021           */
4022          if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4023          {
4024             char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4025
4026             if ((expiration_date[0] == '"')
4027              && (expiration_date[1] != '\0'))
4028             {
4029                /*
4030                 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4031                 * that the expiration date isn't supposed to be quoted,
4032                 * but some servers do it anyway.
4033                 */
4034                expiration_date++;
4035             }
4036
4037             /* Did we detect the date properly? */
4038             if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4039             {
4040                /*
4041                 * Nope, treat it as if it was still valid.
4042                 *
4043                 * XXX: Should we remove the whole cookie instead?
4044                 */
4045                log_error(LOG_LEVEL_ERROR,
4046                   "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4047                string_move(cur_tag, next_tag);
4048                expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4049             }
4050             else
4051             {
4052                /*
4053                 * Yes. Check if the cookie is still valid.
4054                 *
4055                 * If the cookie is already expired it's probably
4056                 * a delete cookie and even if it isn't, the browser
4057                 * will discard it anyway.
4058                 */
4059
4060                /*
4061                 * XXX: timegm() isn't available on some AmigaOS
4062                 * versions and our replacement doesn't work.
4063                 *
4064                 * Our options are to either:
4065                 *
4066                 * - disable session-cookies-only completely if timegm
4067                 *   is missing,
4068                 *
4069                 * - to simply remove all expired tags, like it has
4070                 *   been done until Privoxy 3.0.6 and to live with
4071                 *    the consequence that it can cause login/logout
4072                 *   problems on servers that don't validate their
4073                 *   input properly, or
4074                 *
4075                 * - to replace it with mktime in which
4076                 *   case there is a slight chance of valid cookies
4077                 *   passing as already expired.
4078                 *
4079                 *   This is the way it's currently done and it's not
4080                 *   as bad as it sounds. If the missing GMT offset is
4081                 *   enough to change the result of the expiration check
4082                 *   the cookie will be only valid for a few hours
4083                 *   anyway, which in many cases will be shorter
4084                 *   than a browser session.
4085                 */
4086                if (cookie_time < now)
4087                {
4088                   log_error(LOG_LEVEL_HEADER,
4089                      "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4090                   /* Just in case some clown sets more then one expiration date */
4091                   cur_tag = next_tag;
4092                   expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4093                }
4094                else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4095                {
4096                   log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4097                      "Its lifetime is below the limit.", *header);
4098                   /* Just in case some clown sets more then one expiration date */
4099                   cur_tag = next_tag;
4100                   expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4101                }
4102                else
4103                {
4104                   /*
4105                    * Still valid, delete expiration date by copying
4106                    * the rest of the string over it.
4107                    */
4108                   string_move(cur_tag, next_tag);
4109
4110                   /* That changed the header, need to issue a log message */
4111                   expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4112
4113                   /*
4114                    * Note that the next tag has now been moved to *cur_tag,
4115                    * so we do not need to update the cur_tag pointer.
4116                    */
4117                }
4118             }
4119
4120          }
4121          else
4122          {
4123             /* Move on to next cookie tag */
4124             cur_tag = next_tag;
4125          }
4126       }
4127
4128       if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4129       {
4130          assert(NULL != *header);
4131          if (cookie_lifetime != 0)
4132          {
4133             add_cookie_expiry_date(header, cookie_lifetime);
4134             log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4135          }
4136          else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4137          {
4138             log_error(LOG_LEVEL_HEADER,
4139                "Cookie rewritten to a temporary one: %s", *header);
4140          }
4141       }
4142    }
4143
4144    return JB_ERR_OK;
4145 }
4146
4147
4148 #ifdef FEATURE_FORCE_LOAD
4149 /*********************************************************************
4150  *
4151  * Function    :  strclean
4152  *
4153  * Description :  In-Situ-Eliminate all occurrences of substring in
4154  *                string
4155  *
4156  * Parameters  :
4157  *          1  :  string = string to clean
4158  *          2  :  substring = substring to eliminate
4159  *
4160  * Returns     :  Number of eliminations
4161  *
4162  *********************************************************************/
4163 int strclean(char *string, const char *substring)
4164 {
4165    int hits = 0;
4166    size_t len;
4167    char *pos, *p;
4168
4169    len = strlen(substring);
4170
4171    while((pos = strstr(string, substring)) != NULL)
4172    {
4173       p = pos + len;
4174       do
4175       {
4176          *(p - len) = *p;
4177       }
4178       while (*p++ != '\0');
4179
4180       hits++;
4181    }
4182
4183    return(hits);
4184 }
4185 #endif /* def FEATURE_FORCE_LOAD */
4186
4187
4188 /*********************************************************************
4189  *
4190  * Function    :  parse_header_time
4191  *
4192  * Description :  Parses time formats used in HTTP header strings
4193  *                to get the numerical respresentation.
4194  *
4195  * Parameters  :
4196  *          1  :  header_time = HTTP header time as string.
4197  *          2  :  result = storage for header_time in seconds
4198  *
4199  * Returns     :  JB_ERR_OK if the time format was recognized, or
4200  *                JB_ERR_PARSE otherwise.
4201  *
4202  *********************************************************************/
4203 static jb_err parse_header_time(const char *header_time, time_t *result)
4204 {
4205    struct tm gmt;
4206    /*
4207     * Checking for two-digit years first in an
4208     * attempt to work around GNU libc's strptime()
4209     * reporting negative year values when using %Y.
4210     */
4211    static const char time_formats[][22] = {
4212       /* Tue, 02-Jun-37 20:00:00 */
4213       "%a, %d-%b-%y %H:%M:%S",
4214       /* Tue, 02 Jun 2037 20:00:00 */
4215       "%a, %d %b %Y %H:%M:%S",
4216       /* Tue, 02-Jun-2037 20:00:00 */
4217       "%a, %d-%b-%Y %H:%M:%S",
4218       /* Tuesday, 02-Jun-2037 20:00:00 */
4219       "%A, %d-%b-%Y %H:%M:%S",
4220       /* Tuesday Jun 02 20:00:00 2037 */
4221       "%A %b %d %H:%M:%S %Y"
4222    };
4223    unsigned int i;
4224
4225    for (i = 0; i < SZ(time_formats); i++)
4226    {
4227       /*
4228        * Zero out gmt to prevent time zone offsets.
4229        * Documented to be required for GNU libc.
4230        */
4231       memset(&gmt, 0, sizeof(gmt));
4232
4233       if (NULL != strptime(header_time, time_formats[i], &gmt))
4234       {
4235          /* Sanity check for GNU libc. */
4236          if (gmt.tm_year < 0)
4237          {
4238             log_error(LOG_LEVEL_HEADER,
4239                "Failed to parse '%s' using '%s'. Moving on.",
4240                header_time, time_formats[i]);
4241             continue;
4242          }
4243          *result = timegm(&gmt);
4244
4245 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4246          /*
4247           * Verify that parsing the date recreated from the first
4248           * parse operation gets the previous result. If it doesn't,
4249           * either strptime() or strftime() are malfunctioning.
4250           *
4251           * We could string-compare the recreated date with the original
4252           * header date, but this leads to false positives as strptime()
4253           * may let %a accept all day formats while strftime() will only
4254           * create one.
4255           */
4256          {
4257             char recreated_date[100];
4258             struct tm *tm;
4259             time_t result2;
4260
4261             tm = gmtime(result);
4262             strftime(recreated_date, sizeof(recreated_date), time_formats[i], tm);
4263             memset(&gmt, 0, sizeof(gmt));
4264             if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4265             {
4266                log_error(LOG_LEVEL_ERROR,
4267                   "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4268                   recreated_date, time_formats[i], header_time);
4269                continue;
4270             }
4271             result2 = timegm(&gmt);
4272             if (*result != result2)
4273             {
4274                log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4275                   "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4276                   time_formats[i], header_time, recreated_date, *result, result2);
4277                continue;
4278             }
4279          }
4280 #endif
4281
4282          return JB_ERR_OK;
4283       }
4284    }
4285
4286    return JB_ERR_PARSE;
4287
4288 }
4289
4290
4291 /*********************************************************************
4292  *
4293  * Function    :  get_destination_from_headers
4294  *
4295  * Description :  Parse the "Host:" header to get the request's destination.
4296  *                Only needed if the client's request was forcefully
4297  *                redirected into Privoxy.
4298  *
4299  *                Code mainly copied from client_host() which is currently
4300  *                run too late for this purpose.
4301  *
4302  * Parameters  :
4303  *          1  :  headers = List of headers (one of them hopefully being
4304  *                the "Host:" header)
4305  *          2  :  http = storage for the result (host, port and hostport).
4306  *
4307  * Returns     :  JB_ERR_MEMORY (or terminates) in case of memory problems,
4308  *                JB_ERR_PARSE if the host header couldn't be found,
4309  *                JB_ERR_OK otherwise.
4310  *
4311  *********************************************************************/
4312 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4313 {
4314    char *q;
4315    char *p;
4316    char *host;
4317
4318    host = get_header_value(headers, "Host:");
4319
4320    if (NULL == host)
4321    {
4322       log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4323       return JB_ERR_PARSE;
4324    }
4325
4326    p = strdup_or_die(host);
4327    chomp(p);
4328    q = strdup_or_die(p);
4329
4330    freez(http->hostport);
4331    http->hostport = p;
4332    freez(http->host);
4333    http->host = q;
4334    q = strchr(http->host, ':');
4335    if (q != NULL)
4336    {
4337       /* Terminate hostname and evaluate port string */
4338       *q++ = '\0';
4339       http->port = atoi(q);
4340    }
4341    else
4342    {
4343       http->port = http->ssl ? 443 : 80;
4344    }
4345
4346    /* Rebuild request URL */
4347    freez(http->url);
4348    http->url = strdup(http->ssl ? "https://" : "http://");
4349    string_append(&http->url, http->hostport);
4350    string_append(&http->url, http->path);
4351    if (http->url == NULL)
4352    {
4353       return JB_ERR_MEMORY;
4354    }
4355
4356    log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4357       http->url);
4358
4359    return JB_ERR_OK;
4360
4361 }
4362
4363
4364 /*********************************************************************
4365  *
4366  * Function    :  create_forged_referrer
4367  *
4368  * Description :  Helper for client_referrer to forge a referer as
4369  *                'http://hostname[:port]/' to fool stupid
4370  *                checks for in-site links
4371  *
4372  * Parameters  :
4373  *          1  :  header   = Pointer to header pointer
4374  *          2  :  hostport = Host and optionally port as string
4375  *
4376  * Returns     :  JB_ERR_OK in case of success, or
4377  *                JB_ERR_MEMORY in case of memory problems.
4378  *
4379  *********************************************************************/
4380 static jb_err create_forged_referrer(char **header, const char *hostport)
4381 {
4382     assert(NULL == *header);
4383
4384     *header = strdup("Referer: http://");
4385     string_append(header, hostport);
4386     string_append(header, "/");
4387
4388     if (NULL == *header)
4389     {
4390        return JB_ERR_MEMORY;
4391     }
4392
4393     log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4394
4395     return JB_ERR_OK;
4396
4397 }
4398
4399
4400 /*********************************************************************
4401  *
4402  * Function    :  create_fake_referrer
4403  *
4404  * Description :  Helper for client_referrer to create a fake referrer
4405  *                based on a string supplied by the user.
4406  *
4407  * Parameters  :
4408  *          1  :  header   = Pointer to header pointer
4409  *          2  :  hosthost = Referrer to fake
4410  *
4411  * Returns     :  JB_ERR_OK in case of success, or
4412  *                JB_ERR_MEMORY in case of memory problems.
4413  *
4414  *********************************************************************/
4415 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4416 {
4417    assert(NULL == *header);
4418
4419    if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4420    {
4421       log_error(LOG_LEVEL_HEADER,
4422          "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4423    }
4424    *header = strdup("Referer: ");
4425    string_append(header, fake_referrer);
4426
4427    if (NULL == *header)
4428    {
4429       return JB_ERR_MEMORY;
4430    }
4431
4432    log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4433
4434    return JB_ERR_OK;
4435
4436 }
4437
4438
4439 /*********************************************************************
4440  *
4441  * Function    :  handle_conditional_hide_referrer_parameter
4442  *
4443  * Description :  Helper for client_referrer to crunch or forge
4444  *                the referrer header if the host has changed.
4445  *
4446  * Parameters  :
4447  *          1  :  header = Pointer to header pointer
4448  *          2  :  host   = The target host (may include the port)
4449  *          3  :  parameter_conditional_block = Boolean to signal
4450  *                if we're in conditional-block mode. If not set,
4451  *                we're in conditional-forge mode.
4452  *
4453  * Returns     :  JB_ERR_OK in case of success, or
4454  *                JB_ERR_MEMORY in case of memory problems.
4455  *
4456  *********************************************************************/
4457 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4458    const char *host, const int parameter_conditional_block)
4459 {
4460    char *referer = strdup_or_die(*header);
4461    const size_t hostlength = strlen(host);
4462    const char *referer_url = NULL;
4463
4464    /* referer begins with 'Referer: http[s]://' */
4465    if ((hostlength+17) < strlen(referer))
4466    {
4467       /*
4468        * Shorten referer to make sure the referer is blocked
4469        * if www.example.org/www.example.com-shall-see-the-referer/
4470        * links to www.example.com/
4471        */
4472       referer[hostlength+17] = '\0';
4473    }
4474    referer_url = strstr(referer, "http://");
4475    if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4476    {
4477       /* Host has changed, Referer is invalid or a https URL. */
4478       if (parameter_conditional_block)
4479       {
4480          log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4481          freez(*header);
4482       }
4483       else
4484       {
4485          freez(*header);
4486          freez(referer);
4487          return create_forged_referrer(header, host);
4488       }
4489    }
4490    freez(referer);
4491
4492    return JB_ERR_OK;
4493
4494 }
4495
4496
4497 /*********************************************************************
4498  *
4499  * Function    :  create_content_length_header
4500  *
4501  * Description :  Creates a Content-Length header.
4502  *
4503  * Parameters  :
4504  *          1  :  content_length = The content length to be used in the header.
4505  *          2  :  header = Allocated space to safe the header.
4506  *          3  :  buffer_length = The length of the allocated space.
4507  *
4508  * Returns     :  void
4509  *
4510  *********************************************************************/
4511 static void create_content_length_header(unsigned long long content_length,
4512                                          char *header, size_t buffer_length)
4513 {
4514    snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4515 }
4516
4517
4518 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4519 /*********************************************************************
4520  *
4521  * Function    :  get_expected_content_length
4522  *
4523  * Description :  Figures out the content length from a list of headers.
4524  *
4525  * Parameters  :
4526  *          1  :  headers = List of headers
4527  *
4528  * Returns     :  Number of bytes to expect
4529  *
4530  *********************************************************************/
4531 unsigned long long get_expected_content_length(struct list *headers)
4532 {
4533    const char *content_length_header;
4534    unsigned long long content_length = 0;
4535
4536    content_length_header = get_header_value(headers, "Content-Length:");
4537    if (content_length_header != NULL)
4538    {
4539       if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4540       {
4541          log_error(LOG_LEVEL_ERROR,
4542             "Failed to get the Content-Length in %s", content_length_header);
4543          /* XXX: The header will be removed later on */
4544          return 0;
4545       }
4546    }
4547
4548    return content_length;
4549 }
4550 #endif
4551
4552 /*
4553   Local Variables:
4554   tab-width: 3
4555   end:
4556 */