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