1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2020 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
61 #define GZIP_FLAG_CHECKSUM 0x02
62 #define GZIP_FLAG_EXTRA_FIELDS 0x04
63 #define GZIP_FLAG_FILE_NAME 0x08
64 #define GZIP_FLAG_COMMENT 0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
68 #include <brotli/decode.h>
77 #ifdef FEATURE_PTHREAD
79 /* jcc.h is for mutex semapores only */
80 #endif /* def FEATURE_PTHREAD */
85 #include "jbsockets.h"
90 #ifdef FEATURE_HTTPS_INSPECTION
98 static char *get_header_line(struct iob *iob);
99 static jb_err scan_headers(struct client_state *csp);
100 static jb_err header_tagger(struct client_state *csp, char *header);
101 static jb_err parse_header_time(const char *header_time, time_t *result);
102 static jb_err parse_time_header(const char *header, time_t *result);
104 static jb_err crumble (struct client_state *csp, char **header);
105 static jb_err filter_header (struct client_state *csp, char **header);
106 static jb_err client_connection (struct client_state *csp, char **header);
107 static jb_err client_referrer (struct client_state *csp, char **header);
108 static jb_err client_uagent (struct client_state *csp, char **header);
109 static jb_err client_ua (struct client_state *csp, char **header);
110 static jb_err client_from (struct client_state *csp, char **header);
111 static jb_err client_send_cookie (struct client_state *csp, char **header);
112 static jb_err client_x_forwarded (struct client_state *csp, char **header);
113 static jb_err client_accept_encoding (struct client_state *csp, char **header);
114 static jb_err client_te (struct client_state *csp, char **header);
115 static jb_err client_max_forwards (struct client_state *csp, char **header);
116 static jb_err client_host (struct client_state *csp, char **header);
117 static jb_err client_if_modified_since (struct client_state *csp, char **header);
118 static jb_err client_accept_language (struct client_state *csp, char **header);
119 static jb_err client_if_none_match (struct client_state *csp, char **header);
120 static jb_err crunch_client_header (struct client_state *csp, char **header);
121 static jb_err client_x_filter (struct client_state *csp, char **header);
122 static jb_err client_range (struct client_state *csp, char **header);
123 static jb_err client_expect (struct client_state *csp, char **header);
124 static jb_err server_set_cookie (struct client_state *csp, char **header);
125 static jb_err server_connection (struct client_state *csp, char **header);
126 static jb_err server_content_type (struct client_state *csp, char **header);
127 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
128 static jb_err server_content_md5 (struct client_state *csp, char **header);
129 static jb_err server_content_encoding (struct client_state *csp, char **header);
130 static jb_err server_transfer_coding (struct client_state *csp, char **header);
131 static jb_err server_http (struct client_state *csp, char **header);
132 static jb_err crunch_server_header (struct client_state *csp, char **header);
133 static jb_err server_last_modified (struct client_state *csp, char **header);
134 static jb_err server_content_disposition(struct client_state *csp, char **header);
136 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
139 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
140 static jb_err server_save_content_length(struct client_state *csp, char **header);
141 static jb_err server_keep_alive(struct client_state *csp, char **header);
142 static jb_err server_proxy_connection(struct client_state *csp, char **header);
143 static jb_err client_keep_alive(struct client_state *csp, char **header);
144 static jb_err client_proxy_connection(struct client_state *csp, char **header);
145 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
147 static jb_err client_save_content_length(struct client_state *csp, char **header);
148 static jb_err client_host_adder (struct client_state *csp);
149 static jb_err client_xtra_adder (struct client_state *csp);
150 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
151 static jb_err client_connection_header_adder(struct client_state *csp);
152 static jb_err server_connection_adder(struct client_state *csp);
153 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
154 static jb_err server_proxy_connection_adder(struct client_state *csp);
155 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
156 static jb_err proxy_authentication(struct client_state *csp, char **header);
158 static jb_err create_forged_referrer(char **header, const char *hostport);
159 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
160 static jb_err handle_conditional_hide_referrer_parameter(char **header,
161 const char *host, const int parameter_conditional_block);
162 static void create_content_length_header(unsigned long long content_length,
163 char *header, size_t buffer_length);
166 * List of functions to run on a list of headers.
170 /** The header prefix to match */
173 /** The length of the prefix to match */
176 /** The function to apply to this line */
177 const parser_func_ptr parser;
180 static const struct parsers client_patterns[] = {
181 { "referer:", 8, client_referrer },
182 { "user-agent:", 11, client_uagent },
183 { "ua-", 3, client_ua },
184 { "from:", 5, client_from },
185 { "cookie:", 7, client_send_cookie },
186 { "x-forwarded-for:", 16, client_x_forwarded },
187 { "Accept-Encoding:", 16, client_accept_encoding },
188 { "TE:", 3, client_te },
189 { "Host:", 5, client_host },
190 { "if-modified-since:", 18, client_if_modified_since },
191 { "Content-Length:", 15, client_save_content_length },
192 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
193 { "Keep-Alive:", 11, client_keep_alive },
194 { "Proxy-Connection:", 17, client_proxy_connection },
196 { "Keep-Alive:", 11, crumble },
197 { "Proxy-Connection:", 17, crumble },
199 { "connection:", 11, client_connection },
200 { "max-forwards:", 13, client_max_forwards },
201 { "Accept-Language:", 16, client_accept_language },
202 { "if-none-match:", 14, client_if_none_match },
203 { "Range:", 6, client_range },
204 { "Request-Range:", 14, client_range },
205 { "If-Range:", 9, client_range },
206 { "X-Filter:", 9, client_x_filter },
207 { "Proxy-Authorization:", 20, proxy_authentication },
209 { "Transfer-Encoding:", 18, client_transfer_encoding },
211 { "Expect:", 7, client_expect },
212 { "*", 0, crunch_client_header },
213 { "*", 0, filter_header },
217 static const struct parsers server_patterns[] = {
218 { "HTTP/", 5, server_http },
219 { "set-cookie:", 11, server_set_cookie },
220 { "connection:", 11, server_connection },
221 { "Content-Type:", 13, server_content_type },
222 { "Content-MD5:", 12, server_content_md5 },
223 { "Content-Encoding:", 17, server_content_encoding },
224 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
225 { "Content-Length:", 15, server_save_content_length },
226 { "Keep-Alive:", 11, server_keep_alive },
227 { "Proxy-Connection:", 17, server_proxy_connection },
229 { "Keep-Alive:", 11, crumble },
230 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
231 { "Transfer-Encoding:", 18, server_transfer_coding },
232 { "content-disposition:", 20, server_content_disposition },
233 { "Last-Modified:", 14, server_last_modified },
234 { "Proxy-Authenticate:", 19, proxy_authentication },
235 { "*", 0, crunch_server_header },
236 { "*", 0, filter_header },
240 static const add_header_func_ptr add_client_headers[] = {
242 client_x_forwarded_for_adder,
244 client_connection_header_adder,
248 static const add_header_func_ptr add_server_headers[] = {
249 server_connection_adder,
250 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
251 server_proxy_connection_adder,
252 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
256 /*********************************************************************
258 * Function : flush_iob
260 * Description : Write any pending "buffered" content.
263 * 1 : fd = file descriptor of the socket to read
264 * 2 : iob = The I/O buffer to flush, usually csp->iob.
265 * 3 : delay = Number of milliseconds to delay the writes
267 * Returns : On success, the number of bytes written are returned (zero
268 * indicates nothing was written). On error, -1 is returned,
269 * and errno is set appropriately. If count is zero and the
270 * file descriptor refers to a regular file, 0 will be
271 * returned without causing any other effect. For a special
272 * file, the results are not portable.
274 *********************************************************************/
275 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
277 long len = iob->eod - iob->cur;
284 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
288 iob->eod = iob->cur = iob->buf;
294 /*********************************************************************
296 * Function : add_to_iob
298 * Description : Add content to the buffer, expanding the
299 * buffer if necessary.
302 * 1 : iob = Destination buffer.
303 * 2 : buffer_limit = Limit to which the destination may grow
304 * 3 : src = holds the content to be added
305 * 4 : n = number of bytes to be added
307 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
308 * or buffer limit reached.
310 *********************************************************************/
311 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
313 size_t used, offset, need;
316 if (n <= 0) return JB_ERR_OK;
318 used = (size_t)(iob->eod - iob->buf);
319 offset = (size_t)(iob->cur - iob->buf);
320 need = used + (size_t)n + 1;
323 * If the buffer can't hold the new data, extend it first.
324 * Use the next power of two if possible, else use the actual need.
326 if (need > buffer_limit)
328 log_error(LOG_LEVEL_INFO,
329 "Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
331 return JB_ERR_MEMORY;
334 if (need > iob->size)
336 size_t want = iob->size ? iob->size : 512;
343 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
347 else if (NULL != (p = (char *)realloc(iob->buf, need)))
353 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
354 return JB_ERR_MEMORY;
357 /* Update the iob pointers */
358 iob->cur = p + offset;
363 /* copy the new data into the iob buffer */
364 memcpy(iob->eod, src, (size_t)n);
366 /* point to the end of the data */
369 /* null terminate == cheap insurance */
377 /*********************************************************************
379 * Function : clear_iob
381 * Description : Frees the memory allocated for an I/O buffer and
382 * resets the structure.
385 * 1 : iob = I/O buffer to clear.
389 *********************************************************************/
390 void clear_iob(struct iob *iob)
393 memset(iob, '\0', sizeof(*iob));
398 #ifdef FEATURE_BROTLI
399 /*********************************************************************
401 * Function : decompress_iob_with_brotli
403 * Description : Decompress buffered page using Brotli.
406 * 1 : csp = Current client state (buffers, headers, etc...)
408 * Returns : JB_ERR_OK on success,
409 * JB_ERR_MEMORY if out-of-memory limit reached, and
410 * JB_ERR_COMPRESS if error decompressing buffer.
412 *********************************************************************/
413 static jb_err decompress_iob_with_brotli(struct client_state *csp)
415 BrotliDecoderResult result;
416 char *decoded_buffer;
418 size_t decoded_buffer_size;
420 enum { MAX_COMPRESSION_FACTOR = 15 };
422 encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
424 * The BrotliDecoderDecompress() api is a bit unfortunate
425 * and requires the caller to reserve enough memory for
426 * the decompressed content. Hopefully reserving
427 * MAX_COMPRESSION_FACTOR times the original size is
428 * sufficient. If not, BrotliDecoderDecompress() will fail.
430 decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
432 if (decoded_buffer_size > csp->config->buffer_limit)
434 log_error(LOG_LEVEL_ERROR,
435 "Buffer limit reached before decompressing iob with Brotli");
436 return JB_ERR_MEMORY;
439 decoded_buffer = malloc(decoded_buffer_size);
440 if (decoded_buffer == NULL)
442 log_error(LOG_LEVEL_ERROR,
443 "Failed to allocate %lu bytes for Brotli decompression",
444 decoded_buffer_size);
445 return JB_ERR_MEMORY;
448 decoded_size = decoded_buffer_size;
449 result = BrotliDecoderDecompress(encoded_size,
450 (const uint8_t *)csp->iob->cur, &decoded_size,
451 (uint8_t *)decoded_buffer);
452 if (result == BROTLI_DECODER_RESULT_SUCCESS)
455 * Update the iob, since the decompression was successful.
457 freez(csp->iob->buf);
458 csp->iob->buf = decoded_buffer;
459 csp->iob->cur = csp->iob->buf;
460 csp->iob->eod = csp->iob->cur + decoded_size;
461 csp->iob->size = decoded_buffer_size;
463 log_error(LOG_LEVEL_RE_FILTER,
464 "Decompression successful. Old size: %lu, new size: %lu.",
465 encoded_size, decoded_size);
471 log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
472 freez(decoded_buffer);
474 return JB_ERR_COMPRESS;
479 /*********************************************************************
481 * Function : decompress_iob
483 * Description : Decompress buffered page, expanding the
484 * buffer as necessary. csp->iob->cur
485 * should point to the the beginning of the
486 * compressed data block.
489 * 1 : csp = Current client state (buffers, headers, etc...)
491 * Returns : JB_ERR_OK on success,
492 * JB_ERR_MEMORY if out-of-memory limit reached, and
493 * JB_ERR_COMPRESS if error decompressing buffer.
495 *********************************************************************/
496 jb_err decompress_iob(struct client_state *csp)
498 char *buf; /* new, uncompressed buffer */
499 char *cur; /* Current iob position (to keep the original
500 * iob->cur unmodified if we return early) */
501 size_t bufsize; /* allocated size of the new buffer */
502 size_t old_size; /* Content size before decompression */
503 size_t skip_size; /* Number of bytes at the beginning of the iob
504 that we should NOT decompress. */
505 int status; /* return status of the inflate() call */
506 z_stream zstr; /* used by calls to zlib */
509 assert(csp->iob->cur - csp->iob->buf >= 0);
510 assert(csp->iob->eod - csp->iob->cur >= 0);
512 assert(csp->iob->cur - csp->iob->buf > 0);
513 assert(csp->iob->eod - csp->iob->cur > 0);
516 bufsize = csp->iob->size;
517 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
518 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
522 if (bufsize < (size_t)10)
525 * This is to protect the parsing of gzipped data,
526 * but it should(?) be valid for deflated data also.
528 log_error(LOG_LEVEL_ERROR,
529 "Insufficient data to start decompression. Bytes in buffer: %ld",
530 csp->iob->eod - csp->iob->cur);
531 return JB_ERR_COMPRESS;
534 #ifdef FEATURE_BROTLI
535 if (csp->content_type & CT_BROTLI)
537 return decompress_iob_with_brotli(csp);
541 if (csp->content_type & CT_GZIP)
544 * Our task is slightly complicated by the facts that data
545 * compressed by gzip does not include a zlib header, and
546 * that there is no easily accessible interface in zlib to
547 * handle a gzip header. We strip off the gzip header by
548 * hand, and later inform zlib not to expect a header.
552 * Strip off the gzip header. Please see RFC 1952 for more
553 * explanation of the appropriate fields.
555 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
556 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
557 || (*cur++ != Z_DEFLATED))
559 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
560 return JB_ERR_COMPRESS;
565 if (flags & GZIP_FLAG_RESERVED_BITS)
567 /* The gzip header has reserved bits set; bail out. */
568 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
569 return JB_ERR_COMPRESS;
573 * Skip mtime (4 bytes), extra flags (1 byte)
574 * and OS type (1 byte).
578 /* Skip extra fields if necessary. */
579 if (flags & GZIP_FLAG_EXTRA_FIELDS)
582 * Skip a given number of bytes, specified
583 * as a 16-bit little-endian value.
585 * XXX: this code is untested and should probably be removed.
589 skip_bytes += *cur++ << 8;
592 * The number of bytes to skip should be positive
593 * and we'd like to stay in the buffer.
595 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
597 log_error(LOG_LEVEL_ERROR,
598 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
600 return JB_ERR_COMPRESS;
602 log_error(LOG_LEVEL_INFO,
603 "Skipping %d bytes for gzip compression. Does this sound right?",
608 /* Skip the filename if necessary. */
609 if (flags & GZIP_FLAG_FILE_NAME)
611 /* A null-terminated string is supposed to follow. */
612 while (*cur++ && (cur < csp->iob->eod));
615 /* Skip the comment if necessary. */
616 if (flags & GZIP_FLAG_COMMENT)
618 /* A null-terminated string is supposed to follow. */
619 while (*cur++ && (cur < csp->iob->eod));
622 /* Skip the CRC if necessary. */
623 if (flags & GZIP_FLAG_CHECKSUM)
628 if (cur >= csp->iob->eod)
631 * If the current position pointer reached or passed
632 * the buffer end, we were obviously tricked to skip
635 log_error(LOG_LEVEL_ERROR,
636 "Malformed gzip header detected. Aborting decompression.");
637 return JB_ERR_COMPRESS;
641 else if (csp->content_type & CT_DEFLATE)
644 * In theory (that is, according to RFC 1950), deflate-compressed
645 * data should begin with a two-byte zlib header and have an
646 * adler32 checksum at the end. It seems that in practice only
647 * the raw compressed data is sent. Note that this means that
648 * we are not RFC 1950-compliant here, but the advantage is that
649 * this actually works. :)
651 * We add a dummy null byte to tell zlib where the data ends,
652 * and later inform it not to expect a header.
654 * Fortunately, add_to_iob() has thoughtfully null-terminated
655 * the buffer; we can just increment the end pointer to include
662 log_error(LOG_LEVEL_ERROR,
663 "Unable to determine compression format for decompression");
664 return JB_ERR_COMPRESS;
667 /* Set up the fields required by zlib. */
668 zstr.next_in = (Bytef *)cur;
669 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
670 zstr.zalloc = Z_NULL;
672 zstr.opaque = Z_NULL;
675 * Passing -MAX_WBITS to inflateInit2 tells the library
676 * that there is no zlib header.
678 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
680 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
681 return JB_ERR_COMPRESS;
685 * Next, we allocate new storage for the inflated data.
686 * We don't modify the existing iob yet, so in case there
687 * is error in decompression we can recover gracefully.
689 buf = zalloc(bufsize);
692 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
693 return JB_ERR_MEMORY;
696 assert(bufsize >= skip_size);
697 memcpy(buf, csp->iob->buf, skip_size);
698 zstr.avail_out = (uInt)(bufsize - skip_size);
699 zstr.next_out = (Bytef *)buf + skip_size;
701 /* Try to decompress the whole stream in one shot. */
702 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
704 /* We need to allocate more memory for the output buffer. */
706 char *tmpbuf; /* used for realloc'ing the buffer */
707 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
709 if (0 == zstr.avail_in)
712 * If zlib wants more data then there's a problem, because
713 * the complete compressed file should have been buffered.
715 log_error(LOG_LEVEL_ERROR,
716 "Unexpected end of compressed iob. Using what we got so far.");
721 * If we reached the buffer limit and still didn't have enough
722 * memory, just give up. Due to the ceiling enforced by the next
723 * if block we could actually check for equality here, but as it
724 * can be easily mistaken for a bug we don't.
726 if (bufsize >= csp->config->buffer_limit)
728 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
731 return JB_ERR_MEMORY;
734 /* Try doubling the buffer size each time. */
737 /* Don't exceed the buffer limit. */
738 if (bufsize > csp->config->buffer_limit)
740 bufsize = csp->config->buffer_limit;
743 /* Try to allocate the new buffer. */
744 tmpbuf = realloc(buf, bufsize);
747 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
750 return JB_ERR_MEMORY;
754 char *oldnext_out = (char *)zstr.next_out;
757 * Update the fields for inflate() to use the new
758 * buffer, which may be in a location different from
761 zstr.avail_out += (uInt)(bufsize - oldbufsize);
762 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
765 * Compare with an uglier method of calculating these values
766 * that doesn't require the extra oldbufsize variable.
768 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
769 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
775 if (Z_STREAM_ERROR == inflateEnd(&zstr))
777 log_error(LOG_LEVEL_ERROR,
778 "Inconsistent stream state after decompression: %s", zstr.msg);
780 * XXX: Intentionally no return.
782 * According to zlib.h, Z_STREAM_ERROR is returned
783 * "if the stream state was inconsistent".
785 * I assume in this case inflate()'s status
786 * would also be something different than Z_STREAM_END
787 * so this check should be redundant, but lets see.
791 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
794 * We failed to decompress the stream and it's
795 * not simply because of missing data.
797 log_error(LOG_LEVEL_ERROR,
798 "Unexpected error while decompressing to the buffer (iob): %s",
800 return JB_ERR_COMPRESS;
804 * Finally, we can actually update the iob, since the
805 * decompression was successful. First, free the old
808 freez(csp->iob->buf);
810 /* Now, update the iob to use the new buffer. */
812 csp->iob->cur = csp->iob->buf + skip_size;
813 csp->iob->eod = (char *)zstr.next_out;
814 csp->iob->size = bufsize;
817 * Make sure the new uncompressed iob obeys some minimal
818 * consistency conditions.
820 if ((csp->iob->buf <= csp->iob->cur)
821 && (csp->iob->cur <= csp->iob->eod)
822 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
824 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
825 if (new_size > (size_t)0)
827 log_error(LOG_LEVEL_RE_FILTER,
828 "Decompression successful. Old size: %d, new size: %d.",
833 /* zlib thinks this is OK, so let's do the same. */
834 log_error(LOG_LEVEL_RE_FILTER,
835 "Decompression didn't result in any content.");
840 /* It seems that zlib did something weird. */
841 log_error(LOG_LEVEL_ERROR,
842 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
843 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
844 csp->iob->eod, csp->iob->buf + csp->iob->size);
845 return JB_ERR_COMPRESS;
851 #endif /* defined(FEATURE_ZLIB) */
854 /*********************************************************************
856 * Function : normalize_lws
858 * Description : Reduces unquoted linear whitespace in headers to
859 * a single space in accordance with RFC 7230 3.2.4.
860 * This simplifies parsing and filtering later on.
863 * 1 : header = A header with linear whitespace to reduce.
867 *********************************************************************/
868 static void normalize_lws(char *header)
874 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
878 while (privoxy_isspace(*q))
882 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
888 log_error(LOG_LEVEL_HEADER,
889 "Converting tab to space in '%s'", header);
894 char *end_of_token = strstr(p+1, "\"");
896 if (NULL != end_of_token)
898 /* Don't mess with quoted text. */
903 log_error(LOG_LEVEL_HEADER,
904 "Ignoring single quote in '%s'", header);
910 p = strchr(header, ':');
911 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
914 * There's still space before the colon.
922 /*********************************************************************
924 * Function : get_header
926 * Description : This (odd) routine will parse the csp->iob
927 * to get the next complete header.
930 * 1 : iob = The I/O buffer to parse, usually csp->iob.
932 * Returns : Any one of the following:
934 * 1) a pointer to a dynamically allocated string that contains a header line
935 * 2) NULL indicating that the end of the header was reached
936 * 3) "" indicating that the end of the iob was reached before finding
937 * a complete header line.
939 *********************************************************************/
940 char *get_header(struct iob *iob)
944 header = get_header_line(iob);
946 if ((header == NULL) || (*header == '\0'))
949 * No complete header read yet, tell the client.
954 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
957 * Header spans multiple lines, append the next one.
959 char *continued_header;
961 continued_header = get_header_line(iob);
962 if ((continued_header == NULL) || (*continued_header == '\0'))
965 * No complete header read yet, return what we got.
966 * XXX: Should "unread" header instead.
968 log_error(LOG_LEVEL_INFO,
969 "Failed to read a multi-line header properly: '%s'",
974 if (JB_ERR_OK != string_join(&header, continued_header))
976 log_error(LOG_LEVEL_FATAL,
977 "Out of memory while appending multiple headers.");
981 /* XXX: remove before next stable release. */
982 log_error(LOG_LEVEL_HEADER,
983 "Merged multiple header lines to: '%s'",
988 normalize_lws(header);
995 /*********************************************************************
997 * Function : get_header_line
999 * Description : This (odd) routine will parse the csp->iob
1000 * to get the next header line.
1003 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1005 * Returns : Any one of the following:
1007 * 1) a pointer to a dynamically allocated string that contains a header line
1008 * 2) NULL indicating that the end of the header was reached
1009 * 3) "" indicating that the end of the iob was reached before finding
1010 * a complete header line.
1012 *********************************************************************/
1013 static char *get_header_line(struct iob *iob)
1017 if ((iob->cur == NULL)
1018 || ((p = strchr(iob->cur, '\n')) == NULL))
1020 return(""); /* couldn't find a complete header */
1025 ret = strdup(iob->cur);
1028 /* FIXME No way to handle error properly */
1029 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1031 assert(ret != NULL);
1035 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1037 /* is this a blank line (i.e. the end of the header) ? */
1049 /*********************************************************************
1051 * Function : get_header_value
1053 * Description : Get the value of a given header from a chained list
1054 * of header lines or return NULL if no such header is
1055 * present in the list.
1058 * 1 : header_list = pointer to list
1059 * 2 : header_name = string with name of header to look for.
1060 * Trailing colon required, capitalization
1063 * Returns : NULL if not found, else value of header
1065 *********************************************************************/
1066 char *get_header_value(const struct list *header_list, const char *header_name)
1068 struct list_entry *cur_entry;
1072 assert(header_list);
1073 assert(header_name);
1074 length = strlen(header_name);
1076 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1080 if (!strncmpic(cur_entry->str, header_name, length))
1083 * Found: return pointer to start of value
1085 ret = cur_entry->str + length;
1086 while (*ret && privoxy_isspace(*ret)) ret++;
1100 /*********************************************************************
1102 * Function : scan_headers
1104 * Description : Scans headers, applies tags and updates action bits.
1107 * 1 : csp = Current client state (buffers, headers, etc...)
1109 * Returns : JB_ERR_OK
1111 *********************************************************************/
1112 static jb_err scan_headers(struct client_state *csp)
1114 struct list_entry *h; /* Header */
1115 jb_err err = JB_ERR_OK;
1117 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1119 /* Header crunch()ed in previous run? -> ignore */
1120 if (h->str == NULL) continue;
1121 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1122 err = header_tagger(csp, h->str);
1129 /*********************************************************************
1131 * Function : enforce_header_order
1133 * Description : Enforces a given header order.
1136 * 1 : headers = List of headers to order.
1137 * 2 : ordered_headers = List of ordered header names.
1141 *********************************************************************/
1142 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1144 struct list_entry *sorted_header;
1145 struct list new_headers[1];
1146 struct list_entry *header;
1148 init_list(new_headers);
1150 /* The request line is always the first "header" */
1152 assert(NULL != headers->first->str);
1153 enlist(new_headers, headers->first->str);
1154 freez(headers->first->str)
1156 /* Enlist the specified headers in the given order */
1158 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1159 sorted_header = sorted_header->next)
1161 const size_t sorted_header_length = strlen(sorted_header->str);
1162 for (header = headers->first; header != NULL; header = header->next)
1164 /* Header enlisted in previous run? -> ignore */
1165 if (header->str == NULL) continue;
1167 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1168 && (header->str[sorted_header_length] == ':'))
1170 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1171 if (JB_ERR_OK != enlist(new_headers, header->str))
1173 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1180 /* Enlist the rest of the headers behind the ordered ones */
1181 for (header = headers->first; header != NULL; header = header->next)
1183 /* Header enlisted in previous run? -> ignore */
1184 if (header->str == NULL) continue;
1186 log_error(LOG_LEVEL_HEADER,
1187 "Enlisting left-over header %s", header->str);
1188 if (JB_ERR_OK != enlist(new_headers, header->str))
1190 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1195 list_remove_all(headers);
1196 list_duplicate(headers, new_headers);
1197 list_remove_all(new_headers);
1203 /*********************************************************************
1207 * Description : add, delete or modify lines in the HTTP header streams.
1208 * On entry, it receives a linked list of headers space
1209 * that was allocated dynamically (both the list nodes
1210 * and the header contents).
1212 * As a side effect it frees the space used by the original
1216 * 1 : csp = Current client state (buffers, headers, etc...)
1217 * 2 : filter_server_headers = Boolean to switch between
1218 * server and header filtering.
1220 * Returns : JB_ERR_OK in case off success, or
1221 * JB_ERR_MEMORY on some out-of-memory errors, or
1222 * JB_ERR_PARSE in case of fatal parse errors.
1224 *********************************************************************/
1225 jb_err sed(struct client_state *csp, int filter_server_headers)
1227 /* XXX: use more descriptive names. */
1228 struct list_entry *p;
1229 const struct parsers *v;
1230 const add_header_func_ptr *f;
1231 jb_err err = JB_ERR_OK;
1235 if (filter_server_headers)
1237 v = server_patterns;
1238 f = add_server_headers;
1239 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1243 v = client_patterns;
1244 f = add_client_headers;
1245 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1248 while (v->str != NULL)
1250 for (p = csp->headers->first; p != NULL; p = p->next)
1252 /* Header crunch()ed in previous run? -> ignore */
1253 if (p->str == NULL) continue;
1255 /* Does the current parser handle this header? */
1256 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1257 (v->len == CHECK_EVERY_HEADER_REMAINING))
1259 err = v->parser(csp, &(p->str));
1260 if (err != JB_ERR_OK)
1269 /* place additional headers on the csp->headers list */
1270 while ((err == JB_ERR_OK) && (*f))
1276 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1278 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1285 #ifdef FEATURE_HTTPS_INSPECTION
1286 /*********************************************************************
1288 * Function : sed_https
1290 * Description : add, delete or modify lines in the HTTPS client
1291 * header streams. Wrapper around sed().
1294 * 1 : csp = Current client state (buffers, headers, etc...)
1296 * Returns : JB_ERR_OK in case off success, or
1297 * JB_ERR_MEMORY on some out-of-memory errors, or
1298 * JB_ERR_PARSE in case of fatal parse errors.
1300 *********************************************************************/
1301 jb_err sed_https(struct client_state *csp)
1304 struct list headers;
1307 * Temporarily replace csp->headers with csp->https_headers
1308 * to trick sed() into filtering the https headers.
1310 headers.first = csp->headers->first;
1311 headers.last = csp->headers->last;
1312 csp->headers->first = csp->https_headers->first;
1313 csp->headers->last = csp->https_headers->last;
1316 * Start with fresh tags. Already existing tags may
1317 * be set again. This is necessary to overrule
1318 * URL-based patterns.
1320 destroy_list(csp->tags);
1323 * We want client header filters and taggers
1324 * so temporarily remove the flag.
1326 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1327 err = sed(csp, FILTER_CLIENT_HEADERS);
1328 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1331 * Update the last header which may have changed
1332 * due to header additions,
1334 csp->https_headers->last = csp->headers->last;
1336 csp->headers->first = headers.first;
1337 csp->headers->last = headers.last;
1341 #endif /* def FEATURE_HTTPS_INSPECTION */
1344 /*********************************************************************
1346 * Function : update_server_headers
1348 * Description : Updates server headers after the body has been modified.
1351 * 1 : csp = Current client state (buffers, headers, etc...)
1353 * Returns : JB_ERR_OK in case off success, or
1354 * JB_ERR_MEMORY on out-of-memory error.
1356 *********************************************************************/
1357 jb_err update_server_headers(struct client_state *csp)
1359 jb_err err = JB_ERR_OK;
1361 static const struct parsers server_patterns_light[] = {
1362 { "Content-Length:", 15, server_adjust_content_length },
1363 { "Transfer-Encoding:", 18, server_transfer_coding },
1365 { "Content-Encoding:", 17, server_adjust_content_encoding },
1366 #endif /* def FEATURE_ZLIB */
1370 if (strncmpic(csp->http->cmd, "HEAD", 4))
1372 const struct parsers *v;
1373 struct list_entry *p;
1375 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1377 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1379 /* Header crunch()ed in previous run? -> ignore */
1380 if (p->str == NULL) continue;
1382 /* Does the current parser handle this header? */
1383 if (strncmpic(p->str, v->str, v->len) == 0)
1385 err = v->parser(csp, (char **)&(p->str));
1391 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1392 if ((JB_ERR_OK == err)
1393 && (csp->flags & CSP_FLAG_MODIFIED)
1394 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1395 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1399 create_content_length_header(csp->content_length, header, sizeof(header));
1400 err = enlist(csp->headers, header);
1401 if (JB_ERR_OK == err)
1403 log_error(LOG_LEVEL_HEADER,
1404 "Content modified with no Content-Length header set. "
1405 "Created: %s.", header);
1406 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1409 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1411 #ifdef FEATURE_COMPRESSION
1412 if ((JB_ERR_OK == err)
1413 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1415 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1416 if (JB_ERR_OK == err)
1418 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1427 /*********************************************************************
1429 * Function : header_tagger
1431 * Description : Executes all text substitutions from applying
1432 * tag actions and saves the result as tag.
1434 * XXX: Shares enough code with filter_header() and
1435 * pcrs_filter_response() to warrant some helper functions.
1438 * 1 : csp = Current client state (buffers, headers, etc...)
1439 * 2 : header = Header that is used as tagger input
1441 * Returns : JB_ERR_OK on success and always succeeds
1443 *********************************************************************/
1444 static jb_err header_tagger(struct client_state *csp, char *header)
1446 enum filter_type wanted_filter_type;
1447 int multi_action_index;
1450 struct re_filterfile_spec *b;
1451 struct list_entry *tag_name;
1453 const size_t header_length = strlen(header);
1455 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1457 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1458 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1462 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1463 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1466 if (list_is_empty(csp->action->multi[multi_action_index])
1467 || filters_available(csp) == FALSE)
1469 /* Return early if no taggers apply or if none are available. */
1473 /* Execute all applying taggers */
1474 for (tag_name = csp->action->multi[multi_action_index]->first;
1475 NULL != tag_name; tag_name = tag_name->next)
1477 char *modified_tag = NULL;
1479 size_t size = header_length;
1482 b = get_filter(csp, tag_name->str, wanted_filter_type);
1488 joblist = b->joblist;
1490 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1492 if (NULL == joblist)
1494 log_error(LOG_LEVEL_RE_FILTER,
1495 "Tagger %s has empty joblist. Nothing to do.", b->name);
1499 /* execute their pcrs_joblist on the header. */
1500 for (job = joblist; NULL != job; job = job->next)
1502 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1506 /* Success, continue with the modified version. */
1515 /* Tagger doesn't match */
1518 /* Regex failure, log it but continue anyway. */
1519 assert(NULL != header);
1520 log_error(LOG_LEVEL_ERROR,
1521 "Problems with tagger \'%s\' and header \'%s\': %s",
1522 b->name, *header, pcrs_strerror(hits));
1524 freez(modified_tag);
1528 if (b->dynamic) pcrs_free_joblist(joblist);
1530 /* If this tagger matched */
1536 * There is no technical limitation which makes
1537 * it impossible to use empty tags, but I assume
1538 * no one would do it intentionally.
1541 log_error(LOG_LEVEL_INFO,
1542 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1546 if (!list_contains_item(csp->tags, tag))
1548 if (JB_ERR_OK != enlist(csp->tags, tag))
1550 log_error(LOG_LEVEL_ERROR,
1551 "Insufficient memory to add tag \'%s\', "
1552 "based on tagger \'%s\' and header \'%s\'",
1553 tag, b->name, *header);
1557 char *action_message;
1559 * update the action bits right away, to make
1560 * tagging based on tags set by earlier taggers
1561 * of the same kind possible.
1563 if (update_action_bits_for_tag(csp, tag))
1565 action_message = "Action bits updated accordingly.";
1569 action_message = "No action bits update necessary.";
1572 log_error(LOG_LEVEL_HEADER,
1573 "Tagger \'%s\' added tag \'%s\'. %s",
1574 b->name, tag, action_message);
1579 /* XXX: Is this log-worthy? */
1580 log_error(LOG_LEVEL_HEADER,
1581 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1591 /* here begins the family of parser functions that reformat header lines */
1593 /*********************************************************************
1595 * Function : filter_header
1597 * Description : Executes all text substitutions from all applying
1598 * +(server|client)-header-filter actions on the header.
1599 * Most of the code was copied from pcrs_filter_response,
1600 * including the rather short variable names
1603 * 1 : csp = Current client state (buffers, headers, etc...)
1604 * 2 : header = On input, pointer to header to modify.
1605 * On output, pointer to the modified header, or NULL
1606 * to remove the header. This function frees the
1607 * original string if necessary.
1609 * Returns : JB_ERR_OK on success and always succeeds
1611 *********************************************************************/
1612 static jb_err filter_header(struct client_state *csp, char **header)
1616 size_t size = strlen(*header);
1618 char *newheader = NULL;
1621 struct re_filterfile_spec *b;
1622 struct list_entry *filtername;
1624 enum filter_type wanted_filter_type;
1625 int multi_action_index;
1627 if (csp->flags & CSP_FLAG_NO_FILTERING)
1632 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1634 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1635 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1639 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1640 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1643 if (list_is_empty(csp->action->multi[multi_action_index])
1644 || filters_available(csp) == FALSE)
1646 /* Return early if no filters apply or if none are available. */
1650 /* Execute all applying header filters */
1651 for (filtername = csp->action->multi[multi_action_index]->first;
1652 filtername != NULL; filtername = filtername->next)
1654 int current_hits = 0;
1657 b = get_filter(csp, filtername->str, wanted_filter_type);
1663 joblist = b->joblist;
1665 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1667 if (NULL == joblist)
1669 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1673 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1674 *header, size, b->name);
1676 /* Apply all jobs from the joblist */
1677 for (job = joblist; NULL != job; job = job->next)
1679 matches = pcrs_execute(job, *header, size, &newheader, &size);
1682 current_hits += matches;
1683 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1685 *header = newheader;
1687 else if (0 == matches)
1689 /* Filter doesn't change header */
1695 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1696 *header, b->name, pcrs_strerror(matches));
1697 if (newheader != NULL)
1699 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1705 if (b->dynamic) pcrs_free_joblist(joblist);
1707 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1708 hits += current_hits;
1712 * Additionally checking for hits is important because if
1713 * the continue hack is triggered, server headers can
1714 * arrive empty to separate multiple heads from each other.
1716 if ((0 == size) && hits)
1718 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1726 /*********************************************************************
1728 * Function : server_connection
1730 * Description : Makes sure a proper "Connection:" header is
1731 * set and signals connection_header_adder to
1735 * 1 : csp = Current client state (buffers, headers, etc...)
1736 * 2 : header = On input, pointer to header to modify.
1737 * On output, pointer to the modified header, or NULL
1738 * to remove the header. This function frees the
1739 * original string if necessary.
1741 * Returns : JB_ERR_OK on success.
1743 *********************************************************************/
1744 static jb_err server_connection(struct client_state *csp, char **header)
1746 if (!strcmpic(*header, "Connection: keep-alive")
1747 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1748 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1752 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1753 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1755 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1758 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1760 log_error(LOG_LEVEL_HEADER,
1761 "Keeping the server header '%s' around.", *header);
1764 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1766 char *old_header = *header;
1768 *header = strdup_or_die("Connection: close");
1769 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1774 /* Signal server_connection_adder() to return early. */
1775 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1781 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1782 /*********************************************************************
1784 * Function : server_keep_alive
1786 * Description : Stores the server's keep alive timeout.
1789 * 1 : csp = Current client state (buffers, headers, etc...)
1790 * 2 : header = On input, pointer to header to modify.
1791 * On output, pointer to the modified header, or NULL
1792 * to remove the header. This function frees the
1793 * original string if necessary.
1795 * Returns : JB_ERR_OK.
1797 *********************************************************************/
1798 static jb_err server_keep_alive(struct client_state *csp, char **header)
1800 unsigned int keep_alive_timeout;
1801 const char *timeout_position = strstr(*header, "timeout=");
1803 if ((NULL == timeout_position)
1804 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1806 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1810 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1812 log_error(LOG_LEVEL_HEADER,
1813 "Reducing keep-alive timeout from %u to %u.",
1814 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1815 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1819 /* XXX: Is this log worthy? */
1820 log_error(LOG_LEVEL_HEADER,
1821 "Server keep-alive timeout is %u. Sticking with %u.",
1822 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1824 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1833 /*********************************************************************
1835 * Function : server_proxy_connection
1837 * Description : Figures out whether or not we should add a
1838 * Proxy-Connection header.
1841 * 1 : csp = Current client state (buffers, headers, etc...)
1842 * 2 : header = On input, pointer to header to modify.
1843 * On output, pointer to the modified header, or NULL
1844 * to remove the header. This function frees the
1845 * original string if necessary.
1847 * Returns : JB_ERR_OK.
1849 *********************************************************************/
1850 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1852 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1855 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1858 /*********************************************************************
1860 * Function : proxy_authentication
1862 * Description : Removes headers that are relevant for proxy
1863 * authentication unless forwarding them has
1864 * been explicitly requested.
1867 * 1 : csp = Current client state (buffers, headers, etc...)
1868 * 2 : header = On input, pointer to header to modify.
1869 * On output, pointer to the modified header, or NULL
1870 * to remove the header. This function frees the
1871 * original string if necessary.
1873 * Returns : JB_ERR_OK.
1875 *********************************************************************/
1876 static jb_err proxy_authentication(struct client_state *csp, char **header)
1878 if ((csp->config->feature_flags &
1879 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1880 log_error(LOG_LEVEL_HEADER,
1881 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1888 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1889 /*********************************************************************
1891 * Function : client_keep_alive
1893 * Description : Stores the client's keep alive timeout.
1896 * 1 : csp = Current client state (buffers, headers, etc...)
1897 * 2 : header = On input, pointer to header to modify.
1898 * On output, pointer to the modified header, or NULL
1899 * to remove the header. This function frees the
1900 * original string if necessary.
1902 * Returns : JB_ERR_OK.
1904 *********************************************************************/
1905 static jb_err client_keep_alive(struct client_state *csp, char **header)
1907 unsigned int keep_alive_timeout;
1908 char *timeout_position;
1910 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1912 log_error(LOG_LEVEL_HEADER,
1913 "keep-alive support is disabled. Crunching: %s.", *header);
1918 /* Check for parameter-less format "Keep-Alive: 100" */
1919 timeout_position = strstr(*header, ": ");
1920 if ((NULL == timeout_position)
1921 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1923 /* Assume parameter format "Keep-Alive: timeout=100" */
1924 timeout_position = strstr(*header, "timeout=");
1925 if ((NULL == timeout_position)
1926 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1928 log_error(LOG_LEVEL_HEADER,
1929 "Couldn't parse: '%s'. Using default timeout %u",
1930 *header, csp->config->keep_alive_timeout);
1937 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1939 log_error(LOG_LEVEL_HEADER,
1940 "Reducing keep-alive timeout from %u to %u.",
1941 csp->config->keep_alive_timeout, keep_alive_timeout);
1942 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1946 /* XXX: Is this log worthy? */
1947 log_error(LOG_LEVEL_HEADER,
1948 "Client keep-alive timeout is %u. Sticking with %u.",
1949 keep_alive_timeout, csp->config->keep_alive_timeout);
1955 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1958 /*********************************************************************
1960 * Function : get_content_length
1962 * Description : Gets the content length specified in a
1963 * Content-Length header.
1966 * 1 : header_value = The Content-Length header value.
1967 * 2 : length = Storage to return the value.
1969 * Returns : JB_ERR_OK on success, or
1970 * JB_ERR_PARSE if no value is recognized.
1972 *********************************************************************/
1973 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1976 #if SIZEOF_LONG_LONG < 8
1977 #error sizeof(unsigned long long) too small
1979 if (1 != sscanf(header_value, "%I64u", length))
1981 if (1 != sscanf(header_value, "%llu", length))
1984 return JB_ERR_PARSE;
1991 /*********************************************************************
1993 * Function : client_save_content_length
1995 * Description : Save the Content-Length sent by the client.
1998 * 1 : csp = Current client state (buffers, headers, etc...)
1999 * 2 : header = On input, pointer to header to modify.
2000 * On output, pointer to the modified header, or NULL
2001 * to remove the header. This function frees the
2002 * original string if necessary.
2004 * Returns : JB_ERR_OK on success, or
2005 * JB_ERR_MEMORY on out-of-memory error.
2007 *********************************************************************/
2008 static jb_err client_save_content_length(struct client_state *csp, char **header)
2010 unsigned long long content_length = 0;
2011 const char *header_value;
2013 assert(*(*header+14) == ':');
2015 header_value = *header + 15;
2016 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2018 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2023 csp->expected_client_content_length = content_length;
2030 /*********************************************************************
2032 * Function : client_connection
2034 * Description : Makes sure a proper "Connection:" header is
2035 * set and signals connection_header_adder
2039 * 1 : csp = Current client state (buffers, headers, etc...)
2040 * 2 : header = On input, pointer to header to modify.
2041 * On output, pointer to the modified header, or NULL
2042 * to remove the header. This function frees the
2043 * original string if necessary.
2045 * Returns : JB_ERR_OK on success.
2047 *********************************************************************/
2048 static jb_err client_connection(struct client_state *csp, char **header)
2050 static const char connection_close[] = "Connection: close";
2052 if (!strcmpic(*header, connection_close))
2054 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2055 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2056 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2057 #ifdef FEATURE_HTTPS_INSPECTION
2058 && !client_use_ssl(csp)
2062 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2064 log_error(LOG_LEVEL_HEADER,
2065 "Removing \'%s\' to imply keep-alive.", *header);
2068 * While we imply keep-alive to the server,
2069 * we have to remember that the client didn't.
2071 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2075 char *old_header = *header;
2077 *header = strdup_or_die("Connection: keep-alive");
2078 log_error(LOG_LEVEL_HEADER,
2079 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2085 log_error(LOG_LEVEL_HEADER,
2086 "Keeping the client header '%s' around. "
2087 "The connection will not be kept alive.",
2089 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2092 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2093 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2095 log_error(LOG_LEVEL_HEADER,
2096 "Keeping the client header '%s' around. "
2097 "The server connection will be kept alive if possible.",
2099 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2100 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2104 char *old_header = *header;
2106 *header = strdup_or_die(connection_close);
2107 log_error(LOG_LEVEL_HEADER,
2108 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2112 /* Signal client_connection_header_adder() to return early. */
2113 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2119 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2120 /*********************************************************************
2122 * Function : client_proxy_connection
2124 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2125 * appropriate and removes the Proxy-Connection
2129 * 1 : csp = Current client state (buffers, headers, etc...)
2130 * 2 : header = On input, pointer to header to modify.
2131 * On output, pointer to the modified header, or NULL
2132 * to remove the header. This function frees the
2133 * original string if necessary.
2135 * Returns : JB_ERR_OK
2137 *********************************************************************/
2138 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2140 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2141 && (csp->http->ssl == 0)
2142 && (NULL == strstr(*header, "close")))
2144 log_error(LOG_LEVEL_HEADER,
2145 "The client connection can be kept alive due to: %s", *header);
2146 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2148 crumble(csp, header);
2152 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2155 /*********************************************************************
2157 * Function : client_transfer_encoding
2159 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2160 * the request body is "chunked"
2162 * XXX: Currently not called through sed() as we
2163 * need the flag earlier on. Should be fixed.
2166 * 1 : csp = Current client state (buffers, headers, etc...)
2167 * 2 : header = On input, pointer to header to modify.
2168 * On output, pointer to the modified header, or NULL
2169 * to remove the header. This function frees the
2170 * original string if necessary.
2172 * Returns : JB_ERR_OK on success, or
2174 *********************************************************************/
2175 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2177 if (strstr(*header, "chunked"))
2179 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2180 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2187 /*********************************************************************
2189 * Function : client_expect
2191 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2192 * if the Expect header value is unsupported.
2194 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2195 * MAY and a RFC 2616 (obsolete) MUST.
2198 * 1 : csp = Current client state (buffers, headers, etc...)
2199 * 2 : header = On input, pointer to header to modify.
2200 * On output, pointer to the modified header, or NULL
2201 * to remove the header. This function frees the
2202 * original string if necessary.
2204 * Returns : JB_ERR_OK on success, or
2206 *********************************************************************/
2207 jb_err client_expect(struct client_state *csp, char **header)
2209 if (0 != strcmpic(*header, "Expect: 100-continue"))
2211 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2212 log_error(LOG_LEVEL_HEADER,
2213 "Unsupported client expectaction: %s", *header);
2221 /*********************************************************************
2223 * Function : crumble
2225 * Description : This is called if a header matches a pattern to "crunch"
2228 * 1 : csp = Current client state (buffers, headers, etc...)
2229 * 2 : header = On input, pointer to header to modify.
2230 * On output, pointer to the modified header, or NULL
2231 * to remove the header. This function frees the
2232 * original string if necessary.
2234 * Returns : JB_ERR_OK on success, or
2235 * JB_ERR_MEMORY on out-of-memory error.
2237 *********************************************************************/
2238 static jb_err crumble(struct client_state *csp, char **header)
2241 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2247 /*********************************************************************
2249 * Function : crunch_server_header
2251 * Description : Crunch server header if it matches a string supplied by the
2252 * user. Called from `sed'.
2255 * 1 : csp = Current client state (buffers, headers, etc...)
2256 * 2 : header = On input, pointer to header to modify.
2257 * On output, pointer to the modified header, or NULL
2258 * to remove the header. This function frees the
2259 * original string if necessary.
2261 * Returns : JB_ERR_OK on success and always succeeds
2263 *********************************************************************/
2264 static jb_err crunch_server_header(struct client_state *csp, char **header)
2266 const char *crunch_pattern;
2268 /* Do we feel like crunching? */
2269 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2271 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2273 /* Is the current header the lucky one? */
2274 if (strstr(*header, crunch_pattern))
2276 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2285 /*********************************************************************
2287 * Function : server_content_type
2289 * Description : Set the content-type for filterable types (text/.*,
2290 * .*xml.*, .*script.* and image/gif) unless filtering has been
2291 * forbidden (CT_TABOO) while parsing earlier headers.
2292 * NOTE: Since text/plain is commonly used by web servers
2293 * for files whose correct type is unknown, we don't
2294 * set CT_TEXT for it.
2297 * 1 : csp = Current client state (buffers, headers, etc...)
2298 * 2 : header = On input, pointer to header to modify.
2299 * On output, pointer to the modified header, or NULL
2300 * to remove the header. This function frees the
2301 * original string if necessary.
2303 * Returns : JB_ERR_OK on success, or
2304 * JB_ERR_MEMORY on out-of-memory error.
2306 *********************************************************************/
2307 static jb_err server_content_type(struct client_state *csp, char **header)
2309 /* Remove header if it isn't the first Content-Type header */
2310 if ((csp->content_type & CT_DECLARED))
2312 if (content_filters_enabled(csp->action))
2315 * Making sure the client interprets the content the same way
2316 * Privoxy did is only relevant if Privoxy modified it.
2318 * Checking for this is "hard" as it's not yet known when
2319 * this function is called, thus go shopping and and just
2320 * check if Privoxy could filter it.
2322 * The main thing is that we don't mess with the headers
2323 * unless the user signalled that it's acceptable.
2325 log_error(LOG_LEVEL_HEADER,
2326 "Multiple Content-Type headers detected. "
2327 "Removing and ignoring: %s",
2335 * Signal that the Content-Type has been set.
2337 csp->content_type |= CT_DECLARED;
2339 if (!(csp->content_type & CT_TABOO))
2342 * XXX: The assumption that text/plain is a sign of
2343 * binary data seems to be somewhat unreasonable nowadays
2344 * and should be dropped after 3.0.8 is out.
2346 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2347 || strstr(*header, "xml")
2348 || strstr(*header, "script"))
2350 csp->content_type |= CT_TEXT;
2352 else if (strstr(*header, "image/gif"))
2354 csp->content_type |= CT_GIF;
2359 * Are we messing with the content type?
2361 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2364 * Make sure the user doesn't accidentally
2365 * change the content type of binary documents.
2367 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2371 *header = strdup_or_die("Content-Type: ");
2373 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2374 if (JB_ERR_OK != err)
2376 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2377 return JB_ERR_MEMORY;
2379 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2383 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2384 "It doesn't look like a content type that should be filtered. "
2385 "Enable force-text-mode if you know what you're doing.", *header);
2393 /*********************************************************************
2395 * Function : server_transfer_coding
2397 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2398 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2399 * - Remove header if body was chunked but has been
2400 * de-chunked for filtering.
2403 * 1 : csp = Current client state (buffers, headers, etc...)
2404 * 2 : header = On input, pointer to header to modify.
2405 * On output, pointer to the modified header, or NULL
2406 * to remove the header. This function frees the
2407 * original string if necessary.
2409 * Returns : JB_ERR_OK on success, or
2410 * JB_ERR_MEMORY on out-of-memory error.
2412 *********************************************************************/
2413 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2416 * Turn off pcrs and gif filtering if body compressed
2418 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2422 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2424 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2425 csp->http->cmd, *header);
2426 #endif /* def FEATURE_ZLIB */
2427 csp->content_type = CT_TABOO;
2431 * Raise flag if body chunked
2433 if (strstr(*header, "chunked"))
2435 csp->flags |= CSP_FLAG_CHUNKED;
2438 * If the body was modified, it has been de-chunked first
2439 * and the header must be removed.
2441 * FIXME: If there is more than one transfer encoding,
2442 * only the "chunked" part should be removed here.
2444 if (csp->flags & CSP_FLAG_MODIFIED)
2446 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2455 /*********************************************************************
2457 * Function : server_content_encoding
2459 * Description : Used to check if the content is compressed, and if
2460 * FEATURE_ZLIB is disabled, filtering is disabled as
2463 * If FEATURE_ZLIB is enabled and the compression type
2464 * supported, the content is marked for decompression.
2466 * XXX: Doesn't properly deal with multiple or with
2467 * unsupported but unknown encodings.
2468 * Is case-sensitive but shouldn't be.
2471 * 1 : csp = Current client state (buffers, headers, etc...)
2472 * 2 : header = On input, pointer to header to modify.
2473 * On output, pointer to the modified header, or NULL
2474 * to remove the header. This function frees the
2475 * original string if necessary.
2477 * Returns : JB_ERR_OK on success, or
2478 * JB_ERR_MEMORY on out-of-memory error.
2480 *********************************************************************/
2481 static jb_err server_content_encoding(struct client_state *csp, char **header)
2484 if (strstr(*header, "sdch"))
2487 * Shared Dictionary Compression over HTTP isn't supported,
2488 * filtering it anyway is pretty much guaranteed to mess up
2491 csp->content_type |= CT_TABOO;
2494 * Log a warning if the user expects the content to be filtered.
2496 if (content_filters_enabled(csp->action))
2498 log_error(LOG_LEVEL_INFO,
2499 "SDCH-compressed content detected, content filtering disabled. "
2500 "Consider suppressing SDCH offers made by the client.");
2503 else if (strstr(*header, "gzip"))
2505 /* Mark for gzip decompression */
2506 csp->content_type |= CT_GZIP;
2508 else if (strstr(*header, "deflate"))
2510 /* Mark for zlib decompression */
2511 csp->content_type |= CT_DEFLATE;
2513 else if (strstr(*header, "br"))
2515 #ifdef FEATURE_BROTLI
2516 /* Mark for Brotli decompression */
2517 csp->content_type |= CT_BROTLI;
2519 csp->content_type |= CT_TABOO;
2522 else if (strstr(*header, "compress"))
2525 * We can't decompress this; therefore we can't filter
2528 csp->content_type |= CT_TABOO;
2530 #else /* !defined(FEATURE_ZLIB) */
2532 * XXX: Using a black list here isn't the right approach.
2534 * In case of SDCH, building with zlib support isn't
2537 if (strstr(*header, "gzip") ||
2538 strstr(*header, "compress") ||
2539 strstr(*header, "deflate") ||
2540 strstr(*header, "sdch"))
2543 * Body is compressed, turn off pcrs and gif filtering.
2545 csp->content_type |= CT_TABOO;
2548 * Log a warning if the user expects the content to be filtered.
2550 if (content_filters_enabled(csp->action))
2552 log_error(LOG_LEVEL_INFO,
2553 "Compressed content detected, content filtering disabled. "
2554 "Consider recompiling Privoxy with zlib support or "
2555 "enable the prevent-compression action.");
2558 #endif /* defined(FEATURE_ZLIB) */
2566 /*********************************************************************
2568 * Function : server_adjust_content_encoding
2570 * Description : Remove the Content-Encoding header if the
2571 * decompression was successful and the content
2572 * has been modified.
2575 * 1 : csp = Current client state (buffers, headers, etc...)
2576 * 2 : header = On input, pointer to header to modify.
2577 * On output, pointer to the modified header, or NULL
2578 * to remove the header. This function frees the
2579 * original string if necessary.
2581 * Returns : JB_ERR_OK on success, or
2582 * JB_ERR_MEMORY on out-of-memory error.
2584 *********************************************************************/
2585 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2587 if ((csp->flags & CSP_FLAG_MODIFIED)
2588 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2589 #ifdef FEATURE_BROTLI
2590 || (csp->content_type & CT_BROTLI)
2596 * We successfully decompressed the content,
2597 * and have to clean the header now, so the
2598 * client no longer expects compressed data.
2600 * XXX: There is a difference between cleaning
2601 * and removing it completely.
2603 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2610 #endif /* defined(FEATURE_ZLIB) */
2613 /*********************************************************************
2615 * Function : server_adjust_content_length
2617 * Description : Adjust Content-Length header if we modified
2621 * 1 : csp = Current client state (buffers, headers, etc...)
2622 * 2 : header = On input, pointer to header to modify.
2623 * On output, pointer to the modified header, or NULL
2624 * to remove the header. This function frees the
2625 * original string if necessary.
2627 * Returns : JB_ERR_OK on success, or
2628 * JB_ERR_MEMORY on out-of-memory error.
2630 *********************************************************************/
2631 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2633 /* Regenerate header if the content was modified. */
2634 if (csp->flags & CSP_FLAG_MODIFIED)
2636 const size_t header_length = 50;
2638 *header = malloc(header_length);
2639 if (*header == NULL)
2641 return JB_ERR_MEMORY;
2643 create_content_length_header(csp->content_length, *header, header_length);
2644 log_error(LOG_LEVEL_HEADER,
2645 "Adjusted Content-Length to %llu", csp->content_length);
2652 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2653 /*********************************************************************
2655 * Function : server_save_content_length
2657 * Description : Save the Content-Length sent by the server.
2660 * 1 : csp = Current client state (buffers, headers, etc...)
2661 * 2 : header = On input, pointer to header to modify.
2662 * On output, pointer to the modified header, or NULL
2663 * to remove the header. This function frees the
2664 * original string if necessary.
2666 * Returns : JB_ERR_OK on success, or
2667 * JB_ERR_MEMORY on out-of-memory error.
2669 *********************************************************************/
2670 static jb_err server_save_content_length(struct client_state *csp, char **header)
2672 unsigned long long content_length = 0;
2673 const char *header_value;
2675 assert(*(*header+14) == ':');
2677 header_value = *header + 15;
2678 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2680 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2685 csp->expected_content_length = content_length;
2686 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2687 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2692 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2695 /*********************************************************************
2697 * Function : server_content_md5
2699 * Description : Crumble any Content-MD5 headers if the document was
2700 * modified. FIXME: Should we re-compute instead?
2703 * 1 : csp = Current client state (buffers, headers, etc...)
2704 * 2 : header = On input, pointer to header to modify.
2705 * On output, pointer to the modified header, or NULL
2706 * to remove the header. This function frees the
2707 * original string if necessary.
2709 * Returns : JB_ERR_OK on success, or
2710 * JB_ERR_MEMORY on out-of-memory error.
2712 *********************************************************************/
2713 static jb_err server_content_md5(struct client_state *csp, char **header)
2715 if (csp->flags & CSP_FLAG_MODIFIED)
2717 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2725 /*********************************************************************
2727 * Function : server_content_disposition
2729 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2730 * Called from `sed'.
2733 * 1 : csp = Current client state (buffers, headers, etc...)
2734 * 2 : header = On input, pointer to header to modify.
2735 * On output, pointer to the modified header, or NULL
2736 * to remove the header. This function frees the
2737 * original string if necessary.
2739 * Returns : JB_ERR_OK on success, or
2740 * JB_ERR_MEMORY on out-of-memory error.
2742 *********************************************************************/
2743 static jb_err server_content_disposition(struct client_state *csp, char **header)
2748 * Are we messing with the Content-Disposition header?
2750 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2756 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2758 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2761 * Blocking content-disposition header
2763 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2770 * Replacing Content-Disposition header
2773 *header = strdup("Content-Disposition: ");
2774 string_append(header, newval);
2776 if (*header != NULL)
2778 log_error(LOG_LEVEL_HEADER,
2779 "Content-Disposition header crunched and replaced with: %s", *header);
2782 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2786 /*********************************************************************
2788 * Function : server_last_modified
2790 * Description : Changes Last-Modified header to the actual date
2791 * to help hide-if-modified-since.
2792 * Called from `sed'.
2795 * 1 : csp = Current client state (buffers, headers, etc...)
2796 * 2 : header = On input, pointer to header to modify.
2797 * On output, pointer to the modified header, or NULL
2798 * to remove the header. This function frees the
2799 * original string if necessary.
2801 * Returns : JB_ERR_OK on success, or
2802 * JB_ERR_MEMORY on out-of-memory error.
2804 *********************************************************************/
2805 static jb_err server_last_modified(struct client_state *csp, char **header)
2808 time_t last_modified;
2812 * Are we messing with the Last-Modified header?
2814 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2820 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2822 if (0 == strcmpic(newval, "block"))
2825 * Blocking Last-Modified header. Useless but why not.
2827 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2831 else if (0 == strcmpic(newval, "reset-to-request-time"))
2834 * Setting Last-Modified Header to now.
2837 get_http_time(0, buf, sizeof(buf));
2839 *header = strdup("Last-Modified: ");
2840 string_append(header, buf);
2842 if (*header == NULL)
2844 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2848 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2851 else if (0 == strcmpic(newval, "randomize"))
2853 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2855 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2857 log_error(LOG_LEVEL_HEADER,
2858 "Couldn't parse time in %s (crunching!)", *header);
2864 struct tm *timeptr = NULL;
2869 rtime = (long int)difftime(now, last_modified);
2872 long int days, hours, minutes, seconds;
2873 const int negative_delta = (rtime < 0);
2878 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2880 rtime = pick_from_range(rtime);
2885 last_modified += rtime;
2886 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2887 if ((NULL == timeptr) || !strftime(newheader,
2888 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2890 log_error(LOG_LEVEL_ERROR,
2891 "Randomizing '%s' failed. Crunching the header without replacement.",
2897 *header = strdup("Last-Modified: ");
2898 string_append(header, newheader);
2900 if (*header == NULL)
2902 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2903 return JB_ERR_MEMORY;
2906 days = rtime / (3600 * 24);
2907 hours = rtime / 3600 % 24;
2908 minutes = rtime / 60 % 60;
2909 seconds = rtime % 60;
2911 log_error(LOG_LEVEL_HEADER,
2912 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2913 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2914 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2918 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2927 /*********************************************************************
2929 * Function : client_accept_encoding
2931 * Description : Rewrite the client's Accept-Encoding header so that
2932 * if doesn't allow compression, if the action applies.
2933 * Note: For HTTP/1.0 the absence of the header is enough.
2936 * 1 : csp = Current client state (buffers, headers, etc...)
2937 * 2 : header = On input, pointer to header to modify.
2938 * On output, pointer to the modified header, or NULL
2939 * to remove the header. This function frees the
2940 * original string if necessary.
2942 * Returns : JB_ERR_OK on success, or
2943 * JB_ERR_MEMORY on out-of-memory error.
2945 *********************************************************************/
2946 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2948 #ifdef FEATURE_COMPRESSION
2949 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2950 && strstr(*header, "deflate"))
2952 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2955 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2957 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2965 /*********************************************************************
2967 * Function : client_te
2969 * Description : Rewrite the client's TE header so that
2970 * if doesn't allow compression, if the action applies.
2973 * 1 : csp = Current client state (buffers, headers, etc...)
2974 * 2 : header = On input, pointer to header to modify.
2975 * On output, pointer to the modified header, or NULL
2976 * to remove the header. This function frees the
2977 * original string if necessary.
2979 * Returns : JB_ERR_OK on success, or
2980 * JB_ERR_MEMORY on out-of-memory error.
2982 *********************************************************************/
2983 static jb_err client_te(struct client_state *csp, char **header)
2985 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2988 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2995 /*********************************************************************
2997 * Function : client_referrer
2999 * Description : Handle the "referer" config setting properly.
3000 * Called from `sed'.
3003 * 1 : csp = Current client state (buffers, headers, etc...)
3004 * 2 : header = On input, pointer to header to modify.
3005 * On output, pointer to the modified header, or NULL
3006 * to remove the header. This function frees the
3007 * original string if necessary.
3009 * Returns : JB_ERR_OK on success, or
3010 * JB_ERR_MEMORY on out-of-memory error.
3012 *********************************************************************/
3013 static jb_err client_referrer(struct client_state *csp, char **header)
3015 const char *parameter;
3016 /* booleans for parameters we have to check multiple times */
3017 int parameter_conditional_block;
3018 int parameter_conditional_forge;
3020 #ifdef FEATURE_FORCE_LOAD
3022 * Since the referrer can include the prefix even
3023 * if the request itself is non-forced, we must
3024 * clean it unconditionally.
3026 * XXX: strclean is too broad
3028 strclean(*header, FORCE_PREFIX);
3029 #endif /* def FEATURE_FORCE_LOAD */
3031 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3033 /* Nothing left to do */
3037 parameter = csp->action->string[ACTION_STRING_REFERER];
3038 assert(parameter != NULL);
3039 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3040 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3042 if (!parameter_conditional_block && !parameter_conditional_forge)
3045 * As conditional-block and conditional-forge are the only
3046 * parameters that rely on the original referrer, we can
3047 * remove it now for all the others.
3052 if (0 == strcmpic(parameter, "block"))
3054 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3057 else if (parameter_conditional_block || parameter_conditional_forge)
3059 return handle_conditional_hide_referrer_parameter(header,
3060 csp->http->hostport, parameter_conditional_block);
3062 else if (0 == strcmpic(parameter, "forge"))
3064 return create_forged_referrer(header, csp->http->hostport);
3068 /* interpret parameter as user-supplied referer to fake */
3069 return create_fake_referrer(header, parameter);
3074 /*********************************************************************
3076 * Function : client_accept_language
3078 * Description : Handle the "Accept-Language" config setting properly.
3079 * Called from `sed'.
3082 * 1 : csp = Current client state (buffers, headers, etc...)
3083 * 2 : header = On input, pointer to header to modify.
3084 * On output, pointer to the modified header, or NULL
3085 * to remove the header. This function frees the
3086 * original string if necessary.
3088 * Returns : JB_ERR_OK on success, or
3089 * JB_ERR_MEMORY on out-of-memory error.
3091 *********************************************************************/
3092 static jb_err client_accept_language(struct client_state *csp, char **header)
3097 * Are we messing with the Accept-Language?
3099 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3101 /*I don't think so*/
3105 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3107 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3110 * Blocking Accept-Language header
3112 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3119 * Replacing Accept-Language header
3122 *header = strdup("Accept-Language: ");
3123 string_append(header, newval);
3125 if (*header == NULL)
3127 log_error(LOG_LEVEL_ERROR,
3128 "Insufficient memory. Accept-Language header crunched without replacement.");
3132 log_error(LOG_LEVEL_HEADER,
3133 "Accept-Language header crunched and replaced with: %s", *header);
3136 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3140 /*********************************************************************
3142 * Function : crunch_client_header
3144 * Description : Crunch client header if it matches a string supplied by the
3145 * user. Called from `sed'.
3148 * 1 : csp = Current client state (buffers, headers, etc...)
3149 * 2 : header = On input, pointer to header to modify.
3150 * On output, pointer to the modified header, or NULL
3151 * to remove the header. This function frees the
3152 * original string if necessary.
3154 * Returns : JB_ERR_OK on success and always succeeds
3156 *********************************************************************/
3157 static jb_err crunch_client_header(struct client_state *csp, char **header)
3159 const char *crunch_pattern;
3161 /* Do we feel like crunching? */
3162 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3164 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3166 /* Is the current header the lucky one? */
3167 if (strstr(*header, crunch_pattern))
3169 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3177 /*********************************************************************
3179 * Function : client_uagent
3181 * Description : Handle the "user-agent" config setting properly
3182 * and remember its original value to enable browser
3183 * bug workarounds. Called from `sed'.
3186 * 1 : csp = Current client state (buffers, headers, etc...)
3187 * 2 : header = On input, pointer to header to modify.
3188 * On output, pointer to the modified header, or NULL
3189 * to remove the header. This function frees the
3190 * original string if necessary.
3192 * Returns : JB_ERR_OK on success, or
3193 * JB_ERR_MEMORY on out-of-memory error.
3195 *********************************************************************/
3196 static jb_err client_uagent(struct client_state *csp, char **header)
3200 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3205 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3212 *header = strdup("User-Agent: ");
3213 string_append(header, newval);
3215 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3217 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3221 /*********************************************************************
3223 * Function : client_ua
3225 * Description : Handle "ua-" headers properly. Called from `sed'.
3228 * 1 : csp = Current client state (buffers, headers, etc...)
3229 * 2 : header = On input, pointer to header to modify.
3230 * On output, pointer to the modified header, or NULL
3231 * to remove the header. This function frees the
3232 * original string if necessary.
3234 * Returns : JB_ERR_OK on success, or
3235 * JB_ERR_MEMORY on out-of-memory error.
3237 *********************************************************************/
3238 static jb_err client_ua(struct client_state *csp, char **header)
3240 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3242 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3250 /*********************************************************************
3252 * Function : client_from
3254 * Description : Handle the "from" config setting properly.
3255 * Called from `sed'.
3258 * 1 : csp = Current client state (buffers, headers, etc...)
3259 * 2 : header = On input, pointer to header to modify.
3260 * On output, pointer to the modified header, or NULL
3261 * to remove the header. This function frees the
3262 * original string if necessary.
3264 * Returns : JB_ERR_OK on success, or
3265 * JB_ERR_MEMORY on out-of-memory error.
3267 *********************************************************************/
3268 static jb_err client_from(struct client_state *csp, char **header)
3272 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3279 newval = csp->action->string[ACTION_STRING_FROM];
3282 * Are we blocking the e-mail address?
3284 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3286 log_error(LOG_LEVEL_HEADER, "crunched From!");
3290 log_error(LOG_LEVEL_HEADER, " modified");
3292 *header = strdup("From: ");
3293 string_append(header, newval);
3295 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3299 /*********************************************************************
3301 * Function : client_send_cookie
3303 * Description : Crunches the "cookie" header if necessary.
3304 * Called from `sed'.
3306 * XXX: Stupid name, doesn't send squat.
3309 * 1 : csp = Current client state (buffers, headers, etc...)
3310 * 2 : header = On input, pointer to header to modify.
3311 * On output, pointer to the modified header, or NULL
3312 * to remove the header. This function frees the
3313 * original string if necessary.
3315 * Returns : JB_ERR_OK on success, or
3316 * JB_ERR_MEMORY on out-of-memory error.
3318 *********************************************************************/
3319 static jb_err client_send_cookie(struct client_state *csp, char **header)
3321 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3323 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3331 /*********************************************************************
3333 * Function : client_x_forwarded
3335 * Description : Handle the "x-forwarded-for" config setting properly,
3336 * also used in the add_client_headers list. Called from `sed'.
3339 * 1 : csp = Current client state (buffers, headers, etc...)
3340 * 2 : header = On input, pointer to header to modify.
3341 * On output, pointer to the modified header, or NULL
3342 * to remove the header. This function frees the
3343 * original string if necessary.
3345 * Returns : JB_ERR_OK on success, or
3346 * JB_ERR_MEMORY on out-of-memory error.
3348 *********************************************************************/
3349 jb_err client_x_forwarded(struct client_state *csp, char **header)
3351 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3353 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3355 if (0 == strcmpic(parameter, "block"))
3358 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3360 else if (0 == strcmpic(parameter, "add"))
3362 string_append(header, ", ");
3363 string_append(header, csp->ip_addr_str);
3365 if (*header == NULL)
3367 return JB_ERR_MEMORY;
3369 log_error(LOG_LEVEL_HEADER,
3370 "Appended client IP address to %s", *header);
3371 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3375 log_error(LOG_LEVEL_FATAL,
3376 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3384 /*********************************************************************
3386 * Function : client_max_forwards
3388 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3389 * from the value of the Max-Forwards header field.
3392 * 1 : csp = Current client state (buffers, headers, etc...)
3393 * 2 : header = On input, pointer to header to modify.
3394 * On output, pointer to the modified header, or NULL
3395 * to remove the header. This function frees the
3396 * original string if necessary.
3398 * Returns : JB_ERR_OK on success, or
3399 * JB_ERR_MEMORY on out-of-memory error.
3401 *********************************************************************/
3402 static jb_err client_max_forwards(struct client_state *csp, char **header)
3406 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3407 (0 == strcmpic(csp->http->gpc, "options")))
3409 assert(*(*header+12) == ':');
3410 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3412 if (max_forwards > 0)
3414 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3415 log_error(LOG_LEVEL_HEADER,
3416 "Max-Forwards value for %s request reduced to %d.",
3417 csp->http->gpc, max_forwards);
3419 else if (max_forwards < 0)
3421 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3427 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3436 /*********************************************************************
3438 * Function : client_host
3440 * Description : If the request URI did not contain host and
3441 * port information, parse and evaluate the Host
3445 * 1 : csp = Current client state (buffers, headers, etc...)
3446 * 2 : header = On input, pointer to header to modify.
3447 * On output, pointer to the modified header, or NULL
3448 * to remove the header. This function frees the
3449 * original string if necessary.
3451 * Returns : JB_ERR_OK on success, or
3452 * JB_ERR_MEMORY on out-of-memory error.
3454 *********************************************************************/
3455 static jb_err client_host(struct client_state *csp, char **header)
3459 if (strlen(*header) < 7)
3461 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3466 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3467 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3470 p = strdup_or_die((*header)+6);
3472 q = strdup_or_die(p);
3474 freez(csp->http->hostport);
3475 csp->http->hostport = p;
3476 freez(csp->http->host);
3477 csp->http->host = q;
3478 q = strchr(csp->http->host, ':');
3481 /* Terminate hostname and evaluate port string */
3483 csp->http->port = atoi(q);
3487 csp->http->port = csp->http->ssl ? 443 : 80;
3490 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3491 csp->http->hostport, csp->http->host, csp->http->port);
3494 /* Signal client_host_adder() to return right away */
3495 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3501 /*********************************************************************
3503 * Function : client_if_modified_since
3505 * Description : Remove or modify the If-Modified-Since header.
3508 * 1 : csp = Current client state (buffers, headers, etc...)
3509 * 2 : header = On input, pointer to header to modify.
3510 * On output, pointer to the modified header, or NULL
3511 * to remove the header. This function frees the
3512 * original string if necessary.
3514 * Returns : JB_ERR_OK on success, or
3515 * JB_ERR_MEMORY on out-of-memory error.
3517 *********************************************************************/
3518 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3522 struct tm *timeptr = NULL;
3527 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3530 * The client got an error message because of a temporary problem,
3531 * the problem is gone and the client now tries to revalidate our
3532 * error message on the real server. The revalidation would always
3533 * end with the transmission of the whole document and there is
3534 * no need to expose the bogus If-Modified-Since header.
3536 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3539 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3541 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3543 if ((0 == strcmpic(newval, "block")))
3545 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3548 else /* add random value */
3550 if (JB_ERR_OK != parse_time_header(*header, &tm))
3552 log_error(LOG_LEVEL_HEADER,
3553 "Couldn't parse time in %s (crunching!)", *header);
3558 long int hours, minutes, seconds;
3559 long int rtime = strtol(newval, &endptr, 0);
3560 const int negative_range = (rtime < 0);
3564 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3565 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3571 rtime = pick_from_range(rtime);
3575 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3578 tm += rtime * (negative_range ? -1 : 1);
3579 timeptr = privoxy_gmtime_r(&tm, &gmt);
3580 if ((NULL == timeptr) || !strftime(newheader,
3581 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3583 log_error(LOG_LEVEL_ERROR,
3584 "Randomizing '%s' failed. Crunching the header without replacement.",
3590 *header = strdup("If-Modified-Since: ");
3591 string_append(header, newheader);
3593 if (*header == NULL)
3595 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3596 return JB_ERR_MEMORY;
3599 hours = rtime / 3600;
3600 minutes = rtime / 60 % 60;
3601 seconds = rtime % 60;
3603 log_error(LOG_LEVEL_HEADER,
3604 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3605 *header, (negative_range) ? "subtracted" : "added", hours,
3606 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3607 seconds, (seconds == 1) ? ")" : "s)");
3616 /*********************************************************************
3618 * Function : client_if_none_match
3620 * Description : Remove the If-None-Match header.
3623 * 1 : csp = Current client state (buffers, headers, etc...)
3624 * 2 : header = On input, pointer to header to modify.
3625 * On output, pointer to the modified header, or NULL
3626 * to remove the header. This function frees the
3627 * original string if necessary.
3629 * Returns : JB_ERR_OK on success, or
3630 * JB_ERR_MEMORY on out-of-memory error.
3632 *********************************************************************/
3633 static jb_err client_if_none_match(struct client_state *csp, char **header)
3635 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3637 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3645 /*********************************************************************
3647 * Function : client_x_filter
3649 * Description : Disables filtering if the client set "X-Filter: No".
3650 * Called from `sed'.
3653 * 1 : csp = Current client state (buffers, headers, etc...)
3654 * 2 : header = On input, pointer to header to modify.
3655 * On output, pointer to the modified header, or NULL
3656 * to remove the header. This function frees the
3657 * original string if necessary.
3659 * Returns : JB_ERR_OK on success
3661 *********************************************************************/
3662 jb_err client_x_filter(struct client_state *csp, char **header)
3664 if (0 == strcmpic(*header, "X-Filter: No"))
3666 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3668 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3672 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3674 log_error(LOG_LEVEL_HEADER,
3675 "force-text-mode overruled the client's request to fetch without filtering!");
3679 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3680 csp->flags |= CSP_FLAG_NO_FILTERING;
3681 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3683 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3691 /*********************************************************************
3693 * Function : client_range
3695 * Description : Removes Range, Request-Range and If-Range headers if
3696 * content filtering is enabled and the range doesn't
3699 * If the client's version of the document has been
3700 * altered by Privoxy, the server could interpret the
3701 * range differently than the client intended in which
3702 * case the user could end up with corrupted content.
3704 * If the range starts at byte 0 this isn't an issue
3705 * so the header can pass. Partial requests like this
3706 * are used to render preview images for videos without
3707 * downloading the whole video.
3709 * While HTTP doesn't require that range requests are
3710 * honoured and the client could simply abort the download
3711 * after receiving a sufficient amount of data, various
3712 * clients don't handle complete responses to range
3713 * requests gracefully and emit misleading error messages
3717 * 1 : csp = Current client state (buffers, headers, etc...)
3718 * 2 : header = On input, pointer to header to modify.
3719 * On output, pointer to the modified header, or NULL
3720 * to remove the header. This function frees the
3721 * original string if necessary.
3723 * Returns : JB_ERR_OK
3725 *********************************************************************/
3726 static jb_err client_range(struct client_state *csp, char **header)
3728 if (content_filters_enabled(csp->action)
3729 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3731 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3732 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3739 /* the following functions add headers directly to the header list */
3741 /*********************************************************************
3743 * Function : client_host_adder
3745 * Description : Adds the Host: header field if it is missing.
3746 * Called from `sed'.
3749 * 1 : csp = Current client state (buffers, headers, etc...)
3751 * Returns : JB_ERR_OK on success, or
3752 * JB_ERR_MEMORY on out-of-memory error.
3754 *********************************************************************/
3755 static jb_err client_host_adder(struct client_state *csp)
3760 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3762 /* Header already set by the client, nothing to do. */
3766 if (!csp->http->hostport || !*(csp->http->hostport))
3768 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3769 return JB_ERR_PARSE;
3773 * remove 'user:pass@' from 'proto://user:pass@host'
3775 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3781 p = csp->http->hostport;
3784 /* XXX: Just add it, we already made sure that it will be unique */
3785 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3786 err = enlist_unique_header(csp->headers, "Host", p);
3792 /*********************************************************************
3794 * Function : client_xtra_adder
3796 * Description : Used in the add_client_headers list. Called from `sed'.
3799 * 1 : csp = Current client state (buffers, headers, etc...)
3801 * Returns : JB_ERR_OK on success, or
3802 * JB_ERR_MEMORY on out-of-memory error.
3804 *********************************************************************/
3805 static jb_err client_xtra_adder(struct client_state *csp)
3807 struct list_entry *lst;
3810 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3811 lst ; lst = lst->next)
3813 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3814 err = enlist(csp->headers, lst->str);
3826 /*********************************************************************
3828 * Function : client_x_forwarded_for_adder
3830 * Description : Used in the add_client_headers list. Called from `sed'.
3833 * 1 : csp = Current client state (buffers, headers, etc...)
3835 * Returns : JB_ERR_OK on success, or
3836 * JB_ERR_MEMORY on out-of-memory error.
3838 *********************************************************************/
3839 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3841 char *header = NULL;
3844 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3845 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3846 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3849 * If we aren't adding X-Forwarded-For headers,
3850 * or we already appended an existing X-Forwarded-For
3851 * header, there's nothing left to do here.
3856 header = strdup("X-Forwarded-For: ");
3857 string_append(&header, csp->ip_addr_str);
3861 return JB_ERR_MEMORY;
3864 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3865 err = enlist(csp->headers, header);
3872 /*********************************************************************
3874 * Function : server_connection_adder
3876 * Description : Adds an appropriate "Connection:" header to csp->headers
3877 * unless the header was already present. Called from `sed'.
3880 * 1 : csp = Current client state (buffers, headers, etc...)
3882 * Returns : JB_ERR_OK on success, or
3883 * JB_ERR_MEMORY on out-of-memory error.
3885 *********************************************************************/
3886 static jb_err server_connection_adder(struct client_state *csp)
3888 const unsigned int flags = csp->flags;
3889 const char *response_status_line = csp->headers->first->str;
3890 static const char connection_close[] = "Connection: close";
3892 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3893 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3899 * XXX: if we downgraded the response, this check will fail.
3901 if ((csp->config->feature_flags &
3902 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3903 && (NULL != response_status_line)
3904 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3905 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3906 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3910 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3911 "without Connection header implies keep-alive.");
3912 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3916 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3918 return enlist(csp->headers, connection_close);
3922 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3923 /*********************************************************************
3925 * Function : server_proxy_connection_adder
3927 * Description : Adds a "Proxy-Connection: keep-alive" header to
3928 * csp->headers when appropriate.
3931 * 1 : csp = Current client state (buffers, headers, etc...)
3933 * Returns : JB_ERR_OK on success, or
3934 * JB_ERR_MEMORY on out-of-memory error.
3936 *********************************************************************/
3937 static jb_err server_proxy_connection_adder(struct client_state *csp)
3939 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3940 jb_err err = JB_ERR_OK;
3942 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3943 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3944 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3945 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3946 || (csp->flags & CSP_FLAG_CHUNKED))
3947 #ifdef FEATURE_HTTPS_INSPECTION
3948 && !client_use_ssl(csp)
3953 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3954 err = enlist(csp->headers, proxy_connection_header);
3959 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3962 /*********************************************************************
3964 * Function : client_connection_header_adder
3966 * Description : Adds a proper "Connection:" header to csp->headers
3967 * unless the header was already present or it's a
3968 * CONNECT request. Called from `sed'.
3971 * 1 : csp = Current client state (buffers, headers, etc...)
3973 * Returns : JB_ERR_OK on success, or
3974 * JB_ERR_MEMORY on out-of-memory error.
3976 *********************************************************************/
3977 static jb_err client_connection_header_adder(struct client_state *csp)
3979 static const char connection_close[] = "Connection: close";
3981 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3982 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3988 * In case of CONNECT requests "Connection: close" is implied,
3989 * but actually setting the header has been reported to cause
3990 * problems with some forwarding proxies that close the
3991 * connection prematurely.
3993 if (csp->http->ssl != 0)
3998 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3999 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4000 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4001 && !strcmpic(csp->http->version, "HTTP/1.1"))
4003 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4006 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4008 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4010 return enlist(csp->headers, connection_close);
4014 /*********************************************************************
4016 * Function : server_http
4018 * Description : - Save the HTTP Status into csp->http->status
4019 * - Set CT_TABOO to prevent filtering if the answer
4020 * is a partial range (HTTP status 206)
4021 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4023 * - Normalize the HTTP-version.
4026 * 1 : csp = Current client state (buffers, headers, etc...)
4027 * 2 : header = On input, pointer to header to modify.
4028 * On output, pointer to the modified header, or NULL
4029 * to remove the header. This function frees the
4030 * original string if necessary.
4032 * Returns : JB_ERR_OK on success, or
4033 * JB_ERR_PARSE on fatal parse errors.
4035 *********************************************************************/
4036 static jb_err server_http(struct client_state *csp, char **header)
4038 char *reason_phrase = NULL;
4039 char *new_response_line;
4042 unsigned int major_version;
4043 unsigned int minor_version;
4045 /* Get the reason phrase which start after the second whitespace */
4046 p = strchr(*header, ' ');
4050 reason_phrase = strchr(p, ' ');
4053 if (reason_phrase != NULL)
4059 log_error(LOG_LEVEL_ERROR,
4060 "Response line lacks reason phrase: %s", *header);
4064 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4065 &minor_version, &(csp->http->status)))
4067 log_error(LOG_LEVEL_ERROR,
4068 "Failed to parse the response line: %s", *header);
4069 return JB_ERR_PARSE;
4072 if (csp->http->status == 206)
4074 csp->content_type = CT_TABOO;
4077 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4080 * According to RFC 7230 2.6 intermediaries MUST send
4081 * their own HTTP-version in forwarded messages.
4083 log_error(LOG_LEVEL_ERROR,
4084 "Unsupported HTTP version. Downgrading to 1.1.");
4089 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4091 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4095 /* Rebuild response line. */
4096 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4097 new_response_line = malloc_or_die(length);
4099 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4100 major_version, minor_version, csp->http->status, reason_phrase);
4102 if (0 != strcmp(*header, new_response_line))
4104 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4105 *header, new_response_line);
4109 *header = new_response_line;
4114 /*********************************************************************
4116 * Function : add_cooky_expiry_date
4118 * Description : Adds a cookie expiry date to a string.
4121 * 1 : cookie = On input, pointer to cookie to modify.
4122 * On output, pointer to the modified header.
4123 * The original string is freed.
4124 * 2 : lifetime = Seconds the cookie should be valid
4128 *********************************************************************/
4129 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4132 struct tm *timeptr = NULL;
4133 time_t expiry_date = time(NULL) + lifetime;
4136 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4137 if (NULL == timeptr)
4139 log_error(LOG_LEVEL_FATAL,
4140 "Failed to get the time in add_cooky_expiry_date()");
4142 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4143 if (JB_ERR_OK != string_append(cookie, tmp))
4145 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4150 /*********************************************************************
4152 * Function : server_set_cookie
4154 * Description : Handle the server "cookie" header properly.
4155 * Crunch, accept or rewrite it to a session cookie.
4156 * Called from `sed'.
4159 * 1 : csp = Current client state (buffers, headers, etc...)
4160 * 2 : header = On input, pointer to header to modify.
4161 * On output, pointer to the modified header, or NULL
4162 * to remove the header. This function frees the
4163 * original string if necessary.
4165 * Returns : JB_ERR_OK on success, or
4166 * JB_ERR_MEMORY on out-of-memory error.
4168 *********************************************************************/
4169 static jb_err server_set_cookie(struct client_state *csp, char **header)
4171 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4173 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4176 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4177 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4181 long cookie_lifetime = 0;
4184 NO_EXPIRY_DATE_SPECIFIED,
4185 EXPIRY_DATE_ACCEPTABLE,
4186 EXPIRY_DATE_UNACCEPTABLE
4187 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4189 /* A variable to store the tag we're working on */
4192 /* Skip "Set-Cookie:" (11 characters) in header */
4193 cur_tag = *header + 11;
4195 /* skip whitespace between "Set-Cookie:" and value */
4196 while (*cur_tag && privoxy_isspace(*cur_tag))
4203 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4205 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4207 cookie_lifetime = strtol(param, NULL, 0);
4208 if (cookie_lifetime < 0)
4210 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4212 cookie_lifetime *= 60;
4215 /* Loop through each tag in the cookie */
4219 char *next_tag = strchr(cur_tag, ';');
4220 if (next_tag != NULL)
4222 /* Skip the ';' character itself */
4225 /* skip whitespace ";" and start of tag */
4226 while (*next_tag && privoxy_isspace(*next_tag))
4233 /* "Next tag" is the end of the string */
4234 next_tag = cur_tag + strlen(cur_tag);
4238 * Check the expiration date to see
4239 * if the cookie is still valid, if yes,
4240 * rewrite it to a session cookie.
4242 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4244 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4246 if ((expiration_date[0] == '"')
4247 && (expiration_date[1] != '\0'))
4250 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4251 * that the expiration date isn't supposed to be quoted,
4252 * but some servers do it anyway.
4257 /* Did we detect the date properly? */
4258 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4261 * Nope, treat it as if it was still valid.
4263 * XXX: Should we remove the whole cookie instead?
4265 log_error(LOG_LEVEL_ERROR,
4266 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4267 string_move(cur_tag, next_tag);
4268 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4273 * Yes. Check if the cookie is still valid.
4275 * If the cookie is already expired it's probably
4276 * a delete cookie and even if it isn't, the browser
4277 * will discard it anyway.
4281 * XXX: timegm() isn't available on some AmigaOS
4282 * versions and our replacement doesn't work.
4284 * Our options are to either:
4286 * - disable session-cookies-only completely if timegm
4289 * - to simply remove all expired tags, like it has
4290 * been done until Privoxy 3.0.6 and to live with
4291 * the consequence that it can cause login/logout
4292 * problems on servers that don't validate their
4293 * input properly, or
4295 * - to replace it with mktime in which
4296 * case there is a slight chance of valid cookies
4297 * passing as already expired.
4299 * This is the way it's currently done and it's not
4300 * as bad as it sounds. If the missing GMT offset is
4301 * enough to change the result of the expiration check
4302 * the cookie will be only valid for a few hours
4303 * anyway, which in many cases will be shorter
4304 * than a browser session.
4306 if (cookie_time < now)
4308 log_error(LOG_LEVEL_HEADER,
4309 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4310 /* Just in case some clown sets more then one expiration date */
4312 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4314 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4316 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4317 "Its lifetime is below the limit.", *header);
4318 /* Just in case some clown sets more then one expiration date */
4320 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4325 * Still valid, delete expiration date by copying
4326 * the rest of the string over it.
4328 string_move(cur_tag, next_tag);
4330 /* That changed the header, need to issue a log message */
4331 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4334 * Note that the next tag has now been moved to *cur_tag,
4335 * so we do not need to update the cur_tag pointer.
4343 /* Move on to next cookie tag */
4348 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4350 assert(NULL != *header);
4351 if (cookie_lifetime != 0)
4353 add_cookie_expiry_date(header, cookie_lifetime);
4354 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4356 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4358 log_error(LOG_LEVEL_HEADER,
4359 "Cookie rewritten to a temporary one: %s", *header);
4368 #ifdef FEATURE_FORCE_LOAD
4369 /*********************************************************************
4371 * Function : strclean
4373 * Description : In-Situ-Eliminate all occurrences of substring in
4377 * 1 : string = string to clean
4378 * 2 : substring = substring to eliminate
4380 * Returns : Number of eliminations
4382 *********************************************************************/
4383 int strclean(char *string, const char *substring)
4389 len = strlen(substring);
4391 while((pos = strstr(string, substring)) != NULL)
4398 while (*p++ != '\0');
4405 #endif /* def FEATURE_FORCE_LOAD */
4408 /*********************************************************************
4410 * Function : parse_header_time
4412 * Description : Parses time formats used in HTTP header strings
4413 * to get the numerical respresentation.
4416 * 1 : header_time = HTTP header time as string.
4417 * 2 : result = storage for header_time in seconds
4419 * Returns : JB_ERR_OK if the time format was recognized, or
4420 * JB_ERR_PARSE otherwise.
4422 *********************************************************************/
4423 static jb_err parse_header_time(const char *header_time, time_t *result)
4427 * Checking for two-digit years first in an
4428 * attempt to work around GNU libc's strptime()
4429 * reporting negative year values when using %Y.
4431 static const char time_formats[][22] = {
4432 /* Tue, 02-Jun-37 20:00:00 */
4433 "%a, %d-%b-%y %H:%M:%S",
4434 /* Tue, 02 Jun 2037 20:00:00 */
4435 "%a, %d %b %Y %H:%M:%S",
4436 /* Tue, 02-Jun-2037 20:00:00 */
4437 "%a, %d-%b-%Y %H:%M:%S",
4438 /* Tuesday, 02-Jun-2037 20:00:00 */
4439 "%A, %d-%b-%Y %H:%M:%S",
4440 /* Tuesday Jun 02 20:00:00 2037 */
4441 "%A %b %d %H:%M:%S %Y"
4445 for (i = 0; i < SZ(time_formats); i++)
4448 * Zero out gmt to prevent time zone offsets.
4449 * Documented to be required for GNU libc.
4451 memset(&gmt, 0, sizeof(gmt));
4453 if (NULL != strptime(header_time, time_formats[i], &gmt))
4455 /* Sanity check for GNU libc. */
4456 if (gmt.tm_year < 0)
4458 log_error(LOG_LEVEL_HEADER,
4459 "Failed to parse '%s' using '%s'. Moving on.",
4460 header_time, time_formats[i]);
4463 *result = timegm(&gmt);
4465 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4467 * Verify that parsing the date recreated from the first
4468 * parse operation gets the previous result. If it doesn't,
4469 * either strptime() or strftime() are malfunctioning.
4471 * We could string-compare the recreated date with the original
4472 * header date, but this leads to false positives as strptime()
4473 * may let %a accept all day formats while strftime() will only
4477 char recreated_date[100];
4482 tm = privoxy_gmtime_r(result, &storage);
4483 if (!strftime(recreated_date, sizeof(recreated_date),
4484 time_formats[i], tm))
4486 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4487 header_time, time_formats[i]);
4490 memset(&gmt, 0, sizeof(gmt));
4491 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4493 log_error(LOG_LEVEL_ERROR,
4494 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4495 recreated_date, time_formats[i], header_time);
4498 result2 = timegm(&gmt);
4499 if (*result != result2)
4501 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4502 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4503 time_formats[i], header_time, recreated_date, *result, result2);
4513 return JB_ERR_PARSE;
4517 /*********************************************************************
4519 * Function : parse_time_header
4521 * Description : Parses the time in an HTTP time header to get
4522 * the numerical respresentation.
4525 * 1 : header = HTTP header with a time value
4526 * 2 : result = storage for header_time in seconds
4528 * Returns : JB_ERR_OK if the time format was recognized, or
4529 * JB_ERR_PARSE otherwise.
4531 *********************************************************************/
4532 static jb_err parse_time_header(const char *header, time_t *result)
4534 const char *header_time;
4536 header_time = strchr(header, ':');
4539 * Currently this can't happen as all callers are called
4540 * through sed() which requires a header name followed by
4543 assert(header_time != NULL);
4546 if (*header_time == ' ')
4551 return parse_header_time(header_time, result);
4556 /*********************************************************************
4558 * Function : get_destination_from_headers
4560 * Description : Parse the "Host:" header to get the request's destination.
4561 * Only needed if the client's request was forcefully
4562 * redirected into Privoxy.
4564 * Code mainly copied from client_host() which is currently
4565 * run too late for this purpose.
4568 * 1 : headers = List of headers (one of them hopefully being
4569 * the "Host:" header)
4570 * 2 : http = storage for the result (host, port and hostport).
4572 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4573 * JB_ERR_PARSE if the host header couldn't be found,
4574 * JB_ERR_OK otherwise.
4576 *********************************************************************/
4577 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4583 host = get_header_value(headers, "Host:");
4587 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4588 return JB_ERR_PARSE;
4591 p = strdup_or_die(host);
4593 q = strdup_or_die(p);
4595 freez(http->hostport);
4599 q = strchr(http->host, ':');
4602 /* Terminate hostname and evaluate port string */
4604 http->port = atoi(q);
4611 /* Rebuild request URL */
4613 http->url = strdup("http://");
4614 string_append(&http->url, http->hostport);
4615 string_append(&http->url, http->path);
4616 if (http->url == NULL)
4618 return JB_ERR_MEMORY;
4621 log_error(LOG_LEVEL_HEADER,
4622 "Destination extracted from \"Host\" header. New request URL: %s",
4626 * Regenerate request line in "proxy format"
4627 * to make rewrites more convenient.
4629 assert(http->cmd != NULL);
4631 http->cmd = strdup_or_die(http->gpc);
4632 string_append(&http->cmd, " ");
4633 string_append(&http->cmd, http->url);
4634 string_append(&http->cmd, " ");
4635 string_append(&http->cmd, http->version);
4636 if (http->cmd == NULL)
4638 return JB_ERR_MEMORY;
4646 #ifdef FEATURE_HTTPS_INSPECTION
4647 /*********************************************************************
4649 * Function : get_destination_from_https_headers
4651 * Description : Parse the previously encrypted "Host:" header to
4652 * get the request's destination.
4655 * 1 : headers = List of headers (one of them hopefully being
4656 * the "Host:" header)
4657 * 2 : http = storage for the result (host, port and hostport).
4659 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4660 * JB_ERR_PARSE if the host header couldn't be found,
4661 * JB_ERR_OK otherwise.
4663 *********************************************************************/
4664 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4670 host = get_header_value(headers, "Host:");
4674 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4675 return JB_ERR_PARSE;
4678 p = strdup_or_die(host);
4680 q = strdup_or_die(p);
4682 freez(http->hostport);
4686 q = strchr(http->host, ':');
4689 /* Terminate hostname and evaluate port string */
4691 http->port = atoi(q);
4698 /* Rebuild request URL */
4700 http->url = strdup_or_die(http->path);
4702 log_error(LOG_LEVEL_HEADER,
4703 "Destination extracted from \"Host\" header. New request URL: %s",
4707 * Regenerate request line in "proxy format"
4708 * to make rewrites more convenient.
4710 assert(http->cmd != NULL);
4712 http->cmd = strdup_or_die(http->gpc);
4713 string_append(&http->cmd, " ");
4714 string_append(&http->cmd, http->url);
4715 string_append(&http->cmd, " ");
4716 string_append(&http->cmd, http->version);
4717 if (http->cmd == NULL)
4719 return JB_ERR_MEMORY;
4725 #endif /* def FEATURE_HTTPS_INSPECTION */
4728 /*********************************************************************
4730 * Function : create_forged_referrer
4732 * Description : Helper for client_referrer to forge a referer as
4733 * 'http://hostname[:port]/' to fool stupid
4734 * checks for in-site links
4737 * 1 : header = Pointer to header pointer
4738 * 2 : hostport = Host and optionally port as string
4740 * Returns : JB_ERR_OK in case of success, or
4741 * JB_ERR_MEMORY in case of memory problems.
4743 *********************************************************************/
4744 static jb_err create_forged_referrer(char **header, const char *hostport)
4746 assert(NULL == *header);
4748 *header = strdup("Referer: http://");
4749 string_append(header, hostport);
4750 string_append(header, "/");
4752 if (NULL == *header)
4754 return JB_ERR_MEMORY;
4757 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4764 /*********************************************************************
4766 * Function : create_fake_referrer
4768 * Description : Helper for client_referrer to create a fake referrer
4769 * based on a string supplied by the user.
4772 * 1 : header = Pointer to header pointer
4773 * 2 : hosthost = Referrer to fake
4775 * Returns : JB_ERR_OK in case of success, or
4776 * JB_ERR_MEMORY in case of memory problems.
4778 *********************************************************************/
4779 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4781 assert(NULL == *header);
4783 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4785 log_error(LOG_LEVEL_HEADER,
4786 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4788 *header = strdup("Referer: ");
4789 string_append(header, fake_referrer);
4791 if (NULL == *header)
4793 return JB_ERR_MEMORY;
4796 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4803 /*********************************************************************
4805 * Function : handle_conditional_hide_referrer_parameter
4807 * Description : Helper for client_referrer to crunch or forge
4808 * the referrer header if the host has changed.
4811 * 1 : header = Pointer to header pointer
4812 * 2 : host = The target host (may include the port)
4813 * 3 : parameter_conditional_block = Boolean to signal
4814 * if we're in conditional-block mode. If not set,
4815 * we're in conditional-forge mode.
4817 * Returns : JB_ERR_OK in case of success, or
4818 * JB_ERR_MEMORY in case of memory problems.
4820 *********************************************************************/
4821 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4822 const char *host, const int parameter_conditional_block)
4824 char *referer = strdup_or_die(*header);
4825 const size_t hostlength = strlen(host);
4826 const char *referer_url = NULL;
4828 /* referer begins with 'Referer: http[s]://' */
4829 if ((hostlength+17) < strlen(referer))
4832 * Shorten referer to make sure the referer is blocked
4833 * if www.example.org/www.example.com-shall-see-the-referer/
4834 * links to www.example.com/
4836 referer[hostlength+17] = '\0';
4838 referer_url = strstr(referer, "http://");
4839 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4841 /* Host has changed, Referer is invalid or a https URL. */
4842 if (parameter_conditional_block)
4844 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4851 return create_forged_referrer(header, host);
4861 /*********************************************************************
4863 * Function : create_content_length_header
4865 * Description : Creates a Content-Length header.
4868 * 1 : content_length = The content length to be used in the header.
4869 * 2 : header = Allocated space to safe the header.
4870 * 3 : buffer_length = The length of the allocated space.
4874 *********************************************************************/
4875 static void create_content_length_header(unsigned long long content_length,
4876 char *header, size_t buffer_length)
4879 #if SIZEOF_LONG_LONG < 8
4880 #error sizeof(unsigned long long) too small
4882 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4884 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4889 /*********************************************************************
4891 * Function : get_expected_content_length
4893 * Description : Figures out the content length from a list of headers.
4896 * 1 : headers = List of headers
4898 * Returns : Number of bytes to expect
4900 *********************************************************************/
4901 unsigned long long get_expected_content_length(struct list *headers)
4903 const char *content_length_header;
4904 unsigned long long content_length = 0;
4906 content_length_header = get_header_value(headers, "Content-Length:");
4907 if (content_length_header != NULL)
4909 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4911 log_error(LOG_LEVEL_ERROR,
4912 "Failed to get the Content-Length in %s", content_length_header);
4913 /* XXX: The header will be removed later on */
4918 return content_length;