LCOV - code coverage report
Current view: top level - fuzz - parsers.c (source / functions) Hit Total Coverage
Test: trace.lcov_info_final Lines: 1075 1239 86.8 %
Date: 2021-02-22 04:51:02 Functions: 75 75 100.0 %

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

Generated by: LCOV version 1.14