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>
71 #if !defined(_WIN32) && !defined(__OS2__)
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_save_content_length(struct client_state *csp, char **header);
145 static jb_err client_proxy_connection(struct client_state *csp, char **header);
146 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
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 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
192 { "Keep-Alive:", 11, client_keep_alive },
193 { "Content-Length:", 15, client_save_content_length },
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: %d. Limit: %d",
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 %d 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: %d, new size: %d.",
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: %d",
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");
730 return JB_ERR_MEMORY;
733 /* Try doubling the buffer size each time. */
736 /* Don't exceed the buffer limit. */
737 if (bufsize > csp->config->buffer_limit)
739 bufsize = csp->config->buffer_limit;
742 /* Try to allocate the new buffer. */
743 tmpbuf = realloc(buf, bufsize);
746 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
748 return JB_ERR_MEMORY;
752 char *oldnext_out = (char *)zstr.next_out;
755 * Update the fields for inflate() to use the new
756 * buffer, which may be in a location different from
759 zstr.avail_out += (uInt)(bufsize - oldbufsize);
760 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
763 * Compare with an uglier method of calculating these values
764 * that doesn't require the extra oldbufsize variable.
766 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
767 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
773 if (Z_STREAM_ERROR == inflateEnd(&zstr))
775 log_error(LOG_LEVEL_ERROR,
776 "Inconsistent stream state after decompression: %s", zstr.msg);
778 * XXX: Intentionally no return.
780 * According to zlib.h, Z_STREAM_ERROR is returned
781 * "if the stream state was inconsistent".
783 * I assume in this case inflate()'s status
784 * would also be something different than Z_STREAM_END
785 * so this check should be redundant, but lets see.
789 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
792 * We failed to decompress the stream and it's
793 * not simply because of missing data.
795 log_error(LOG_LEVEL_ERROR,
796 "Unexpected error while decompressing to the buffer (iob): %s",
798 return JB_ERR_COMPRESS;
802 * Finally, we can actually update the iob, since the
803 * decompression was successful. First, free the old
806 freez(csp->iob->buf);
808 /* Now, update the iob to use the new buffer. */
810 csp->iob->cur = csp->iob->buf + skip_size;
811 csp->iob->eod = (char *)zstr.next_out;
812 csp->iob->size = bufsize;
815 * Make sure the new uncompressed iob obeys some minimal
816 * consistency conditions.
818 if ((csp->iob->buf <= csp->iob->cur)
819 && (csp->iob->cur <= csp->iob->eod)
820 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
822 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
823 if (new_size > (size_t)0)
825 log_error(LOG_LEVEL_RE_FILTER,
826 "Decompression successful. Old size: %d, new size: %d.",
831 /* zlib thinks this is OK, so let's do the same. */
832 log_error(LOG_LEVEL_RE_FILTER,
833 "Decompression didn't result in any content.");
838 /* It seems that zlib did something weird. */
839 log_error(LOG_LEVEL_ERROR,
840 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
841 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
842 csp->iob->eod, csp->iob->buf + csp->iob->size);
843 return JB_ERR_COMPRESS;
849 #endif /* defined(FEATURE_ZLIB) */
852 /*********************************************************************
854 * Function : normalize_lws
856 * Description : Reduces unquoted linear whitespace in headers to
857 * a single space in accordance with RFC 7230 3.2.4.
858 * This simplifies parsing and filtering later on.
861 * 1 : header = A header with linear whitespace to reduce.
865 *********************************************************************/
866 static void normalize_lws(char *header)
872 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
876 while (privoxy_isspace(*q))
880 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
886 log_error(LOG_LEVEL_HEADER,
887 "Converting tab to space in '%s'", header);
892 char *end_of_token = strstr(p+1, "\"");
894 if (NULL != end_of_token)
896 /* Don't mess with quoted text. */
901 log_error(LOG_LEVEL_HEADER,
902 "Ignoring single quote in '%s'", header);
908 p = strchr(header, ':');
909 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
912 * There's still space before the colon.
920 /*********************************************************************
922 * Function : get_header
924 * Description : This (odd) routine will parse the csp->iob
925 * to get the next complete header.
928 * 1 : iob = The I/O buffer to parse, usually csp->iob.
930 * Returns : Any one of the following:
932 * 1) a pointer to a dynamically allocated string that contains a header line
933 * 2) NULL indicating that the end of the header was reached
934 * 3) "" indicating that the end of the iob was reached before finding
935 * a complete header line.
937 *********************************************************************/
938 char *get_header(struct iob *iob)
942 header = get_header_line(iob);
944 if ((header == NULL) || (*header == '\0'))
947 * No complete header read yet, tell the client.
952 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
955 * Header spans multiple lines, append the next one.
957 char *continued_header;
959 continued_header = get_header_line(iob);
960 if ((continued_header == NULL) || (*continued_header == '\0'))
963 * No complete header read yet, return what we got.
964 * XXX: Should "unread" header instead.
966 log_error(LOG_LEVEL_INFO,
967 "Failed to read a multi-line header properly: '%s'",
972 if (JB_ERR_OK != string_join(&header, continued_header))
974 log_error(LOG_LEVEL_FATAL,
975 "Out of memory while appending multiple headers.");
979 /* XXX: remove before next stable release. */
980 log_error(LOG_LEVEL_HEADER,
981 "Merged multiple header lines to: '%s'",
986 normalize_lws(header);
993 /*********************************************************************
995 * Function : get_header_line
997 * Description : This (odd) routine will parse the csp->iob
998 * to get the next header line.
1001 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1003 * Returns : Any one of the following:
1005 * 1) a pointer to a dynamically allocated string that contains a header line
1006 * 2) NULL indicating that the end of the header was reached
1007 * 3) "" indicating that the end of the iob was reached before finding
1008 * a complete header line.
1010 *********************************************************************/
1011 static char *get_header_line(struct iob *iob)
1015 if ((iob->cur == NULL)
1016 || ((p = strchr(iob->cur, '\n')) == NULL))
1018 return(""); /* couldn't find a complete header */
1023 ret = strdup(iob->cur);
1026 /* FIXME No way to handle error properly */
1027 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1029 assert(ret != NULL);
1033 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1035 /* is this a blank line (i.e. the end of the header) ? */
1047 /*********************************************************************
1049 * Function : get_header_value
1051 * Description : Get the value of a given header from a chained list
1052 * of header lines or return NULL if no such header is
1053 * present in the list.
1056 * 1 : header_list = pointer to list
1057 * 2 : header_name = string with name of header to look for.
1058 * Trailing colon required, capitalization
1061 * Returns : NULL if not found, else value of header
1063 *********************************************************************/
1064 char *get_header_value(const struct list *header_list, const char *header_name)
1066 struct list_entry *cur_entry;
1070 assert(header_list);
1071 assert(header_name);
1072 length = strlen(header_name);
1074 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1078 if (!strncmpic(cur_entry->str, header_name, length))
1081 * Found: return pointer to start of value
1083 ret = cur_entry->str + length;
1084 while (*ret && privoxy_isspace(*ret)) ret++;
1098 /*********************************************************************
1100 * Function : scan_headers
1102 * Description : Scans headers, applies tags and updates action bits.
1105 * 1 : csp = Current client state (buffers, headers, etc...)
1107 * Returns : JB_ERR_OK
1109 *********************************************************************/
1110 static jb_err scan_headers(struct client_state *csp)
1112 struct list_entry *h; /* Header */
1113 jb_err err = JB_ERR_OK;
1115 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1117 /* Header crunch()ed in previous run? -> ignore */
1118 if (h->str == NULL) continue;
1119 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1120 err = header_tagger(csp, h->str);
1127 /*********************************************************************
1129 * Function : enforce_header_order
1131 * Description : Enforces a given header order.
1134 * 1 : headers = List of headers to order.
1135 * 2 : ordered_headers = List of ordered header names.
1139 *********************************************************************/
1140 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1142 struct list_entry *sorted_header;
1143 struct list new_headers[1];
1144 struct list_entry *header;
1146 init_list(new_headers);
1148 /* The request line is always the first "header" */
1150 assert(NULL != headers->first->str);
1151 enlist(new_headers, headers->first->str);
1152 freez(headers->first->str)
1154 /* Enlist the specified headers in the given order */
1156 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1157 sorted_header = sorted_header->next)
1159 const size_t sorted_header_length = strlen(sorted_header->str);
1160 for (header = headers->first; header != NULL; header = header->next)
1162 /* Header enlisted in previous run? -> ignore */
1163 if (header->str == NULL) continue;
1165 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1166 && (header->str[sorted_header_length] == ':'))
1168 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1169 if (JB_ERR_OK != enlist(new_headers, header->str))
1171 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1178 /* Enlist the rest of the headers behind the ordered ones */
1179 for (header = headers->first; header != NULL; header = header->next)
1181 /* Header enlisted in previous run? -> ignore */
1182 if (header->str == NULL) continue;
1184 log_error(LOG_LEVEL_HEADER,
1185 "Enlisting left-over header %s", header->str);
1186 if (JB_ERR_OK != enlist(new_headers, header->str))
1188 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1193 list_remove_all(headers);
1194 list_duplicate(headers, new_headers);
1195 list_remove_all(new_headers);
1201 /*********************************************************************
1205 * Description : add, delete or modify lines in the HTTP header streams.
1206 * On entry, it receives a linked list of headers space
1207 * that was allocated dynamically (both the list nodes
1208 * and the header contents).
1210 * As a side effect it frees the space used by the original
1214 * 1 : csp = Current client state (buffers, headers, etc...)
1215 * 2 : filter_server_headers = Boolean to switch between
1216 * server and header filtering.
1218 * Returns : JB_ERR_OK in case off success, or
1219 * JB_ERR_MEMORY on some out-of-memory errors, or
1220 * JB_ERR_PARSE in case of fatal parse errors.
1222 *********************************************************************/
1223 jb_err sed(struct client_state *csp, int filter_server_headers)
1225 /* XXX: use more descriptive names. */
1226 struct list_entry *p;
1227 const struct parsers *v;
1228 const add_header_func_ptr *f;
1229 jb_err err = JB_ERR_OK;
1233 if (filter_server_headers)
1235 v = server_patterns;
1236 f = add_server_headers;
1237 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1241 v = client_patterns;
1242 f = add_client_headers;
1243 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1246 while (v->str != NULL)
1248 for (p = csp->headers->first; p != NULL; p = p->next)
1250 /* Header crunch()ed in previous run? -> ignore */
1251 if (p->str == NULL) continue;
1253 /* Does the current parser handle this header? */
1254 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1255 (v->len == CHECK_EVERY_HEADER_REMAINING))
1257 err = v->parser(csp, &(p->str));
1258 if (err != JB_ERR_OK)
1267 /* place additional headers on the csp->headers list */
1268 while ((err == JB_ERR_OK) && (*f))
1274 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1276 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1283 #ifdef FEATURE_HTTPS_INSPECTION
1284 /*********************************************************************
1286 * Function : sed_https
1288 * Description : add, delete or modify lines in the HTTPS client
1289 * header streams. Wrapper around sed().
1292 * 1 : csp = Current client state (buffers, headers, etc...)
1294 * Returns : JB_ERR_OK in case off success, or
1295 * JB_ERR_MEMORY on some out-of-memory errors, or
1296 * JB_ERR_PARSE in case of fatal parse errors.
1298 *********************************************************************/
1299 jb_err sed_https(struct client_state *csp)
1302 struct list headers;
1305 * Temporarily replace csp->headers with csp->https_headers
1306 * to trick sed() into filtering the https headers.
1308 headers.first = csp->headers->first;
1309 headers.last = csp->headers->last;
1310 csp->headers->first = csp->https_headers->first;
1311 csp->headers->last = csp->https_headers->last;
1314 * Start with fresh tags. Already existing tags may
1315 * be set again. This is necessary to overrule
1316 * URL-based patterns.
1318 destroy_list(csp->tags);
1321 * We want client header filters and taggers
1322 * so temporarily remove the flag.
1324 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1325 err = sed(csp, FILTER_CLIENT_HEADERS);
1326 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1329 * Update the last header which may have changed
1330 * due to header additions,
1332 csp->https_headers->last = csp->headers->last;
1334 csp->headers->first = headers.first;
1335 csp->headers->last = headers.last;
1339 #endif /* def FEATURE_HTTPS_INSPECTION */
1342 /*********************************************************************
1344 * Function : update_server_headers
1346 * Description : Updates server headers after the body has been modified.
1349 * 1 : csp = Current client state (buffers, headers, etc...)
1351 * Returns : JB_ERR_OK in case off success, or
1352 * JB_ERR_MEMORY on out-of-memory error.
1354 *********************************************************************/
1355 jb_err update_server_headers(struct client_state *csp)
1357 jb_err err = JB_ERR_OK;
1359 static const struct parsers server_patterns_light[] = {
1360 { "Content-Length:", 15, server_adjust_content_length },
1361 { "Transfer-Encoding:", 18, server_transfer_coding },
1363 { "Content-Encoding:", 17, server_adjust_content_encoding },
1364 #endif /* def FEATURE_ZLIB */
1368 if (strncmpic(csp->http->cmd, "HEAD", 4))
1370 const struct parsers *v;
1371 struct list_entry *p;
1373 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1375 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1377 /* Header crunch()ed in previous run? -> ignore */
1378 if (p->str == NULL) continue;
1380 /* Does the current parser handle this header? */
1381 if (strncmpic(p->str, v->str, v->len) == 0)
1383 err = v->parser(csp, (char **)&(p->str));
1389 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1390 if ((JB_ERR_OK == err)
1391 && (csp->flags & CSP_FLAG_MODIFIED)
1392 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1393 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1397 create_content_length_header(csp->content_length, header, sizeof(header));
1398 err = enlist(csp->headers, header);
1399 if (JB_ERR_OK == err)
1401 log_error(LOG_LEVEL_HEADER,
1402 "Content modified with no Content-Length header set. "
1403 "Created: %s.", header);
1404 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1407 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1409 #ifdef FEATURE_COMPRESSION
1410 if ((JB_ERR_OK == err)
1411 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1413 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1414 if (JB_ERR_OK == err)
1416 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1425 /*********************************************************************
1427 * Function : header_tagger
1429 * Description : Executes all text substitutions from applying
1430 * tag actions and saves the result as tag.
1432 * XXX: Shares enough code with filter_header() and
1433 * pcrs_filter_response() to warrant some helper functions.
1436 * 1 : csp = Current client state (buffers, headers, etc...)
1437 * 2 : header = Header that is used as tagger input
1439 * Returns : JB_ERR_OK on success and always succeeds
1441 *********************************************************************/
1442 static jb_err header_tagger(struct client_state *csp, char *header)
1444 enum filter_type wanted_filter_type;
1445 int multi_action_index;
1448 struct re_filterfile_spec *b;
1449 struct list_entry *tag_name;
1451 const size_t header_length = strlen(header);
1453 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1455 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1456 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1460 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1461 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1464 if (list_is_empty(csp->action->multi[multi_action_index])
1465 || filters_available(csp) == FALSE)
1467 /* Return early if no taggers apply or if none are available. */
1471 /* Execute all applying taggers */
1472 for (tag_name = csp->action->multi[multi_action_index]->first;
1473 NULL != tag_name; tag_name = tag_name->next)
1475 char *modified_tag = NULL;
1477 size_t size = header_length;
1480 b = get_filter(csp, tag_name->str, wanted_filter_type);
1486 joblist = b->joblist;
1488 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1490 if (NULL == joblist)
1492 log_error(LOG_LEVEL_RE_FILTER,
1493 "Tagger %s has empty joblist. Nothing to do.", b->name);
1497 /* execute their pcrs_joblist on the header. */
1498 for (job = joblist; NULL != job; job = job->next)
1500 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1504 /* Success, continue with the modified version. */
1513 /* Tagger doesn't match */
1516 /* Regex failure, log it but continue anyway. */
1517 assert(NULL != header);
1518 log_error(LOG_LEVEL_ERROR,
1519 "Problems with tagger \'%s\' and header \'%s\': %s",
1520 b->name, *header, pcrs_strerror(hits));
1522 freez(modified_tag);
1526 if (b->dynamic) pcrs_free_joblist(joblist);
1528 /* If this tagger matched */
1534 * There is no technical limitation which makes
1535 * it impossible to use empty tags, but I assume
1536 * no one would do it intentionally.
1539 log_error(LOG_LEVEL_INFO,
1540 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1544 if (!list_contains_item(csp->tags, tag))
1546 if (JB_ERR_OK != enlist(csp->tags, tag))
1548 log_error(LOG_LEVEL_ERROR,
1549 "Insufficient memory to add tag \'%s\', "
1550 "based on tagger \'%s\' and header \'%s\'",
1551 tag, b->name, *header);
1555 char *action_message;
1557 * update the action bits right away, to make
1558 * tagging based on tags set by earlier taggers
1559 * of the same kind possible.
1561 if (update_action_bits_for_tag(csp, tag))
1563 action_message = "Action bits updated accordingly.";
1567 action_message = "No action bits update necessary.";
1570 log_error(LOG_LEVEL_HEADER,
1571 "Tagger \'%s\' added tag \'%s\'. %s",
1572 b->name, tag, action_message);
1577 /* XXX: Is this log-worthy? */
1578 log_error(LOG_LEVEL_HEADER,
1579 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1589 /* here begins the family of parser functions that reformat header lines */
1591 /*********************************************************************
1593 * Function : filter_header
1595 * Description : Executes all text substitutions from all applying
1596 * +(server|client)-header-filter actions on the header.
1597 * Most of the code was copied from pcrs_filter_response,
1598 * including the rather short variable names
1601 * 1 : csp = Current client state (buffers, headers, etc...)
1602 * 2 : header = On input, pointer to header to modify.
1603 * On output, pointer to the modified header, or NULL
1604 * to remove the header. This function frees the
1605 * original string if necessary.
1607 * Returns : JB_ERR_OK on success and always succeeds
1609 *********************************************************************/
1610 static jb_err filter_header(struct client_state *csp, char **header)
1614 size_t size = strlen(*header);
1616 char *newheader = NULL;
1619 struct re_filterfile_spec *b;
1620 struct list_entry *filtername;
1622 enum filter_type wanted_filter_type;
1623 int multi_action_index;
1625 if (csp->flags & CSP_FLAG_NO_FILTERING)
1630 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1632 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1633 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1637 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1638 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1641 if (list_is_empty(csp->action->multi[multi_action_index])
1642 || filters_available(csp) == FALSE)
1644 /* Return early if no filters apply or if none are available. */
1648 /* Execute all applying header filters */
1649 for (filtername = csp->action->multi[multi_action_index]->first;
1650 filtername != NULL; filtername = filtername->next)
1652 int current_hits = 0;
1655 b = get_filter(csp, filtername->str, wanted_filter_type);
1661 joblist = b->joblist;
1663 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1665 if (NULL == joblist)
1667 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1671 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1672 *header, size, b->name);
1674 /* Apply all jobs from the joblist */
1675 for (job = joblist; NULL != job; job = job->next)
1677 matches = pcrs_execute(job, *header, size, &newheader, &size);
1680 current_hits += matches;
1681 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1683 *header = newheader;
1685 else if (0 == matches)
1687 /* Filter doesn't change header */
1693 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1694 *header, b->name, pcrs_strerror(matches));
1695 if (newheader != NULL)
1697 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1703 if (b->dynamic) pcrs_free_joblist(joblist);
1705 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1706 hits += current_hits;
1710 * Additionally checking for hits is important because if
1711 * the continue hack is triggered, server headers can
1712 * arrive empty to separate multiple heads from each other.
1714 if ((0 == size) && hits)
1716 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1724 /*********************************************************************
1726 * Function : server_connection
1728 * Description : Makes sure a proper "Connection:" header is
1729 * set and signals connection_header_adder to
1733 * 1 : csp = Current client state (buffers, headers, etc...)
1734 * 2 : header = On input, pointer to header to modify.
1735 * On output, pointer to the modified header, or NULL
1736 * to remove the header. This function frees the
1737 * original string if necessary.
1739 * Returns : JB_ERR_OK on success.
1741 *********************************************************************/
1742 static jb_err server_connection(struct client_state *csp, char **header)
1744 if (!strcmpic(*header, "Connection: keep-alive")
1745 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1746 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1750 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1751 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1753 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1756 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1758 log_error(LOG_LEVEL_HEADER,
1759 "Keeping the server header '%s' around.", *header);
1762 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1764 char *old_header = *header;
1766 *header = strdup_or_die("Connection: close");
1767 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1772 /* Signal server_connection_adder() to return early. */
1773 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1779 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1780 /*********************************************************************
1782 * Function : server_keep_alive
1784 * Description : Stores the server's keep alive timeout.
1787 * 1 : csp = Current client state (buffers, headers, etc...)
1788 * 2 : header = On input, pointer to header to modify.
1789 * On output, pointer to the modified header, or NULL
1790 * to remove the header. This function frees the
1791 * original string if necessary.
1793 * Returns : JB_ERR_OK.
1795 *********************************************************************/
1796 static jb_err server_keep_alive(struct client_state *csp, char **header)
1798 unsigned int keep_alive_timeout;
1799 const char *timeout_position = strstr(*header, "timeout=");
1801 if ((NULL == timeout_position)
1802 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1804 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1808 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1810 log_error(LOG_LEVEL_HEADER,
1811 "Reducing keep-alive timeout from %u to %u.",
1812 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1813 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1817 /* XXX: Is this log worthy? */
1818 log_error(LOG_LEVEL_HEADER,
1819 "Server keep-alive timeout is %u. Sticking with %u.",
1820 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1822 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1831 /*********************************************************************
1833 * Function : server_proxy_connection
1835 * Description : Figures out whether or not we should add a
1836 * Proxy-Connection header.
1839 * 1 : csp = Current client state (buffers, headers, etc...)
1840 * 2 : header = On input, pointer to header to modify.
1841 * On output, pointer to the modified header, or NULL
1842 * to remove the header. This function frees the
1843 * original string if necessary.
1845 * Returns : JB_ERR_OK.
1847 *********************************************************************/
1848 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1850 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1855 /*********************************************************************
1857 * Function : proxy_authentication
1859 * Description : Removes headers that are relevant for proxy
1860 * authentication unless forwarding them has
1861 * been explicitly requested.
1864 * 1 : csp = Current client state (buffers, headers, etc...)
1865 * 2 : header = On input, pointer to header to modify.
1866 * On output, pointer to the modified header, or NULL
1867 * to remove the header. This function frees the
1868 * original string if necessary.
1870 * Returns : JB_ERR_OK.
1872 *********************************************************************/
1873 static jb_err proxy_authentication(struct client_state *csp, char **header)
1875 if ((csp->config->feature_flags &
1876 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1877 log_error(LOG_LEVEL_HEADER,
1878 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1885 /*********************************************************************
1887 * Function : client_keep_alive
1889 * Description : Stores the client's keep alive timeout.
1892 * 1 : csp = Current client state (buffers, headers, etc...)
1893 * 2 : header = On input, pointer to header to modify.
1894 * On output, pointer to the modified header, or NULL
1895 * to remove the header. This function frees the
1896 * original string if necessary.
1898 * Returns : JB_ERR_OK.
1900 *********************************************************************/
1901 static jb_err client_keep_alive(struct client_state *csp, char **header)
1903 unsigned int keep_alive_timeout;
1904 char *timeout_position;
1906 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1908 log_error(LOG_LEVEL_HEADER,
1909 "keep-alive support is disabled. Crunching: %s.", *header);
1914 /* Check for parameter-less format "Keep-Alive: 100" */
1915 timeout_position = strstr(*header, ": ");
1916 if ((NULL == timeout_position)
1917 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1919 /* Assume parameter format "Keep-Alive: timeout=100" */
1920 timeout_position = strstr(*header, "timeout=");
1921 if ((NULL == timeout_position)
1922 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1924 log_error(LOG_LEVEL_HEADER,
1925 "Couldn't parse: '%s'. Using default timeout %u",
1926 *header, csp->config->keep_alive_timeout);
1933 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1935 log_error(LOG_LEVEL_HEADER,
1936 "Reducing keep-alive timeout from %u to %u.",
1937 csp->config->keep_alive_timeout, keep_alive_timeout);
1938 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1942 /* XXX: Is this log worthy? */
1943 log_error(LOG_LEVEL_HEADER,
1944 "Client keep-alive timeout is %u. Sticking with %u.",
1945 keep_alive_timeout, csp->config->keep_alive_timeout);
1953 /*********************************************************************
1955 * Function : get_content_length
1957 * Description : Gets the content length specified in a
1958 * Content-Length header.
1961 * 1 : header_value = The Content-Length header value.
1962 * 2 : length = Storage to return the value.
1964 * Returns : JB_ERR_OK on success, or
1965 * JB_ERR_PARSE if no value is recognized.
1967 *********************************************************************/
1968 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1971 #if SIZEOF_LONG_LONG < 8
1972 #error sizeof(unsigned long long) too small
1974 if (1 != sscanf(header_value, "%I64u", length))
1976 if (1 != sscanf(header_value, "%llu", length))
1979 return JB_ERR_PARSE;
1986 /*********************************************************************
1988 * Function : client_save_content_length
1990 * Description : Save the Content-Length sent by the client.
1993 * 1 : csp = Current client state (buffers, headers, etc...)
1994 * 2 : header = On input, pointer to header to modify.
1995 * On output, pointer to the modified header, or NULL
1996 * to remove the header. This function frees the
1997 * original string if necessary.
1999 * Returns : JB_ERR_OK on success, or
2000 * JB_ERR_MEMORY on out-of-memory error.
2002 *********************************************************************/
2003 static jb_err client_save_content_length(struct client_state *csp, char **header)
2005 unsigned long long content_length = 0;
2006 const char *header_value;
2008 assert(*(*header+14) == ':');
2010 header_value = *header + 15;
2011 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2013 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2018 csp->expected_client_content_length = content_length;
2023 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2027 /*********************************************************************
2029 * Function : client_connection
2031 * Description : Makes sure a proper "Connection:" header is
2032 * set and signals connection_header_adder
2036 * 1 : csp = Current client state (buffers, headers, etc...)
2037 * 2 : header = On input, pointer to header to modify.
2038 * On output, pointer to the modified header, or NULL
2039 * to remove the header. This function frees the
2040 * original string if necessary.
2042 * Returns : JB_ERR_OK on success.
2044 *********************************************************************/
2045 static jb_err client_connection(struct client_state *csp, char **header)
2047 static const char connection_close[] = "Connection: close";
2049 if (!strcmpic(*header, connection_close))
2051 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2052 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2053 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2054 #ifdef FEATURE_HTTPS_INSPECTION
2055 && !client_use_ssl(csp)
2059 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2061 log_error(LOG_LEVEL_HEADER,
2062 "Removing \'%s\' to imply keep-alive.", *header);
2065 * While we imply keep-alive to the server,
2066 * we have to remember that the client didn't.
2068 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2072 char *old_header = *header;
2074 *header = strdup_or_die("Connection: keep-alive");
2075 log_error(LOG_LEVEL_HEADER,
2076 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2082 log_error(LOG_LEVEL_HEADER,
2083 "Keeping the client header '%s' around. "
2084 "The connection will not be kept alive.",
2086 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2089 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2090 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2092 log_error(LOG_LEVEL_HEADER,
2093 "Keeping the client header '%s' around. "
2094 "The server connection will be kept alive if possible.",
2096 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2097 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2101 char *old_header = *header;
2103 *header = strdup_or_die(connection_close);
2104 log_error(LOG_LEVEL_HEADER,
2105 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2109 /* Signal client_connection_header_adder() to return early. */
2110 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2116 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2117 /*********************************************************************
2119 * Function : client_proxy_connection
2121 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2122 * appropriate and removes the Proxy-Connection
2126 * 1 : csp = Current client state (buffers, headers, etc...)
2127 * 2 : header = On input, pointer to header to modify.
2128 * On output, pointer to the modified header, or NULL
2129 * to remove the header. This function frees the
2130 * original string if necessary.
2132 * Returns : JB_ERR_OK
2134 *********************************************************************/
2135 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2137 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2138 && (csp->http->ssl == 0)
2139 && (NULL == strstr(*header, "close")))
2141 log_error(LOG_LEVEL_HEADER,
2142 "The client connection can be kept alive due to: %s", *header);
2143 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2145 crumble(csp, header);
2149 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2152 /*********************************************************************
2154 * Function : client_transfer_encoding
2156 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2157 * the request body is "chunked"
2159 * XXX: Currently not called through sed() as we
2160 * need the flag earlier on. Should be fixed.
2163 * 1 : csp = Current client state (buffers, headers, etc...)
2164 * 2 : header = On input, pointer to header to modify.
2165 * On output, pointer to the modified header, or NULL
2166 * to remove the header. This function frees the
2167 * original string if necessary.
2169 * Returns : JB_ERR_OK on success, or
2171 *********************************************************************/
2172 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2174 if (strstr(*header, "chunked"))
2176 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2177 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2184 /*********************************************************************
2186 * Function : client_expect
2188 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2189 * if the Expect header value is unsupported.
2191 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2192 * MAY and a RFC 2616 (obsolete) MUST.
2195 * 1 : csp = Current client state (buffers, headers, etc...)
2196 * 2 : header = On input, pointer to header to modify.
2197 * On output, pointer to the modified header, or NULL
2198 * to remove the header. This function frees the
2199 * original string if necessary.
2201 * Returns : JB_ERR_OK on success, or
2203 *********************************************************************/
2204 jb_err client_expect(struct client_state *csp, char **header)
2206 if (0 != strcmpic(*header, "Expect: 100-continue"))
2208 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2209 log_error(LOG_LEVEL_HEADER,
2210 "Unsupported client expectaction: %s", *header);
2218 /*********************************************************************
2220 * Function : crumble
2222 * Description : This is called if a header matches a pattern to "crunch"
2225 * 1 : csp = Current client state (buffers, headers, etc...)
2226 * 2 : header = On input, pointer to header to modify.
2227 * On output, pointer to the modified header, or NULL
2228 * to remove the header. This function frees the
2229 * original string if necessary.
2231 * Returns : JB_ERR_OK on success, or
2232 * JB_ERR_MEMORY on out-of-memory error.
2234 *********************************************************************/
2235 static jb_err crumble(struct client_state *csp, char **header)
2238 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2244 /*********************************************************************
2246 * Function : crunch_server_header
2248 * Description : Crunch server header if it matches a string supplied by the
2249 * user. Called from `sed'.
2252 * 1 : csp = Current client state (buffers, headers, etc...)
2253 * 2 : header = On input, pointer to header to modify.
2254 * On output, pointer to the modified header, or NULL
2255 * to remove the header. This function frees the
2256 * original string if necessary.
2258 * Returns : JB_ERR_OK on success and always succeeds
2260 *********************************************************************/
2261 static jb_err crunch_server_header(struct client_state *csp, char **header)
2263 const char *crunch_pattern;
2265 /* Do we feel like crunching? */
2266 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2268 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2270 /* Is the current header the lucky one? */
2271 if (strstr(*header, crunch_pattern))
2273 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2282 /*********************************************************************
2284 * Function : server_content_type
2286 * Description : Set the content-type for filterable types (text/.*,
2287 * .*xml.*, .*script.* and image/gif) unless filtering has been
2288 * forbidden (CT_TABOO) while parsing earlier headers.
2289 * NOTE: Since text/plain is commonly used by web servers
2290 * for files whose correct type is unknown, we don't
2291 * set CT_TEXT for it.
2294 * 1 : csp = Current client state (buffers, headers, etc...)
2295 * 2 : header = On input, pointer to header to modify.
2296 * On output, pointer to the modified header, or NULL
2297 * to remove the header. This function frees the
2298 * original string if necessary.
2300 * Returns : JB_ERR_OK on success, or
2301 * JB_ERR_MEMORY on out-of-memory error.
2303 *********************************************************************/
2304 static jb_err server_content_type(struct client_state *csp, char **header)
2306 /* Remove header if it isn't the first Content-Type header */
2307 if ((csp->content_type & CT_DECLARED))
2309 if (content_filters_enabled(csp->action))
2312 * Making sure the client interprets the content the same way
2313 * Privoxy did is only relevant if Privoxy modified it.
2315 * Checking for this is "hard" as it's not yet known when
2316 * this function is called, thus go shopping and and just
2317 * check if Privoxy could filter it.
2319 * The main thing is that we don't mess with the headers
2320 * unless the user signalled that it's acceptable.
2322 log_error(LOG_LEVEL_HEADER,
2323 "Multiple Content-Type headers detected. "
2324 "Removing and ignoring: %s",
2332 * Signal that the Content-Type has been set.
2334 csp->content_type |= CT_DECLARED;
2336 if (!(csp->content_type & CT_TABOO))
2339 * XXX: The assumption that text/plain is a sign of
2340 * binary data seems to be somewhat unreasonable nowadays
2341 * and should be dropped after 3.0.8 is out.
2343 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2344 || strstr(*header, "xml")
2345 || strstr(*header, "script"))
2347 csp->content_type |= CT_TEXT;
2349 else if (strstr(*header, "image/gif"))
2351 csp->content_type |= CT_GIF;
2356 * Are we messing with the content type?
2358 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2361 * Make sure the user doesn't accidentally
2362 * change the content type of binary documents.
2364 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2368 *header = strdup_or_die("Content-Type: ");
2370 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2371 if (JB_ERR_OK != err)
2373 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2374 return JB_ERR_MEMORY;
2376 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2380 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2381 "It doesn't look like a content type that should be filtered. "
2382 "Enable force-text-mode if you know what you're doing.", *header);
2390 /*********************************************************************
2392 * Function : server_transfer_coding
2394 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2395 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2396 * - Remove header if body was chunked but has been
2397 * de-chunked for filtering.
2400 * 1 : csp = Current client state (buffers, headers, etc...)
2401 * 2 : header = On input, pointer to header to modify.
2402 * On output, pointer to the modified header, or NULL
2403 * to remove the header. This function frees the
2404 * original string if necessary.
2406 * Returns : JB_ERR_OK on success, or
2407 * JB_ERR_MEMORY on out-of-memory error.
2409 *********************************************************************/
2410 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2413 * Turn off pcrs and gif filtering if body compressed
2415 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2419 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2421 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2422 csp->http->cmd, *header);
2423 #endif /* def FEATURE_ZLIB */
2424 csp->content_type = CT_TABOO;
2428 * Raise flag if body chunked
2430 if (strstr(*header, "chunked"))
2432 csp->flags |= CSP_FLAG_CHUNKED;
2435 * If the body was modified, it has been de-chunked first
2436 * and the header must be removed.
2438 * FIXME: If there is more than one transfer encoding,
2439 * only the "chunked" part should be removed here.
2441 if (csp->flags & CSP_FLAG_MODIFIED)
2443 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2452 /*********************************************************************
2454 * Function : server_content_encoding
2456 * Description : Used to check if the content is compressed, and if
2457 * FEATURE_ZLIB is disabled, filtering is disabled as
2460 * If FEATURE_ZLIB is enabled and the compression type
2461 * supported, the content is marked for decompression.
2463 * XXX: Doesn't properly deal with multiple or with
2464 * unsupported but unknown encodings.
2465 * Is case-sensitive but shouldn't be.
2468 * 1 : csp = Current client state (buffers, headers, etc...)
2469 * 2 : header = On input, pointer to header to modify.
2470 * On output, pointer to the modified header, or NULL
2471 * to remove the header. This function frees the
2472 * original string if necessary.
2474 * Returns : JB_ERR_OK on success, or
2475 * JB_ERR_MEMORY on out-of-memory error.
2477 *********************************************************************/
2478 static jb_err server_content_encoding(struct client_state *csp, char **header)
2481 if (strstr(*header, "sdch"))
2484 * Shared Dictionary Compression over HTTP isn't supported,
2485 * filtering it anyway is pretty much guaranteed to mess up
2488 csp->content_type |= CT_TABOO;
2491 * Log a warning if the user expects the content to be filtered.
2493 if (content_filters_enabled(csp->action))
2495 log_error(LOG_LEVEL_INFO,
2496 "SDCH-compressed content detected, content filtering disabled. "
2497 "Consider suppressing SDCH offers made by the client.");
2500 else if (strstr(*header, "gzip"))
2502 /* Mark for gzip decompression */
2503 csp->content_type |= CT_GZIP;
2505 else if (strstr(*header, "deflate"))
2507 /* Mark for zlib decompression */
2508 csp->content_type |= CT_DEFLATE;
2510 else if (strstr(*header, "br"))
2512 #ifdef FEATURE_BROTLI
2513 /* Mark for Brotli decompression */
2514 csp->content_type |= CT_BROTLI;
2516 csp->content_type |= CT_TABOO;
2519 else if (strstr(*header, "compress"))
2522 * We can't decompress this; therefore we can't filter
2525 csp->content_type |= CT_TABOO;
2527 #else /* !defined(FEATURE_ZLIB) */
2529 * XXX: Using a black list here isn't the right approach.
2531 * In case of SDCH, building with zlib support isn't
2534 if (strstr(*header, "gzip") ||
2535 strstr(*header, "compress") ||
2536 strstr(*header, "deflate") ||
2537 strstr(*header, "sdch"))
2540 * Body is compressed, turn off pcrs and gif filtering.
2542 csp->content_type |= CT_TABOO;
2545 * Log a warning if the user expects the content to be filtered.
2547 if (content_filters_enabled(csp->action))
2549 log_error(LOG_LEVEL_INFO,
2550 "Compressed content detected, content filtering disabled. "
2551 "Consider recompiling Privoxy with zlib support or "
2552 "enable the prevent-compression action.");
2555 #endif /* defined(FEATURE_ZLIB) */
2563 /*********************************************************************
2565 * Function : server_adjust_content_encoding
2567 * Description : Remove the Content-Encoding header if the
2568 * decompression was successful and the content
2569 * has been modified.
2572 * 1 : csp = Current client state (buffers, headers, etc...)
2573 * 2 : header = On input, pointer to header to modify.
2574 * On output, pointer to the modified header, or NULL
2575 * to remove the header. This function frees the
2576 * original string if necessary.
2578 * Returns : JB_ERR_OK on success, or
2579 * JB_ERR_MEMORY on out-of-memory error.
2581 *********************************************************************/
2582 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2584 if ((csp->flags & CSP_FLAG_MODIFIED)
2585 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2586 #ifdef FEATURE_BROTLI
2587 || (csp->content_type & CT_BROTLI)
2593 * We successfully decompressed the content,
2594 * and have to clean the header now, so the
2595 * client no longer expects compressed data.
2597 * XXX: There is a difference between cleaning
2598 * and removing it completely.
2600 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2607 #endif /* defined(FEATURE_ZLIB) */
2610 /*********************************************************************
2612 * Function : server_adjust_content_length
2614 * Description : Adjust Content-Length header if we modified
2618 * 1 : csp = Current client state (buffers, headers, etc...)
2619 * 2 : header = On input, pointer to header to modify.
2620 * On output, pointer to the modified header, or NULL
2621 * to remove the header. This function frees the
2622 * original string if necessary.
2624 * Returns : JB_ERR_OK on success, or
2625 * JB_ERR_MEMORY on out-of-memory error.
2627 *********************************************************************/
2628 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2630 /* Regenerate header if the content was modified. */
2631 if (csp->flags & CSP_FLAG_MODIFIED)
2633 const size_t header_length = 50;
2635 *header = malloc(header_length);
2636 if (*header == NULL)
2638 return JB_ERR_MEMORY;
2640 create_content_length_header(csp->content_length, *header, header_length);
2641 log_error(LOG_LEVEL_HEADER,
2642 "Adjusted Content-Length to %llu", csp->content_length);
2649 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2650 /*********************************************************************
2652 * Function : server_save_content_length
2654 * Description : Save the Content-Length sent by the server.
2657 * 1 : csp = Current client state (buffers, headers, etc...)
2658 * 2 : header = On input, pointer to header to modify.
2659 * On output, pointer to the modified header, or NULL
2660 * to remove the header. This function frees the
2661 * original string if necessary.
2663 * Returns : JB_ERR_OK on success, or
2664 * JB_ERR_MEMORY on out-of-memory error.
2666 *********************************************************************/
2667 static jb_err server_save_content_length(struct client_state *csp, char **header)
2669 unsigned long long content_length = 0;
2670 const char *header_value;
2672 assert(*(*header+14) == ':');
2674 header_value = *header + 15;
2675 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2677 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2682 csp->expected_content_length = content_length;
2683 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2684 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2689 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2692 /*********************************************************************
2694 * Function : server_content_md5
2696 * Description : Crumble any Content-MD5 headers if the document was
2697 * modified. FIXME: Should we re-compute instead?
2700 * 1 : csp = Current client state (buffers, headers, etc...)
2701 * 2 : header = On input, pointer to header to modify.
2702 * On output, pointer to the modified header, or NULL
2703 * to remove the header. This function frees the
2704 * original string if necessary.
2706 * Returns : JB_ERR_OK on success, or
2707 * JB_ERR_MEMORY on out-of-memory error.
2709 *********************************************************************/
2710 static jb_err server_content_md5(struct client_state *csp, char **header)
2712 if (csp->flags & CSP_FLAG_MODIFIED)
2714 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2722 /*********************************************************************
2724 * Function : server_content_disposition
2726 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2727 * Called from `sed'.
2730 * 1 : csp = Current client state (buffers, headers, etc...)
2731 * 2 : header = On input, pointer to header to modify.
2732 * On output, pointer to the modified header, or NULL
2733 * to remove the header. This function frees the
2734 * original string if necessary.
2736 * Returns : JB_ERR_OK on success, or
2737 * JB_ERR_MEMORY on out-of-memory error.
2739 *********************************************************************/
2740 static jb_err server_content_disposition(struct client_state *csp, char **header)
2745 * Are we messing with the Content-Disposition header?
2747 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2753 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2755 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2758 * Blocking content-disposition header
2760 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2767 * Replacing Content-Disposition header
2770 *header = strdup("Content-Disposition: ");
2771 string_append(header, newval);
2773 if (*header != NULL)
2775 log_error(LOG_LEVEL_HEADER,
2776 "Content-Disposition header crunched and replaced with: %s", *header);
2779 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2783 /*********************************************************************
2785 * Function : server_last_modified
2787 * Description : Changes Last-Modified header to the actual date
2788 * to help hide-if-modified-since.
2789 * Called from `sed'.
2792 * 1 : csp = Current client state (buffers, headers, etc...)
2793 * 2 : header = On input, pointer to header to modify.
2794 * On output, pointer to the modified header, or NULL
2795 * to remove the header. This function frees the
2796 * original string if necessary.
2798 * Returns : JB_ERR_OK on success, or
2799 * JB_ERR_MEMORY on out-of-memory error.
2801 *********************************************************************/
2802 static jb_err server_last_modified(struct client_state *csp, char **header)
2805 time_t last_modified;
2809 * Are we messing with the Last-Modified header?
2811 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2817 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2819 if (0 == strcmpic(newval, "block"))
2822 * Blocking Last-Modified header. Useless but why not.
2824 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2828 else if (0 == strcmpic(newval, "reset-to-request-time"))
2831 * Setting Last-Modified Header to now.
2834 get_http_time(0, buf, sizeof(buf));
2836 *header = strdup("Last-Modified: ");
2837 string_append(header, buf);
2839 if (*header == NULL)
2841 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2845 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2848 else if (0 == strcmpic(newval, "randomize"))
2850 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2852 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2854 log_error(LOG_LEVEL_HEADER,
2855 "Couldn't parse time in %s (crunching!)", *header);
2861 struct tm *timeptr = NULL;
2866 rtime = (long int)difftime(now, last_modified);
2869 long int days, hours, minutes, seconds;
2870 const int negative_delta = (rtime < 0);
2875 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2877 rtime = pick_from_range(rtime);
2882 last_modified += rtime;
2883 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2884 if ((NULL == timeptr) || !strftime(newheader,
2885 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2887 log_error(LOG_LEVEL_ERROR,
2888 "Randomizing '%s' failed. Crunching the header without replacement.",
2894 *header = strdup("Last-Modified: ");
2895 string_append(header, newheader);
2897 if (*header == NULL)
2899 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2900 return JB_ERR_MEMORY;
2903 days = rtime / (3600 * 24);
2904 hours = rtime / 3600 % 24;
2905 minutes = rtime / 60 % 60;
2906 seconds = rtime % 60;
2908 log_error(LOG_LEVEL_HEADER,
2909 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2910 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2911 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2915 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2924 /*********************************************************************
2926 * Function : client_accept_encoding
2928 * Description : Rewrite the client's Accept-Encoding header so that
2929 * if doesn't allow compression, if the action applies.
2930 * Note: For HTTP/1.0 the absence of the header is enough.
2933 * 1 : csp = Current client state (buffers, headers, etc...)
2934 * 2 : header = On input, pointer to header to modify.
2935 * On output, pointer to the modified header, or NULL
2936 * to remove the header. This function frees the
2937 * original string if necessary.
2939 * Returns : JB_ERR_OK on success, or
2940 * JB_ERR_MEMORY on out-of-memory error.
2942 *********************************************************************/
2943 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2945 #ifdef FEATURE_COMPRESSION
2946 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2947 && strstr(*header, "deflate"))
2949 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2952 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2954 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2962 /*********************************************************************
2964 * Function : client_te
2966 * Description : Rewrite the client's TE header so that
2967 * if doesn't allow compression, if the action applies.
2970 * 1 : csp = Current client state (buffers, headers, etc...)
2971 * 2 : header = On input, pointer to header to modify.
2972 * On output, pointer to the modified header, or NULL
2973 * to remove the header. This function frees the
2974 * original string if necessary.
2976 * Returns : JB_ERR_OK on success, or
2977 * JB_ERR_MEMORY on out-of-memory error.
2979 *********************************************************************/
2980 static jb_err client_te(struct client_state *csp, char **header)
2982 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2985 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2992 /*********************************************************************
2994 * Function : client_referrer
2996 * Description : Handle the "referer" config setting properly.
2997 * Called from `sed'.
3000 * 1 : csp = Current client state (buffers, headers, etc...)
3001 * 2 : header = On input, pointer to header to modify.
3002 * On output, pointer to the modified header, or NULL
3003 * to remove the header. This function frees the
3004 * original string if necessary.
3006 * Returns : JB_ERR_OK on success, or
3007 * JB_ERR_MEMORY on out-of-memory error.
3009 *********************************************************************/
3010 static jb_err client_referrer(struct client_state *csp, char **header)
3012 const char *parameter;
3013 /* booleans for parameters we have to check multiple times */
3014 int parameter_conditional_block;
3015 int parameter_conditional_forge;
3017 #ifdef FEATURE_FORCE_LOAD
3019 * Since the referrer can include the prefix even
3020 * if the request itself is non-forced, we must
3021 * clean it unconditionally.
3023 * XXX: strclean is too broad
3025 strclean(*header, FORCE_PREFIX);
3026 #endif /* def FEATURE_FORCE_LOAD */
3028 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3030 /* Nothing left to do */
3034 parameter = csp->action->string[ACTION_STRING_REFERER];
3035 assert(parameter != NULL);
3036 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3037 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3039 if (!parameter_conditional_block && !parameter_conditional_forge)
3042 * As conditional-block and conditional-forge are the only
3043 * parameters that rely on the original referrer, we can
3044 * remove it now for all the others.
3049 if (0 == strcmpic(parameter, "block"))
3051 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3054 else if (parameter_conditional_block || parameter_conditional_forge)
3056 return handle_conditional_hide_referrer_parameter(header,
3057 csp->http->hostport, parameter_conditional_block);
3059 else if (0 == strcmpic(parameter, "forge"))
3061 return create_forged_referrer(header, csp->http->hostport);
3065 /* interpret parameter as user-supplied referer to fake */
3066 return create_fake_referrer(header, parameter);
3071 /*********************************************************************
3073 * Function : client_accept_language
3075 * Description : Handle the "Accept-Language" config setting properly.
3076 * Called from `sed'.
3079 * 1 : csp = Current client state (buffers, headers, etc...)
3080 * 2 : header = On input, pointer to header to modify.
3081 * On output, pointer to the modified header, or NULL
3082 * to remove the header. This function frees the
3083 * original string if necessary.
3085 * Returns : JB_ERR_OK on success, or
3086 * JB_ERR_MEMORY on out-of-memory error.
3088 *********************************************************************/
3089 static jb_err client_accept_language(struct client_state *csp, char **header)
3094 * Are we messing with the Accept-Language?
3096 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3098 /*I don't think so*/
3102 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3104 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3107 * Blocking Accept-Language header
3109 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3116 * Replacing Accept-Language header
3119 *header = strdup("Accept-Language: ");
3120 string_append(header, newval);
3122 if (*header == NULL)
3124 log_error(LOG_LEVEL_ERROR,
3125 "Insufficient memory. Accept-Language header crunched without replacement.");
3129 log_error(LOG_LEVEL_HEADER,
3130 "Accept-Language header crunched and replaced with: %s", *header);
3133 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3137 /*********************************************************************
3139 * Function : crunch_client_header
3141 * Description : Crunch client header if it matches a string supplied by the
3142 * user. Called from `sed'.
3145 * 1 : csp = Current client state (buffers, headers, etc...)
3146 * 2 : header = On input, pointer to header to modify.
3147 * On output, pointer to the modified header, or NULL
3148 * to remove the header. This function frees the
3149 * original string if necessary.
3151 * Returns : JB_ERR_OK on success and always succeeds
3153 *********************************************************************/
3154 static jb_err crunch_client_header(struct client_state *csp, char **header)
3156 const char *crunch_pattern;
3158 /* Do we feel like crunching? */
3159 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3161 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3163 /* Is the current header the lucky one? */
3164 if (strstr(*header, crunch_pattern))
3166 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3174 /*********************************************************************
3176 * Function : client_uagent
3178 * Description : Handle the "user-agent" config setting properly
3179 * and remember its original value to enable browser
3180 * bug workarounds. Called from `sed'.
3183 * 1 : csp = Current client state (buffers, headers, etc...)
3184 * 2 : header = On input, pointer to header to modify.
3185 * On output, pointer to the modified header, or NULL
3186 * to remove the header. This function frees the
3187 * original string if necessary.
3189 * Returns : JB_ERR_OK on success, or
3190 * JB_ERR_MEMORY on out-of-memory error.
3192 *********************************************************************/
3193 static jb_err client_uagent(struct client_state *csp, char **header)
3197 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3202 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3209 *header = strdup("User-Agent: ");
3210 string_append(header, newval);
3212 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3214 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3218 /*********************************************************************
3220 * Function : client_ua
3222 * Description : Handle "ua-" headers properly. Called from `sed'.
3225 * 1 : csp = Current client state (buffers, headers, etc...)
3226 * 2 : header = On input, pointer to header to modify.
3227 * On output, pointer to the modified header, or NULL
3228 * to remove the header. This function frees the
3229 * original string if necessary.
3231 * Returns : JB_ERR_OK on success, or
3232 * JB_ERR_MEMORY on out-of-memory error.
3234 *********************************************************************/
3235 static jb_err client_ua(struct client_state *csp, char **header)
3237 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3239 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3247 /*********************************************************************
3249 * Function : client_from
3251 * Description : Handle the "from" config setting properly.
3252 * Called from `sed'.
3255 * 1 : csp = Current client state (buffers, headers, etc...)
3256 * 2 : header = On input, pointer to header to modify.
3257 * On output, pointer to the modified header, or NULL
3258 * to remove the header. This function frees the
3259 * original string if necessary.
3261 * Returns : JB_ERR_OK on success, or
3262 * JB_ERR_MEMORY on out-of-memory error.
3264 *********************************************************************/
3265 static jb_err client_from(struct client_state *csp, char **header)
3269 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3276 newval = csp->action->string[ACTION_STRING_FROM];
3279 * Are we blocking the e-mail address?
3281 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3283 log_error(LOG_LEVEL_HEADER, "crunched From!");
3287 log_error(LOG_LEVEL_HEADER, " modified");
3289 *header = strdup("From: ");
3290 string_append(header, newval);
3292 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3296 /*********************************************************************
3298 * Function : client_send_cookie
3300 * Description : Crunches the "cookie" header if necessary.
3301 * Called from `sed'.
3303 * XXX: Stupid name, doesn't send squat.
3306 * 1 : csp = Current client state (buffers, headers, etc...)
3307 * 2 : header = On input, pointer to header to modify.
3308 * On output, pointer to the modified header, or NULL
3309 * to remove the header. This function frees the
3310 * original string if necessary.
3312 * Returns : JB_ERR_OK on success, or
3313 * JB_ERR_MEMORY on out-of-memory error.
3315 *********************************************************************/
3316 static jb_err client_send_cookie(struct client_state *csp, char **header)
3318 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3320 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3328 /*********************************************************************
3330 * Function : client_x_forwarded
3332 * Description : Handle the "x-forwarded-for" config setting properly,
3333 * also used in the add_client_headers list. Called from `sed'.
3336 * 1 : csp = Current client state (buffers, headers, etc...)
3337 * 2 : header = On input, pointer to header to modify.
3338 * On output, pointer to the modified header, or NULL
3339 * to remove the header. This function frees the
3340 * original string if necessary.
3342 * Returns : JB_ERR_OK on success, or
3343 * JB_ERR_MEMORY on out-of-memory error.
3345 *********************************************************************/
3346 jb_err client_x_forwarded(struct client_state *csp, char **header)
3348 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3350 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3352 if (0 == strcmpic(parameter, "block"))
3355 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3357 else if (0 == strcmpic(parameter, "add"))
3359 string_append(header, ", ");
3360 string_append(header, csp->ip_addr_str);
3362 if (*header == NULL)
3364 return JB_ERR_MEMORY;
3366 log_error(LOG_LEVEL_HEADER,
3367 "Appended client IP address to %s", *header);
3368 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3372 log_error(LOG_LEVEL_FATAL,
3373 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3381 /*********************************************************************
3383 * Function : client_max_forwards
3385 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3386 * from the value of the Max-Forwards header field.
3389 * 1 : csp = Current client state (buffers, headers, etc...)
3390 * 2 : header = On input, pointer to header to modify.
3391 * On output, pointer to the modified header, or NULL
3392 * to remove the header. This function frees the
3393 * original string if necessary.
3395 * Returns : JB_ERR_OK on success, or
3396 * JB_ERR_MEMORY on out-of-memory error.
3398 *********************************************************************/
3399 static jb_err client_max_forwards(struct client_state *csp, char **header)
3403 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3404 (0 == strcmpic(csp->http->gpc, "options")))
3406 assert(*(*header+12) == ':');
3407 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3409 if (max_forwards > 0)
3411 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3412 log_error(LOG_LEVEL_HEADER,
3413 "Max-Forwards value for %s request reduced to %d.",
3414 csp->http->gpc, max_forwards);
3416 else if (max_forwards < 0)
3418 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3424 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3433 /*********************************************************************
3435 * Function : client_host
3437 * Description : If the request URI did not contain host and
3438 * port information, parse and evaluate the Host
3442 * 1 : csp = Current client state (buffers, headers, etc...)
3443 * 2 : header = On input, pointer to header to modify.
3444 * On output, pointer to the modified header, or NULL
3445 * to remove the header. This function frees the
3446 * original string if necessary.
3448 * Returns : JB_ERR_OK on success, or
3449 * JB_ERR_MEMORY on out-of-memory error.
3451 *********************************************************************/
3452 static jb_err client_host(struct client_state *csp, char **header)
3456 if (strlen(*header) < 7)
3458 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3463 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3464 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3467 p = strdup_or_die((*header)+6);
3469 q = strdup_or_die(p);
3471 freez(csp->http->hostport);
3472 csp->http->hostport = p;
3473 freez(csp->http->host);
3474 csp->http->host = q;
3475 q = strchr(csp->http->host, ':');
3478 /* Terminate hostname and evaluate port string */
3480 csp->http->port = atoi(q);
3484 csp->http->port = csp->http->ssl ? 443 : 80;
3487 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3488 csp->http->hostport, csp->http->host, csp->http->port);
3491 /* Signal client_host_adder() to return right away */
3492 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3498 /*********************************************************************
3500 * Function : client_if_modified_since
3502 * Description : Remove or modify the If-Modified-Since header.
3505 * 1 : csp = Current client state (buffers, headers, etc...)
3506 * 2 : header = On input, pointer to header to modify.
3507 * On output, pointer to the modified header, or NULL
3508 * to remove the header. This function frees the
3509 * original string if necessary.
3511 * Returns : JB_ERR_OK on success, or
3512 * JB_ERR_MEMORY on out-of-memory error.
3514 *********************************************************************/
3515 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3519 struct tm *timeptr = NULL;
3524 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3527 * The client got an error message because of a temporary problem,
3528 * the problem is gone and the client now tries to revalidate our
3529 * error message on the real server. The revalidation would always
3530 * end with the transmission of the whole document and there is
3531 * no need to expose the bogus If-Modified-Since header.
3533 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3536 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3538 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3540 if ((0 == strcmpic(newval, "block")))
3542 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3545 else /* add random value */
3547 if (JB_ERR_OK != parse_time_header(*header, &tm))
3549 log_error(LOG_LEVEL_HEADER,
3550 "Couldn't parse time in %s (crunching!)", *header);
3555 long int hours, minutes, seconds;
3556 long int rtime = strtol(newval, &endptr, 0);
3557 const int negative_range = (rtime < 0);
3561 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3562 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3568 rtime = pick_from_range(rtime);
3572 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3575 tm += rtime * (negative_range ? -1 : 1);
3576 timeptr = privoxy_gmtime_r(&tm, &gmt);
3577 if ((NULL == timeptr) || !strftime(newheader,
3578 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3580 log_error(LOG_LEVEL_ERROR,
3581 "Randomizing '%s' failed. Crunching the header without replacement.",
3587 *header = strdup("If-Modified-Since: ");
3588 string_append(header, newheader);
3590 if (*header == NULL)
3592 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3593 return JB_ERR_MEMORY;
3596 hours = rtime / 3600;
3597 minutes = rtime / 60 % 60;
3598 seconds = rtime % 60;
3600 log_error(LOG_LEVEL_HEADER,
3601 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3602 *header, (negative_range) ? "subtracted" : "added", hours,
3603 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3604 seconds, (seconds == 1) ? ")" : "s)");
3613 /*********************************************************************
3615 * Function : client_if_none_match
3617 * Description : Remove the If-None-Match header.
3620 * 1 : csp = Current client state (buffers, headers, etc...)
3621 * 2 : header = On input, pointer to header to modify.
3622 * On output, pointer to the modified header, or NULL
3623 * to remove the header. This function frees the
3624 * original string if necessary.
3626 * Returns : JB_ERR_OK on success, or
3627 * JB_ERR_MEMORY on out-of-memory error.
3629 *********************************************************************/
3630 static jb_err client_if_none_match(struct client_state *csp, char **header)
3632 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3634 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3642 /*********************************************************************
3644 * Function : client_x_filter
3646 * Description : Disables filtering if the client set "X-Filter: No".
3647 * Called from `sed'.
3650 * 1 : csp = Current client state (buffers, headers, etc...)
3651 * 2 : header = On input, pointer to header to modify.
3652 * On output, pointer to the modified header, or NULL
3653 * to remove the header. This function frees the
3654 * original string if necessary.
3656 * Returns : JB_ERR_OK on success
3658 *********************************************************************/
3659 jb_err client_x_filter(struct client_state *csp, char **header)
3661 if (0 == strcmpic(*header, "X-Filter: No"))
3663 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3665 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3669 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3671 log_error(LOG_LEVEL_HEADER,
3672 "force-text-mode overruled the client's request to fetch without filtering!");
3676 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3677 csp->flags |= CSP_FLAG_NO_FILTERING;
3678 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3680 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3688 /*********************************************************************
3690 * Function : client_range
3692 * Description : Removes Range, Request-Range and If-Range headers if
3693 * content filtering is enabled and the range doesn't
3696 * If the client's version of the document has been
3697 * altered by Privoxy, the server could interpret the
3698 * range differently than the client intended in which
3699 * case the user could end up with corrupted content.
3701 * If the range starts at byte 0 this isn't an issue
3702 * so the header can pass. Partial requests like this
3703 * are used to render preview images for videos without
3704 * downloading the whole video.
3706 * While HTTP doesn't require that range requests are
3707 * honoured and the client could simply abort the download
3708 * after receiving a sufficient amount of data, various
3709 * clients don't handle complete responses to range
3710 * requests gracefully and emit misleading error messages
3714 * 1 : csp = Current client state (buffers, headers, etc...)
3715 * 2 : header = On input, pointer to header to modify.
3716 * On output, pointer to the modified header, or NULL
3717 * to remove the header. This function frees the
3718 * original string if necessary.
3720 * Returns : JB_ERR_OK
3722 *********************************************************************/
3723 static jb_err client_range(struct client_state *csp, char **header)
3725 if (content_filters_enabled(csp->action)
3726 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3728 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3729 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3736 /* the following functions add headers directly to the header list */
3738 /*********************************************************************
3740 * Function : client_host_adder
3742 * Description : Adds the Host: header field if it is missing.
3743 * Called from `sed'.
3746 * 1 : csp = Current client state (buffers, headers, etc...)
3748 * Returns : JB_ERR_OK on success, or
3749 * JB_ERR_MEMORY on out-of-memory error.
3751 *********************************************************************/
3752 static jb_err client_host_adder(struct client_state *csp)
3757 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3759 /* Header already set by the client, nothing to do. */
3763 if (!csp->http->hostport || !*(csp->http->hostport))
3765 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3766 return JB_ERR_PARSE;
3770 * remove 'user:pass@' from 'proto://user:pass@host'
3772 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3778 p = csp->http->hostport;
3781 /* XXX: Just add it, we already made sure that it will be unique */
3782 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3783 err = enlist_unique_header(csp->headers, "Host", p);
3789 /*********************************************************************
3791 * Function : client_xtra_adder
3793 * Description : Used in the add_client_headers list. Called from `sed'.
3796 * 1 : csp = Current client state (buffers, headers, etc...)
3798 * Returns : JB_ERR_OK on success, or
3799 * JB_ERR_MEMORY on out-of-memory error.
3801 *********************************************************************/
3802 static jb_err client_xtra_adder(struct client_state *csp)
3804 struct list_entry *lst;
3807 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3808 lst ; lst = lst->next)
3810 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3811 err = enlist(csp->headers, lst->str);
3823 /*********************************************************************
3825 * Function : client_x_forwarded_for_adder
3827 * Description : Used in the add_client_headers list. Called from `sed'.
3830 * 1 : csp = Current client state (buffers, headers, etc...)
3832 * Returns : JB_ERR_OK on success, or
3833 * JB_ERR_MEMORY on out-of-memory error.
3835 *********************************************************************/
3836 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3838 char *header = NULL;
3841 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3842 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3843 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3846 * If we aren't adding X-Forwarded-For headers,
3847 * or we already appended an existing X-Forwarded-For
3848 * header, there's nothing left to do here.
3853 header = strdup("X-Forwarded-For: ");
3854 string_append(&header, csp->ip_addr_str);
3858 return JB_ERR_MEMORY;
3861 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3862 err = enlist(csp->headers, header);
3869 /*********************************************************************
3871 * Function : server_connection_adder
3873 * Description : Adds an appropriate "Connection:" header to csp->headers
3874 * unless the header was already present. Called from `sed'.
3877 * 1 : csp = Current client state (buffers, headers, etc...)
3879 * Returns : JB_ERR_OK on success, or
3880 * JB_ERR_MEMORY on out-of-memory error.
3882 *********************************************************************/
3883 static jb_err server_connection_adder(struct client_state *csp)
3885 const unsigned int flags = csp->flags;
3886 const char *response_status_line = csp->headers->first->str;
3887 static const char connection_close[] = "Connection: close";
3889 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3890 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3896 * XXX: if we downgraded the response, this check will fail.
3898 if ((csp->config->feature_flags &
3899 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3900 && (NULL != response_status_line)
3901 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3902 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3903 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3907 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3908 "without Connection header implies keep-alive.");
3909 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3913 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3915 return enlist(csp->headers, connection_close);
3919 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3920 /*********************************************************************
3922 * Function : server_proxy_connection_adder
3924 * Description : Adds a "Proxy-Connection: keep-alive" header to
3925 * csp->headers when appropriate.
3928 * 1 : csp = Current client state (buffers, headers, etc...)
3930 * Returns : JB_ERR_OK on success, or
3931 * JB_ERR_MEMORY on out-of-memory error.
3933 *********************************************************************/
3934 static jb_err server_proxy_connection_adder(struct client_state *csp)
3936 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3937 jb_err err = JB_ERR_OK;
3939 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3940 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3941 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3942 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3943 || (csp->flags & CSP_FLAG_CHUNKED))
3944 #ifdef FEATURE_HTTPS_INSPECTION
3945 && !client_use_ssl(csp)
3950 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3951 err = enlist(csp->headers, proxy_connection_header);
3956 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3959 /*********************************************************************
3961 * Function : client_connection_header_adder
3963 * Description : Adds a proper "Connection:" header to csp->headers
3964 * unless the header was already present or it's a
3965 * CONNECT request. Called from `sed'.
3968 * 1 : csp = Current client state (buffers, headers, etc...)
3970 * Returns : JB_ERR_OK on success, or
3971 * JB_ERR_MEMORY on out-of-memory error.
3973 *********************************************************************/
3974 static jb_err client_connection_header_adder(struct client_state *csp)
3976 static const char connection_close[] = "Connection: close";
3978 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3979 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3985 * In case of CONNECT requests "Connection: close" is implied,
3986 * but actually setting the header has been reported to cause
3987 * problems with some forwarding proxies that close the
3988 * connection prematurely.
3990 if (csp->http->ssl != 0)
3995 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3996 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3997 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3998 && !strcmpic(csp->http->version, "HTTP/1.1"))
4000 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4003 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4005 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4007 return enlist(csp->headers, connection_close);
4011 /*********************************************************************
4013 * Function : server_http
4015 * Description : - Save the HTTP Status into csp->http->status
4016 * - Set CT_TABOO to prevent filtering if the answer
4017 * is a partial range (HTTP status 206)
4018 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4020 * - Normalize the HTTP-version.
4023 * 1 : csp = Current client state (buffers, headers, etc...)
4024 * 2 : header = On input, pointer to header to modify.
4025 * On output, pointer to the modified header, or NULL
4026 * to remove the header. This function frees the
4027 * original string if necessary.
4029 * Returns : JB_ERR_OK on success, or
4030 * JB_ERR_PARSE on fatal parse errors.
4032 *********************************************************************/
4033 static jb_err server_http(struct client_state *csp, char **header)
4035 char *reason_phrase = NULL;
4036 char *new_response_line;
4039 unsigned int major_version;
4040 unsigned int minor_version;
4042 /* Get the reason phrase which start after the second whitespace */
4043 p = strchr(*header, ' ');
4047 reason_phrase = strchr(p, ' ');
4050 if (reason_phrase != NULL)
4056 log_error(LOG_LEVEL_ERROR,
4057 "Response line lacks reason phrase: %s", *header);
4061 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4062 &minor_version, &(csp->http->status)))
4064 log_error(LOG_LEVEL_ERROR,
4065 "Failed to parse the response line: %s", *header);
4066 return JB_ERR_PARSE;
4069 if (csp->http->status == 206)
4071 csp->content_type = CT_TABOO;
4074 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4077 * According to RFC 7230 2.6 intermediaries MUST send
4078 * their own HTTP-version in forwarded messages.
4080 log_error(LOG_LEVEL_ERROR,
4081 "Unsupported HTTP version. Downgrading to 1.1.");
4086 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4088 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4092 /* Rebuild response line. */
4093 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4094 new_response_line = malloc_or_die(length);
4096 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4097 major_version, minor_version, csp->http->status, reason_phrase);
4099 if (0 != strcmp(*header, new_response_line))
4101 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4102 *header, new_response_line);
4106 *header = new_response_line;
4111 /*********************************************************************
4113 * Function : add_cooky_expiry_date
4115 * Description : Adds a cookie expiry date to a string.
4118 * 1 : cookie = On input, pointer to cookie to modify.
4119 * On output, pointer to the modified header.
4120 * The original string is freed.
4121 * 2 : lifetime = Seconds the cookie should be valid
4125 *********************************************************************/
4126 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4129 struct tm *timeptr = NULL;
4130 time_t expiry_date = time(NULL) + lifetime;
4133 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4134 if (NULL == timeptr)
4136 log_error(LOG_LEVEL_FATAL,
4137 "Failed to get the time in add_cooky_expiry_date()");
4139 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4140 if (JB_ERR_OK != string_append(cookie, tmp))
4142 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4147 /*********************************************************************
4149 * Function : server_set_cookie
4151 * Description : Handle the server "cookie" header properly.
4152 * Crunch, accept or rewrite it to a session cookie.
4153 * Called from `sed'.
4156 * 1 : csp = Current client state (buffers, headers, etc...)
4157 * 2 : header = On input, pointer to header to modify.
4158 * On output, pointer to the modified header, or NULL
4159 * to remove the header. This function frees the
4160 * original string if necessary.
4162 * Returns : JB_ERR_OK on success, or
4163 * JB_ERR_MEMORY on out-of-memory error.
4165 *********************************************************************/
4166 static jb_err server_set_cookie(struct client_state *csp, char **header)
4168 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4170 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4173 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4174 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4178 long cookie_lifetime = 0;
4181 NO_EXPIRY_DATE_SPECIFIED,
4182 EXPIRY_DATE_ACCEPTABLE,
4183 EXPIRY_DATE_UNACCEPTABLE
4184 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4186 /* A variable to store the tag we're working on */
4189 /* Skip "Set-Cookie:" (11 characters) in header */
4190 cur_tag = *header + 11;
4192 /* skip whitespace between "Set-Cookie:" and value */
4193 while (*cur_tag && privoxy_isspace(*cur_tag))
4200 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4202 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4204 cookie_lifetime = strtol(param, NULL, 0);
4205 if (cookie_lifetime < 0)
4207 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4209 cookie_lifetime *= 60;
4212 /* Loop through each tag in the cookie */
4216 char *next_tag = strchr(cur_tag, ';');
4217 if (next_tag != NULL)
4219 /* Skip the ';' character itself */
4222 /* skip whitespace ";" and start of tag */
4223 while (*next_tag && privoxy_isspace(*next_tag))
4230 /* "Next tag" is the end of the string */
4231 next_tag = cur_tag + strlen(cur_tag);
4235 * Check the expiration date to see
4236 * if the cookie is still valid, if yes,
4237 * rewrite it to a session cookie.
4239 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4241 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4243 if ((expiration_date[0] == '"')
4244 && (expiration_date[1] != '\0'))
4247 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4248 * that the expiration date isn't supposed to be quoted,
4249 * but some servers do it anyway.
4254 /* Did we detect the date properly? */
4255 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4258 * Nope, treat it as if it was still valid.
4260 * XXX: Should we remove the whole cookie instead?
4262 log_error(LOG_LEVEL_ERROR,
4263 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4264 string_move(cur_tag, next_tag);
4265 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4270 * Yes. Check if the cookie is still valid.
4272 * If the cookie is already expired it's probably
4273 * a delete cookie and even if it isn't, the browser
4274 * will discard it anyway.
4278 * XXX: timegm() isn't available on some AmigaOS
4279 * versions and our replacement doesn't work.
4281 * Our options are to either:
4283 * - disable session-cookies-only completely if timegm
4286 * - to simply remove all expired tags, like it has
4287 * been done until Privoxy 3.0.6 and to live with
4288 * the consequence that it can cause login/logout
4289 * problems on servers that don't validate their
4290 * input properly, or
4292 * - to replace it with mktime in which
4293 * case there is a slight chance of valid cookies
4294 * passing as already expired.
4296 * This is the way it's currently done and it's not
4297 * as bad as it sounds. If the missing GMT offset is
4298 * enough to change the result of the expiration check
4299 * the cookie will be only valid for a few hours
4300 * anyway, which in many cases will be shorter
4301 * than a browser session.
4303 if (cookie_time < now)
4305 log_error(LOG_LEVEL_HEADER,
4306 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4307 /* Just in case some clown sets more then one expiration date */
4309 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4311 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4313 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4314 "Its lifetime is below the limit.", *header);
4315 /* Just in case some clown sets more then one expiration date */
4317 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4322 * Still valid, delete expiration date by copying
4323 * the rest of the string over it.
4325 string_move(cur_tag, next_tag);
4327 /* That changed the header, need to issue a log message */
4328 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4331 * Note that the next tag has now been moved to *cur_tag,
4332 * so we do not need to update the cur_tag pointer.
4340 /* Move on to next cookie tag */
4345 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4347 assert(NULL != *header);
4348 if (cookie_lifetime != 0)
4350 add_cookie_expiry_date(header, cookie_lifetime);
4351 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4353 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4355 log_error(LOG_LEVEL_HEADER,
4356 "Cookie rewritten to a temporary one: %s", *header);
4365 #ifdef FEATURE_FORCE_LOAD
4366 /*********************************************************************
4368 * Function : strclean
4370 * Description : In-Situ-Eliminate all occurrences of substring in
4374 * 1 : string = string to clean
4375 * 2 : substring = substring to eliminate
4377 * Returns : Number of eliminations
4379 *********************************************************************/
4380 int strclean(char *string, const char *substring)
4386 len = strlen(substring);
4388 while((pos = strstr(string, substring)) != NULL)
4395 while (*p++ != '\0');
4402 #endif /* def FEATURE_FORCE_LOAD */
4405 /*********************************************************************
4407 * Function : parse_header_time
4409 * Description : Parses time formats used in HTTP header strings
4410 * to get the numerical respresentation.
4413 * 1 : header_time = HTTP header time as string.
4414 * 2 : result = storage for header_time in seconds
4416 * Returns : JB_ERR_OK if the time format was recognized, or
4417 * JB_ERR_PARSE otherwise.
4419 *********************************************************************/
4420 static jb_err parse_header_time(const char *header_time, time_t *result)
4424 * Checking for two-digit years first in an
4425 * attempt to work around GNU libc's strptime()
4426 * reporting negative year values when using %Y.
4428 static const char time_formats[][22] = {
4429 /* Tue, 02-Jun-37 20:00:00 */
4430 "%a, %d-%b-%y %H:%M:%S",
4431 /* Tue, 02 Jun 2037 20:00:00 */
4432 "%a, %d %b %Y %H:%M:%S",
4433 /* Tue, 02-Jun-2037 20:00:00 */
4434 "%a, %d-%b-%Y %H:%M:%S",
4435 /* Tuesday, 02-Jun-2037 20:00:00 */
4436 "%A, %d-%b-%Y %H:%M:%S",
4437 /* Tuesday Jun 02 20:00:00 2037 */
4438 "%A %b %d %H:%M:%S %Y"
4442 for (i = 0; i < SZ(time_formats); i++)
4445 * Zero out gmt to prevent time zone offsets.
4446 * Documented to be required for GNU libc.
4448 memset(&gmt, 0, sizeof(gmt));
4450 if (NULL != strptime(header_time, time_formats[i], &gmt))
4452 /* Sanity check for GNU libc. */
4453 if (gmt.tm_year < 0)
4455 log_error(LOG_LEVEL_HEADER,
4456 "Failed to parse '%s' using '%s'. Moving on.",
4457 header_time, time_formats[i]);
4460 *result = timegm(&gmt);
4462 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4464 * Verify that parsing the date recreated from the first
4465 * parse operation gets the previous result. If it doesn't,
4466 * either strptime() or strftime() are malfunctioning.
4468 * We could string-compare the recreated date with the original
4469 * header date, but this leads to false positives as strptime()
4470 * may let %a accept all day formats while strftime() will only
4474 char recreated_date[100];
4479 tm = privoxy_gmtime_r(result, &storage);
4480 if (!strftime(recreated_date, sizeof(recreated_date),
4481 time_formats[i], tm))
4483 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4484 header_time, time_formats[i]);
4487 memset(&gmt, 0, sizeof(gmt));
4488 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4490 log_error(LOG_LEVEL_ERROR,
4491 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4492 recreated_date, time_formats[i], header_time);
4495 result2 = timegm(&gmt);
4496 if (*result != result2)
4498 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4499 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4500 time_formats[i], header_time, recreated_date, *result, result2);
4510 return JB_ERR_PARSE;
4514 /*********************************************************************
4516 * Function : parse_time_header
4518 * Description : Parses the time in an HTTP time header to get
4519 * the numerical respresentation.
4522 * 1 : header = HTTP header with a time value
4523 * 2 : result = storage for header_time in seconds
4525 * Returns : JB_ERR_OK if the time format was recognized, or
4526 * JB_ERR_PARSE otherwise.
4528 *********************************************************************/
4529 static jb_err parse_time_header(const char *header, time_t *result)
4531 const char *header_time;
4533 header_time = strchr(header, ':');
4536 * Currently this can't happen as all callers are called
4537 * through sed() which requires a header name followed by
4540 assert(header_time != NULL);
4543 if (*header_time == ' ')
4548 return parse_header_time(header_time, result);
4553 /*********************************************************************
4555 * Function : get_destination_from_headers
4557 * Description : Parse the "Host:" header to get the request's destination.
4558 * Only needed if the client's request was forcefully
4559 * redirected into Privoxy.
4561 * Code mainly copied from client_host() which is currently
4562 * run too late for this purpose.
4565 * 1 : headers = List of headers (one of them hopefully being
4566 * the "Host:" header)
4567 * 2 : http = storage for the result (host, port and hostport).
4569 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4570 * JB_ERR_PARSE if the host header couldn't be found,
4571 * JB_ERR_OK otherwise.
4573 *********************************************************************/
4574 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4580 host = get_header_value(headers, "Host:");
4584 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4585 return JB_ERR_PARSE;
4588 p = strdup_or_die(host);
4590 q = strdup_or_die(p);
4592 freez(http->hostport);
4596 q = strchr(http->host, ':');
4599 /* Terminate hostname and evaluate port string */
4601 http->port = atoi(q);
4608 /* Rebuild request URL */
4610 http->url = strdup("http://");
4611 string_append(&http->url, http->hostport);
4612 string_append(&http->url, http->path);
4613 if (http->url == NULL)
4615 return JB_ERR_MEMORY;
4618 log_error(LOG_LEVEL_HEADER,
4619 "Destination extracted from \"Host\" header. New request URL: %s",
4623 * Regenerate request line in "proxy format"
4624 * to make rewrites more convenient.
4626 assert(http->cmd != NULL);
4628 http->cmd = strdup_or_die(http->gpc);
4629 string_append(&http->cmd, " ");
4630 string_append(&http->cmd, http->url);
4631 string_append(&http->cmd, " ");
4632 string_append(&http->cmd, http->version);
4633 if (http->cmd == NULL)
4635 return JB_ERR_MEMORY;
4643 #ifdef FEATURE_HTTPS_INSPECTION
4644 /*********************************************************************
4646 * Function : get_destination_from_https_headers
4648 * Description : Parse the previously encrypted "Host:" header to
4649 * get the request's destination.
4652 * 1 : headers = List of headers (one of them hopefully being
4653 * the "Host:" header)
4654 * 2 : http = storage for the result (host, port and hostport).
4656 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4657 * JB_ERR_PARSE if the host header couldn't be found,
4658 * JB_ERR_OK otherwise.
4660 *********************************************************************/
4661 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4667 host = get_header_value(headers, "Host:");
4671 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4672 return JB_ERR_PARSE;
4675 p = strdup_or_die(host);
4677 q = strdup_or_die(p);
4679 freez(http->hostport);
4683 q = strchr(http->host, ':');
4686 /* Terminate hostname and evaluate port string */
4688 http->port = atoi(q);
4695 /* Rebuild request URL */
4697 http->url = strdup_or_die(http->path);
4699 log_error(LOG_LEVEL_HEADER,
4700 "Destination extracted from \"Host\" header. New request URL: %s",
4704 * Regenerate request line in "proxy format"
4705 * to make rewrites more convenient.
4707 assert(http->cmd != NULL);
4709 http->cmd = strdup_or_die(http->gpc);
4710 string_append(&http->cmd, " ");
4711 string_append(&http->cmd, http->url);
4712 string_append(&http->cmd, " ");
4713 string_append(&http->cmd, http->version);
4714 if (http->cmd == NULL)
4716 return JB_ERR_MEMORY;
4722 #endif /* def FEATURE_HTTPS_INSPECTION */
4725 /*********************************************************************
4727 * Function : create_forged_referrer
4729 * Description : Helper for client_referrer to forge a referer as
4730 * 'http://hostname[:port]/' to fool stupid
4731 * checks for in-site links
4734 * 1 : header = Pointer to header pointer
4735 * 2 : hostport = Host and optionally port as string
4737 * Returns : JB_ERR_OK in case of success, or
4738 * JB_ERR_MEMORY in case of memory problems.
4740 *********************************************************************/
4741 static jb_err create_forged_referrer(char **header, const char *hostport)
4743 assert(NULL == *header);
4745 *header = strdup("Referer: http://");
4746 string_append(header, hostport);
4747 string_append(header, "/");
4749 if (NULL == *header)
4751 return JB_ERR_MEMORY;
4754 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4761 /*********************************************************************
4763 * Function : create_fake_referrer
4765 * Description : Helper for client_referrer to create a fake referrer
4766 * based on a string supplied by the user.
4769 * 1 : header = Pointer to header pointer
4770 * 2 : hosthost = Referrer to fake
4772 * Returns : JB_ERR_OK in case of success, or
4773 * JB_ERR_MEMORY in case of memory problems.
4775 *********************************************************************/
4776 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4778 assert(NULL == *header);
4780 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4782 log_error(LOG_LEVEL_HEADER,
4783 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4785 *header = strdup("Referer: ");
4786 string_append(header, fake_referrer);
4788 if (NULL == *header)
4790 return JB_ERR_MEMORY;
4793 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4800 /*********************************************************************
4802 * Function : handle_conditional_hide_referrer_parameter
4804 * Description : Helper for client_referrer to crunch or forge
4805 * the referrer header if the host has changed.
4808 * 1 : header = Pointer to header pointer
4809 * 2 : host = The target host (may include the port)
4810 * 3 : parameter_conditional_block = Boolean to signal
4811 * if we're in conditional-block mode. If not set,
4812 * we're in conditional-forge mode.
4814 * Returns : JB_ERR_OK in case of success, or
4815 * JB_ERR_MEMORY in case of memory problems.
4817 *********************************************************************/
4818 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4819 const char *host, const int parameter_conditional_block)
4821 char *referer = strdup_or_die(*header);
4822 const size_t hostlength = strlen(host);
4823 const char *referer_url = NULL;
4825 /* referer begins with 'Referer: http[s]://' */
4826 if ((hostlength+17) < strlen(referer))
4829 * Shorten referer to make sure the referer is blocked
4830 * if www.example.org/www.example.com-shall-see-the-referer/
4831 * links to www.example.com/
4833 referer[hostlength+17] = '\0';
4835 referer_url = strstr(referer, "http://");
4836 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4838 /* Host has changed, Referer is invalid or a https URL. */
4839 if (parameter_conditional_block)
4841 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4848 return create_forged_referrer(header, host);
4858 /*********************************************************************
4860 * Function : create_content_length_header
4862 * Description : Creates a Content-Length header.
4865 * 1 : content_length = The content length to be used in the header.
4866 * 2 : header = Allocated space to safe the header.
4867 * 3 : buffer_length = The length of the allocated space.
4871 *********************************************************************/
4872 static void create_content_length_header(unsigned long long content_length,
4873 char *header, size_t buffer_length)
4876 #if SIZEOF_LONG_LONG < 8
4877 #error sizeof(unsigned long long) too small
4879 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4881 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4886 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4887 /*********************************************************************
4889 * Function : get_expected_content_length
4891 * Description : Figures out the content length from a list of headers.
4894 * 1 : headers = List of headers
4896 * Returns : Number of bytes to expect
4898 *********************************************************************/
4899 unsigned long long get_expected_content_length(struct list *headers)
4901 const char *content_length_header;
4902 unsigned long long content_length = 0;
4904 content_length_header = get_header_value(headers, "Content-Length:");
4905 if (content_length_header != NULL)
4907 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4909 log_error(LOG_LEVEL_ERROR,
4910 "Failed to get the Content-Length in %s", content_length_header);
4911 /* XXX: The header will be removed later on */
4916 return content_length;