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-2020 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 : add_to_iob
298 * Description : Add content to the buffer, expanding the
299 * buffer if necessary.
302 * 1 : iob = Destination buffer.
303 * 2 : buffer_limit = Limit to which the destination may grow
304 * 3 : src = holds the content to be added
305 * 4 : n = number of bytes to be added
307 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
308 * or buffer limit reached.
310 *********************************************************************/
311 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
313 size_t used, offset, need;
316 if (n <= 0) return JB_ERR_OK;
318 used = (size_t)(iob->eod - iob->buf);
319 offset = (size_t)(iob->cur - iob->buf);
320 need = used + (size_t)n + 1;
323 * If the buffer can't hold the new data, extend it first.
324 * Use the next power of two if possible, else use the actual need.
326 if (need > buffer_limit)
328 log_error(LOG_LEVEL_INFO,
329 "Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
331 return JB_ERR_MEMORY;
334 if (need > iob->size)
336 size_t want = iob->size ? iob->size : 512;
343 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
347 else if (NULL != (p = (char *)realloc(iob->buf, need)))
353 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
354 return JB_ERR_MEMORY;
357 /* Update the iob pointers */
358 iob->cur = p + offset;
363 /* copy the new data into the iob buffer */
364 memcpy(iob->eod, src, (size_t)n);
366 /* point to the end of the data */
369 /* null terminate == cheap insurance */
377 /*********************************************************************
379 * Function : clear_iob
381 * Description : Frees the memory allocated for an I/O buffer and
382 * resets the structure.
385 * 1 : iob = I/O buffer to clear.
389 *********************************************************************/
390 void clear_iob(struct iob *iob)
393 memset(iob, '\0', sizeof(*iob));
398 #ifdef FEATURE_BROTLI
399 /*********************************************************************
401 * Function : decompress_iob_with_brotli
403 * Description : Decompress buffered page using Brotli.
406 * 1 : csp = Current client state (buffers, headers, etc...)
408 * Returns : JB_ERR_OK on success,
409 * JB_ERR_MEMORY if out-of-memory limit reached, and
410 * JB_ERR_COMPRESS if error decompressing buffer.
412 *********************************************************************/
413 static jb_err decompress_iob_with_brotli(struct client_state *csp)
415 BrotliDecoderResult result;
416 char *decoded_buffer;
418 size_t decoded_buffer_size;
420 enum { MAX_COMPRESSION_FACTOR = 15 };
422 encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
424 * The BrotliDecoderDecompress() api is a bit unfortunate
425 * and requires the caller to reserve enough memory for
426 * the decompressed content. Hopefully reserving
427 * MAX_COMPRESSION_FACTOR times the original size is
428 * sufficient. If not, BrotliDecoderDecompress() will fail.
430 decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
432 if (decoded_buffer_size > csp->config->buffer_limit)
434 log_error(LOG_LEVEL_ERROR,
435 "Buffer limit reached before decompressing iob with Brotli");
436 return JB_ERR_MEMORY;
439 decoded_buffer = malloc(decoded_buffer_size);
440 if (decoded_buffer == NULL)
442 log_error(LOG_LEVEL_ERROR,
443 "Failed to allocate %lu bytes for Brotli decompression",
444 decoded_buffer_size);
445 return JB_ERR_MEMORY;
448 decoded_size = decoded_buffer_size;
449 result = BrotliDecoderDecompress(encoded_size,
450 (const uint8_t *)csp->iob->cur, &decoded_size,
451 (uint8_t *)decoded_buffer);
452 if (result == BROTLI_DECODER_RESULT_SUCCESS)
455 * Update the iob, since the decompression was successful.
457 freez(csp->iob->buf);
458 csp->iob->buf = decoded_buffer;
459 csp->iob->cur = csp->iob->buf;
460 csp->iob->eod = csp->iob->cur + decoded_size;
461 csp->iob->size = decoded_buffer_size;
463 log_error(LOG_LEVEL_RE_FILTER,
464 "Decompression successful. Old size: %lu, new size: %lu.",
465 encoded_size, decoded_size);
471 log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
472 freez(decoded_buffer);
474 return JB_ERR_COMPRESS;
479 /*********************************************************************
481 * Function : decompress_iob
483 * Description : Decompress buffered page, expanding the
484 * buffer as necessary. csp->iob->cur
485 * should point to the the beginning of the
486 * compressed data block.
489 * 1 : csp = Current client state (buffers, headers, etc...)
491 * Returns : JB_ERR_OK on success,
492 * JB_ERR_MEMORY if out-of-memory limit reached, and
493 * JB_ERR_COMPRESS if error decompressing buffer.
495 *********************************************************************/
496 jb_err decompress_iob(struct client_state *csp)
498 char *buf; /* new, uncompressed buffer */
499 char *cur; /* Current iob position (to keep the original
500 * iob->cur unmodified if we return early) */
501 size_t bufsize; /* allocated size of the new buffer */
502 size_t old_size; /* Content size before decompression */
503 size_t skip_size; /* Number of bytes at the beginning of the iob
504 that we should NOT decompress. */
505 int status; /* return status of the inflate() call */
506 z_stream zstr; /* used by calls to zlib */
509 assert(csp->iob->cur - csp->iob->buf >= 0);
510 assert(csp->iob->eod - csp->iob->cur >= 0);
512 assert(csp->iob->cur - csp->iob->buf > 0);
513 assert(csp->iob->eod - csp->iob->cur > 0);
516 bufsize = csp->iob->size;
517 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
518 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
522 if (bufsize < (size_t)10)
525 * This is to protect the parsing of gzipped data,
526 * but it should(?) be valid for deflated data also.
528 log_error(LOG_LEVEL_ERROR,
529 "Insufficient data to start decompression. Bytes in buffer: %ld",
530 csp->iob->eod - csp->iob->cur);
531 return JB_ERR_COMPRESS;
534 #ifdef FEATURE_BROTLI
535 if (csp->content_type & CT_BROTLI)
537 return decompress_iob_with_brotli(csp);
541 if (csp->content_type & CT_GZIP)
544 * Our task is slightly complicated by the facts that data
545 * compressed by gzip does not include a zlib header, and
546 * that there is no easily accessible interface in zlib to
547 * handle a gzip header. We strip off the gzip header by
548 * hand, and later inform zlib not to expect a header.
552 * Strip off the gzip header. Please see RFC 1952 for more
553 * explanation of the appropriate fields.
555 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
556 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
557 || (*cur++ != Z_DEFLATED))
559 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
560 return JB_ERR_COMPRESS;
565 if (flags & GZIP_FLAG_RESERVED_BITS)
567 /* The gzip header has reserved bits set; bail out. */
568 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
569 return JB_ERR_COMPRESS;
573 * Skip mtime (4 bytes), extra flags (1 byte)
574 * and OS type (1 byte).
578 /* Skip extra fields if necessary. */
579 if (flags & GZIP_FLAG_EXTRA_FIELDS)
582 * Skip a given number of bytes, specified
583 * as a 16-bit little-endian value.
585 * XXX: this code is untested and should probably be removed.
589 skip_bytes += *cur++ << 8;
592 * The number of bytes to skip should be positive
593 * and we'd like to stay in the buffer.
595 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
597 log_error(LOG_LEVEL_ERROR,
598 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
600 return JB_ERR_COMPRESS;
602 log_error(LOG_LEVEL_INFO,
603 "Skipping %d bytes for gzip compression. Does this sound right?",
608 /* Skip the filename if necessary. */
609 if (flags & GZIP_FLAG_FILE_NAME)
611 /* A null-terminated string is supposed to follow. */
612 while (*cur++ && (cur < csp->iob->eod));
615 /* Skip the comment if necessary. */
616 if (flags & GZIP_FLAG_COMMENT)
618 /* A null-terminated string is supposed to follow. */
619 while (*cur++ && (cur < csp->iob->eod));
622 /* Skip the CRC if necessary. */
623 if (flags & GZIP_FLAG_CHECKSUM)
628 if (cur >= csp->iob->eod)
631 * If the current position pointer reached or passed
632 * the buffer end, we were obviously tricked to skip
635 log_error(LOG_LEVEL_ERROR,
636 "Malformed gzip header detected. Aborting decompression.");
637 return JB_ERR_COMPRESS;
641 else if (csp->content_type & CT_DEFLATE)
644 * In theory (that is, according to RFC 1950), deflate-compressed
645 * data should begin with a two-byte zlib header and have an
646 * adler32 checksum at the end. It seems that in practice only
647 * the raw compressed data is sent. Note that this means that
648 * we are not RFC 1950-compliant here, but the advantage is that
649 * this actually works. :)
651 * We add a dummy null byte to tell zlib where the data ends,
652 * and later inform it not to expect a header.
654 * Fortunately, add_to_iob() has thoughtfully null-terminated
655 * the buffer; we can just increment the end pointer to include
662 log_error(LOG_LEVEL_ERROR,
663 "Unable to determine compression format for decompression");
664 return JB_ERR_COMPRESS;
667 /* Set up the fields required by zlib. */
668 zstr.next_in = (Bytef *)cur;
669 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
670 zstr.zalloc = Z_NULL;
672 zstr.opaque = Z_NULL;
675 * Passing -MAX_WBITS to inflateInit2 tells the library
676 * that there is no zlib header.
678 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
680 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
681 return JB_ERR_COMPRESS;
685 * Next, we allocate new storage for the inflated data.
686 * We don't modify the existing iob yet, so in case there
687 * is error in decompression we can recover gracefully.
689 buf = zalloc(bufsize);
692 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
693 return JB_ERR_MEMORY;
696 assert(bufsize >= skip_size);
697 memcpy(buf, csp->iob->buf, skip_size);
698 zstr.avail_out = (uInt)(bufsize - skip_size);
699 zstr.next_out = (Bytef *)buf + skip_size;
701 /* Try to decompress the whole stream in one shot. */
702 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
704 /* We need to allocate more memory for the output buffer. */
706 char *tmpbuf; /* used for realloc'ing the buffer */
707 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
709 if (0 == zstr.avail_in)
712 * If zlib wants more data then there's a problem, because
713 * the complete compressed file should have been buffered.
715 log_error(LOG_LEVEL_ERROR,
716 "Unexpected end of compressed iob. Using what we got so far.");
721 * If we reached the buffer limit and still didn't have enough
722 * memory, just give up. Due to the ceiling enforced by the next
723 * if block we could actually check for equality here, but as it
724 * can be easily mistaken for a bug we don't.
726 if (bufsize >= csp->config->buffer_limit)
728 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
731 return JB_ERR_MEMORY;
734 /* Try doubling the buffer size each time. */
737 /* Don't exceed the buffer limit. */
738 if (bufsize > csp->config->buffer_limit)
740 bufsize = csp->config->buffer_limit;
743 /* Try to allocate the new buffer. */
744 tmpbuf = realloc(buf, bufsize);
747 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
750 return JB_ERR_MEMORY;
754 char *oldnext_out = (char *)zstr.next_out;
757 * Update the fields for inflate() to use the new
758 * buffer, which may be in a location different from
761 zstr.avail_out += (uInt)(bufsize - oldbufsize);
762 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
765 * Compare with an uglier method of calculating these values
766 * that doesn't require the extra oldbufsize variable.
768 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
769 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
775 if (Z_STREAM_ERROR == inflateEnd(&zstr))
777 log_error(LOG_LEVEL_ERROR,
778 "Inconsistent stream state after decompression: %s", zstr.msg);
780 * XXX: Intentionally no return.
782 * According to zlib.h, Z_STREAM_ERROR is returned
783 * "if the stream state was inconsistent".
785 * I assume in this case inflate()'s status
786 * would also be something different than Z_STREAM_END
787 * so this check should be redundant, but lets see.
791 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
794 * We failed to decompress the stream and it's
795 * not simply because of missing data.
797 log_error(LOG_LEVEL_ERROR,
798 "Unexpected error while decompressing to the buffer (iob): %s",
800 return JB_ERR_COMPRESS;
804 * Finally, we can actually update the iob, since the
805 * decompression was successful. First, free the old
808 freez(csp->iob->buf);
810 /* Now, update the iob to use the new buffer. */
812 csp->iob->cur = csp->iob->buf + skip_size;
813 csp->iob->eod = (char *)zstr.next_out;
814 csp->iob->size = bufsize;
817 * Make sure the new uncompressed iob obeys some minimal
818 * consistency conditions.
820 if ((csp->iob->buf <= csp->iob->cur)
821 && (csp->iob->cur <= csp->iob->eod)
822 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
824 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
825 if (new_size > (size_t)0)
827 log_error(LOG_LEVEL_RE_FILTER,
828 "Decompression successful. Old size: %lu, new size: %lu.",
833 /* zlib thinks this is OK, so let's do the same. */
834 log_error(LOG_LEVEL_RE_FILTER,
835 "Decompression didn't result in any content.");
840 /* It seems that zlib did something weird. */
841 log_error(LOG_LEVEL_ERROR, "Inconsistent buffer after decompression");
842 return JB_ERR_COMPRESS;
848 #endif /* defined(FEATURE_ZLIB) */
851 /*********************************************************************
853 * Function : normalize_lws
855 * Description : Reduces unquoted linear whitespace in headers to
856 * a single space in accordance with RFC 7230 3.2.4.
857 * This simplifies parsing and filtering later on.
860 * 1 : header = A header with linear whitespace to reduce.
864 *********************************************************************/
865 static void normalize_lws(char *header)
871 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
875 while (privoxy_isspace(*q))
879 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
885 log_error(LOG_LEVEL_HEADER,
886 "Converting tab to space in '%s'", header);
891 char *end_of_token = strstr(p+1, "\"");
893 if (NULL != end_of_token)
895 /* Don't mess with quoted text. */
900 log_error(LOG_LEVEL_HEADER,
901 "Ignoring single quote in '%s'", header);
907 p = strchr(header, ':');
908 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
911 * There's still space before the colon.
919 /*********************************************************************
921 * Function : get_header
923 * Description : This (odd) routine will parse the csp->iob
924 * to get the next complete header.
927 * 1 : iob = The I/O buffer to parse, usually csp->iob.
929 * Returns : Any one of the following:
931 * 1) a pointer to a dynamically allocated string that contains a header line
932 * 2) NULL indicating that the end of the header was reached
933 * 3) "" indicating that the end of the iob was reached before finding
934 * a complete header line.
936 *********************************************************************/
937 char *get_header(struct iob *iob)
941 header = get_header_line(iob);
943 if ((header == NULL) || (*header == '\0'))
946 * No complete header read yet, tell the client.
951 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
954 * Header spans multiple lines, append the next one.
956 char *continued_header;
958 continued_header = get_header_line(iob);
959 if ((continued_header == NULL) || (*continued_header == '\0'))
962 * No complete header read yet, return what we got.
963 * XXX: Should "unread" header instead.
965 log_error(LOG_LEVEL_INFO,
966 "Failed to read a multi-line header properly: '%s'",
971 if (JB_ERR_OK != string_join(&header, continued_header))
973 log_error(LOG_LEVEL_FATAL,
974 "Out of memory while appending multiple headers.");
978 /* XXX: remove before next stable release. */
979 log_error(LOG_LEVEL_HEADER,
980 "Merged multiple header lines to: '%s'",
985 normalize_lws(header);
992 /*********************************************************************
994 * Function : get_header_line
996 * Description : This (odd) routine will parse the csp->iob
997 * to get the next header line.
1000 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1002 * Returns : Any one of the following:
1004 * 1) a pointer to a dynamically allocated string that contains a header line
1005 * 2) NULL indicating that the end of the header was reached
1006 * 3) "" indicating that the end of the iob was reached before finding
1007 * a complete header line.
1009 *********************************************************************/
1010 static char *get_header_line(struct iob *iob)
1014 if ((iob->cur == NULL)
1015 || ((p = strchr(iob->cur, '\n')) == NULL))
1017 return(""); /* couldn't find a complete header */
1022 ret = strdup(iob->cur);
1025 /* FIXME No way to handle error properly */
1026 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1028 assert(ret != NULL);
1032 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1034 /* is this a blank line (i.e. the end of the header) ? */
1046 /*********************************************************************
1048 * Function : get_header_value
1050 * Description : Get the value of a given header from a chained list
1051 * of header lines or return NULL if no such header is
1052 * present in the list.
1055 * 1 : header_list = pointer to list
1056 * 2 : header_name = string with name of header to look for.
1057 * Trailing colon required, capitalization
1060 * Returns : NULL if not found, else value of header
1062 *********************************************************************/
1063 char *get_header_value(const struct list *header_list, const char *header_name)
1065 struct list_entry *cur_entry;
1069 assert(header_list);
1070 assert(header_name);
1071 length = strlen(header_name);
1073 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1077 if (!strncmpic(cur_entry->str, header_name, length))
1080 * Found: return pointer to start of value
1082 ret = cur_entry->str + length;
1083 while (*ret && privoxy_isspace(*ret)) ret++;
1097 /*********************************************************************
1099 * Function : scan_headers
1101 * Description : Scans headers, applies tags and updates action bits.
1104 * 1 : csp = Current client state (buffers, headers, etc...)
1106 * Returns : JB_ERR_OK
1108 *********************************************************************/
1109 static jb_err scan_headers(struct client_state *csp)
1111 struct list_entry *h; /* Header */
1112 jb_err err = JB_ERR_OK;
1114 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1116 /* Header crunch()ed in previous run? -> ignore */
1117 if (h->str == NULL) continue;
1118 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1119 err = header_tagger(csp, h->str);
1126 /*********************************************************************
1128 * Function : enforce_header_order
1130 * Description : Enforces a given header order.
1133 * 1 : headers = List of headers to order.
1134 * 2 : ordered_headers = List of ordered header names.
1138 *********************************************************************/
1139 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1141 struct list_entry *sorted_header;
1142 struct list new_headers[1];
1143 struct list_entry *header;
1145 init_list(new_headers);
1147 /* The request line is always the first "header" */
1149 assert(NULL != headers->first->str);
1150 enlist(new_headers, headers->first->str);
1151 freez(headers->first->str)
1153 /* Enlist the specified headers in the given order */
1155 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1156 sorted_header = sorted_header->next)
1158 const size_t sorted_header_length = strlen(sorted_header->str);
1159 for (header = headers->first; header != NULL; header = header->next)
1161 /* Header enlisted in previous run? -> ignore */
1162 if (header->str == NULL) continue;
1164 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1165 && (header->str[sorted_header_length] == ':'))
1167 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1168 if (JB_ERR_OK != enlist(new_headers, header->str))
1170 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1177 /* Enlist the rest of the headers behind the ordered ones */
1178 for (header = headers->first; header != NULL; header = header->next)
1180 /* Header enlisted in previous run? -> ignore */
1181 if (header->str == NULL) continue;
1183 log_error(LOG_LEVEL_HEADER,
1184 "Enlisting left-over header %s", header->str);
1185 if (JB_ERR_OK != enlist(new_headers, header->str))
1187 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1192 list_remove_all(headers);
1193 list_duplicate(headers, new_headers);
1194 list_remove_all(new_headers);
1200 /*********************************************************************
1204 * Description : add, delete or modify lines in the HTTP header streams.
1205 * On entry, it receives a linked list of headers space
1206 * that was allocated dynamically (both the list nodes
1207 * and the header contents).
1209 * As a side effect it frees the space used by the original
1213 * 1 : csp = Current client state (buffers, headers, etc...)
1214 * 2 : filter_server_headers = Boolean to switch between
1215 * server and header filtering.
1217 * Returns : JB_ERR_OK in case off success, or
1218 * JB_ERR_MEMORY on some out-of-memory errors, or
1219 * JB_ERR_PARSE in case of fatal parse errors.
1221 *********************************************************************/
1222 jb_err sed(struct client_state *csp, int filter_server_headers)
1224 /* XXX: use more descriptive names. */
1225 struct list_entry *p;
1226 const struct parsers *v;
1227 const add_header_func_ptr *f;
1228 jb_err err = JB_ERR_OK;
1232 if (filter_server_headers)
1234 v = server_patterns;
1235 f = add_server_headers;
1236 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1240 v = client_patterns;
1241 f = add_client_headers;
1242 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1245 while (v->str != NULL)
1247 for (p = csp->headers->first; p != NULL; p = p->next)
1249 /* Header crunch()ed in previous run? -> ignore */
1250 if (p->str == NULL) continue;
1252 /* Does the current parser handle this header? */
1253 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1254 (v->len == CHECK_EVERY_HEADER_REMAINING))
1256 err = v->parser(csp, &(p->str));
1257 if (err != JB_ERR_OK)
1266 /* place additional headers on the csp->headers list */
1267 while ((err == JB_ERR_OK) && (*f))
1273 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1275 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1282 #ifdef FEATURE_HTTPS_INSPECTION
1283 /*********************************************************************
1285 * Function : sed_https
1287 * Description : add, delete or modify lines in the HTTPS client
1288 * header streams. Wrapper around sed().
1291 * 1 : csp = Current client state (buffers, headers, etc...)
1293 * Returns : JB_ERR_OK in case off success, or
1294 * JB_ERR_MEMORY on some out-of-memory errors, or
1295 * JB_ERR_PARSE in case of fatal parse errors.
1297 *********************************************************************/
1298 jb_err sed_https(struct client_state *csp)
1301 struct list headers;
1304 * Temporarily replace csp->headers with csp->https_headers
1305 * to trick sed() into filtering the https headers.
1307 headers.first = csp->headers->first;
1308 headers.last = csp->headers->last;
1309 csp->headers->first = csp->https_headers->first;
1310 csp->headers->last = csp->https_headers->last;
1313 * Start with fresh tags. Already existing tags may
1314 * be set again. This is necessary to overrule
1315 * URL-based patterns.
1317 destroy_list(csp->tags);
1320 * We want client header filters and taggers
1321 * so temporarily remove the flag.
1323 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1324 err = sed(csp, FILTER_CLIENT_HEADERS);
1325 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1328 * Update the last header which may have changed
1329 * due to header additions,
1331 csp->https_headers->last = csp->headers->last;
1333 csp->headers->first = headers.first;
1334 csp->headers->last = headers.last;
1338 #endif /* def FEATURE_HTTPS_INSPECTION */
1341 /*********************************************************************
1343 * Function : update_server_headers
1345 * Description : Updates server headers after the body has been modified.
1348 * 1 : csp = Current client state (buffers, headers, etc...)
1350 * Returns : JB_ERR_OK in case off success, or
1351 * JB_ERR_MEMORY on out-of-memory error.
1353 *********************************************************************/
1354 jb_err update_server_headers(struct client_state *csp)
1356 jb_err err = JB_ERR_OK;
1358 static const struct parsers server_patterns_light[] = {
1359 { "Content-Length:", 15, server_adjust_content_length },
1360 { "Transfer-Encoding:", 18, server_transfer_coding },
1362 { "Content-Encoding:", 17, server_adjust_content_encoding },
1363 #endif /* def FEATURE_ZLIB */
1367 if (strncmpic(csp->http->cmd, "HEAD", 4))
1369 const struct parsers *v;
1370 struct list_entry *p;
1372 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1374 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1376 /* Header crunch()ed in previous run? -> ignore */
1377 if (p->str == NULL) continue;
1379 /* Does the current parser handle this header? */
1380 if (strncmpic(p->str, v->str, v->len) == 0)
1382 err = v->parser(csp, (char **)&(p->str));
1388 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1389 if ((JB_ERR_OK == err)
1390 && (csp->flags & CSP_FLAG_MODIFIED)
1391 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1392 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1396 create_content_length_header(csp->content_length, header, sizeof(header));
1397 err = enlist(csp->headers, header);
1398 if (JB_ERR_OK == err)
1400 log_error(LOG_LEVEL_HEADER,
1401 "Content modified with no Content-Length header set. "
1402 "Created: %s.", header);
1403 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1406 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1408 #ifdef FEATURE_COMPRESSION
1409 if ((JB_ERR_OK == err)
1410 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1412 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1413 if (JB_ERR_OK == err)
1415 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1424 /*********************************************************************
1426 * Function : header_tagger
1428 * Description : Executes all text substitutions from applying
1429 * tag actions and saves the result as tag.
1431 * XXX: Shares enough code with filter_header() and
1432 * pcrs_filter_response() to warrant some helper functions.
1435 * 1 : csp = Current client state (buffers, headers, etc...)
1436 * 2 : header = Header that is used as tagger input
1438 * Returns : JB_ERR_OK on success and always succeeds
1440 *********************************************************************/
1441 static jb_err header_tagger(struct client_state *csp, char *header)
1443 enum filter_type wanted_filter_type;
1444 int multi_action_index;
1447 struct re_filterfile_spec *b;
1448 struct list_entry *tag_name;
1450 const size_t header_length = strlen(header);
1452 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1454 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1455 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1459 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1460 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1463 if (list_is_empty(csp->action->multi[multi_action_index])
1464 || filters_available(csp) == FALSE)
1466 /* Return early if no taggers apply or if none are available. */
1470 /* Execute all applying taggers */
1471 for (tag_name = csp->action->multi[multi_action_index]->first;
1472 NULL != tag_name; tag_name = tag_name->next)
1474 char *modified_tag = NULL;
1476 size_t size = header_length;
1479 b = get_filter(csp, tag_name->str, wanted_filter_type);
1485 joblist = b->joblist;
1487 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1489 if (NULL == joblist)
1491 log_error(LOG_LEVEL_TAGGING,
1492 "Tagger %s has empty joblist. Nothing to do.", b->name);
1496 /* execute their pcrs_joblist on the header. */
1497 for (job = joblist; NULL != job; job = job->next)
1499 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1503 /* Success, continue with the modified version. */
1512 /* Tagger doesn't match */
1515 /* Regex failure, log it but continue anyway. */
1516 assert(NULL != header);
1517 log_error(LOG_LEVEL_ERROR,
1518 "Problems with tagger \'%s\' and header \'%s\': %s",
1519 b->name, header, pcrs_strerror(hits));
1521 freez(modified_tag);
1525 if (b->dynamic) pcrs_free_joblist(joblist);
1527 /* If this tagger matched */
1533 * There is no technical limitation which makes
1534 * it impossible to use empty tags, but I assume
1535 * no one would do it intentionally.
1538 log_error(LOG_LEVEL_TAGGING,
1539 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1543 if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
1545 log_error(LOG_LEVEL_TAGGING,
1546 "Tagger \'%s\' didn't add tag \'%s\': suppressed",
1552 if (!list_contains_item(csp->tags, tag))
1554 if (JB_ERR_OK != enlist(csp->tags, tag))
1556 log_error(LOG_LEVEL_ERROR,
1557 "Insufficient memory to add tag \'%s\', "
1558 "based on tagger \'%s\' and header \'%s\'",
1559 tag, b->name, header);
1563 char *action_message;
1565 * update the action bits right away, to make
1566 * tagging based on tags set by earlier taggers
1567 * of the same kind possible.
1569 if (update_action_bits_for_tag(csp, tag))
1571 action_message = "Action bits updated accordingly.";
1575 action_message = "No action bits update necessary.";
1578 log_error(LOG_LEVEL_TAGGING,
1579 "Tagger \'%s\' added tag \'%s\'. %s",
1580 b->name, tag, action_message);
1585 /* XXX: Is this log-worthy? */
1586 log_error(LOG_LEVEL_TAGGING,
1587 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1597 /* here begins the family of parser functions that reformat header lines */
1599 /*********************************************************************
1601 * Function : filter_header
1603 * Description : Executes all text substitutions from all applying
1604 * +(server|client)-header-filter actions on the header.
1605 * Most of the code was copied from pcrs_filter_response,
1606 * including the rather short variable names
1609 * 1 : csp = Current client state (buffers, headers, etc...)
1610 * 2 : header = On input, pointer to header to modify.
1611 * On output, pointer to the modified header, or NULL
1612 * to remove the header. This function frees the
1613 * original string if necessary.
1615 * Returns : JB_ERR_OK on success and always succeeds
1617 *********************************************************************/
1618 static jb_err filter_header(struct client_state *csp, char **header)
1622 size_t size = strlen(*header);
1624 char *newheader = NULL;
1627 struct re_filterfile_spec *b;
1628 struct list_entry *filtername;
1630 enum filter_type wanted_filter_type;
1631 int multi_action_index;
1633 if (csp->flags & CSP_FLAG_NO_FILTERING)
1638 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1640 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1641 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1645 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1646 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1649 if (list_is_empty(csp->action->multi[multi_action_index])
1650 || filters_available(csp) == FALSE)
1652 /* Return early if no filters apply or if none are available. */
1656 /* Execute all applying header filters */
1657 for (filtername = csp->action->multi[multi_action_index]->first;
1658 filtername != NULL; filtername = filtername->next)
1660 int current_hits = 0;
1663 b = get_filter(csp, filtername->str, wanted_filter_type);
1669 joblist = b->joblist;
1671 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1673 if (NULL == joblist)
1675 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1679 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %lu) with \'%s\' ...",
1680 *header, size, b->name);
1682 /* Apply all jobs from the joblist */
1683 for (job = joblist; NULL != job; job = job->next)
1685 matches = pcrs_execute(job, *header, size, &newheader, &size);
1688 current_hits += matches;
1689 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1691 *header = newheader;
1693 else if (0 == matches)
1695 /* Filter doesn't change header */
1701 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1702 *header, b->name, pcrs_strerror(matches));
1703 if (newheader != NULL)
1705 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1711 if (b->dynamic) pcrs_free_joblist(joblist);
1713 log_error(LOG_LEVEL_RE_FILTER,
1714 "... produced %d hits (new size %lu).", current_hits, size);
1715 hits += current_hits;
1719 * Additionally checking for hits is important because if
1720 * the continue hack is triggered, server headers can
1721 * arrive empty to separate multiple heads from each other.
1723 if ((0 == size) && hits)
1725 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1733 /*********************************************************************
1735 * Function : server_connection
1737 * Description : Makes sure a proper "Connection:" header is
1738 * set and signals connection_header_adder to
1742 * 1 : csp = Current client state (buffers, headers, etc...)
1743 * 2 : header = On input, pointer to header to modify.
1744 * On output, pointer to the modified header, or NULL
1745 * to remove the header. This function frees the
1746 * original string if necessary.
1748 * Returns : JB_ERR_OK on success.
1750 *********************************************************************/
1751 static jb_err server_connection(struct client_state *csp, char **header)
1753 if (!strcmpic(*header, "Connection: keep-alive")
1754 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1755 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1759 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1760 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1762 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1765 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1767 log_error(LOG_LEVEL_HEADER,
1768 "Keeping the server header '%s' around.", *header);
1771 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1773 char *old_header = *header;
1775 *header = strdup_or_die("Connection: close");
1776 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1781 /* Signal server_connection_adder() to return early. */
1782 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1788 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1789 /*********************************************************************
1791 * Function : server_keep_alive
1793 * Description : Stores the server's keep alive timeout.
1796 * 1 : csp = Current client state (buffers, headers, etc...)
1797 * 2 : header = On input, pointer to header to modify.
1798 * On output, pointer to the modified header, or NULL
1799 * to remove the header. This function frees the
1800 * original string if necessary.
1802 * Returns : JB_ERR_OK.
1804 *********************************************************************/
1805 static jb_err server_keep_alive(struct client_state *csp, char **header)
1807 unsigned int keep_alive_timeout;
1808 const char *timeout_position = strstr(*header, "timeout=");
1810 if ((NULL == timeout_position)
1811 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1813 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1817 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1819 log_error(LOG_LEVEL_HEADER,
1820 "Reducing keep-alive timeout from %u to %u.",
1821 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1822 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1826 /* XXX: Is this log worthy? */
1827 log_error(LOG_LEVEL_HEADER,
1828 "Server keep-alive timeout is %u. Sticking with %u.",
1829 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1831 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1840 /*********************************************************************
1842 * Function : server_proxy_connection
1844 * Description : Figures out whether or not we should add a
1845 * Proxy-Connection header.
1848 * 1 : csp = Current client state (buffers, headers, etc...)
1849 * 2 : header = On input, pointer to header to modify.
1850 * On output, pointer to the modified header, or NULL
1851 * to remove the header. This function frees the
1852 * original string if necessary.
1854 * Returns : JB_ERR_OK.
1856 *********************************************************************/
1857 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1859 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1862 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1865 /*********************************************************************
1867 * Function : proxy_authentication
1869 * Description : Removes headers that are relevant for proxy
1870 * authentication unless forwarding them has
1871 * been explicitly requested.
1874 * 1 : csp = Current client state (buffers, headers, etc...)
1875 * 2 : header = On input, pointer to header to modify.
1876 * On output, pointer to the modified header, or NULL
1877 * to remove the header. This function frees the
1878 * original string if necessary.
1880 * Returns : JB_ERR_OK.
1882 *********************************************************************/
1883 static jb_err proxy_authentication(struct client_state *csp, char **header)
1885 if ((csp->config->feature_flags &
1886 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1887 log_error(LOG_LEVEL_HEADER,
1888 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1895 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1896 /*********************************************************************
1898 * Function : client_keep_alive
1900 * Description : Stores the client's keep alive timeout.
1903 * 1 : csp = Current client state (buffers, headers, etc...)
1904 * 2 : header = On input, pointer to header to modify.
1905 * On output, pointer to the modified header, or NULL
1906 * to remove the header. This function frees the
1907 * original string if necessary.
1909 * Returns : JB_ERR_OK.
1911 *********************************************************************/
1912 static jb_err client_keep_alive(struct client_state *csp, char **header)
1914 unsigned int keep_alive_timeout;
1915 char *timeout_position;
1917 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1919 log_error(LOG_LEVEL_HEADER,
1920 "keep-alive support is disabled. Crunching: %s.", *header);
1925 /* Check for parameter-less format "Keep-Alive: 100" */
1926 timeout_position = strstr(*header, ": ");
1927 if ((NULL == timeout_position)
1928 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1930 /* Assume parameter format "Keep-Alive: timeout=100" */
1931 timeout_position = strstr(*header, "timeout=");
1932 if ((NULL == timeout_position)
1933 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1935 log_error(LOG_LEVEL_HEADER,
1936 "Couldn't parse: '%s'. Using default timeout %u",
1937 *header, csp->config->keep_alive_timeout);
1944 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1946 log_error(LOG_LEVEL_HEADER,
1947 "Reducing keep-alive timeout from %u to %u.",
1948 csp->config->keep_alive_timeout, keep_alive_timeout);
1949 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1953 /* XXX: Is this log worthy? */
1954 log_error(LOG_LEVEL_HEADER,
1955 "Client keep-alive timeout is %u. Sticking with %u.",
1956 keep_alive_timeout, csp->config->keep_alive_timeout);
1962 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1965 /*********************************************************************
1967 * Function : get_content_length
1969 * Description : Gets the content length specified in a
1970 * Content-Length header.
1973 * 1 : header_value = The Content-Length header value.
1974 * 2 : length = Storage to return the value.
1976 * Returns : JB_ERR_OK on success, or
1977 * JB_ERR_PARSE if no value is recognized.
1979 *********************************************************************/
1980 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1983 #if SIZEOF_LONG_LONG < 8
1984 #error sizeof(unsigned long long) too small
1986 if (1 != sscanf(header_value, "%I64u", length))
1988 if (1 != sscanf(header_value, "%llu", length))
1991 return JB_ERR_PARSE;
1998 /*********************************************************************
2000 * Function : client_save_content_length
2002 * Description : Save the Content-Length sent by the client.
2005 * 1 : csp = Current client state (buffers, headers, etc...)
2006 * 2 : header = On input, pointer to header to modify.
2007 * On output, pointer to the modified header, or NULL
2008 * to remove the header. This function frees the
2009 * original string if necessary.
2011 * Returns : JB_ERR_OK on success, or
2012 * JB_ERR_MEMORY on out-of-memory error.
2014 *********************************************************************/
2015 static jb_err client_save_content_length(struct client_state *csp, char **header)
2017 unsigned long long content_length = 0;
2018 const char *header_value;
2020 assert(*(*header+14) == ':');
2022 header_value = *header + 15;
2023 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2025 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2030 csp->expected_client_content_length = content_length;
2037 /*********************************************************************
2039 * Function : client_connection
2041 * Description : Makes sure a proper "Connection:" header is
2042 * set and signals connection_header_adder
2046 * 1 : csp = Current client state (buffers, headers, etc...)
2047 * 2 : header = On input, pointer to header to modify.
2048 * On output, pointer to the modified header, or NULL
2049 * to remove the header. This function frees the
2050 * original string if necessary.
2052 * Returns : JB_ERR_OK on success.
2054 *********************************************************************/
2055 static jb_err client_connection(struct client_state *csp, char **header)
2057 static const char connection_close[] = "Connection: close";
2059 if (!strcmpic(*header, connection_close))
2061 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2062 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2063 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2064 #ifdef FEATURE_HTTPS_INSPECTION
2065 && !client_use_ssl(csp)
2069 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2071 log_error(LOG_LEVEL_HEADER,
2072 "Removing \'%s\' to imply keep-alive.", *header);
2075 * While we imply keep-alive to the server,
2076 * we have to remember that the client didn't.
2078 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2082 char *old_header = *header;
2084 *header = strdup_or_die("Connection: keep-alive");
2085 log_error(LOG_LEVEL_HEADER,
2086 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2092 log_error(LOG_LEVEL_HEADER,
2093 "Keeping the client header '%s' around. "
2094 "The connection will not be kept alive.",
2096 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2099 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2100 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2102 log_error(LOG_LEVEL_HEADER,
2103 "Keeping the client header '%s' around. "
2104 "The server connection will be kept alive if possible.",
2106 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2107 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2111 char *old_header = *header;
2113 *header = strdup_or_die(connection_close);
2114 log_error(LOG_LEVEL_HEADER,
2115 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2119 /* Signal client_connection_header_adder() to return early. */
2120 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2126 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2127 /*********************************************************************
2129 * Function : client_proxy_connection
2131 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2132 * appropriate and removes the Proxy-Connection
2136 * 1 : csp = Current client state (buffers, headers, etc...)
2137 * 2 : header = On input, pointer to header to modify.
2138 * On output, pointer to the modified header, or NULL
2139 * to remove the header. This function frees the
2140 * original string if necessary.
2142 * Returns : JB_ERR_OK
2144 *********************************************************************/
2145 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2147 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2148 && (csp->http->ssl == 0)
2149 && (NULL == strstr(*header, "close")))
2151 log_error(LOG_LEVEL_HEADER,
2152 "The client connection can be kept alive due to: %s", *header);
2153 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2155 crumble(csp, header);
2159 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2162 /*********************************************************************
2164 * Function : client_transfer_encoding
2166 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2167 * the request body is "chunked"
2169 * XXX: Currently not called through sed() as we
2170 * need the flag earlier on. Should be fixed.
2173 * 1 : csp = Current client state (buffers, headers, etc...)
2174 * 2 : header = On input, pointer to header to modify.
2175 * On output, pointer to the modified header, or NULL
2176 * to remove the header. This function frees the
2177 * original string if necessary.
2179 * Returns : JB_ERR_OK on success, or
2181 *********************************************************************/
2182 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2184 if (strstr(*header, "chunked"))
2186 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2187 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2194 /*********************************************************************
2196 * Function : client_expect
2198 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2199 * if the Expect header value is unsupported.
2201 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2202 * MAY and a RFC 2616 (obsolete) MUST.
2205 * 1 : csp = Current client state (buffers, headers, etc...)
2206 * 2 : header = On input, pointer to header to modify.
2207 * On output, pointer to the modified header, or NULL
2208 * to remove the header. This function frees the
2209 * original string if necessary.
2211 * Returns : JB_ERR_OK on success, or
2213 *********************************************************************/
2214 jb_err client_expect(struct client_state *csp, char **header)
2216 if (0 != strcmpic(*header, "Expect: 100-continue"))
2218 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2219 log_error(LOG_LEVEL_HEADER,
2220 "Unsupported client expectaction: %s", *header);
2228 /*********************************************************************
2230 * Function : crumble
2232 * Description : This is called if a header matches a pattern to "crunch"
2235 * 1 : csp = Current client state (buffers, headers, etc...)
2236 * 2 : header = On input, pointer to header to modify.
2237 * On output, pointer to the modified header, or NULL
2238 * to remove the header. This function frees the
2239 * original string if necessary.
2241 * Returns : JB_ERR_OK on success, or
2242 * JB_ERR_MEMORY on out-of-memory error.
2244 *********************************************************************/
2245 static jb_err crumble(struct client_state *csp, char **header)
2248 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2254 /*********************************************************************
2256 * Function : crunch_server_header
2258 * Description : Crunch server header if it matches a string supplied by the
2259 * user. Called from `sed'.
2262 * 1 : csp = Current client state (buffers, headers, etc...)
2263 * 2 : header = On input, pointer to header to modify.
2264 * On output, pointer to the modified header, or NULL
2265 * to remove the header. This function frees the
2266 * original string if necessary.
2268 * Returns : JB_ERR_OK on success and always succeeds
2270 *********************************************************************/
2271 static jb_err crunch_server_header(struct client_state *csp, char **header)
2273 const char *crunch_pattern;
2275 /* Do we feel like crunching? */
2276 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2278 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2280 /* Is the current header the lucky one? */
2281 if (strstr(*header, crunch_pattern))
2283 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2292 /*********************************************************************
2294 * Function : server_content_type
2296 * Description : Set the content-type for filterable types (text/.*,
2297 * .*xml.*, .*script.* and image/gif) unless filtering has been
2298 * forbidden (CT_TABOO) while parsing earlier headers.
2299 * NOTE: Since text/plain is commonly used by web servers
2300 * for files whose correct type is unknown, we don't
2301 * set CT_TEXT for it.
2304 * 1 : csp = Current client state (buffers, headers, etc...)
2305 * 2 : header = On input, pointer to header to modify.
2306 * On output, pointer to the modified header, or NULL
2307 * to remove the header. This function frees the
2308 * original string if necessary.
2310 * Returns : JB_ERR_OK on success, or
2311 * JB_ERR_MEMORY on out-of-memory error.
2313 *********************************************************************/
2314 static jb_err server_content_type(struct client_state *csp, char **header)
2316 /* Remove header if it isn't the first Content-Type header */
2317 if ((csp->content_type & CT_DECLARED))
2319 if (content_filters_enabled(csp->action))
2322 * Making sure the client interprets the content the same way
2323 * Privoxy did is only relevant if Privoxy modified it.
2325 * Checking for this is "hard" as it's not yet known when
2326 * this function is called, thus go shopping and and just
2327 * check if Privoxy could filter it.
2329 * The main thing is that we don't mess with the headers
2330 * unless the user signalled that it's acceptable.
2332 log_error(LOG_LEVEL_HEADER,
2333 "Multiple Content-Type headers detected. "
2334 "Removing and ignoring: %s",
2342 * Signal that the Content-Type has been set.
2344 csp->content_type |= CT_DECLARED;
2346 if (!(csp->content_type & CT_TABOO))
2349 * XXX: The assumption that text/plain is a sign of
2350 * binary data seems to be somewhat unreasonable nowadays
2351 * and should be dropped after 3.0.8 is out.
2353 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2354 || strstr(*header, "xml")
2355 || strstr(*header, "script"))
2357 csp->content_type |= CT_TEXT;
2359 else if (strstr(*header, "image/gif"))
2361 csp->content_type |= CT_GIF;
2366 * Are we messing with the content type?
2368 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2371 * Make sure the user doesn't accidentally
2372 * change the content type of binary documents.
2374 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2378 *header = strdup_or_die("Content-Type: ");
2380 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2381 if (JB_ERR_OK != err)
2383 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2384 return JB_ERR_MEMORY;
2386 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2390 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2391 "It doesn't look like a content type that should be filtered. "
2392 "Enable force-text-mode if you know what you're doing.", *header);
2400 /*********************************************************************
2402 * Function : server_transfer_coding
2404 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2405 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2406 * - Remove header if body was chunked but has been
2407 * de-chunked for filtering.
2410 * 1 : csp = Current client state (buffers, headers, etc...)
2411 * 2 : header = On input, pointer to header to modify.
2412 * On output, pointer to the modified header, or NULL
2413 * to remove the header. This function frees the
2414 * original string if necessary.
2416 * Returns : JB_ERR_OK on success, or
2417 * JB_ERR_MEMORY on out-of-memory error.
2419 *********************************************************************/
2420 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2423 * Turn off pcrs and gif filtering if body compressed
2425 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2429 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2431 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2432 csp->http->cmd, *header);
2433 #endif /* def FEATURE_ZLIB */
2434 csp->content_type = CT_TABOO;
2438 * Raise flag if body chunked
2440 if (strstr(*header, "chunked"))
2442 csp->flags |= CSP_FLAG_CHUNKED;
2445 * If the body was modified, it has been de-chunked first
2446 * and the header must be removed.
2448 * FIXME: If there is more than one transfer encoding,
2449 * only the "chunked" part should be removed here.
2451 if (csp->flags & CSP_FLAG_MODIFIED)
2453 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2462 /*********************************************************************
2464 * Function : server_content_encoding
2466 * Description : Used to check if the content is compressed, and if
2467 * FEATURE_ZLIB is disabled, filtering is disabled as
2470 * If FEATURE_ZLIB is enabled and the compression type
2471 * supported, the content is marked for decompression.
2473 * XXX: Doesn't properly deal with multiple or with
2474 * unsupported but unknown encodings.
2475 * Is case-sensitive but shouldn't be.
2478 * 1 : csp = Current client state (buffers, headers, etc...)
2479 * 2 : header = On input, pointer to header to modify.
2480 * On output, pointer to the modified header, or NULL
2481 * to remove the header. This function frees the
2482 * original string if necessary.
2484 * Returns : JB_ERR_OK on success, or
2485 * JB_ERR_MEMORY on out-of-memory error.
2487 *********************************************************************/
2488 static jb_err server_content_encoding(struct client_state *csp, char **header)
2491 if (strstr(*header, "sdch"))
2494 * Shared Dictionary Compression over HTTP isn't supported,
2495 * filtering it anyway is pretty much guaranteed to mess up
2498 csp->content_type |= CT_TABOO;
2501 * Log a warning if the user expects the content to be filtered.
2503 if (content_filters_enabled(csp->action))
2505 log_error(LOG_LEVEL_INFO,
2506 "SDCH-compressed content detected, content filtering disabled. "
2507 "Consider suppressing SDCH offers made by the client.");
2510 else if (strstr(*header, "gzip"))
2512 /* Mark for gzip decompression */
2513 csp->content_type |= CT_GZIP;
2515 else if (strstr(*header, "deflate"))
2517 /* Mark for zlib decompression */
2518 csp->content_type |= CT_DEFLATE;
2520 else if (strstr(*header, "br"))
2522 #ifdef FEATURE_BROTLI
2523 /* Mark for Brotli decompression */
2524 csp->content_type |= CT_BROTLI;
2526 csp->content_type |= CT_TABOO;
2529 else if (strstr(*header, "compress"))
2532 * We can't decompress this; therefore we can't filter
2535 csp->content_type |= CT_TABOO;
2537 #else /* !defined(FEATURE_ZLIB) */
2539 * XXX: Using a black list here isn't the right approach.
2541 * In case of SDCH, building with zlib support isn't
2544 if (strstr(*header, "gzip") ||
2545 strstr(*header, "compress") ||
2546 strstr(*header, "deflate") ||
2547 strstr(*header, "sdch"))
2550 * Body is compressed, turn off pcrs and gif filtering.
2552 csp->content_type |= CT_TABOO;
2555 * Log a warning if the user expects the content to be filtered.
2557 if (content_filters_enabled(csp->action))
2559 log_error(LOG_LEVEL_INFO,
2560 "Compressed content detected, content filtering disabled. "
2561 "Consider recompiling Privoxy with zlib support or "
2562 "enable the prevent-compression action.");
2565 #endif /* defined(FEATURE_ZLIB) */
2573 /*********************************************************************
2575 * Function : server_adjust_content_encoding
2577 * Description : Remove the Content-Encoding header if the
2578 * decompression was successful and the content
2579 * has been modified.
2582 * 1 : csp = Current client state (buffers, headers, etc...)
2583 * 2 : header = On input, pointer to header to modify.
2584 * On output, pointer to the modified header, or NULL
2585 * to remove the header. This function frees the
2586 * original string if necessary.
2588 * Returns : JB_ERR_OK on success, or
2589 * JB_ERR_MEMORY on out-of-memory error.
2591 *********************************************************************/
2592 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2594 if ((csp->flags & CSP_FLAG_MODIFIED)
2595 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2596 #ifdef FEATURE_BROTLI
2597 || (csp->content_type & CT_BROTLI)
2603 * We successfully decompressed the content,
2604 * and have to clean the header now, so the
2605 * client no longer expects compressed data.
2607 * XXX: There is a difference between cleaning
2608 * and removing it completely.
2610 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2617 #endif /* defined(FEATURE_ZLIB) */
2620 /*********************************************************************
2622 * Function : server_adjust_content_length
2624 * Description : Adjust Content-Length header if we modified
2628 * 1 : csp = Current client state (buffers, headers, etc...)
2629 * 2 : header = On input, pointer to header to modify.
2630 * On output, pointer to the modified header, or NULL
2631 * to remove the header. This function frees the
2632 * original string if necessary.
2634 * Returns : JB_ERR_OK on success, or
2635 * JB_ERR_MEMORY on out-of-memory error.
2637 *********************************************************************/
2638 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2640 /* Regenerate header if the content was modified. */
2641 if (csp->flags & CSP_FLAG_MODIFIED)
2643 const size_t header_length = 50;
2645 *header = malloc(header_length);
2646 if (*header == NULL)
2648 return JB_ERR_MEMORY;
2650 create_content_length_header(csp->content_length, *header, header_length);
2651 log_error(LOG_LEVEL_HEADER,
2652 "Adjusted Content-Length to %llu", csp->content_length);
2659 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2660 /*********************************************************************
2662 * Function : server_save_content_length
2664 * Description : Save the Content-Length sent by the server.
2667 * 1 : csp = Current client state (buffers, headers, etc...)
2668 * 2 : header = On input, pointer to header to modify.
2669 * On output, pointer to the modified header, or NULL
2670 * to remove the header. This function frees the
2671 * original string if necessary.
2673 * Returns : JB_ERR_OK on success, or
2674 * JB_ERR_MEMORY on out-of-memory error.
2676 *********************************************************************/
2677 static jb_err server_save_content_length(struct client_state *csp, char **header)
2679 unsigned long long content_length = 0;
2680 const char *header_value;
2682 assert(*(*header+14) == ':');
2684 header_value = *header + 15;
2685 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2687 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2692 csp->expected_content_length = content_length;
2693 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2694 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2699 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2702 /*********************************************************************
2704 * Function : server_content_md5
2706 * Description : Crumble any Content-MD5 headers if the document was
2707 * modified. FIXME: Should we re-compute instead?
2710 * 1 : csp = Current client state (buffers, headers, etc...)
2711 * 2 : header = On input, pointer to header to modify.
2712 * On output, pointer to the modified header, or NULL
2713 * to remove the header. This function frees the
2714 * original string if necessary.
2716 * Returns : JB_ERR_OK on success, or
2717 * JB_ERR_MEMORY on out-of-memory error.
2719 *********************************************************************/
2720 static jb_err server_content_md5(struct client_state *csp, char **header)
2722 if (csp->flags & CSP_FLAG_MODIFIED)
2724 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2732 /*********************************************************************
2734 * Function : server_content_disposition
2736 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2737 * Called from `sed'.
2740 * 1 : csp = Current client state (buffers, headers, etc...)
2741 * 2 : header = On input, pointer to header to modify.
2742 * On output, pointer to the modified header, or NULL
2743 * to remove the header. This function frees the
2744 * original string if necessary.
2746 * Returns : JB_ERR_OK on success, or
2747 * JB_ERR_MEMORY on out-of-memory error.
2749 *********************************************************************/
2750 static jb_err server_content_disposition(struct client_state *csp, char **header)
2755 * Are we messing with the Content-Disposition header?
2757 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2763 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2765 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2768 * Blocking content-disposition header
2770 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2777 * Replacing Content-Disposition header
2780 *header = strdup("Content-Disposition: ");
2781 string_append(header, newval);
2783 if (*header != NULL)
2785 log_error(LOG_LEVEL_HEADER,
2786 "Content-Disposition header crunched and replaced with: %s", *header);
2789 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2793 /*********************************************************************
2795 * Function : server_last_modified
2797 * Description : Changes Last-Modified header to the actual date
2798 * to help hide-if-modified-since.
2799 * Called from `sed'.
2802 * 1 : csp = Current client state (buffers, headers, etc...)
2803 * 2 : header = On input, pointer to header to modify.
2804 * On output, pointer to the modified header, or NULL
2805 * to remove the header. This function frees the
2806 * original string if necessary.
2808 * Returns : JB_ERR_OK on success, or
2809 * JB_ERR_MEMORY on out-of-memory error.
2811 *********************************************************************/
2812 static jb_err server_last_modified(struct client_state *csp, char **header)
2815 time_t last_modified;
2819 * Are we messing with the Last-Modified header?
2821 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2827 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2829 if (0 == strcmpic(newval, "block"))
2832 * Blocking Last-Modified header. Useless but why not.
2834 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2838 else if (0 == strcmpic(newval, "reset-to-request-time"))
2841 * Setting Last-Modified Header to now.
2844 get_http_time(0, buf, sizeof(buf));
2846 *header = strdup("Last-Modified: ");
2847 string_append(header, buf);
2849 if (*header == NULL)
2851 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2855 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2858 else if (0 == strcmpic(newval, "randomize"))
2860 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2862 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2864 log_error(LOG_LEVEL_HEADER,
2865 "Couldn't parse time in %s (crunching!)", *header);
2871 struct tm *timeptr = NULL;
2876 rtime = (long int)difftime(now, last_modified);
2879 long int days, hours, minutes, seconds;
2880 const int negative_delta = (rtime < 0);
2885 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2887 rtime = pick_from_range(rtime);
2892 last_modified += rtime;
2893 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2894 if ((NULL == timeptr) || !strftime(newheader,
2895 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2897 log_error(LOG_LEVEL_ERROR,
2898 "Randomizing '%s' failed. Crunching the header without replacement.",
2904 *header = strdup("Last-Modified: ");
2905 string_append(header, newheader);
2907 if (*header == NULL)
2909 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2910 return JB_ERR_MEMORY;
2913 days = rtime / (3600 * 24);
2914 hours = rtime / 3600 % 24;
2915 minutes = rtime / 60 % 60;
2916 seconds = rtime % 60;
2918 log_error(LOG_LEVEL_HEADER,
2919 "Randomized: %s (added %ld da%s %ld hou%s %ld minut%s %ld second%s",
2920 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2921 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2925 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2934 /*********************************************************************
2936 * Function : client_accept_encoding
2938 * Description : Rewrite the client's Accept-Encoding header so that
2939 * if doesn't allow compression, if the action applies.
2940 * Note: For HTTP/1.0 the absence of the header is enough.
2943 * 1 : csp = Current client state (buffers, headers, etc...)
2944 * 2 : header = On input, pointer to header to modify.
2945 * On output, pointer to the modified header, or NULL
2946 * to remove the header. This function frees the
2947 * original string if necessary.
2949 * Returns : JB_ERR_OK on success, or
2950 * JB_ERR_MEMORY on out-of-memory error.
2952 *********************************************************************/
2953 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2955 #ifdef FEATURE_COMPRESSION
2956 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2957 && strstr(*header, "deflate"))
2959 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2962 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2964 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2972 /*********************************************************************
2974 * Function : client_te
2976 * Description : Rewrite the client's TE header so that
2977 * if doesn't allow compression, if the action applies.
2980 * 1 : csp = Current client state (buffers, headers, etc...)
2981 * 2 : header = On input, pointer to header to modify.
2982 * On output, pointer to the modified header, or NULL
2983 * to remove the header. This function frees the
2984 * original string if necessary.
2986 * Returns : JB_ERR_OK on success, or
2987 * JB_ERR_MEMORY on out-of-memory error.
2989 *********************************************************************/
2990 static jb_err client_te(struct client_state *csp, char **header)
2992 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2995 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3002 /*********************************************************************
3004 * Function : client_referrer
3006 * Description : Handle the "referer" config setting properly.
3007 * Called from `sed'.
3010 * 1 : csp = Current client state (buffers, headers, etc...)
3011 * 2 : header = On input, pointer to header to modify.
3012 * On output, pointer to the modified header, or NULL
3013 * to remove the header. This function frees the
3014 * original string if necessary.
3016 * Returns : JB_ERR_OK on success, or
3017 * JB_ERR_MEMORY on out-of-memory error.
3019 *********************************************************************/
3020 static jb_err client_referrer(struct client_state *csp, char **header)
3022 const char *parameter;
3023 /* booleans for parameters we have to check multiple times */
3024 int parameter_conditional_block;
3025 int parameter_conditional_forge;
3027 #ifdef FEATURE_FORCE_LOAD
3029 * Since the referrer can include the prefix even
3030 * if the request itself is non-forced, we must
3031 * clean it unconditionally.
3033 * XXX: strclean is too broad
3035 strclean(*header, FORCE_PREFIX);
3036 #endif /* def FEATURE_FORCE_LOAD */
3038 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3040 /* Nothing left to do */
3044 parameter = csp->action->string[ACTION_STRING_REFERER];
3045 assert(parameter != NULL);
3046 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3047 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3049 if (!parameter_conditional_block && !parameter_conditional_forge)
3052 * As conditional-block and conditional-forge are the only
3053 * parameters that rely on the original referrer, we can
3054 * remove it now for all the others.
3059 if (0 == strcmpic(parameter, "block"))
3061 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3064 else if (parameter_conditional_block || parameter_conditional_forge)
3066 return handle_conditional_hide_referrer_parameter(header,
3067 csp->http->hostport, parameter_conditional_block);
3069 else if (0 == strcmpic(parameter, "forge"))
3071 return create_forged_referrer(header, csp->http->hostport);
3075 /* interpret parameter as user-supplied referer to fake */
3076 return create_fake_referrer(header, parameter);
3081 /*********************************************************************
3083 * Function : client_accept_language
3085 * Description : Handle the "Accept-Language" config setting properly.
3086 * Called from `sed'.
3089 * 1 : csp = Current client state (buffers, headers, etc...)
3090 * 2 : header = On input, pointer to header to modify.
3091 * On output, pointer to the modified header, or NULL
3092 * to remove the header. This function frees the
3093 * original string if necessary.
3095 * Returns : JB_ERR_OK on success, or
3096 * JB_ERR_MEMORY on out-of-memory error.
3098 *********************************************************************/
3099 static jb_err client_accept_language(struct client_state *csp, char **header)
3104 * Are we messing with the Accept-Language?
3106 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3108 /*I don't think so*/
3112 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3114 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3117 * Blocking Accept-Language header
3119 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3126 * Replacing Accept-Language header
3129 *header = strdup("Accept-Language: ");
3130 string_append(header, newval);
3132 if (*header == NULL)
3134 log_error(LOG_LEVEL_ERROR,
3135 "Insufficient memory. Accept-Language header crunched without replacement.");
3139 log_error(LOG_LEVEL_HEADER,
3140 "Accept-Language header crunched and replaced with: %s", *header);
3143 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3147 /*********************************************************************
3149 * Function : crunch_client_header
3151 * Description : Crunch client header if it matches a string supplied by the
3152 * user. Called from `sed'.
3155 * 1 : csp = Current client state (buffers, headers, etc...)
3156 * 2 : header = On input, pointer to header to modify.
3157 * On output, pointer to the modified header, or NULL
3158 * to remove the header. This function frees the
3159 * original string if necessary.
3161 * Returns : JB_ERR_OK on success and always succeeds
3163 *********************************************************************/
3164 static jb_err crunch_client_header(struct client_state *csp, char **header)
3166 const char *crunch_pattern;
3168 /* Do we feel like crunching? */
3169 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3171 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3173 /* Is the current header the lucky one? */
3174 if (strstr(*header, crunch_pattern))
3176 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3184 /*********************************************************************
3186 * Function : client_uagent
3188 * Description : Handle the "user-agent" config setting properly
3189 * and remember its original value to enable browser
3190 * bug workarounds. Called from `sed'.
3193 * 1 : csp = Current client state (buffers, headers, etc...)
3194 * 2 : header = On input, pointer to header to modify.
3195 * On output, pointer to the modified header, or NULL
3196 * to remove the header. This function frees the
3197 * original string if necessary.
3199 * Returns : JB_ERR_OK on success, or
3200 * JB_ERR_MEMORY on out-of-memory error.
3202 *********************************************************************/
3203 static jb_err client_uagent(struct client_state *csp, char **header)
3207 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3212 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3219 *header = strdup("User-Agent: ");
3220 string_append(header, newval);
3222 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3224 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3228 /*********************************************************************
3230 * Function : client_ua
3232 * Description : Handle "ua-" headers properly. 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, or
3242 * JB_ERR_MEMORY on out-of-memory error.
3244 *********************************************************************/
3245 static jb_err client_ua(struct client_state *csp, char **header)
3247 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3249 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3257 /*********************************************************************
3259 * Function : client_from
3261 * Description : Handle the "from" config setting properly.
3262 * Called from `sed'.
3265 * 1 : csp = Current client state (buffers, headers, etc...)
3266 * 2 : header = On input, pointer to header to modify.
3267 * On output, pointer to the modified header, or NULL
3268 * to remove the header. This function frees the
3269 * original string if necessary.
3271 * Returns : JB_ERR_OK on success, or
3272 * JB_ERR_MEMORY on out-of-memory error.
3274 *********************************************************************/
3275 static jb_err client_from(struct client_state *csp, char **header)
3279 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3286 newval = csp->action->string[ACTION_STRING_FROM];
3289 * Are we blocking the e-mail address?
3291 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3293 log_error(LOG_LEVEL_HEADER, "crunched From!");
3297 log_error(LOG_LEVEL_HEADER, " modified");
3299 *header = strdup("From: ");
3300 string_append(header, newval);
3302 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3306 /*********************************************************************
3308 * Function : client_send_cookie
3310 * Description : Crunches the "cookie" header if necessary.
3311 * Called from `sed'.
3313 * XXX: Stupid name, doesn't send squat.
3316 * 1 : csp = Current client state (buffers, headers, etc...)
3317 * 2 : header = On input, pointer to header to modify.
3318 * On output, pointer to the modified header, or NULL
3319 * to remove the header. This function frees the
3320 * original string if necessary.
3322 * Returns : JB_ERR_OK on success, or
3323 * JB_ERR_MEMORY on out-of-memory error.
3325 *********************************************************************/
3326 static jb_err client_send_cookie(struct client_state *csp, char **header)
3328 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3330 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3338 /*********************************************************************
3340 * Function : client_x_forwarded
3342 * Description : Handle the "x-forwarded-for" config setting properly,
3343 * also used in the add_client_headers list. Called from `sed'.
3346 * 1 : csp = Current client state (buffers, headers, etc...)
3347 * 2 : header = On input, pointer to header to modify.
3348 * On output, pointer to the modified header, or NULL
3349 * to remove the header. This function frees the
3350 * original string if necessary.
3352 * Returns : JB_ERR_OK on success, or
3353 * JB_ERR_MEMORY on out-of-memory error.
3355 *********************************************************************/
3356 jb_err client_x_forwarded(struct client_state *csp, char **header)
3358 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3360 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3362 if (0 == strcmpic(parameter, "block"))
3365 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3367 else if (0 == strcmpic(parameter, "add"))
3369 string_append(header, ", ");
3370 string_append(header, csp->ip_addr_str);
3372 if (*header == NULL)
3374 return JB_ERR_MEMORY;
3376 log_error(LOG_LEVEL_HEADER,
3377 "Appended client IP address to %s", *header);
3378 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3382 log_error(LOG_LEVEL_FATAL,
3383 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3391 /*********************************************************************
3393 * Function : client_max_forwards
3395 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3396 * from the value of the Max-Forwards header field.
3399 * 1 : csp = Current client state (buffers, headers, etc...)
3400 * 2 : header = On input, pointer to header to modify.
3401 * On output, pointer to the modified header, or NULL
3402 * to remove the header. This function frees the
3403 * original string if necessary.
3405 * Returns : JB_ERR_OK on success, or
3406 * JB_ERR_MEMORY on out-of-memory error.
3408 *********************************************************************/
3409 static jb_err client_max_forwards(struct client_state *csp, char **header)
3413 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3414 (0 == strcmpic(csp->http->gpc, "options")))
3416 assert(*(*header+12) == ':');
3417 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3419 if (max_forwards > 0)
3421 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3422 log_error(LOG_LEVEL_HEADER,
3423 "Max-Forwards value for %s request reduced to %d.",
3424 csp->http->gpc, max_forwards);
3426 else if (max_forwards < 0)
3428 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3434 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3443 /*********************************************************************
3445 * Function : client_host
3447 * Description : If the request URI did not contain host and
3448 * port information, parse and evaluate the Host
3452 * 1 : csp = Current client state (buffers, headers, etc...)
3453 * 2 : header = On input, pointer to header to modify.
3454 * On output, pointer to the modified header, or NULL
3455 * to remove the header. This function frees the
3456 * original string if necessary.
3458 * Returns : JB_ERR_OK on success, or
3459 * JB_ERR_MEMORY on out-of-memory error.
3461 *********************************************************************/
3462 static jb_err client_host(struct client_state *csp, char **header)
3466 if (strlen(*header) < 7)
3468 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3473 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3474 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3477 p = strdup_or_die((*header)+6);
3479 q = strdup_or_die(p);
3481 freez(csp->http->hostport);
3482 csp->http->hostport = p;
3483 freez(csp->http->host);
3484 csp->http->host = q;
3485 q = strchr(csp->http->host, ':');
3488 /* Terminate hostname and evaluate port string */
3490 csp->http->port = atoi(q);
3494 csp->http->port = csp->http->ssl ? 443 : 80;
3497 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3498 csp->http->hostport, csp->http->host, csp->http->port);
3501 /* Signal client_host_adder() to return right away */
3502 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3508 /*********************************************************************
3510 * Function : client_if_modified_since
3512 * Description : Remove or modify the If-Modified-Since header.
3515 * 1 : csp = Current client state (buffers, headers, etc...)
3516 * 2 : header = On input, pointer to header to modify.
3517 * On output, pointer to the modified header, or NULL
3518 * to remove the header. This function frees the
3519 * original string if necessary.
3521 * Returns : JB_ERR_OK on success, or
3522 * JB_ERR_MEMORY on out-of-memory error.
3524 *********************************************************************/
3525 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3529 struct tm *timeptr = NULL;
3534 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3537 * The client got an error message because of a temporary problem,
3538 * the problem is gone and the client now tries to revalidate our
3539 * error message on the real server. The revalidation would always
3540 * end with the transmission of the whole document and there is
3541 * no need to expose the bogus If-Modified-Since header.
3543 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3546 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3548 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3550 if ((0 == strcmpic(newval, "block")))
3552 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3555 else /* add random value */
3557 if (JB_ERR_OK != parse_time_header(*header, &tm))
3559 log_error(LOG_LEVEL_HEADER,
3560 "Couldn't parse time in %s (crunching!)", *header);
3565 long int hours, minutes, seconds;
3566 long int rtime = strtol(newval, &endptr, 0);
3567 const int negative_range = (rtime < 0);
3571 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %ld minut%s)",
3572 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3578 rtime = pick_from_range(rtime);
3582 log_error(LOG_LEVEL_ERROR,
3583 "Random range is 0. Assuming time transformation test.");
3585 tm += rtime * (negative_range ? -1 : 1);
3586 timeptr = privoxy_gmtime_r(&tm, &gmt);
3587 if ((NULL == timeptr) || !strftime(newheader,
3588 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3590 log_error(LOG_LEVEL_ERROR,
3591 "Randomizing '%s' failed. Crunching the header without replacement.",
3597 *header = strdup("If-Modified-Since: ");
3598 string_append(header, newheader);
3600 if (*header == NULL)
3602 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3603 return JB_ERR_MEMORY;
3606 hours = rtime / 3600;
3607 minutes = rtime / 60 % 60;
3608 seconds = rtime % 60;
3610 log_error(LOG_LEVEL_HEADER,
3611 "Randomized: %s (%s %ld hou%s %ld minut%s %ld second%s",
3612 *header, (negative_range) ? "subtracted" : "added", hours,
3613 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3614 seconds, (seconds == 1) ? ")" : "s)");
3623 /*********************************************************************
3625 * Function : client_if_none_match
3627 * Description : Remove the If-None-Match header.
3630 * 1 : csp = Current client state (buffers, headers, etc...)
3631 * 2 : header = On input, pointer to header to modify.
3632 * On output, pointer to the modified header, or NULL
3633 * to remove the header. This function frees the
3634 * original string if necessary.
3636 * Returns : JB_ERR_OK on success, or
3637 * JB_ERR_MEMORY on out-of-memory error.
3639 *********************************************************************/
3640 static jb_err client_if_none_match(struct client_state *csp, char **header)
3642 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3644 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3652 /*********************************************************************
3654 * Function : client_x_filter
3656 * Description : Disables filtering if the client set "X-Filter: No".
3657 * Called from `sed'.
3660 * 1 : csp = Current client state (buffers, headers, etc...)
3661 * 2 : header = On input, pointer to header to modify.
3662 * On output, pointer to the modified header, or NULL
3663 * to remove the header. This function frees the
3664 * original string if necessary.
3666 * Returns : JB_ERR_OK on success
3668 *********************************************************************/
3669 jb_err client_x_filter(struct client_state *csp, char **header)
3671 if (0 == strcmpic(*header, "X-Filter: No"))
3673 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3675 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3679 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3681 log_error(LOG_LEVEL_HEADER,
3682 "force-text-mode overruled the client's request to fetch without filtering!");
3686 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3687 csp->flags |= CSP_FLAG_NO_FILTERING;
3688 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3690 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3698 /*********************************************************************
3700 * Function : client_range
3702 * Description : Removes Range, Request-Range and If-Range headers if
3703 * content filtering is enabled and the range doesn't
3706 * If the client's version of the document has been
3707 * altered by Privoxy, the server could interpret the
3708 * range differently than the client intended in which
3709 * case the user could end up with corrupted content.
3711 * If the range starts at byte 0 this isn't an issue
3712 * so the header can pass. Partial requests like this
3713 * are used to render preview images for videos without
3714 * downloading the whole video.
3716 * While HTTP doesn't require that range requests are
3717 * honoured and the client could simply abort the download
3718 * after receiving a sufficient amount of data, various
3719 * clients don't handle complete responses to range
3720 * requests gracefully and emit misleading error messages
3724 * 1 : csp = Current client state (buffers, headers, etc...)
3725 * 2 : header = On input, pointer to header to modify.
3726 * On output, pointer to the modified header, or NULL
3727 * to remove the header. This function frees the
3728 * original string if necessary.
3730 * Returns : JB_ERR_OK
3732 *********************************************************************/
3733 static jb_err client_range(struct client_state *csp, char **header)
3735 if (content_filters_enabled(csp->action)
3736 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3738 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3739 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3746 /* the following functions add headers directly to the header list */
3748 /*********************************************************************
3750 * Function : client_host_adder
3752 * Description : Adds the Host: header field if it is missing.
3753 * Called from `sed'.
3756 * 1 : csp = Current client state (buffers, headers, etc...)
3758 * Returns : JB_ERR_OK on success, or
3759 * JB_ERR_MEMORY on out-of-memory error.
3761 *********************************************************************/
3762 static jb_err client_host_adder(struct client_state *csp)
3767 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3769 /* Header already set by the client, nothing to do. */
3773 if (!csp->http->hostport || !*(csp->http->hostport))
3775 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3776 return JB_ERR_PARSE;
3780 * remove 'user:pass@' from 'proto://user:pass@host'
3782 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3788 p = csp->http->hostport;
3791 /* XXX: Just add it, we already made sure that it will be unique */
3792 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3793 err = enlist_unique_header(csp->headers, "Host", p);
3799 /*********************************************************************
3801 * Function : client_xtra_adder
3803 * Description : Used in the add_client_headers list. Called from `sed'.
3806 * 1 : csp = Current client state (buffers, headers, etc...)
3808 * Returns : JB_ERR_OK on success, or
3809 * JB_ERR_MEMORY on out-of-memory error.
3811 *********************************************************************/
3812 static jb_err client_xtra_adder(struct client_state *csp)
3814 struct list_entry *lst;
3817 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3818 lst ; lst = lst->next)
3820 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3821 err = enlist(csp->headers, lst->str);
3833 /*********************************************************************
3835 * Function : client_x_forwarded_for_adder
3837 * Description : Used in the add_client_headers list. Called from `sed'.
3840 * 1 : csp = Current client state (buffers, headers, etc...)
3842 * Returns : JB_ERR_OK on success, or
3843 * JB_ERR_MEMORY on out-of-memory error.
3845 *********************************************************************/
3846 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3848 char *header = NULL;
3851 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3852 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3853 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3856 * If we aren't adding X-Forwarded-For headers,
3857 * or we already appended an existing X-Forwarded-For
3858 * header, there's nothing left to do here.
3863 header = strdup("X-Forwarded-For: ");
3864 string_append(&header, csp->ip_addr_str);
3868 return JB_ERR_MEMORY;
3871 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3872 err = enlist(csp->headers, header);
3879 /*********************************************************************
3881 * Function : server_connection_adder
3883 * Description : Adds an appropriate "Connection:" header to csp->headers
3884 * unless the header was already present. Called from `sed'.
3887 * 1 : csp = Current client state (buffers, headers, etc...)
3889 * Returns : JB_ERR_OK on success, or
3890 * JB_ERR_MEMORY on out-of-memory error.
3892 *********************************************************************/
3893 static jb_err server_connection_adder(struct client_state *csp)
3895 const unsigned int flags = csp->flags;
3896 const char *response_status_line = csp->headers->first->str;
3897 static const char connection_close[] = "Connection: close";
3899 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3900 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3906 * XXX: if we downgraded the response, this check will fail.
3908 if ((csp->config->feature_flags &
3909 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3910 && (NULL != response_status_line)
3911 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3912 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3913 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3917 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3918 "without Connection header implies keep-alive.");
3919 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3923 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3925 return enlist(csp->headers, connection_close);
3929 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3930 /*********************************************************************
3932 * Function : server_proxy_connection_adder
3934 * Description : Adds a "Proxy-Connection: keep-alive" header to
3935 * csp->headers when appropriate.
3938 * 1 : csp = Current client state (buffers, headers, etc...)
3940 * Returns : JB_ERR_OK on success, or
3941 * JB_ERR_MEMORY on out-of-memory error.
3943 *********************************************************************/
3944 static jb_err server_proxy_connection_adder(struct client_state *csp)
3946 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3947 jb_err err = JB_ERR_OK;
3949 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3950 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3951 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3952 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3953 || (csp->flags & CSP_FLAG_CHUNKED))
3954 #ifdef FEATURE_HTTPS_INSPECTION
3955 && !client_use_ssl(csp)
3960 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3961 err = enlist(csp->headers, proxy_connection_header);
3966 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3969 /*********************************************************************
3971 * Function : client_connection_header_adder
3973 * Description : Adds a proper "Connection:" header to csp->headers
3974 * unless the header was already present or it's a
3975 * CONNECT request. Called from `sed'.
3978 * 1 : csp = Current client state (buffers, headers, etc...)
3980 * Returns : JB_ERR_OK on success, or
3981 * JB_ERR_MEMORY on out-of-memory error.
3983 *********************************************************************/
3984 static jb_err client_connection_header_adder(struct client_state *csp)
3986 static const char connection_close[] = "Connection: close";
3988 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3989 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3995 * In case of CONNECT requests "Connection: close" is implied,
3996 * but actually setting the header has been reported to cause
3997 * problems with some forwarding proxies that close the
3998 * connection prematurely.
4000 if (csp->http->ssl != 0)
4005 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4006 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4007 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4008 && !strcmpic(csp->http->version, "HTTP/1.1"))
4010 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4013 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4015 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4017 return enlist(csp->headers, connection_close);
4021 /*********************************************************************
4023 * Function : server_http
4025 * Description : - Save the HTTP Status into csp->http->status
4026 * - Set CT_TABOO to prevent filtering if the answer
4027 * is a partial range (HTTP status 206)
4028 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4030 * - Normalize the HTTP-version.
4033 * 1 : csp = Current client state (buffers, headers, etc...)
4034 * 2 : header = On input, pointer to header to modify.
4035 * On output, pointer to the modified header, or NULL
4036 * to remove the header. This function frees the
4037 * original string if necessary.
4039 * Returns : JB_ERR_OK on success, or
4040 * JB_ERR_PARSE on fatal parse errors.
4042 *********************************************************************/
4043 static jb_err server_http(struct client_state *csp, char **header)
4045 char *reason_phrase = NULL;
4046 char *new_response_line;
4049 unsigned int major_version;
4050 unsigned int minor_version;
4052 /* Get the reason phrase which start after the second whitespace */
4053 p = strchr(*header, ' ');
4057 reason_phrase = strchr(p, ' ');
4060 if (reason_phrase != NULL)
4066 log_error(LOG_LEVEL_ERROR,
4067 "Response line lacks reason phrase: %s", *header);
4071 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4072 &minor_version, &(csp->http->status)))
4074 log_error(LOG_LEVEL_ERROR,
4075 "Failed to parse the response line: %s", *header);
4076 return JB_ERR_PARSE;
4079 if (csp->http->status == 101 ||
4080 csp->http->status == 206)
4082 csp->content_type = CT_TABOO;
4085 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4088 * According to RFC 7230 2.6 intermediaries MUST send
4089 * their own HTTP-version in forwarded messages.
4091 log_error(LOG_LEVEL_ERROR,
4092 "Unsupported HTTP version. Downgrading to 1.1.");
4097 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4099 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4103 /* Rebuild response line. */
4104 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4105 new_response_line = malloc_or_die(length);
4107 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4108 major_version, minor_version, csp->http->status, reason_phrase);
4110 if (0 != strcmp(*header, new_response_line))
4112 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4113 *header, new_response_line);
4117 *header = new_response_line;
4122 /*********************************************************************
4124 * Function : add_cooky_expiry_date
4126 * Description : Adds a cookie expiry date to a string.
4129 * 1 : cookie = On input, pointer to cookie to modify.
4130 * On output, pointer to the modified header.
4131 * The original string is freed.
4132 * 2 : lifetime = Seconds the cookie should be valid
4136 *********************************************************************/
4137 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4140 struct tm *timeptr = NULL;
4141 time_t expiry_date = time(NULL) + lifetime;
4144 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4145 if (NULL == timeptr)
4147 log_error(LOG_LEVEL_FATAL,
4148 "Failed to get the time in add_cooky_expiry_date()");
4150 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4151 if (JB_ERR_OK != string_append(cookie, tmp))
4153 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4158 /*********************************************************************
4160 * Function : server_set_cookie
4162 * Description : Handle the server "cookie" header properly.
4163 * Crunch, accept or rewrite it to a session cookie.
4164 * Called from `sed'.
4167 * 1 : csp = Current client state (buffers, headers, etc...)
4168 * 2 : header = On input, pointer to header to modify.
4169 * On output, pointer to the modified header, or NULL
4170 * to remove the header. This function frees the
4171 * original string if necessary.
4173 * Returns : JB_ERR_OK on success, or
4174 * JB_ERR_MEMORY on out-of-memory error.
4176 *********************************************************************/
4177 static jb_err server_set_cookie(struct client_state *csp, char **header)
4179 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4181 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4184 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4185 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4189 long cookie_lifetime = 0;
4192 NO_EXPIRY_DATE_SPECIFIED,
4193 EXPIRY_DATE_ACCEPTABLE,
4194 EXPIRY_DATE_UNACCEPTABLE
4195 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4197 /* A variable to store the tag we're working on */
4200 /* Skip "Set-Cookie:" (11 characters) in header */
4201 cur_tag = *header + 11;
4203 /* skip whitespace between "Set-Cookie:" and value */
4204 while (*cur_tag && privoxy_isspace(*cur_tag))
4211 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4213 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4215 cookie_lifetime = strtol(param, NULL, 0);
4216 if (cookie_lifetime < 0)
4218 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4220 cookie_lifetime *= 60;
4223 /* Loop through each tag in the cookie */
4227 char *next_tag = strchr(cur_tag, ';');
4228 if (next_tag != NULL)
4230 /* Skip the ';' character itself */
4233 /* skip whitespace ";" and start of tag */
4234 while (*next_tag && privoxy_isspace(*next_tag))
4241 /* "Next tag" is the end of the string */
4242 next_tag = cur_tag + strlen(cur_tag);
4246 * Check the expiration date to see
4247 * if the cookie is still valid, if yes,
4248 * rewrite it to a session cookie.
4250 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4252 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4254 if ((expiration_date[0] == '"')
4255 && (expiration_date[1] != '\0'))
4258 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4259 * that the expiration date isn't supposed to be quoted,
4260 * but some servers do it anyway.
4265 /* Did we detect the date properly? */
4266 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4269 * Nope, treat it as if it was still valid.
4271 * XXX: Should we remove the whole cookie instead?
4273 log_error(LOG_LEVEL_ERROR,
4274 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4275 string_move(cur_tag, next_tag);
4276 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4281 * Yes. Check if the cookie is still valid.
4283 * If the cookie is already expired it's probably
4284 * a delete cookie and even if it isn't, the browser
4285 * will discard it anyway.
4289 * XXX: timegm() isn't available on some AmigaOS
4290 * versions and our replacement doesn't work.
4292 * Our options are to either:
4294 * - disable session-cookies-only completely if timegm
4297 * - to simply remove all expired tags, like it has
4298 * been done until Privoxy 3.0.6 and to live with
4299 * the consequence that it can cause login/logout
4300 * problems on servers that don't validate their
4301 * input properly, or
4303 * - to replace it with mktime in which
4304 * case there is a slight chance of valid cookies
4305 * passing as already expired.
4307 * This is the way it's currently done and it's not
4308 * as bad as it sounds. If the missing GMT offset is
4309 * enough to change the result of the expiration check
4310 * the cookie will be only valid for a few hours
4311 * anyway, which in many cases will be shorter
4312 * than a browser session.
4314 if (cookie_time < now)
4316 log_error(LOG_LEVEL_HEADER,
4317 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4318 /* Just in case some clown sets more then one expiration date */
4320 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4322 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4324 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4325 "Its lifetime is below the limit.", *header);
4326 /* Just in case some clown sets more then one expiration date */
4328 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4333 * Still valid, delete expiration date by copying
4334 * the rest of the string over it.
4336 string_move(cur_tag, next_tag);
4338 /* That changed the header, need to issue a log message */
4339 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4342 * Note that the next tag has now been moved to *cur_tag,
4343 * so we do not need to update the cur_tag pointer.
4351 /* Move on to next cookie tag */
4356 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4358 assert(NULL != *header);
4359 if (cookie_lifetime != 0)
4361 add_cookie_expiry_date(header, cookie_lifetime);
4362 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4364 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4366 log_error(LOG_LEVEL_HEADER,
4367 "Cookie rewritten to a temporary one: %s", *header);
4376 #ifdef FEATURE_FORCE_LOAD
4377 /*********************************************************************
4379 * Function : strclean
4381 * Description : In-Situ-Eliminate all occurrences of substring in
4385 * 1 : string = string to clean
4386 * 2 : substring = substring to eliminate
4388 * Returns : Number of eliminations
4390 *********************************************************************/
4391 int strclean(char *string, const char *substring)
4397 len = strlen(substring);
4399 while((pos = strstr(string, substring)) != NULL)
4406 while (*p++ != '\0');
4413 #endif /* def FEATURE_FORCE_LOAD */
4416 /*********************************************************************
4418 * Function : parse_header_time
4420 * Description : Parses time formats used in HTTP header strings
4421 * to get the numerical respresentation.
4424 * 1 : header_time = HTTP header time as string.
4425 * 2 : result = storage for header_time in seconds
4427 * Returns : JB_ERR_OK if the time format was recognized, or
4428 * JB_ERR_PARSE otherwise.
4430 *********************************************************************/
4431 static jb_err parse_header_time(const char *header_time, time_t *result)
4435 * Checking for two-digit years first in an
4436 * attempt to work around GNU libc's strptime()
4437 * reporting negative year values when using %Y.
4439 static const char time_formats[][22] = {
4440 /* Tue, 02-Jun-37 20:00:00 */
4441 "%a, %d-%b-%y %H:%M:%S",
4442 /* Tue, 02 Jun 2037 20:00:00 */
4443 "%a, %d %b %Y %H:%M:%S",
4444 /* Tue, 02-Jun-2037 20:00:00 */
4445 "%a, %d-%b-%Y %H:%M:%S",
4446 /* Tuesday, 02-Jun-2037 20:00:00 */
4447 "%A, %d-%b-%Y %H:%M:%S",
4448 /* Tuesday Jun 02 20:00:00 2037 */
4449 "%A %b %d %H:%M:%S %Y"
4453 for (i = 0; i < SZ(time_formats); i++)
4456 * Zero out gmt to prevent time zone offsets.
4457 * Documented to be required for GNU libc.
4459 memset(&gmt, 0, sizeof(gmt));
4461 if (NULL != strptime(header_time, time_formats[i], &gmt))
4463 /* Sanity check for GNU libc. */
4464 if (gmt.tm_year < 0)
4466 log_error(LOG_LEVEL_HEADER,
4467 "Failed to parse '%s' using '%s'. Moving on.",
4468 header_time, time_formats[i]);
4471 *result = timegm(&gmt);
4473 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4475 * Verify that parsing the date recreated from the first
4476 * parse operation gets the previous result. If it doesn't,
4477 * either strptime() or strftime() are malfunctioning.
4479 * We could string-compare the recreated date with the original
4480 * header date, but this leads to false positives as strptime()
4481 * may let %a accept all day formats while strftime() will only
4485 char recreated_date[100];
4490 tm = privoxy_gmtime_r(result, &storage);
4491 if (!strftime(recreated_date, sizeof(recreated_date),
4492 time_formats[i], tm))
4494 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4495 header_time, time_formats[i]);
4498 memset(&gmt, 0, sizeof(gmt));
4499 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4501 log_error(LOG_LEVEL_ERROR,
4502 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4503 recreated_date, time_formats[i], header_time);
4506 result2 = timegm(&gmt);
4507 if (*result != result2)
4509 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4510 "Format: '%s'. In: '%s', out: '%s'. %ld != %ld. Rejecting.",
4511 time_formats[i], header_time, recreated_date, *result, result2);
4521 return JB_ERR_PARSE;
4525 /*********************************************************************
4527 * Function : parse_time_header
4529 * Description : Parses the time in an HTTP time header to get
4530 * the numerical respresentation.
4533 * 1 : header = HTTP header with a time value
4534 * 2 : result = storage for header_time in seconds
4536 * Returns : JB_ERR_OK if the time format was recognized, or
4537 * JB_ERR_PARSE otherwise.
4539 *********************************************************************/
4540 static jb_err parse_time_header(const char *header, time_t *result)
4542 const char *header_time;
4544 header_time = strchr(header, ':');
4547 * Currently this can't happen as all callers are called
4548 * through sed() which requires a header name followed by
4551 assert(header_time != NULL);
4554 if (*header_time == ' ')
4559 return parse_header_time(header_time, result);
4564 /*********************************************************************
4566 * Function : get_destination_from_headers
4568 * Description : Parse the "Host:" header to get the request's destination.
4569 * Only needed if the client's request was forcefully
4570 * redirected into Privoxy.
4572 * Code mainly copied from client_host() which is currently
4573 * run too late for this purpose.
4576 * 1 : headers = List of headers (one of them hopefully being
4577 * the "Host:" header)
4578 * 2 : http = storage for the result (host, port and hostport).
4580 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4581 * JB_ERR_PARSE if the host header couldn't be found,
4582 * JB_ERR_OK otherwise.
4584 *********************************************************************/
4585 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4591 host = get_header_value(headers, "Host:");
4595 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4596 return JB_ERR_PARSE;
4599 p = string_tolower(host);
4602 return JB_ERR_MEMORY;
4605 q = strdup_or_die(p);
4607 freez(http->hostport);
4611 q = strchr(http->host, ':');
4614 /* Terminate hostname and evaluate port string */
4616 http->port = atoi(q);
4623 /* Rebuild request URL */
4625 http->url = strdup("http://");
4626 string_append(&http->url, http->hostport);
4627 string_append(&http->url, http->path);
4628 if (http->url == NULL)
4630 return JB_ERR_MEMORY;
4633 log_error(LOG_LEVEL_HEADER,
4634 "Destination extracted from \"Host\" header. New request URL: %s",
4638 * Regenerate request line in "proxy format"
4639 * to make rewrites more convenient.
4641 assert(http->cmd != NULL);
4643 http->cmd = strdup_or_die(http->gpc);
4644 string_append(&http->cmd, " ");
4645 string_append(&http->cmd, http->url);
4646 string_append(&http->cmd, " ");
4647 string_append(&http->cmd, http->version);
4648 if (http->cmd == NULL)
4650 return JB_ERR_MEMORY;
4658 #ifdef FEATURE_HTTPS_INSPECTION
4659 /*********************************************************************
4661 * Function : get_destination_from_https_headers
4663 * Description : Parse the previously encrypted "Host:" header to
4664 * get the request's destination.
4667 * 1 : headers = List of headers (one of them hopefully being
4668 * the "Host:" header)
4669 * 2 : http = storage for the result (host, port and hostport).
4671 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4672 * JB_ERR_PARSE if the host header couldn't be found,
4673 * JB_ERR_OK otherwise.
4675 *********************************************************************/
4676 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4682 host = get_header_value(headers, "Host:");
4686 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4687 return JB_ERR_PARSE;
4690 p = string_tolower(host);
4693 return JB_ERR_MEMORY;
4696 q = strdup_or_die(p);
4698 freez(http->hostport);
4702 q = strchr(http->host, ':');
4705 /* Terminate hostname and evaluate port string */
4707 http->port = atoi(q);
4714 /* Rebuild request URL */
4716 http->url = strdup_or_die(http->path);
4718 log_error(LOG_LEVEL_HEADER,
4719 "Destination extracted from \"Host\" header. New request URL: %s",
4723 * Regenerate request line in "proxy format"
4724 * to make rewrites more convenient.
4726 assert(http->cmd != NULL);
4728 http->cmd = strdup_or_die(http->gpc);
4729 string_append(&http->cmd, " ");
4730 string_append(&http->cmd, http->url);
4731 string_append(&http->cmd, " ");
4732 string_append(&http->cmd, http->version);
4733 if (http->cmd == NULL)
4735 return JB_ERR_MEMORY;
4741 #endif /* def FEATURE_HTTPS_INSPECTION */
4744 /*********************************************************************
4746 * Function : create_forged_referrer
4748 * Description : Helper for client_referrer to forge a referer as
4749 * 'http://hostname[:port]/' to fool stupid
4750 * checks for in-site links
4753 * 1 : header = Pointer to header pointer
4754 * 2 : hostport = Host and optionally port as string
4756 * Returns : JB_ERR_OK in case of success, or
4757 * JB_ERR_MEMORY in case of memory problems.
4759 *********************************************************************/
4760 static jb_err create_forged_referrer(char **header, const char *hostport)
4762 assert(NULL == *header);
4764 *header = strdup("Referer: http://");
4765 string_append(header, hostport);
4766 string_append(header, "/");
4768 if (NULL == *header)
4770 return JB_ERR_MEMORY;
4773 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4780 /*********************************************************************
4782 * Function : create_fake_referrer
4784 * Description : Helper for client_referrer to create a fake referrer
4785 * based on a string supplied by the user.
4788 * 1 : header = Pointer to header pointer
4789 * 2 : hosthost = Referrer to fake
4791 * Returns : JB_ERR_OK in case of success, or
4792 * JB_ERR_MEMORY in case of memory problems.
4794 *********************************************************************/
4795 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4797 assert(NULL == *header);
4799 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4801 log_error(LOG_LEVEL_HEADER,
4802 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4804 *header = strdup("Referer: ");
4805 string_append(header, fake_referrer);
4807 if (NULL == *header)
4809 return JB_ERR_MEMORY;
4812 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4819 /*********************************************************************
4821 * Function : handle_conditional_hide_referrer_parameter
4823 * Description : Helper for client_referrer to crunch or forge
4824 * the referrer header if the host has changed.
4827 * 1 : header = Pointer to header pointer
4828 * 2 : host = The target host (may include the port)
4829 * 3 : parameter_conditional_block = Boolean to signal
4830 * if we're in conditional-block mode. If not set,
4831 * we're in conditional-forge mode.
4833 * Returns : JB_ERR_OK in case of success, or
4834 * JB_ERR_MEMORY in case of memory problems.
4836 *********************************************************************/
4837 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4838 const char *host, const int parameter_conditional_block)
4840 char *referer = strdup_or_die(*header);
4841 const size_t hostlength = strlen(host);
4842 const char *referer_url = NULL;
4844 /* referer begins with 'Referer: http[s]://' */
4845 if ((hostlength+17) < strlen(referer))
4848 * Shorten referer to make sure the referer is blocked
4849 * if www.example.org/www.example.com-shall-see-the-referer/
4850 * links to www.example.com/
4852 referer[hostlength+17] = '\0';
4854 referer_url = strstr(referer, "http://");
4855 if (NULL == referer_url)
4857 referer_url = strstr(referer, "https://");
4859 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4861 /* Host has changed, Referer is invalid or a https URL. */
4862 if (parameter_conditional_block)
4864 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4871 return create_forged_referrer(header, host);
4881 /*********************************************************************
4883 * Function : create_content_length_header
4885 * Description : Creates a Content-Length header.
4888 * 1 : content_length = The content length to be used in the header.
4889 * 2 : header = Allocated space to safe the header.
4890 * 3 : buffer_length = The length of the allocated space.
4894 *********************************************************************/
4895 static void create_content_length_header(unsigned long long content_length,
4896 char *header, size_t buffer_length)
4899 #if SIZEOF_LONG_LONG < 8
4900 #error sizeof(unsigned long long) too small
4902 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4904 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4909 /*********************************************************************
4911 * Function : get_expected_content_length
4913 * Description : Figures out the content length from a list of headers.
4916 * 1 : headers = List of headers
4918 * Returns : Number of bytes to expect
4920 *********************************************************************/
4921 unsigned long long get_expected_content_length(struct list *headers)
4923 const char *content_length_header;
4924 unsigned long long content_length = 0;
4926 content_length_header = get_header_value(headers, "Content-Length:");
4927 if (content_length_header != NULL)
4929 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4931 log_error(LOG_LEVEL_ERROR,
4932 "Failed to get the Content-Length in %s", content_length_header);
4933 /* XXX: The header will be removed later on */
4938 return content_length;