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