1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2021 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
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.
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.
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.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
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
68 #include <brotli/decode.h>
77 #ifdef FEATURE_PTHREAD
79 /* jcc.h is for mutex semapores only */
80 #endif /* def FEATURE_PTHREAD */
85 #include "jbsockets.h"
90 #ifdef FEATURE_HTTPS_INSPECTION
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);
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);
136 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
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 */
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);
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);
166 * List of functions to run on a list of headers.
170 /** The header prefix to match */
173 /** The length of the prefix to match */
176 /** The function to apply to this line */
177 const parser_func_ptr parser;
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 },
196 { "Keep-Alive:", 11, crumble },
197 { "Proxy-Connection:", 17, crumble },
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 },
209 { "Transfer-Encoding:", 18, client_transfer_encoding },
211 { "Expect:", 7, client_expect },
212 { "*", 0, crunch_client_header },
213 { "*", 0, filter_header },
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 },
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 },
240 static const add_header_func_ptr add_client_headers[] = {
242 client_x_forwarded_for_adder,
244 client_connection_header_adder,
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 */
256 /*********************************************************************
258 * Function : flush_iob
260 * Description : Write any pending "buffered" content.
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
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.
274 *********************************************************************/
275 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
277 long len = iob->eod - iob->cur;
284 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
288 iob->eod = iob->cur = iob->buf;
294 /*********************************************************************
296 * Function : can_add_to_iob
298 * Description : Checks if the given number of bytes can be added to the given iob
299 * without exceeding the given buffer limit.
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
306 * Returns : TRUE if the given iob can handle given number of bytes
307 * FALSE buffer limit will be exceeded
309 *********************************************************************/
310 int can_add_to_iob(const struct iob *iob, const size_t buffer_limit, size_t n)
312 return ((size_t)(iob->eod - iob->buf) + n + 1) > buffer_limit ? FALSE : TRUE;
315 /*********************************************************************
317 * Function : add_to_iob
319 * Description : Add content to the buffer, expanding the
320 * buffer if necessary.
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
328 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
329 * or buffer limit reached.
331 *********************************************************************/
332 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, const char *src, long n)
334 size_t used, offset, need;
337 if (n <= 0) return JB_ERR_OK;
339 used = (size_t)(iob->eod - iob->buf);
340 offset = (size_t)(iob->cur - iob->buf);
341 need = used + (size_t)n + 1;
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.
347 if (need > buffer_limit)
349 log_error(LOG_LEVEL_INFO,
350 "Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
352 return JB_ERR_MEMORY;
355 if (need > iob->size)
357 size_t want = iob->size ? iob->size : 512;
364 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
368 else if (NULL != (p = (char *)realloc(iob->buf, need)))
374 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
375 return JB_ERR_MEMORY;
378 /* Update the iob pointers */
379 iob->cur = p + offset;
384 /* copy the new data into the iob buffer */
385 memcpy(iob->eod, src, (size_t)n);
387 /* point to the end of the data */
390 /* null terminate == cheap insurance */
398 /*********************************************************************
400 * Function : clear_iob
402 * Description : Frees the memory allocated for an I/O buffer and
403 * resets the structure.
406 * 1 : iob = I/O buffer to clear.
410 *********************************************************************/
411 void clear_iob(struct iob *iob)
414 memset(iob, '\0', sizeof(*iob));
419 #ifdef FEATURE_BROTLI
420 /*********************************************************************
422 * Function : decompress_iob_with_brotli
424 * Description : Decompress buffered page using Brotli.
427 * 1 : csp = Current client state (buffers, headers, etc...)
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.
433 *********************************************************************/
434 static jb_err decompress_iob_with_brotli(struct client_state *csp)
436 BrotliDecoderResult result;
437 char *decoded_buffer;
439 size_t decoded_buffer_size;
441 enum { MAX_COMPRESSION_FACTOR = 15 };
443 encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
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.
451 decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
453 if (decoded_buffer_size > csp->config->buffer_limit)
455 log_error(LOG_LEVEL_ERROR,
456 "Buffer limit reached before decompressing iob with Brotli");
457 return JB_ERR_MEMORY;
460 decoded_buffer = malloc(decoded_buffer_size);
461 if (decoded_buffer == NULL)
463 log_error(LOG_LEVEL_ERROR,
464 "Failed to allocate %lu bytes for Brotli decompression",
465 decoded_buffer_size);
466 return JB_ERR_MEMORY;
469 decoded_size = decoded_buffer_size;
470 result = BrotliDecoderDecompress(encoded_size,
471 (const uint8_t *)csp->iob->cur, &decoded_size,
472 (uint8_t *)decoded_buffer);
473 if (result == BROTLI_DECODER_RESULT_SUCCESS)
476 * Update the iob, since the decompression was successful.
478 freez(csp->iob->buf);
479 csp->iob->buf = decoded_buffer;
480 csp->iob->cur = csp->iob->buf;
481 csp->iob->eod = csp->iob->cur + decoded_size;
482 csp->iob->size = decoded_buffer_size;
484 log_error(LOG_LEVEL_RE_FILTER,
485 "Decompression successful. Old size: %lu, new size: %lu.",
486 encoded_size, decoded_size);
492 log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
493 freez(decoded_buffer);
495 return JB_ERR_COMPRESS;
500 /*********************************************************************
502 * Function : decompress_iob
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.
510 * 1 : csp = Current client state (buffers, headers, etc...)
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.
516 *********************************************************************/
517 jb_err decompress_iob(struct client_state *csp)
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 */
530 assert(csp->iob->cur - csp->iob->buf >= 0);
531 assert(csp->iob->eod - csp->iob->cur >= 0);
533 assert(csp->iob->cur - csp->iob->buf > 0);
534 assert(csp->iob->eod - csp->iob->cur > 0);
537 bufsize = csp->iob->size;
538 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
539 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
543 if (old_size < (size_t)10)
546 * This is to protect the parsing of gzipped data,
547 * but it should(?) be valid for deflated data also.
549 log_error(LOG_LEVEL_ERROR,
550 "Insufficient data to start decompression. Bytes in buffer: %ld",
551 csp->iob->eod - csp->iob->cur);
552 return JB_ERR_COMPRESS;
555 #ifdef FEATURE_BROTLI
556 if (csp->content_type & CT_BROTLI)
558 return decompress_iob_with_brotli(csp);
562 if (csp->content_type & CT_GZIP)
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.
573 * Strip off the gzip header. Please see RFC 1952 for more
574 * explanation of the appropriate fields.
576 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
577 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
578 || (*cur++ != Z_DEFLATED))
580 log_error(LOG_LEVEL_ERROR,
581 "Invalid gzip header when decompressing.");
582 return JB_ERR_COMPRESS;
587 if (flags & GZIP_FLAG_RESERVED_BITS)
589 /* The gzip header has reserved bits set; bail out. */
590 log_error(LOG_LEVEL_ERROR,
591 "Invalid gzip header flags when decompressing.");
592 return JB_ERR_COMPRESS;
596 * Skip mtime (4 bytes), extra flags (1 byte)
597 * and OS type (1 byte).
601 /* Skip extra fields if necessary. */
602 if (flags & GZIP_FLAG_EXTRA_FIELDS)
605 * Skip a given number of bytes, specified
606 * as a 16-bit little-endian value.
608 * XXX: this code is untested and should probably be removed.
612 if (cur + 2 >= csp->iob->eod)
614 log_error(LOG_LEVEL_ERROR,
615 "gzip extra field flag set but insufficient data available.");
616 return JB_ERR_COMPRESS;
620 skip_bytes += (unsigned char)*cur++ << 8;
623 * The number of bytes to skip should be positive
624 * and we'd like to stay in the buffer.
626 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
628 log_error(LOG_LEVEL_ERROR,
629 "Unreasonable amount of bytes to skip (%d). "
630 "Stopping decompression.",
632 return JB_ERR_COMPRESS;
634 log_error(LOG_LEVEL_INFO,
635 "Skipping %d bytes for gzip compression. "
636 "Does this sound right?",
641 /* Skip the filename if necessary. */
642 if (flags & GZIP_FLAG_FILE_NAME)
644 /* A null-terminated string is supposed to follow. */
645 while ((cur < csp->iob->eod) && *cur++);
648 /* Skip the comment if necessary. */
649 if (flags & GZIP_FLAG_COMMENT)
651 /* A null-terminated string is supposed to follow. */
652 while ((cur < csp->iob->eod) && *cur++);
655 /* Skip the CRC if necessary. */
656 if (flags & GZIP_FLAG_CHECKSUM)
661 if (cur >= csp->iob->eod)
664 * If the current position pointer reached or passed
665 * the buffer end, we were obviously tricked to skip
668 log_error(LOG_LEVEL_ERROR,
669 "Malformed gzip header detected. Aborting decompression.");
670 return JB_ERR_COMPRESS;
674 else if (csp->content_type & CT_DEFLATE)
677 * In theory (that is, according to RFC 1950), deflate-compressed
678 * data should begin with a two-byte zlib header and have an
679 * adler32 checksum at the end. It seems that in practice only
680 * the raw compressed data is sent. Note that this means that
681 * we are not RFC 1950-compliant here, but the advantage is that
682 * this actually works. :)
684 * We add a dummy null byte to tell zlib where the data ends,
685 * and later inform it not to expect a header.
687 * Fortunately, add_to_iob() has thoughtfully null-terminated
688 * the buffer; we can just increment the end pointer to include
695 log_error(LOG_LEVEL_ERROR,
696 "Unable to determine compression format for decompression.");
697 return JB_ERR_COMPRESS;
700 /* Set up the fields required by zlib. */
701 zstr.next_in = (Bytef *)cur;
702 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
703 zstr.zalloc = Z_NULL;
705 zstr.opaque = Z_NULL;
708 * Passing -MAX_WBITS to inflateInit2 tells the library
709 * that there is no zlib header.
711 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
713 log_error(LOG_LEVEL_ERROR, "Error initializing decompression.");
714 return JB_ERR_COMPRESS;
718 * Next, we allocate new storage for the inflated data.
719 * We don't modify the existing iob yet, so in case there
720 * is an error in decompression we can recover gracefully.
722 buf = zalloc(bufsize);
725 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob.");
726 return JB_ERR_MEMORY;
729 assert(bufsize >= skip_size);
730 memcpy(buf, csp->iob->buf, skip_size);
731 zstr.avail_out = (uInt)(bufsize - skip_size);
732 zstr.next_out = (Bytef *)buf + skip_size;
734 /* Try to decompress the whole stream in one shot. */
735 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
737 /* We need to allocate more memory for the output buffer. */
739 char *tmpbuf; /* used for realloc'ing the buffer */
740 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
742 if (0 == zstr.avail_in)
745 * If zlib wants more data then there's a problem, because
746 * the complete compressed file should have been buffered.
748 log_error(LOG_LEVEL_ERROR,
749 "Unexpected end of compressed iob. Using what we got so far.");
754 * If we reached the buffer limit and still didn't have enough
755 * memory, just give up. Due to the ceiling enforced by the next
756 * if block we could actually check for equality here, but as it
757 * can be easily mistaken for a bug we don't.
759 if (bufsize >= csp->config->buffer_limit)
761 log_error(LOG_LEVEL_ERROR,
762 "Buffer limit reached while decompressing iob.");
765 return JB_ERR_MEMORY;
768 /* Try doubling the buffer size each time. */
771 /* Don't exceed the buffer limit. */
772 if (bufsize > csp->config->buffer_limit)
774 bufsize = csp->config->buffer_limit;
777 /* Try to allocate the new buffer. */
778 tmpbuf = realloc(buf, bufsize);
781 log_error(LOG_LEVEL_ERROR,
782 "Out of memory decompressing iob.");
785 return JB_ERR_MEMORY;
790 char *oldnext_out = (char *)zstr.next_out;
793 * Update the fields for inflate() to use the new
794 * buffer, which may be in a location different from
797 zstr.avail_out += (uInt)(bufsize - oldbufsize);
798 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
801 * Compare with an uglier method of calculating these values
802 * that doesn't require the extra oldbufsize variable.
804 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
805 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
811 if (Z_STREAM_ERROR == inflateEnd(&zstr))
813 log_error(LOG_LEVEL_ERROR,
814 "Inconsistent stream state after decompression: %s", zstr.msg);
816 * XXX: Intentionally no return.
818 * According to zlib.h, Z_STREAM_ERROR is returned
819 * "if the stream state was inconsistent".
821 * I assume in this case inflate()'s status
822 * would also be something different than Z_STREAM_END
823 * so this check should be redundant, but lets see.
827 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
830 * We failed to decompress the stream and it's
831 * not simply because of missing data.
833 log_error(LOG_LEVEL_ERROR,
834 "Unexpected error while decompressing to the buffer (iob): %s",
837 return JB_ERR_COMPRESS;
841 * Finally, we can actually update the iob, since the
842 * decompression was successful. First, free the old
845 freez(csp->iob->buf);
847 /* Now, update the iob to use the new buffer. */
849 csp->iob->cur = csp->iob->buf + skip_size;
850 csp->iob->eod = (char *)zstr.next_out;
851 csp->iob->size = bufsize;
854 * Make sure the new uncompressed iob obeys some minimal
855 * consistency conditions.
857 if ((csp->iob->buf <= csp->iob->cur)
858 && (csp->iob->cur <= csp->iob->eod)
859 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
861 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
862 if (new_size > (size_t)0)
864 log_error(LOG_LEVEL_RE_FILTER,
865 "Decompression successful. Old size: %lu, new size: %lu.",
870 /* zlib thinks this is OK, so let's do the same. */
871 log_error(LOG_LEVEL_RE_FILTER,
872 "Decompression didn't result in any content.");
877 /* It seems that zlib did something weird. */
878 log_error(LOG_LEVEL_ERROR,
879 "Inconsistent buffer after decompression.");
880 return JB_ERR_COMPRESS;
886 #endif /* defined(FEATURE_ZLIB) */
889 /*********************************************************************
891 * Function : normalize_lws
893 * Description : Reduces unquoted linear whitespace in headers to
894 * a single space in accordance with RFC 7230 3.2.4.
895 * This simplifies parsing and filtering later on.
898 * 1 : header = A header with linear whitespace to reduce.
902 *********************************************************************/
903 static void normalize_lws(char *header)
909 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
913 while (privoxy_isspace(*q))
917 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
923 log_error(LOG_LEVEL_HEADER,
924 "Converting tab to space in '%s'", header);
929 char *end_of_token = strstr(p+1, "\"");
931 if (NULL != end_of_token)
933 /* Don't mess with quoted text. */
938 log_error(LOG_LEVEL_HEADER,
939 "Ignoring single quote in '%s'", header);
945 p = strchr(header, ':');
946 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
949 * There's still space before the colon.
957 /*********************************************************************
959 * Function : get_header
961 * Description : This (odd) routine will parse the csp->iob
962 * to get the next complete header.
965 * 1 : iob = The I/O buffer to parse, usually csp->iob.
967 * Returns : Any one of the following:
969 * 1) a pointer to a dynamically allocated string that contains a header line
970 * 2) NULL indicating that the end of the header was reached
971 * 3) "" indicating that the end of the iob was reached before finding
972 * a complete header line.
974 *********************************************************************/
975 char *get_header(struct iob *iob)
979 header = get_header_line(iob);
981 if ((header == NULL) || (*header == '\0'))
984 * No complete header read yet, tell the client.
989 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
992 * Header spans multiple lines, append the next one.
994 char *continued_header;
996 continued_header = get_header_line(iob);
997 if ((continued_header == NULL) || (*continued_header == '\0'))
1000 * No complete header read yet, return what we got.
1001 * XXX: Should "unread" header instead.
1003 log_error(LOG_LEVEL_INFO,
1004 "Failed to read a multi-line header properly: '%s'",
1009 if (JB_ERR_OK != string_join(&header, continued_header))
1011 log_error(LOG_LEVEL_FATAL,
1012 "Out of memory while appending multiple headers.");
1016 /* XXX: remove before next stable release. */
1017 log_error(LOG_LEVEL_HEADER,
1018 "Merged multiple header lines to: '%s'",
1023 normalize_lws(header);
1030 /*********************************************************************
1032 * Function : get_header_line
1034 * Description : This (odd) routine will parse the csp->iob
1035 * to get the next header line.
1038 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1040 * Returns : Any one of the following:
1042 * 1) a pointer to a dynamically allocated string that contains a header line
1043 * 2) NULL indicating that the end of the header was reached
1044 * 3) "" indicating that the end of the iob was reached before finding
1045 * a complete header line.
1047 *********************************************************************/
1048 static char *get_header_line(struct iob *iob)
1052 if ((iob->cur == NULL)
1053 || ((p = strchr(iob->cur, '\n')) == NULL))
1055 return(""); /* couldn't find a complete header */
1060 ret = strdup(iob->cur);
1063 /* FIXME No way to handle error properly */
1064 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1066 assert(ret != NULL);
1070 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1072 /* is this a blank line (i.e. the end of the header) ? */
1084 /*********************************************************************
1086 * Function : get_header_value
1088 * Description : Get the value of a given header from a chained list
1089 * of header lines or return NULL if no such header is
1090 * present in the list.
1093 * 1 : header_list = pointer to list
1094 * 2 : header_name = string with name of header to look for.
1095 * Trailing colon required, capitalization
1098 * Returns : NULL if not found, else value of header
1100 *********************************************************************/
1101 char *get_header_value(const struct list *header_list, const char *header_name)
1103 struct list_entry *cur_entry;
1107 assert(header_list);
1108 assert(header_name);
1109 length = strlen(header_name);
1111 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1115 if (!strncmpic(cur_entry->str, header_name, length))
1118 * Found: return pointer to start of value
1120 ret = cur_entry->str + length;
1121 while (*ret && privoxy_isspace(*ret)) ret++;
1135 /*********************************************************************
1137 * Function : scan_headers
1139 * Description : Scans headers, applies tags and updates action bits.
1142 * 1 : csp = Current client state (buffers, headers, etc...)
1144 * Returns : JB_ERR_OK
1146 *********************************************************************/
1147 static jb_err scan_headers(struct client_state *csp)
1149 struct list_entry *h; /* Header */
1150 jb_err err = JB_ERR_OK;
1152 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1154 /* Header crunch()ed in previous run? -> ignore */
1155 if (h->str == NULL) continue;
1156 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1157 err = header_tagger(csp, h->str);
1164 /*********************************************************************
1166 * Function : enforce_header_order
1168 * Description : Enforces a given header order.
1171 * 1 : headers = List of headers to order.
1172 * 2 : ordered_headers = List of ordered header names.
1176 *********************************************************************/
1177 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1179 struct list_entry *sorted_header;
1180 struct list new_headers[1];
1181 struct list_entry *header;
1183 init_list(new_headers);
1185 /* The request line is always the first "header" */
1187 assert(NULL != headers->first->str);
1188 enlist(new_headers, headers->first->str);
1189 freez(headers->first->str)
1191 /* Enlist the specified headers in the given order */
1193 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1194 sorted_header = sorted_header->next)
1196 const size_t sorted_header_length = strlen(sorted_header->str);
1197 for (header = headers->first; header != NULL; header = header->next)
1199 /* Header enlisted in previous run? -> ignore */
1200 if (header->str == NULL) continue;
1202 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1203 && (header->str[sorted_header_length] == ':'))
1205 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1206 if (JB_ERR_OK != enlist(new_headers, header->str))
1208 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1215 /* Enlist the rest of the headers behind the ordered ones */
1216 for (header = headers->first; header != NULL; header = header->next)
1218 /* Header enlisted in previous run? -> ignore */
1219 if (header->str == NULL) continue;
1221 log_error(LOG_LEVEL_HEADER,
1222 "Enlisting left-over header %s", header->str);
1223 if (JB_ERR_OK != enlist(new_headers, header->str))
1225 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1230 list_remove_all(headers);
1231 headers->first = new_headers->first;
1232 headers->last = new_headers->last;
1238 /*********************************************************************
1242 * Description : add, delete or modify lines in the HTTP header streams.
1243 * On entry, it receives a linked list of headers space
1244 * that was allocated dynamically (both the list nodes
1245 * and the header contents).
1247 * As a side effect it frees the space used by the original
1251 * 1 : csp = Current client state (buffers, headers, etc...)
1252 * 2 : filter_server_headers = Boolean to switch between
1253 * server and header filtering.
1255 * Returns : JB_ERR_OK in case off success, or
1256 * JB_ERR_MEMORY on some out-of-memory errors, or
1257 * JB_ERR_PARSE in case of fatal parse errors.
1259 *********************************************************************/
1260 jb_err sed(struct client_state *csp, int filter_server_headers)
1262 /* XXX: use more descriptive names. */
1263 struct list_entry *p;
1264 const struct parsers *v;
1265 const add_header_func_ptr *f;
1266 jb_err err = JB_ERR_OK;
1270 if (filter_server_headers)
1272 v = server_patterns;
1273 f = add_server_headers;
1274 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1278 v = client_patterns;
1279 f = add_client_headers;
1280 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1283 while (v->str != NULL)
1285 for (p = csp->headers->first; p != NULL; p = p->next)
1287 /* Header crunch()ed in previous run? -> ignore */
1288 if (p->str == NULL) continue;
1290 /* Does the current parser handle this header? */
1291 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1292 (v->len == CHECK_EVERY_HEADER_REMAINING))
1294 err = v->parser(csp, &(p->str));
1295 if (err != JB_ERR_OK)
1304 if (filter_server_headers &&
1305 (csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET) &&
1306 (csp->flags & CSP_FLAG_CHUNKED))
1308 /* RFC 2616 4.4 3 */
1309 log_error(LOG_LEVEL_HEADER, "Ignoring the Content-Length header "
1310 "sent by the server as the response is chunk-encoded.");
1311 csp->flags &= ~CSP_FLAG_CONTENT_LENGTH_SET;
1312 csp->expected_content_length = 0;
1315 /* place additional headers on the csp->headers list */
1316 while ((err == JB_ERR_OK) && (*f))
1322 if (!filter_server_headers &&
1323 !list_is_empty(csp->config->ordered_client_headers) &&
1324 csp->headers->first->str != NULL)
1326 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1333 #ifdef FEATURE_HTTPS_INSPECTION
1334 /*********************************************************************
1336 * Function : sed_https
1338 * Description : add, delete or modify lines in the HTTPS client
1339 * header streams. Wrapper around sed().
1342 * 1 : csp = Current client state (buffers, headers, etc...)
1344 * Returns : JB_ERR_OK in case off success, or
1345 * JB_ERR_MEMORY on some out-of-memory errors, or
1346 * JB_ERR_PARSE in case of fatal parse errors.
1348 *********************************************************************/
1349 jb_err sed_https(struct client_state *csp)
1352 struct list headers;
1355 * Temporarily replace csp->headers with csp->https_headers
1356 * to trick sed() into filtering the https headers.
1358 headers.first = csp->headers->first;
1359 headers.last = csp->headers->last;
1360 csp->headers->first = csp->https_headers->first;
1361 csp->headers->last = csp->https_headers->last;
1364 * Start with fresh tags. Already existing tags may
1365 * be set again. This is necessary to overrule
1366 * URL-based patterns.
1368 destroy_list(csp->tags);
1371 * We want client header filters and taggers
1372 * so temporarily remove the flag.
1374 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1375 err = sed(csp, FILTER_CLIENT_HEADERS);
1376 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1379 * Update the https headers list which may have
1380 * been modified due to header additions or header
1383 csp->https_headers->first = csp->headers->first;
1384 csp->https_headers->last = csp->headers->last;
1386 csp->headers->first = headers.first;
1387 csp->headers->last = headers.last;
1391 #endif /* def FEATURE_HTTPS_INSPECTION */
1394 /*********************************************************************
1396 * Function : update_server_headers
1398 * Description : Updates server headers after the body has been modified.
1401 * 1 : csp = Current client state (buffers, headers, etc...)
1403 * Returns : JB_ERR_OK in case off success, or
1404 * JB_ERR_MEMORY on out-of-memory error.
1406 *********************************************************************/
1407 jb_err update_server_headers(struct client_state *csp)
1409 jb_err err = JB_ERR_OK;
1411 static const struct parsers server_patterns_light[] = {
1412 { "Content-Length:", 15, server_adjust_content_length },
1413 { "Transfer-Encoding:", 18, server_transfer_coding },
1415 { "Content-Encoding:", 17, server_adjust_content_encoding },
1416 #endif /* def FEATURE_ZLIB */
1420 if (strncmpic(csp->http->cmd, "HEAD", 4))
1422 const struct parsers *v;
1423 struct list_entry *p;
1425 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1427 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1429 /* Header crunch()ed in previous run? -> ignore */
1430 if (p->str == NULL) continue;
1432 /* Does the current parser handle this header? */
1433 if (strncmpic(p->str, v->str, v->len) == 0)
1435 err = v->parser(csp, (char **)&(p->str));
1441 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1442 if ((JB_ERR_OK == err)
1443 && (csp->flags & CSP_FLAG_MODIFIED)
1444 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1445 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1449 create_content_length_header(csp->content_length, header, sizeof(header));
1450 err = enlist(csp->headers, header);
1451 if (JB_ERR_OK == err)
1453 log_error(LOG_LEVEL_HEADER,
1454 "Content modified with no Content-Length header set. "
1455 "Created: %s.", header);
1456 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1459 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1461 #ifdef FEATURE_COMPRESSION
1462 if ((JB_ERR_OK == err)
1463 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1465 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1466 if (JB_ERR_OK == err)
1468 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1477 /*********************************************************************
1479 * Function : header_tagger
1481 * Description : Executes all text substitutions from applying
1482 * tag actions and saves the result as tag.
1484 * XXX: Shares enough code with filter_header() and
1485 * pcrs_filter_response() to warrant some helper functions.
1488 * 1 : csp = Current client state (buffers, headers, etc...)
1489 * 2 : header = Header that is used as tagger input
1491 * Returns : JB_ERR_OK on success and always succeeds
1493 *********************************************************************/
1494 static jb_err header_tagger(struct client_state *csp, char *header)
1496 enum filter_type wanted_filter_type;
1497 int multi_action_index;
1500 struct re_filterfile_spec *b;
1501 struct list_entry *tag_name;
1503 const size_t header_length = strlen(header);
1505 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1507 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1508 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1512 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1513 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1516 if (list_is_empty(csp->action->multi[multi_action_index])
1517 || filters_available(csp) == FALSE)
1519 /* Return early if no taggers apply or if none are available. */
1523 /* Execute all applying taggers */
1524 for (tag_name = csp->action->multi[multi_action_index]->first;
1525 NULL != tag_name; tag_name = tag_name->next)
1527 char *modified_tag = NULL;
1529 size_t size = header_length;
1532 b = get_filter(csp, tag_name->str, wanted_filter_type);
1538 joblist = b->joblist;
1540 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1542 if (NULL == joblist)
1544 log_error(LOG_LEVEL_TAGGING,
1545 "Tagger %s has empty joblist. Nothing to do.", b->name);
1549 /* execute their pcrs_joblist on the header. */
1550 for (job = joblist; NULL != job; job = job->next)
1552 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1556 /* Success, continue with the modified version. */
1565 /* Tagger doesn't match */
1568 /* Regex failure, log it but continue anyway. */
1569 assert(NULL != header);
1570 log_error(LOG_LEVEL_ERROR,
1571 "Problems with tagger \'%s\' and header \'%s\': %s",
1572 b->name, header, pcrs_strerror(hits));
1574 freez(modified_tag);
1578 if (b->dynamic) pcrs_free_joblist(joblist);
1580 /* If this tagger matched */
1586 * There is no technical limitation which makes
1587 * it impossible to use empty tags, but I assume
1588 * no one would do it intentionally.
1591 log_error(LOG_LEVEL_TAGGING,
1592 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1596 if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
1598 log_error(LOG_LEVEL_TAGGING,
1599 "Tagger \'%s\' didn't add tag \'%s\': suppressed",
1605 if (!list_contains_item(csp->tags, tag))
1607 if (JB_ERR_OK != enlist(csp->tags, tag))
1609 log_error(LOG_LEVEL_ERROR,
1610 "Insufficient memory to add tag \'%s\', "
1611 "based on tagger \'%s\' and header \'%s\'",
1612 tag, b->name, header);
1616 char *action_message;
1618 * update the action bits right away, to make
1619 * tagging based on tags set by earlier taggers
1620 * of the same kind possible.
1622 if (update_action_bits_for_tag(csp, tag))
1624 action_message = "Action bits updated accordingly.";
1628 action_message = "No action bits update necessary.";
1631 log_error(LOG_LEVEL_TAGGING,
1632 "Tagger \'%s\' added tag \'%s\'. %s",
1633 b->name, tag, action_message);
1638 /* XXX: Is this log-worthy? */
1639 log_error(LOG_LEVEL_TAGGING,
1640 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1650 /* here begins the family of parser functions that reformat header lines */
1652 /*********************************************************************
1654 * Function : filter_header
1656 * Description : Executes all text substitutions from all applying
1657 * +(server|client)-header-filter actions on the header.
1658 * Most of the code was copied from pcrs_filter_response,
1659 * including the rather short variable names
1662 * 1 : csp = Current client state (buffers, headers, etc...)
1663 * 2 : header = On input, pointer to header to modify.
1664 * On output, pointer to the modified header, or NULL
1665 * to remove the header. This function frees the
1666 * original string if necessary.
1668 * Returns : JB_ERR_OK on success and always succeeds
1670 *********************************************************************/
1671 static jb_err filter_header(struct client_state *csp, char **header)
1675 size_t size = strlen(*header);
1677 char *newheader = NULL;
1680 struct re_filterfile_spec *b;
1681 struct list_entry *filtername;
1683 enum filter_type wanted_filter_type;
1684 int multi_action_index;
1686 if (csp->flags & CSP_FLAG_NO_FILTERING)
1691 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1693 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1694 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1698 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1699 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1702 if (list_is_empty(csp->action->multi[multi_action_index])
1703 || filters_available(csp) == FALSE)
1705 /* Return early if no filters apply or if none are available. */
1709 /* Execute all applying header filters */
1710 for (filtername = csp->action->multi[multi_action_index]->first;
1711 filtername != NULL; filtername = filtername->next)
1713 int current_hits = 0;
1716 b = get_filter(csp, filtername->str, wanted_filter_type);
1722 joblist = b->joblist;
1724 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1726 if (NULL == joblist)
1728 log_error(LOG_LEVEL_RE_FILTER,
1729 "Filter %s has empty joblist. Nothing to do.", b->name);
1733 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %lu) with \'%s\' ...",
1734 *header, size, b->name);
1736 /* Apply all jobs from the joblist */
1737 for (job = joblist; NULL != job; job = job->next)
1739 matches = pcrs_execute(job, *header, size, &newheader, &size);
1742 current_hits += matches;
1743 log_error(LOG_LEVEL_HEADER,
1744 "Transforming \"%s\" to \"%s\"", *header, newheader);
1746 *header = newheader;
1748 else if (0 == matches)
1750 /* Filter doesn't change header */
1756 log_error(LOG_LEVEL_ERROR,
1757 "Filtering \'%s\' with \'%s\' didn't work out: %s",
1758 *header, b->name, pcrs_strerror(matches));
1759 if (newheader != NULL)
1761 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1767 if (b->dynamic) pcrs_free_joblist(joblist);
1769 log_error(LOG_LEVEL_RE_FILTER,
1770 "... produced %d hits (new size %lu).", current_hits, size);
1771 hits += current_hits;
1775 * Additionally checking for hits is important because if
1776 * the continue hack is triggered, server headers can
1777 * arrive empty to separate multiple heads from each other.
1779 if ((0 == size) && hits)
1781 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1789 /*********************************************************************
1791 * Function : server_connection
1793 * Description : Makes sure a proper "Connection:" header is
1794 * set and signals connection_header_adder to
1798 * 1 : csp = Current client state (buffers, headers, etc...)
1799 * 2 : header = On input, pointer to header to modify.
1800 * On output, pointer to the modified header, or NULL
1801 * to remove the header. This function frees the
1802 * original string if necessary.
1804 * Returns : JB_ERR_OK on success.
1806 *********************************************************************/
1807 static jb_err server_connection(struct client_state *csp, char **header)
1809 if (!strcmpic(*header, "Connection: keep-alive")
1810 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1811 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1815 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1816 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1818 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1821 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1823 log_error(LOG_LEVEL_HEADER,
1824 "Keeping the server header '%s' around.", *header);
1827 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1829 char *old_header = *header;
1831 *header = strdup_or_die("Connection: close");
1832 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1837 /* Signal server_connection_adder() to return early. */
1838 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1844 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1845 /*********************************************************************
1847 * Function : server_keep_alive
1849 * Description : Stores the server's keep alive timeout.
1852 * 1 : csp = Current client state (buffers, headers, etc...)
1853 * 2 : header = On input, pointer to header to modify.
1854 * On output, pointer to the modified header, or NULL
1855 * to remove the header. This function frees the
1856 * original string if necessary.
1858 * Returns : JB_ERR_OK.
1860 *********************************************************************/
1861 static jb_err server_keep_alive(struct client_state *csp, char **header)
1863 unsigned int keep_alive_timeout;
1864 const char *timeout_position = strstr(*header, "timeout=");
1866 if ((NULL == timeout_position)
1867 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1869 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1873 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1875 log_error(LOG_LEVEL_HEADER,
1876 "Reducing keep-alive timeout from %u to %u.",
1877 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1878 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1882 /* XXX: Is this log worthy? */
1883 log_error(LOG_LEVEL_HEADER,
1884 "Server keep-alive timeout is %u. Sticking with %u.",
1885 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1887 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1896 /*********************************************************************
1898 * Function : server_proxy_connection
1900 * Description : Figures out whether or not we should add a
1901 * Proxy-Connection header.
1904 * 1 : csp = Current client state (buffers, headers, etc...)
1905 * 2 : header = On input, pointer to header to modify.
1906 * On output, pointer to the modified header, or NULL
1907 * to remove the header. This function frees the
1908 * original string if necessary.
1910 * Returns : JB_ERR_OK.
1912 *********************************************************************/
1913 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1915 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1918 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1921 /*********************************************************************
1923 * Function : proxy_authentication
1925 * Description : Removes headers that are relevant for proxy
1926 * authentication unless forwarding them has
1927 * been explicitly requested.
1930 * 1 : csp = Current client state (buffers, headers, etc...)
1931 * 2 : header = On input, pointer to header to modify.
1932 * On output, pointer to the modified header, or NULL
1933 * to remove the header. This function frees the
1934 * original string if necessary.
1936 * Returns : JB_ERR_OK.
1938 *********************************************************************/
1939 static jb_err proxy_authentication(struct client_state *csp, char **header)
1941 if ((csp->config->feature_flags &
1942 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1943 log_error(LOG_LEVEL_HEADER,
1944 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1951 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1952 /*********************************************************************
1954 * Function : client_keep_alive
1956 * Description : Stores the client's keep alive timeout.
1959 * 1 : csp = Current client state (buffers, headers, etc...)
1960 * 2 : header = On input, pointer to header to modify.
1961 * On output, pointer to the modified header, or NULL
1962 * to remove the header. This function frees the
1963 * original string if necessary.
1965 * Returns : JB_ERR_OK.
1967 *********************************************************************/
1968 static jb_err client_keep_alive(struct client_state *csp, char **header)
1970 unsigned int keep_alive_timeout;
1971 char *timeout_position;
1973 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1975 log_error(LOG_LEVEL_HEADER,
1976 "keep-alive support is disabled. Crunching: %s.", *header);
1981 /* Check for parameter-less format "Keep-Alive: 100" */
1982 timeout_position = strstr(*header, ": ");
1983 if ((NULL == timeout_position)
1984 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1986 /* Assume parameter format "Keep-Alive: timeout=100" */
1987 timeout_position = strstr(*header, "timeout=");
1988 if ((NULL == timeout_position)
1989 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1991 log_error(LOG_LEVEL_HEADER,
1992 "Couldn't parse: '%s'. Using default timeout %u",
1993 *header, csp->config->keep_alive_timeout);
2000 if (keep_alive_timeout < csp->config->keep_alive_timeout)
2002 log_error(LOG_LEVEL_HEADER,
2003 "Reducing keep-alive timeout from %u to %u.",
2004 csp->config->keep_alive_timeout, keep_alive_timeout);
2005 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
2009 /* XXX: Is this log worthy? */
2010 log_error(LOG_LEVEL_HEADER,
2011 "Client keep-alive timeout is %u. Sticking with %u.",
2012 keep_alive_timeout, csp->config->keep_alive_timeout);
2018 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2021 /*********************************************************************
2023 * Function : get_content_length
2025 * Description : Gets the content length specified in a
2026 * Content-Length header.
2029 * 1 : header_value = The Content-Length header value.
2030 * 2 : length = Storage to return the value.
2032 * Returns : JB_ERR_OK on success, or
2033 * JB_ERR_PARSE if no value is recognized.
2035 *********************************************************************/
2036 static jb_err get_content_length(const char *header_value, unsigned long long *length)
2039 #if SIZEOF_LONG_LONG < 8
2040 #error sizeof(unsigned long long) too small
2042 if (1 != sscanf(header_value, "%I64u", length))
2044 if (1 != sscanf(header_value, "%llu", length))
2047 return JB_ERR_PARSE;
2054 /*********************************************************************
2056 * Function : client_save_content_length
2058 * Description : Save the Content-Length sent by the client.
2061 * 1 : csp = Current client state (buffers, headers, etc...)
2062 * 2 : header = pointer to the Content-Length header
2064 * Returns : JB_ERR_OK on success, or
2065 * JB_ERR_MEMORY on out-of-memory error.
2067 *********************************************************************/
2068 static jb_err client_save_content_length(struct client_state *csp, char **header)
2070 unsigned long long content_length = 0;
2071 const char *header_value;
2073 assert(*(*header+14) == ':');
2075 header_value = *header + 15;
2076 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2078 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2083 csp->expected_client_content_length = content_length;
2090 /*********************************************************************
2092 * Function : client_connection
2094 * Description : Makes sure a proper "Connection:" header is
2095 * set and signals connection_header_adder
2099 * 1 : csp = Current client state (buffers, headers, etc...)
2100 * 2 : header = On input, pointer to header to modify.
2101 * On output, pointer to the modified header, or NULL
2102 * to remove the header. This function frees the
2103 * original string if necessary.
2105 * Returns : JB_ERR_OK on success.
2107 *********************************************************************/
2108 static jb_err client_connection(struct client_state *csp, char **header)
2110 static const char connection_close[] = "Connection: close";
2112 if (!strcmpic(*header, connection_close))
2114 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2115 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2116 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2117 #ifdef FEATURE_HTTPS_INSPECTION
2118 && !client_use_ssl(csp)
2122 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2124 log_error(LOG_LEVEL_HEADER,
2125 "Removing \'%s\' to imply keep-alive.", *header);
2128 * While we imply keep-alive to the server,
2129 * we have to remember that the client didn't.
2131 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2135 char *old_header = *header;
2137 *header = strdup_or_die("Connection: keep-alive");
2138 log_error(LOG_LEVEL_HEADER,
2139 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2145 log_error(LOG_LEVEL_HEADER,
2146 "Keeping the client header '%s' around. "
2147 "The connection will not be kept alive.",
2149 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2152 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2153 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2155 log_error(LOG_LEVEL_HEADER,
2156 "Keeping the client header '%s' around. "
2157 "The server connection will be kept alive if possible.",
2159 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2160 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2164 char *old_header = *header;
2166 *header = strdup_or_die(connection_close);
2167 log_error(LOG_LEVEL_HEADER,
2168 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2172 /* Signal client_connection_header_adder() to return early. */
2173 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2179 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2180 /*********************************************************************
2182 * Function : client_proxy_connection
2184 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2185 * appropriate and removes the Proxy-Connection
2189 * 1 : csp = Current client state (buffers, headers, etc...)
2190 * 2 : header = On input, pointer to header to modify.
2191 * On output, pointer to the modified header, or NULL
2192 * to remove the header. This function frees the
2193 * original string if necessary.
2195 * Returns : JB_ERR_OK
2197 *********************************************************************/
2198 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2200 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2201 && (csp->http->ssl == 0)
2202 && (NULL == strstr(*header, "close")))
2204 log_error(LOG_LEVEL_HEADER,
2205 "The client connection can be kept alive due to: %s", *header);
2206 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2208 crumble(csp, header);
2212 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2215 /*********************************************************************
2217 * Function : client_transfer_encoding
2219 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2220 * the request body is "chunked"
2222 * XXX: Currently not called through sed() as we
2223 * need the flag earlier on. Should be fixed.
2226 * 1 : csp = Current client state (buffers, headers, etc...)
2227 * 2 : header = On input, pointer to header to modify.
2228 * On output, pointer to the modified header, or NULL
2229 * to remove the header. This function frees the
2230 * original string if necessary.
2232 * Returns : JB_ERR_OK on success, or
2234 *********************************************************************/
2235 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2237 if (strstr(*header, "chunked"))
2239 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2240 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2247 /*********************************************************************
2249 * Function : client_expect
2251 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2252 * if the Expect header value is unsupported.
2254 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2255 * MAY and a RFC 2616 (obsolete) MUST.
2258 * 1 : csp = Current client state (buffers, headers, etc...)
2259 * 2 : header = On input, pointer to header to modify.
2260 * On output, pointer to the modified header, or NULL
2261 * to remove the header. This function frees the
2262 * original string if necessary.
2264 * Returns : JB_ERR_OK on success, or
2266 *********************************************************************/
2267 jb_err client_expect(struct client_state *csp, char **header)
2269 if (0 != strcmpic(*header, "Expect: 100-continue"))
2271 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2272 log_error(LOG_LEVEL_HEADER,
2273 "Unsupported client expectaction: %s", *header);
2281 /*********************************************************************
2283 * Function : crumble
2285 * Description : This is called if a header matches a pattern to "crunch"
2288 * 1 : csp = Current client state (buffers, headers, etc...)
2289 * 2 : header = On input, pointer to header to modify.
2290 * On output, pointer to the modified header, or NULL
2291 * to remove the header. This function frees the
2292 * original string if necessary.
2294 * Returns : JB_ERR_OK on success, or
2295 * JB_ERR_MEMORY on out-of-memory error.
2297 *********************************************************************/
2298 static jb_err crumble(struct client_state *csp, char **header)
2301 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2307 /*********************************************************************
2309 * Function : crunch_server_header
2311 * Description : Crunch server header if it matches a string supplied by the
2312 * user. Called from `sed'.
2315 * 1 : csp = Current client state (buffers, headers, etc...)
2316 * 2 : header = On input, pointer to header to modify.
2317 * On output, pointer to the modified header, or NULL
2318 * to remove the header. This function frees the
2319 * original string if necessary.
2321 * Returns : JB_ERR_OK on success and always succeeds
2323 *********************************************************************/
2324 static jb_err crunch_server_header(struct client_state *csp, char **header)
2326 const char *crunch_pattern;
2328 /* Do we feel like crunching? */
2329 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2331 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2333 /* Is the current header the lucky one? */
2334 if (strstr(*header, crunch_pattern))
2336 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2345 /*********************************************************************
2347 * Function : server_content_type
2349 * Description : Set the content-type for filterable types (text/.*,
2350 * .*xml.*, .*script.* and image/gif) unless filtering has been
2351 * forbidden (CT_TABOO) while parsing earlier headers.
2352 * NOTE: Since text/plain is commonly used by web servers
2353 * for files whose correct type is unknown, we don't
2354 * set CT_TEXT for it.
2357 * 1 : csp = Current client state (buffers, headers, etc...)
2358 * 2 : header = On input, pointer to header to modify.
2359 * On output, pointer to the modified header, or NULL
2360 * to remove the header. This function frees the
2361 * original string if necessary.
2363 * Returns : JB_ERR_OK on success, or
2364 * JB_ERR_MEMORY on out-of-memory error.
2366 *********************************************************************/
2367 static jb_err server_content_type(struct client_state *csp, char **header)
2369 /* Remove header if it isn't the first Content-Type header */
2370 if ((csp->content_type & CT_DECLARED))
2372 if (content_filters_enabled(csp->action))
2375 * Making sure the client interprets the content the same way
2376 * Privoxy did is only relevant if Privoxy modified it.
2378 * Checking for this is "hard" as it's not yet known when
2379 * this function is called, thus go shopping and and just
2380 * check if Privoxy could filter it.
2382 * The main thing is that we don't mess with the headers
2383 * unless the user signalled that it's acceptable.
2385 log_error(LOG_LEVEL_HEADER,
2386 "Multiple Content-Type headers detected. "
2387 "Removing and ignoring: %s",
2395 * Signal that the Content-Type has been set.
2397 csp->content_type |= CT_DECLARED;
2399 if (!(csp->content_type & CT_TABOO))
2402 * XXX: The assumption that text/plain is a sign of
2403 * binary data seems to be somewhat unreasonable nowadays
2404 * and should be dropped after 3.0.8 is out.
2406 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2407 || strstr(*header, "xml")
2408 || strstr(*header, "script"))
2410 csp->content_type |= CT_TEXT;
2412 else if (strstr(*header, "image/gif"))
2414 csp->content_type |= CT_GIF;
2419 * Are we messing with the content type?
2421 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2424 * Make sure the user doesn't accidentally
2425 * change the content type of binary documents.
2427 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2431 *header = strdup_or_die("Content-Type: ");
2433 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2434 if (JB_ERR_OK != err)
2436 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2437 return JB_ERR_MEMORY;
2439 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2443 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2444 "It doesn't look like a content type that should be filtered. "
2445 "Enable force-text-mode if you know what you're doing.", *header);
2453 /*********************************************************************
2455 * Function : server_transfer_coding
2457 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2458 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2459 * - Remove header if body was chunked but has been
2460 * de-chunked for filtering.
2463 * 1 : csp = Current client state (buffers, headers, etc...)
2464 * 2 : header = On input, pointer to header to modify.
2465 * On output, pointer to the modified header, or NULL
2466 * to remove the header. This function frees the
2467 * original string if necessary.
2469 * Returns : JB_ERR_OK on success, or
2470 * JB_ERR_MEMORY on out-of-memory error.
2472 *********************************************************************/
2473 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2476 * Turn off pcrs and gif filtering if body compressed
2478 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2482 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2484 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2485 csp->http->cmd, *header);
2486 #endif /* def FEATURE_ZLIB */
2487 csp->content_type = CT_TABOO;
2491 * Raise flag if body chunked
2493 if (strstr(*header, "chunked"))
2495 csp->flags |= CSP_FLAG_CHUNKED;
2498 * If the body was modified, it has been de-chunked first
2499 * and the header must be removed.
2501 * FIXME: If there is more than one transfer encoding,
2502 * only the "chunked" part should be removed here.
2504 if (csp->flags & CSP_FLAG_MODIFIED)
2506 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2515 /*********************************************************************
2517 * Function : server_content_encoding
2519 * Description : Used to check if the content is compressed, and if
2520 * FEATURE_ZLIB is disabled, filtering is disabled as
2523 * If FEATURE_ZLIB is enabled and the compression type
2524 * supported, the content is marked for decompression.
2526 * XXX: Doesn't properly deal with multiple or with
2527 * unsupported but unknown encodings.
2528 * Is case-sensitive but shouldn't be.
2531 * 1 : csp = Current client state (buffers, headers, etc...)
2532 * 2 : header = On input, pointer to header to modify.
2533 * On output, pointer to the modified header, or NULL
2534 * to remove the header. This function frees the
2535 * original string if necessary.
2537 * Returns : JB_ERR_OK on success, or
2538 * JB_ERR_MEMORY on out-of-memory error.
2540 *********************************************************************/
2541 static jb_err server_content_encoding(struct client_state *csp, char **header)
2544 if (strstr(*header, "sdch"))
2547 * Shared Dictionary Compression over HTTP isn't supported,
2548 * filtering it anyway is pretty much guaranteed to mess up
2551 csp->content_type |= CT_TABOO;
2554 * Log a warning if the user expects the content to be filtered.
2556 if (content_filters_enabled(csp->action))
2558 log_error(LOG_LEVEL_INFO,
2559 "SDCH-compressed content detected, content filtering disabled. "
2560 "Consider suppressing SDCH offers made by the client.");
2563 else if (strstr(*header, "gzip"))
2565 /* Mark for gzip decompression */
2566 csp->content_type |= CT_GZIP;
2568 else if (strstr(*header, "deflate"))
2570 /* Mark for zlib decompression */
2571 csp->content_type |= CT_DEFLATE;
2573 else if (strstr(*header, "br"))
2575 #ifdef FEATURE_BROTLI
2576 /* Mark for Brotli decompression */
2577 csp->content_type |= CT_BROTLI;
2579 csp->content_type |= CT_TABOO;
2582 else if (strstr(*header, "compress"))
2585 * We can't decompress this; therefore we can't filter
2588 csp->content_type |= CT_TABOO;
2590 #else /* !defined(FEATURE_ZLIB) */
2592 * XXX: Using a black list here isn't the right approach.
2594 * In case of SDCH, building with zlib support isn't
2597 if (strstr(*header, "gzip") ||
2598 strstr(*header, "compress") ||
2599 strstr(*header, "deflate") ||
2600 strstr(*header, "sdch"))
2603 * Body is compressed, turn off pcrs and gif filtering.
2605 csp->content_type |= CT_TABOO;
2608 * Log a warning if the user expects the content to be filtered.
2610 if (content_filters_enabled(csp->action))
2612 log_error(LOG_LEVEL_INFO,
2613 "Compressed content detected, content filtering disabled. "
2614 "Consider recompiling Privoxy with zlib support or "
2615 "enable the prevent-compression action.");
2618 #endif /* defined(FEATURE_ZLIB) */
2626 /*********************************************************************
2628 * Function : server_adjust_content_encoding
2630 * Description : Remove the Content-Encoding header if the
2631 * decompression was successful and the content
2632 * has been modified.
2635 * 1 : csp = Current client state (buffers, headers, etc...)
2636 * 2 : header = On input, pointer to header to modify.
2637 * On output, pointer to the modified header, or NULL
2638 * to remove the header. This function frees the
2639 * original string if necessary.
2641 * Returns : JB_ERR_OK on success, or
2642 * JB_ERR_MEMORY on out-of-memory error.
2644 *********************************************************************/
2645 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2647 if ((csp->flags & CSP_FLAG_MODIFIED)
2648 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2649 #ifdef FEATURE_BROTLI
2650 || (csp->content_type & CT_BROTLI)
2656 * We successfully decompressed the content,
2657 * and have to clean the header now, so the
2658 * client no longer expects compressed data.
2660 * XXX: There is a difference between cleaning
2661 * and removing it completely.
2663 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2670 #endif /* defined(FEATURE_ZLIB) */
2673 /*********************************************************************
2675 * Function : header_adjust_content_length
2677 * Description : Replace given header with new Content-Length header.
2680 * 1 : header = On input, pointer to header to modify.
2681 * On output, pointer to the modified header, or NULL
2682 * to remove the header. This function frees the
2683 * original string if necessary.
2684 * 2 : content_length = content length value to set
2686 * Returns : JB_ERR_OK on success, or
2687 * JB_ERR_MEMORY on out-of-memory error.
2689 *********************************************************************/
2690 jb_err header_adjust_content_length(char **header, size_t content_length)
2692 const size_t header_length = 50;
2694 *header = malloc(header_length);
2695 if (*header == NULL)
2697 return JB_ERR_MEMORY;
2699 create_content_length_header(content_length, *header, header_length);
2704 /*********************************************************************
2706 * Function : server_adjust_content_length
2708 * Description : Adjust Content-Length header if we modified
2712 * 1 : csp = Current client state (buffers, headers, etc...)
2713 * 2 : header = On input, pointer to header to modify.
2714 * On output, pointer to the modified header, or NULL
2715 * to remove the header. This function frees the
2716 * original string if necessary.
2718 * Returns : JB_ERR_OK on success, or
2719 * JB_ERR_MEMORY on out-of-memory error.
2721 *********************************************************************/
2722 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2724 /* Regenerate header if the content was modified. */
2725 if (csp->flags & CSP_FLAG_MODIFIED)
2727 if (JB_ERR_OK != header_adjust_content_length(header, csp->content_length))
2729 return JB_ERR_MEMORY;
2731 log_error(LOG_LEVEL_HEADER,
2732 "Adjusted Content-Length to %llu", csp->content_length);
2739 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2740 /*********************************************************************
2742 * Function : server_save_content_length
2744 * Description : Save the Content-Length sent by the server.
2747 * 1 : csp = Current client state (buffers, headers, etc...)
2748 * 2 : header = On input, pointer to header to modify.
2749 * On output, pointer to the modified header, or NULL
2750 * to remove the header. This function frees the
2751 * original string if necessary.
2753 * Returns : JB_ERR_OK on success, or
2754 * JB_ERR_MEMORY on out-of-memory error.
2756 *********************************************************************/
2757 static jb_err server_save_content_length(struct client_state *csp, char **header)
2759 unsigned long long content_length = 0;
2760 const char *header_value;
2762 assert(*(*header+14) == ':');
2764 header_value = *header + 15;
2765 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2767 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2772 csp->expected_content_length = content_length;
2773 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2774 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2779 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2782 /*********************************************************************
2784 * Function : server_content_md5
2786 * Description : Crumble any Content-MD5 headers if the document was
2787 * modified. FIXME: Should we re-compute instead?
2790 * 1 : csp = Current client state (buffers, headers, etc...)
2791 * 2 : header = On input, pointer to header to modify.
2792 * On output, pointer to the modified header, or NULL
2793 * to remove the header. This function frees the
2794 * original string if necessary.
2796 * Returns : JB_ERR_OK on success, or
2797 * JB_ERR_MEMORY on out-of-memory error.
2799 *********************************************************************/
2800 static jb_err server_content_md5(struct client_state *csp, char **header)
2802 if (csp->flags & CSP_FLAG_MODIFIED)
2804 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2812 /*********************************************************************
2814 * Function : server_content_disposition
2816 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2817 * Called from `sed'.
2820 * 1 : csp = Current client state (buffers, headers, etc...)
2821 * 2 : header = On input, pointer to header to modify.
2822 * On output, pointer to the modified header, or NULL
2823 * to remove the header. This function frees the
2824 * original string if necessary.
2826 * Returns : JB_ERR_OK on success, or
2827 * JB_ERR_MEMORY on out-of-memory error.
2829 *********************************************************************/
2830 static jb_err server_content_disposition(struct client_state *csp, char **header)
2835 * Are we messing with the Content-Disposition header?
2837 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2843 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2845 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2848 * Blocking content-disposition header
2850 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2857 * Replacing Content-Disposition header
2860 *header = strdup("Content-Disposition: ");
2861 string_append(header, newval);
2863 if (*header != NULL)
2865 log_error(LOG_LEVEL_HEADER,
2866 "Content-Disposition header crunched and replaced with: %s", *header);
2869 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2873 /*********************************************************************
2875 * Function : server_last_modified
2877 * Description : Changes Last-Modified header to the actual date
2878 * to help hide-if-modified-since.
2879 * Called from `sed'.
2882 * 1 : csp = Current client state (buffers, headers, etc...)
2883 * 2 : header = On input, pointer to header to modify.
2884 * On output, pointer to the modified header, or NULL
2885 * to remove the header. This function frees the
2886 * original string if necessary.
2888 * Returns : JB_ERR_OK on success, or
2889 * JB_ERR_MEMORY on out-of-memory error.
2891 *********************************************************************/
2892 static jb_err server_last_modified(struct client_state *csp, char **header)
2895 time_t last_modified;
2899 * Are we messing with the Last-Modified header?
2901 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2907 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2909 if (0 == strcmpic(newval, "block"))
2912 * Blocking Last-Modified header. Useless but why not.
2914 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2918 else if (0 == strcmpic(newval, "reset-to-request-time"))
2921 * Setting Last-Modified Header to now.
2924 get_http_time(0, buf, sizeof(buf));
2926 *header = strdup("Last-Modified: ");
2927 string_append(header, buf);
2929 if (*header == NULL)
2931 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2935 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2938 else if (0 == strcmpic(newval, "randomize"))
2940 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2942 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2944 log_error(LOG_LEVEL_HEADER,
2945 "Couldn't parse time in %s (crunching!)", *header);
2951 struct tm *timeptr = NULL;
2956 rtime = (long int)difftime(now, last_modified);
2959 long int days, hours, minutes, seconds;
2960 const int negative_delta = (rtime < 0);
2965 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2967 rtime = pick_from_range(rtime);
2972 last_modified += rtime;
2973 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2974 if ((NULL == timeptr) || !strftime(newheader,
2975 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2977 log_error(LOG_LEVEL_ERROR,
2978 "Randomizing '%s' failed. Crunching the header without replacement.",
2984 *header = strdup("Last-Modified: ");
2985 string_append(header, newheader);
2987 if (*header == NULL)
2989 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2990 return JB_ERR_MEMORY;
2993 days = rtime / (3600 * 24);
2994 hours = rtime / 3600 % 24;
2995 minutes = rtime / 60 % 60;
2996 seconds = rtime % 60;
2998 log_error(LOG_LEVEL_HEADER,
2999 "Randomized: %s (added %ld da%s %ld hou%s %ld minut%s %ld second%s",
3000 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3001 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3005 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3014 /*********************************************************************
3016 * Function : client_accept_encoding
3018 * Description : Rewrite the client's Accept-Encoding header so that
3019 * if doesn't allow compression, if the action applies.
3020 * Note: For HTTP/1.0 the absence of the header is enough.
3023 * 1 : csp = Current client state (buffers, headers, etc...)
3024 * 2 : header = On input, pointer to header to modify.
3025 * On output, pointer to the modified header, or NULL
3026 * to remove the header. This function frees the
3027 * original string if necessary.
3029 * Returns : JB_ERR_OK on success, or
3030 * JB_ERR_MEMORY on out-of-memory error.
3032 *********************************************************************/
3033 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3035 #ifdef FEATURE_COMPRESSION
3036 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
3037 && strstr(*header, "deflate"))
3039 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
3042 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3044 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3052 /*********************************************************************
3054 * Function : client_te
3056 * Description : Rewrite the client's TE header so that
3057 * if doesn't allow compression, if the action applies.
3060 * 1 : csp = Current client state (buffers, headers, etc...)
3061 * 2 : header = On input, pointer to header to modify.
3062 * On output, pointer to the modified header, or NULL
3063 * to remove the header. This function frees the
3064 * original string if necessary.
3066 * Returns : JB_ERR_OK on success, or
3067 * JB_ERR_MEMORY on out-of-memory error.
3069 *********************************************************************/
3070 static jb_err client_te(struct client_state *csp, char **header)
3072 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3075 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3082 /*********************************************************************
3084 * Function : client_referrer
3086 * Description : Handle the "referer" config setting properly.
3087 * Called from `sed'.
3090 * 1 : csp = Current client state (buffers, headers, etc...)
3091 * 2 : header = On input, pointer to header to modify.
3092 * On output, pointer to the modified header, or NULL
3093 * to remove the header. This function frees the
3094 * original string if necessary.
3096 * Returns : JB_ERR_OK on success, or
3097 * JB_ERR_MEMORY on out-of-memory error.
3099 *********************************************************************/
3100 static jb_err client_referrer(struct client_state *csp, char **header)
3102 const char *parameter;
3103 /* booleans for parameters we have to check multiple times */
3104 int parameter_conditional_block;
3105 int parameter_conditional_forge;
3107 #ifdef FEATURE_FORCE_LOAD
3109 * Since the referrer can include the prefix even
3110 * if the request itself is non-forced, we must
3111 * clean it unconditionally.
3113 * XXX: strclean is too broad
3115 strclean(*header, FORCE_PREFIX);
3116 #endif /* def FEATURE_FORCE_LOAD */
3118 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3120 /* Nothing left to do */
3124 parameter = csp->action->string[ACTION_STRING_REFERER];
3125 assert(parameter != NULL);
3126 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3127 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3129 if (!parameter_conditional_block && !parameter_conditional_forge)
3132 * As conditional-block and conditional-forge are the only
3133 * parameters that rely on the original referrer, we can
3134 * remove it now for all the others.
3139 if (0 == strcmpic(parameter, "block"))
3141 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3144 else if (parameter_conditional_block || parameter_conditional_forge)
3146 return handle_conditional_hide_referrer_parameter(header,
3147 csp->http->hostport, parameter_conditional_block);
3149 else if (0 == strcmpic(parameter, "forge"))
3151 return create_forged_referrer(header, csp->http->hostport);
3155 /* interpret parameter as user-supplied referer to fake */
3156 return create_fake_referrer(header, parameter);
3161 /*********************************************************************
3163 * Function : client_accept_language
3165 * Description : Handle the "Accept-Language" config setting properly.
3166 * Called from `sed'.
3169 * 1 : csp = Current client state (buffers, headers, etc...)
3170 * 2 : header = On input, pointer to header to modify.
3171 * On output, pointer to the modified header, or NULL
3172 * to remove the header. This function frees the
3173 * original string if necessary.
3175 * Returns : JB_ERR_OK on success, or
3176 * JB_ERR_MEMORY on out-of-memory error.
3178 *********************************************************************/
3179 static jb_err client_accept_language(struct client_state *csp, char **header)
3184 * Are we messing with the Accept-Language?
3186 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3188 /*I don't think so*/
3192 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3194 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3197 * Blocking Accept-Language header
3199 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3206 * Replacing Accept-Language header
3209 *header = strdup("Accept-Language: ");
3210 string_append(header, newval);
3212 if (*header == NULL)
3214 log_error(LOG_LEVEL_ERROR,
3215 "Insufficient memory. Accept-Language header crunched without replacement.");
3219 log_error(LOG_LEVEL_HEADER,
3220 "Accept-Language header crunched and replaced with: %s", *header);
3223 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3227 /*********************************************************************
3229 * Function : crunch_client_header
3231 * Description : Crunch client header if it matches a string supplied by the
3232 * user. Called from `sed'.
3235 * 1 : csp = Current client state (buffers, headers, etc...)
3236 * 2 : header = On input, pointer to header to modify.
3237 * On output, pointer to the modified header, or NULL
3238 * to remove the header. This function frees the
3239 * original string if necessary.
3241 * Returns : JB_ERR_OK on success and always succeeds
3243 *********************************************************************/
3244 static jb_err crunch_client_header(struct client_state *csp, char **header)
3246 const char *crunch_pattern;
3248 /* Do we feel like crunching? */
3249 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3251 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3253 /* Is the current header the lucky one? */
3254 if (strstr(*header, crunch_pattern))
3256 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3264 /*********************************************************************
3266 * Function : client_uagent
3268 * Description : Handle the "user-agent" config setting properly
3269 * and remember its original value to enable browser
3270 * bug workarounds. Called from `sed'.
3273 * 1 : csp = Current client state (buffers, headers, etc...)
3274 * 2 : header = On input, pointer to header to modify.
3275 * On output, pointer to the modified header, or NULL
3276 * to remove the header. This function frees the
3277 * original string if necessary.
3279 * Returns : JB_ERR_OK on success, or
3280 * JB_ERR_MEMORY on out-of-memory error.
3282 *********************************************************************/
3283 static jb_err client_uagent(struct client_state *csp, char **header)
3287 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3292 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3299 *header = strdup("User-Agent: ");
3300 string_append(header, newval);
3302 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3304 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3308 /*********************************************************************
3310 * Function : client_ua
3312 * Description : Handle "ua-" headers properly. Called from `sed'.
3315 * 1 : csp = Current client state (buffers, headers, etc...)
3316 * 2 : header = On input, pointer to header to modify.
3317 * On output, pointer to the modified header, or NULL
3318 * to remove the header. This function frees the
3319 * original string if necessary.
3321 * Returns : JB_ERR_OK on success, or
3322 * JB_ERR_MEMORY on out-of-memory error.
3324 *********************************************************************/
3325 static jb_err client_ua(struct client_state *csp, char **header)
3327 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3329 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3337 /*********************************************************************
3339 * Function : client_from
3341 * Description : Handle the "from" config setting properly.
3342 * Called from `sed'.
3345 * 1 : csp = Current client state (buffers, headers, etc...)
3346 * 2 : header = On input, pointer to header to modify.
3347 * On output, pointer to the modified header, or NULL
3348 * to remove the header. This function frees the
3349 * original string if necessary.
3351 * Returns : JB_ERR_OK on success, or
3352 * JB_ERR_MEMORY on out-of-memory error.
3354 *********************************************************************/
3355 static jb_err client_from(struct client_state *csp, char **header)
3359 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3366 newval = csp->action->string[ACTION_STRING_FROM];
3369 * Are we blocking the e-mail address?
3371 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3373 log_error(LOG_LEVEL_HEADER, "crunched From!");
3377 log_error(LOG_LEVEL_HEADER, " modified");
3379 *header = strdup("From: ");
3380 string_append(header, newval);
3382 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3386 /*********************************************************************
3388 * Function : client_send_cookie
3390 * Description : Crunches the "cookie" header if necessary.
3391 * Called from `sed'.
3393 * XXX: Stupid name, doesn't send squat.
3396 * 1 : csp = Current client state (buffers, headers, etc...)
3397 * 2 : header = On input, pointer to header to modify.
3398 * On output, pointer to the modified header, or NULL
3399 * to remove the header. This function frees the
3400 * original string if necessary.
3402 * Returns : JB_ERR_OK on success, or
3403 * JB_ERR_MEMORY on out-of-memory error.
3405 *********************************************************************/
3406 static jb_err client_send_cookie(struct client_state *csp, char **header)
3408 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3410 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3418 /*********************************************************************
3420 * Function : client_x_forwarded
3422 * Description : Handle the "x-forwarded-for" config setting properly,
3423 * also used in the add_client_headers list. Called from `sed'.
3426 * 1 : csp = Current client state (buffers, headers, etc...)
3427 * 2 : header = On input, pointer to header to modify.
3428 * On output, pointer to the modified header, or NULL
3429 * to remove the header. This function frees the
3430 * original string if necessary.
3432 * Returns : JB_ERR_OK on success, or
3433 * JB_ERR_MEMORY on out-of-memory error.
3435 *********************************************************************/
3436 jb_err client_x_forwarded(struct client_state *csp, char **header)
3438 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3440 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3442 if (0 == strcmpic(parameter, "block"))
3445 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3447 else if (0 == strcmpic(parameter, "add"))
3449 string_append(header, ", ");
3450 string_append(header, csp->ip_addr_str);
3452 if (*header == NULL)
3454 return JB_ERR_MEMORY;
3456 log_error(LOG_LEVEL_HEADER,
3457 "Appended client IP address to %s", *header);
3458 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3462 log_error(LOG_LEVEL_FATAL,
3463 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3471 /*********************************************************************
3473 * Function : client_max_forwards
3475 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3476 * from the value of the Max-Forwards header field.
3479 * 1 : csp = Current client state (buffers, headers, etc...)
3480 * 2 : header = On input, pointer to header to modify.
3481 * On output, pointer to the modified header, or NULL
3482 * to remove the header. This function frees the
3483 * original string if necessary.
3485 * Returns : JB_ERR_OK on success, or
3486 * JB_ERR_MEMORY on out-of-memory error.
3488 *********************************************************************/
3489 static jb_err client_max_forwards(struct client_state *csp, char **header)
3493 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3494 (0 == strcmpic(csp->http->gpc, "options")))
3496 assert(*(*header+12) == ':');
3497 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3499 if (max_forwards > 0)
3501 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3502 log_error(LOG_LEVEL_HEADER,
3503 "Max-Forwards value for %s request reduced to %d.",
3504 csp->http->gpc, max_forwards);
3506 else if (max_forwards < 0)
3508 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3514 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3523 /*********************************************************************
3525 * Function : client_host
3527 * Description : If the request URI did not contain host and
3528 * port information, parse and evaluate the Host
3532 * 1 : csp = Current client state (buffers, headers, etc...)
3533 * 2 : header = On input, pointer to header to modify.
3534 * On output, pointer to the modified header, or NULL
3535 * to remove the header. This function frees the
3536 * original string if necessary.
3538 * Returns : JB_ERR_OK on success, or
3539 * JB_ERR_MEMORY on out-of-memory error.
3541 *********************************************************************/
3542 static jb_err client_host(struct client_state *csp, char **header)
3546 if (strlen(*header) < 7)
3548 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3553 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3554 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3557 p = strdup_or_die((*header)+6);
3559 q = strdup_or_die(p);
3561 freez(csp->http->hostport);
3562 csp->http->hostport = p;
3563 freez(csp->http->host);
3564 csp->http->host = q;
3565 q = strchr(csp->http->host, ':');
3568 /* Terminate hostname and evaluate port string */
3570 csp->http->port = atoi(q);
3574 csp->http->port = csp->http->ssl ? 443 : 80;
3577 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3578 csp->http->hostport, csp->http->host, csp->http->port);
3581 /* Signal client_host_adder() to return right away */
3582 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3588 /*********************************************************************
3590 * Function : client_if_modified_since
3592 * Description : Remove or modify the If-Modified-Since header.
3595 * 1 : csp = Current client state (buffers, headers, etc...)
3596 * 2 : header = On input, pointer to header to modify.
3597 * On output, pointer to the modified header, or NULL
3598 * to remove the header. This function frees the
3599 * original string if necessary.
3601 * Returns : JB_ERR_OK on success, or
3602 * JB_ERR_MEMORY on out-of-memory error.
3604 *********************************************************************/
3605 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3609 struct tm *timeptr = NULL;
3614 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3617 * The client got an error message because of a temporary problem,
3618 * the problem is gone and the client now tries to revalidate our
3619 * error message on the real server. The revalidation would always
3620 * end with the transmission of the whole document and there is
3621 * no need to expose the bogus If-Modified-Since header.
3623 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3626 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3628 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3630 if ((0 == strcmpic(newval, "block")))
3632 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3635 else /* add random value */
3637 if (JB_ERR_OK != parse_time_header(*header, &tm))
3639 log_error(LOG_LEVEL_HEADER,
3640 "Couldn't parse time in %s (crunching!)", *header);
3645 long int hours, minutes, seconds;
3646 long int rtime = strtol(newval, &endptr, 0);
3647 const int negative_range = (rtime < 0);
3651 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %ld minut%s)",
3652 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3658 rtime = pick_from_range(rtime);
3662 log_error(LOG_LEVEL_ERROR,
3663 "Random range is 0. Assuming time transformation test.");
3665 tm += rtime * (negative_range ? -1 : 1);
3666 timeptr = privoxy_gmtime_r(&tm, &gmt);
3667 if ((NULL == timeptr) || !strftime(newheader,
3668 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3670 log_error(LOG_LEVEL_ERROR,
3671 "Randomizing '%s' failed. Crunching the header without replacement.",
3677 *header = strdup("If-Modified-Since: ");
3678 string_append(header, newheader);
3680 if (*header == NULL)
3682 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3683 return JB_ERR_MEMORY;
3686 hours = rtime / 3600;
3687 minutes = rtime / 60 % 60;
3688 seconds = rtime % 60;
3690 log_error(LOG_LEVEL_HEADER,
3691 "Randomized: %s (%s %ld hou%s %ld minut%s %ld second%s",
3692 *header, (negative_range) ? "subtracted" : "added", hours,
3693 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3694 seconds, (seconds == 1) ? ")" : "s)");
3703 /*********************************************************************
3705 * Function : client_if_none_match
3707 * Description : Remove the If-None-Match header.
3710 * 1 : csp = Current client state (buffers, headers, etc...)
3711 * 2 : header = On input, pointer to header to modify.
3712 * On output, pointer to the modified header, or NULL
3713 * to remove the header. This function frees the
3714 * original string if necessary.
3716 * Returns : JB_ERR_OK on success, or
3717 * JB_ERR_MEMORY on out-of-memory error.
3719 *********************************************************************/
3720 static jb_err client_if_none_match(struct client_state *csp, char **header)
3722 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3724 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3732 /*********************************************************************
3734 * Function : client_x_filter
3736 * Description : Disables filtering if the client set "X-Filter: No".
3737 * Called from `sed'.
3740 * 1 : csp = Current client state (buffers, headers, etc...)
3741 * 2 : header = On input, pointer to header to modify.
3742 * On output, pointer to the modified header, or NULL
3743 * to remove the header. This function frees the
3744 * original string if necessary.
3746 * Returns : JB_ERR_OK on success
3748 *********************************************************************/
3749 jb_err client_x_filter(struct client_state *csp, char **header)
3751 if (0 == strcmpic(*header, "X-Filter: No"))
3753 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3755 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3759 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3761 log_error(LOG_LEVEL_HEADER,
3762 "force-text-mode overruled the client's request to fetch without filtering!");
3766 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3767 csp->flags |= CSP_FLAG_NO_FILTERING;
3768 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3770 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3778 /*********************************************************************
3780 * Function : client_range
3782 * Description : Removes Range, Request-Range and If-Range headers if
3783 * content filtering is enabled and the range doesn't
3786 * If the client's version of the document has been
3787 * altered by Privoxy, the server could interpret the
3788 * range differently than the client intended in which
3789 * case the user could end up with corrupted content.
3791 * If the range starts at byte 0 this isn't an issue
3792 * so the header can pass. Partial requests like this
3793 * are used to render preview images for videos without
3794 * downloading the whole video.
3796 * While HTTP doesn't require that range requests are
3797 * honoured and the client could simply abort the download
3798 * after receiving a sufficient amount of data, various
3799 * clients don't handle complete responses to range
3800 * requests gracefully and emit misleading error messages
3804 * 1 : csp = Current client state (buffers, headers, etc...)
3805 * 2 : header = On input, pointer to header to modify.
3806 * On output, pointer to the modified header, or NULL
3807 * to remove the header. This function frees the
3808 * original string if necessary.
3810 * Returns : JB_ERR_OK
3812 *********************************************************************/
3813 static jb_err client_range(struct client_state *csp, char **header)
3815 if (content_filters_enabled(csp->action)
3816 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3818 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3819 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3826 /* the following functions add headers directly to the header list */
3828 /*********************************************************************
3830 * Function : client_host_adder
3832 * Description : Adds the Host: header field if it is missing.
3833 * Called from `sed'.
3836 * 1 : csp = Current client state (buffers, headers, etc...)
3838 * Returns : JB_ERR_OK on success, or
3839 * JB_ERR_MEMORY on out-of-memory error.
3841 *********************************************************************/
3842 static jb_err client_host_adder(struct client_state *csp)
3847 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3849 /* Header already set by the client, nothing to do. */
3853 if (!csp->http->hostport || !*(csp->http->hostport))
3855 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3856 return JB_ERR_PARSE;
3860 * remove 'user:pass@' from 'proto://user:pass@host'
3862 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3868 p = csp->http->hostport;
3871 /* XXX: Just add it, we already made sure that it will be unique */
3872 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3873 err = enlist_unique_header(csp->headers, "Host", p);
3879 /*********************************************************************
3881 * Function : client_xtra_adder
3883 * Description : Used in the add_client_headers list. Called from `sed'.
3886 * 1 : csp = Current client state (buffers, headers, etc...)
3888 * Returns : JB_ERR_OK on success, or
3889 * JB_ERR_MEMORY on out-of-memory error.
3891 *********************************************************************/
3892 static jb_err client_xtra_adder(struct client_state *csp)
3894 struct list_entry *lst;
3897 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3898 lst ; lst = lst->next)
3900 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3901 err = enlist(csp->headers, lst->str);
3913 /*********************************************************************
3915 * Function : client_x_forwarded_for_adder
3917 * Description : Used in the add_client_headers list. Called from `sed'.
3920 * 1 : csp = Current client state (buffers, headers, etc...)
3922 * Returns : JB_ERR_OK on success, or
3923 * JB_ERR_MEMORY on out-of-memory error.
3925 *********************************************************************/
3926 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3928 char *header = NULL;
3931 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3932 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3933 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3936 * If we aren't adding X-Forwarded-For headers,
3937 * or we already appended an existing X-Forwarded-For
3938 * header, there's nothing left to do here.
3943 header = strdup("X-Forwarded-For: ");
3944 string_append(&header, csp->ip_addr_str);
3948 return JB_ERR_MEMORY;
3951 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3952 err = enlist(csp->headers, header);
3959 /*********************************************************************
3961 * Function : server_connection_adder
3963 * Description : Adds an appropriate "Connection:" header to csp->headers
3964 * unless the header was already present. Called from `sed'.
3967 * 1 : csp = Current client state (buffers, headers, etc...)
3969 * Returns : JB_ERR_OK on success, or
3970 * JB_ERR_MEMORY on out-of-memory error.
3972 *********************************************************************/
3973 static jb_err server_connection_adder(struct client_state *csp)
3975 const unsigned int flags = csp->flags;
3976 const char *response_status_line = csp->headers->first->str;
3977 static const char connection_close[] = "Connection: close";
3979 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3980 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3986 * XXX: if we downgraded the response, this check will fail.
3988 if ((csp->config->feature_flags &
3989 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3990 && (NULL != response_status_line)
3991 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3992 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3993 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3997 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3998 "without Connection header implies keep-alive.");
3999 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
4003 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4005 return enlist(csp->headers, connection_close);
4009 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4010 /*********************************************************************
4012 * Function : server_proxy_connection_adder
4014 * Description : Adds a "Proxy-Connection: keep-alive" header to
4015 * csp->headers when appropriate.
4018 * 1 : csp = Current client state (buffers, headers, etc...)
4020 * Returns : JB_ERR_OK on success, or
4021 * JB_ERR_MEMORY on out-of-memory error.
4023 *********************************************************************/
4024 static jb_err server_proxy_connection_adder(struct client_state *csp)
4026 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
4027 jb_err err = JB_ERR_OK;
4029 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4030 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4031 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
4032 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4033 || (csp->flags & CSP_FLAG_CHUNKED))
4034 #ifdef FEATURE_HTTPS_INSPECTION
4035 && !client_use_ssl(csp)
4040 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
4041 err = enlist(csp->headers, proxy_connection_header);
4046 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4049 /*********************************************************************
4051 * Function : client_connection_header_adder
4053 * Description : Adds a proper "Connection:" header to csp->headers
4054 * unless the header was already present or it's a
4055 * CONNECT request. Called from `sed'.
4058 * 1 : csp = Current client state (buffers, headers, etc...)
4060 * Returns : JB_ERR_OK on success, or
4061 * JB_ERR_MEMORY on out-of-memory error.
4063 *********************************************************************/
4064 static jb_err client_connection_header_adder(struct client_state *csp)
4066 static const char connection_close[] = "Connection: close";
4068 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4069 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4075 * In case of CONNECT requests "Connection: close" is implied,
4076 * but actually setting the header has been reported to cause
4077 * problems with some forwarding proxies that close the
4078 * connection prematurely.
4080 if (csp->http->ssl != 0)
4085 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4086 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4087 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4088 && !strcmpic(csp->http->version, "HTTP/1.1"))
4090 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4093 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4095 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4097 return enlist(csp->headers, connection_close);
4101 /*********************************************************************
4103 * Function : server_http
4105 * Description : - Save the HTTP Status into csp->http->status
4106 * - Set CT_TABOO to prevent filtering if the answer
4107 * is a partial range (HTTP status 206)
4108 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4110 * - Normalize the HTTP-version.
4113 * 1 : csp = Current client state (buffers, headers, etc...)
4114 * 2 : header = On input, pointer to header to modify.
4115 * On output, pointer to the modified header, or NULL
4116 * to remove the header. This function frees the
4117 * original string if necessary.
4119 * Returns : JB_ERR_OK on success, or
4120 * JB_ERR_PARSE on fatal parse errors.
4122 *********************************************************************/
4123 static jb_err server_http(struct client_state *csp, char **header)
4125 char *reason_phrase = NULL;
4126 char *new_response_line;
4129 unsigned int major_version;
4130 unsigned int minor_version;
4132 /* Get the reason phrase which start after the second whitespace */
4133 p = strchr(*header, ' ');
4137 reason_phrase = strchr(p, ' ');
4140 if (reason_phrase != NULL)
4146 log_error(LOG_LEVEL_ERROR,
4147 "Response line lacks reason phrase: %s", *header);
4151 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4152 &minor_version, &(csp->http->status)))
4154 log_error(LOG_LEVEL_ERROR,
4155 "Failed to parse the response line: %s", *header);
4156 return JB_ERR_PARSE;
4159 if (csp->http->status == 101 ||
4160 csp->http->status == 206)
4162 csp->content_type = CT_TABOO;
4165 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4168 * According to RFC 7230 2.6 intermediaries MUST send
4169 * their own HTTP-version in forwarded messages.
4171 log_error(LOG_LEVEL_ERROR,
4172 "Unsupported HTTP version. Downgrading to 1.1.");
4177 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4179 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4183 /* Rebuild response line. */
4184 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4185 new_response_line = malloc_or_die(length);
4187 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4188 major_version, minor_version, csp->http->status, reason_phrase);
4190 if (0 != strcmp(*header, new_response_line))
4192 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4193 *header, new_response_line);
4197 *header = new_response_line;
4202 /*********************************************************************
4204 * Function : add_cooky_expiry_date
4206 * Description : Adds a cookie expiry date to a string.
4209 * 1 : cookie = On input, pointer to cookie to modify.
4210 * On output, pointer to the modified header.
4211 * The original string is freed.
4212 * 2 : lifetime = Seconds the cookie should be valid
4216 *********************************************************************/
4217 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4220 struct tm *timeptr = NULL;
4221 time_t expiry_date = time(NULL) + lifetime;
4224 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4225 if (NULL == timeptr)
4227 log_error(LOG_LEVEL_FATAL,
4228 "Failed to get the time in add_cooky_expiry_date()");
4230 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4231 if (JB_ERR_OK != string_append(cookie, tmp))
4233 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4238 /*********************************************************************
4240 * Function : server_set_cookie
4242 * Description : Handle the server "cookie" header properly.
4243 * Crunch, accept or rewrite it to a session cookie.
4244 * Called from `sed'.
4247 * 1 : csp = Current client state (buffers, headers, etc...)
4248 * 2 : header = On input, pointer to header to modify.
4249 * On output, pointer to the modified header, or NULL
4250 * to remove the header. This function frees the
4251 * original string if necessary.
4253 * Returns : JB_ERR_OK on success, or
4254 * JB_ERR_MEMORY on out-of-memory error.
4256 *********************************************************************/
4257 static jb_err server_set_cookie(struct client_state *csp, char **header)
4259 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4261 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4264 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4265 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4269 long cookie_lifetime = 0;
4272 NO_EXPIRY_DATE_SPECIFIED,
4273 EXPIRY_DATE_ACCEPTABLE,
4274 EXPIRY_DATE_UNACCEPTABLE
4275 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4277 /* A variable to store the tag we're working on */
4280 /* Skip "Set-Cookie:" (11 characters) in header */
4281 cur_tag = *header + 11;
4283 /* skip whitespace between "Set-Cookie:" and value */
4284 while (*cur_tag && privoxy_isspace(*cur_tag))
4291 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4293 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4295 cookie_lifetime = strtol(param, NULL, 0);
4296 if (cookie_lifetime < 0)
4298 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4300 cookie_lifetime *= 60;
4303 /* Loop through each tag in the cookie */
4307 char *next_tag = strchr(cur_tag, ';');
4308 if (next_tag != NULL)
4310 /* Skip the ';' character itself */
4313 /* skip whitespace ";" and start of tag */
4314 while (*next_tag && privoxy_isspace(*next_tag))
4321 /* "Next tag" is the end of the string */
4322 next_tag = cur_tag + strlen(cur_tag);
4326 * Check the expiration date to see
4327 * if the cookie is still valid, if yes,
4328 * rewrite it to a session cookie.
4330 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4332 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4334 if ((expiration_date[0] == '"')
4335 && (expiration_date[1] != '\0'))
4338 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4339 * that the expiration date isn't supposed to be quoted,
4340 * but some servers do it anyway.
4345 /* Did we detect the date properly? */
4346 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4349 * Nope, treat it as if it was still valid.
4351 * XXX: Should we remove the whole cookie instead?
4353 log_error(LOG_LEVEL_ERROR,
4354 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4355 string_move(cur_tag, next_tag);
4356 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4361 * Yes. Check if the cookie is still valid.
4363 * If the cookie is already expired it's probably
4364 * a delete cookie and even if it isn't, the browser
4365 * will discard it anyway.
4369 * XXX: timegm() isn't available on some AmigaOS
4370 * versions and our replacement doesn't work.
4372 * Our options are to either:
4374 * - disable session-cookies-only completely if timegm
4377 * - to simply remove all expired tags, like it has
4378 * been done until Privoxy 3.0.6 and to live with
4379 * the consequence that it can cause login/logout
4380 * problems on servers that don't validate their
4381 * input properly, or
4383 * - to replace it with mktime in which
4384 * case there is a slight chance of valid cookies
4385 * passing as already expired.
4387 * This is the way it's currently done and it's not
4388 * as bad as it sounds. If the missing GMT offset is
4389 * enough to change the result of the expiration check
4390 * the cookie will be only valid for a few hours
4391 * anyway, which in many cases will be shorter
4392 * than a browser session.
4394 if (cookie_time < now)
4396 log_error(LOG_LEVEL_HEADER,
4397 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4398 /* Just in case some clown sets more then one expiration date */
4400 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4402 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4404 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4405 "Its lifetime is below the limit.", *header);
4406 /* Just in case some clown sets more then one expiration date */
4408 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4413 * Still valid, delete expiration date by copying
4414 * the rest of the string over it.
4416 string_move(cur_tag, next_tag);
4418 /* That changed the header, need to issue a log message */
4419 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4422 * Note that the next tag has now been moved to *cur_tag,
4423 * so we do not need to update the cur_tag pointer.
4431 /* Move on to next cookie tag */
4436 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4438 assert(NULL != *header);
4439 if (cookie_lifetime != 0)
4441 add_cookie_expiry_date(header, cookie_lifetime);
4442 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4444 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4446 log_error(LOG_LEVEL_HEADER,
4447 "Cookie rewritten to a temporary one: %s", *header);
4456 #ifdef FEATURE_FORCE_LOAD
4457 /*********************************************************************
4459 * Function : strclean
4461 * Description : In-Situ-Eliminate all occurrences of substring in
4465 * 1 : string = string to clean
4466 * 2 : substring = substring to eliminate
4468 * Returns : Number of eliminations
4470 *********************************************************************/
4471 int strclean(char *string, const char *substring)
4477 len = strlen(substring);
4479 while((pos = strstr(string, substring)) != NULL)
4486 while (*p++ != '\0');
4493 #endif /* def FEATURE_FORCE_LOAD */
4496 /*********************************************************************
4498 * Function : parse_header_time
4500 * Description : Parses time formats used in HTTP header strings
4501 * to get the numerical respresentation.
4504 * 1 : header_time = HTTP header time as string.
4505 * 2 : result = storage for header_time in seconds
4507 * Returns : JB_ERR_OK if the time format was recognized, or
4508 * JB_ERR_PARSE otherwise.
4510 *********************************************************************/
4511 static jb_err parse_header_time(const char *header_time, time_t *result)
4515 * Checking for two-digit years first in an
4516 * attempt to work around GNU libc's strptime()
4517 * reporting negative year values when using %Y.
4519 static const char time_formats[][22] = {
4520 /* Tue, 02-Jun-37 20:00:00 */
4521 "%a, %d-%b-%y %H:%M:%S",
4522 /* Tue, 02 Jun 2037 20:00:00 */
4523 "%a, %d %b %Y %H:%M:%S",
4524 /* Tue, 02-Jun-2037 20:00:00 */
4525 "%a, %d-%b-%Y %H:%M:%S",
4526 /* Tuesday, 02-Jun-2037 20:00:00 */
4527 "%A, %d-%b-%Y %H:%M:%S",
4528 /* Tuesday Jun 02 20:00:00 2037 */
4529 "%A %b %d %H:%M:%S %Y"
4533 for (i = 0; i < SZ(time_formats); i++)
4536 * Zero out gmt to prevent time zone offsets.
4537 * Documented to be required for GNU libc.
4539 memset(&gmt, 0, sizeof(gmt));
4541 if (NULL != strptime(header_time, time_formats[i], &gmt))
4543 /* Sanity check for GNU libc. */
4544 if (gmt.tm_year < 0)
4546 log_error(LOG_LEVEL_HEADER,
4547 "Failed to parse '%s' using '%s'. Moving on.",
4548 header_time, time_formats[i]);
4551 *result = timegm(&gmt);
4553 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4555 * Verify that parsing the date recreated from the first
4556 * parse operation gets the previous result. If it doesn't,
4557 * either strptime() or strftime() are malfunctioning.
4559 * We could string-compare the recreated date with the original
4560 * header date, but this leads to false positives as strptime()
4561 * may let %a accept all day formats while strftime() will only
4565 char recreated_date[100];
4570 tm = privoxy_gmtime_r(result, &storage);
4571 if (!strftime(recreated_date, sizeof(recreated_date),
4572 time_formats[i], tm))
4574 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4575 header_time, time_formats[i]);
4578 memset(&gmt, 0, sizeof(gmt));
4579 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4581 log_error(LOG_LEVEL_ERROR,
4582 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4583 recreated_date, time_formats[i], header_time);
4586 result2 = timegm(&gmt);
4587 if (*result != result2)
4589 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4590 "Format: '%s'. In: '%s', out: '%s'. %ld != %ld. Rejecting.",
4591 time_formats[i], header_time, recreated_date, *result, result2);
4601 return JB_ERR_PARSE;
4605 /*********************************************************************
4607 * Function : parse_time_header
4609 * Description : Parses the time in an HTTP time header to get
4610 * the numerical respresentation.
4613 * 1 : header = HTTP header with a time value
4614 * 2 : result = storage for header_time in seconds
4616 * Returns : JB_ERR_OK if the time format was recognized, or
4617 * JB_ERR_PARSE otherwise.
4619 *********************************************************************/
4620 static jb_err parse_time_header(const char *header, time_t *result)
4622 const char *header_time;
4624 header_time = strchr(header, ':');
4627 * Currently this can't happen as all callers are called
4628 * through sed() which requires a header name followed by
4631 if (header_time == NULL)
4633 return JB_ERR_PARSE;
4637 if (*header_time == ' ')
4642 return parse_header_time(header_time, result);
4647 /*********************************************************************
4649 * Function : get_destination_from_headers
4651 * Description : Parse the "Host:" header to get the request's destination.
4652 * Only needed if the client's request was forcefully
4653 * redirected into Privoxy.
4655 * Code mainly copied from client_host() which is currently
4656 * run too late for this purpose.
4659 * 1 : headers = List of headers (one of them hopefully being
4660 * the "Host:" header)
4661 * 2 : http = storage for the result (host, port and hostport).
4663 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4664 * JB_ERR_PARSE if the host header couldn't be found,
4665 * JB_ERR_OK otherwise.
4667 *********************************************************************/
4668 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4674 host = get_header_value(headers, "Host:");
4678 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4679 return JB_ERR_PARSE;
4682 p = string_tolower(host);
4685 return JB_ERR_MEMORY;
4688 q = strdup_or_die(p);
4690 freez(http->hostport);
4694 q = strchr(http->host, ':');
4697 /* Terminate hostname and evaluate port string */
4699 http->port = atoi(q);
4706 /* Rebuild request URL */
4708 http->url = strdup("http://");
4709 string_append(&http->url, http->hostport);
4710 string_append(&http->url, http->path);
4711 if (http->url == NULL)
4713 return JB_ERR_MEMORY;
4716 log_error(LOG_LEVEL_HEADER,
4717 "Destination extracted from \"Host\" header. New request URL: %s",
4721 * Regenerate request line in "proxy format"
4722 * to make rewrites more convenient.
4724 assert(http->cmd != NULL);
4726 http->cmd = strdup_or_die(http->gpc);
4727 string_append(&http->cmd, " ");
4728 string_append(&http->cmd, http->url);
4729 string_append(&http->cmd, " ");
4730 string_append(&http->cmd, http->version);
4731 if (http->cmd == NULL)
4733 return JB_ERR_MEMORY;
4741 #ifdef FEATURE_HTTPS_INSPECTION
4742 /*********************************************************************
4744 * Function : get_destination_from_https_headers
4746 * Description : Parse the previously encrypted "Host:" header to
4747 * get the request's destination.
4750 * 1 : headers = List of headers (one of them hopefully being
4751 * the "Host:" header)
4752 * 2 : http = storage for the result (host, port and hostport).
4754 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4755 * JB_ERR_PARSE if the host header couldn't be found,
4756 * JB_ERR_OK otherwise.
4758 *********************************************************************/
4759 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4765 host = get_header_value(headers, "Host:");
4769 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4770 return JB_ERR_PARSE;
4773 p = string_tolower(host);
4776 return JB_ERR_MEMORY;
4779 q = strdup_or_die(p);
4781 freez(http->hostport);
4785 q = strchr(http->host, ':');
4788 /* Terminate hostname and evaluate port string */
4790 http->port = atoi(q);
4797 /* Rebuild request URL */
4799 http->url = strdup_or_die(http->path);
4801 log_error(LOG_LEVEL_HEADER,
4802 "Destination extracted from \"Host\" header. New request URL: %s",
4806 * Regenerate request line in "proxy format"
4807 * to make rewrites more convenient.
4809 assert(http->cmd != NULL);
4811 http->cmd = strdup_or_die(http->gpc);
4812 string_append(&http->cmd, " ");
4813 string_append(&http->cmd, http->url);
4814 string_append(&http->cmd, " ");
4815 string_append(&http->cmd, http->version);
4816 if (http->cmd == NULL)
4818 return JB_ERR_MEMORY;
4824 #endif /* def FEATURE_HTTPS_INSPECTION */
4827 /*********************************************************************
4829 * Function : create_forged_referrer
4831 * Description : Helper for client_referrer to forge a referer as
4832 * 'http://hostname[:port]/' to fool stupid
4833 * checks for in-site links
4836 * 1 : header = Pointer to header pointer
4837 * 2 : hostport = Host and optionally port as string
4839 * Returns : JB_ERR_OK in case of success, or
4840 * JB_ERR_MEMORY in case of memory problems.
4842 *********************************************************************/
4843 static jb_err create_forged_referrer(char **header, const char *hostport)
4845 assert(NULL == *header);
4847 *header = strdup("Referer: http://");
4848 string_append(header, hostport);
4849 string_append(header, "/");
4851 if (NULL == *header)
4853 return JB_ERR_MEMORY;
4856 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4863 /*********************************************************************
4865 * Function : create_fake_referrer
4867 * Description : Helper for client_referrer to create a fake referrer
4868 * based on a string supplied by the user.
4871 * 1 : header = Pointer to header pointer
4872 * 2 : hosthost = Referrer to fake
4874 * Returns : JB_ERR_OK in case of success, or
4875 * JB_ERR_MEMORY in case of memory problems.
4877 *********************************************************************/
4878 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4880 assert(NULL == *header);
4882 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4884 log_error(LOG_LEVEL_HEADER,
4885 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4887 *header = strdup("Referer: ");
4888 string_append(header, fake_referrer);
4890 if (NULL == *header)
4892 return JB_ERR_MEMORY;
4895 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4902 /*********************************************************************
4904 * Function : handle_conditional_hide_referrer_parameter
4906 * Description : Helper for client_referrer to crunch or forge
4907 * the referrer header if the host has changed.
4910 * 1 : header = Pointer to header pointer
4911 * 2 : host = The target host (may include the port)
4912 * 3 : parameter_conditional_block = Boolean to signal
4913 * if we're in conditional-block mode. If not set,
4914 * we're in conditional-forge mode.
4916 * Returns : JB_ERR_OK in case of success, or
4917 * JB_ERR_MEMORY in case of memory problems.
4919 *********************************************************************/
4920 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4921 const char *host, const int parameter_conditional_block)
4923 char *referer = strdup_or_die(*header);
4924 const size_t hostlength = strlen(host);
4925 const char *referer_url = NULL;
4927 /* referer begins with 'Referer: http[s]://' */
4928 if ((hostlength+17) < strlen(referer))
4931 * Shorten referer to make sure the referer is blocked
4932 * if www.example.org/www.example.com-shall-see-the-referer/
4933 * links to www.example.com/
4935 referer[hostlength+17] = '\0';
4937 referer_url = strstr(referer, "http://");
4938 if (NULL == referer_url)
4940 referer_url = strstr(referer, "https://");
4942 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4944 /* Host has changed, Referer is invalid or a https URL. */
4945 if (parameter_conditional_block)
4947 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4954 return create_forged_referrer(header, host);
4964 /*********************************************************************
4966 * Function : create_content_length_header
4968 * Description : Creates a Content-Length header.
4971 * 1 : content_length = The content length to be used in the header.
4972 * 2 : header = Allocated space to safe the header.
4973 * 3 : buffer_length = The length of the allocated space.
4977 *********************************************************************/
4978 static void create_content_length_header(unsigned long long content_length,
4979 char *header, size_t buffer_length)
4982 #if SIZEOF_LONG_LONG < 8
4983 #error sizeof(unsigned long long) too small
4985 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4987 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4992 /*********************************************************************
4994 * Function : get_expected_content_length
4996 * Description : Figures out the content length from a list of headers.
4999 * 1 : headers = List of headers
5001 * Returns : Number of bytes to expect
5003 *********************************************************************/
5004 unsigned long long get_expected_content_length(struct list *headers)
5006 const char *content_length_header;
5007 unsigned long long content_length = 0;
5009 content_length_header = get_header_value(headers, "Content-Length:");
5010 if (content_length_header != NULL)
5012 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
5014 log_error(LOG_LEVEL_ERROR,
5015 "Failed to get the Content-Length in %s", content_length_header);
5016 /* XXX: The header will be removed later on */
5021 return content_length;