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