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