1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2020 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
61 #define GZIP_FLAG_CHECKSUM 0x02
62 #define GZIP_FLAG_EXTRA_FIELDS 0x04
63 #define GZIP_FLAG_FILE_NAME 0x08
64 #define GZIP_FLAG_COMMENT 0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
68 #include <brotli/decode.h>
77 #ifdef FEATURE_PTHREAD
79 /* jcc.h is for mutex semapores only */
80 #endif /* def FEATURE_PTHREAD */
85 #include "jbsockets.h"
90 #ifdef FEATURE_HTTPS_INSPECTION
98 static char *get_header_line(struct iob *iob);
99 static jb_err scan_headers(struct client_state *csp);
100 static jb_err header_tagger(struct client_state *csp, char *header);
101 static jb_err parse_header_time(const char *header_time, time_t *result);
102 static jb_err parse_time_header(const char *header, time_t *result);
104 static jb_err crumble (struct client_state *csp, char **header);
105 static jb_err filter_header (struct client_state *csp, char **header);
106 static jb_err client_connection (struct client_state *csp, char **header);
107 static jb_err client_referrer (struct client_state *csp, char **header);
108 static jb_err client_uagent (struct client_state *csp, char **header);
109 static jb_err client_ua (struct client_state *csp, char **header);
110 static jb_err client_from (struct client_state *csp, char **header);
111 static jb_err client_send_cookie (struct client_state *csp, char **header);
112 static jb_err client_x_forwarded (struct client_state *csp, char **header);
113 static jb_err client_accept_encoding (struct client_state *csp, char **header);
114 static jb_err client_te (struct client_state *csp, char **header);
115 static jb_err client_max_forwards (struct client_state *csp, char **header);
116 static jb_err client_host (struct client_state *csp, char **header);
117 static jb_err client_if_modified_since (struct client_state *csp, char **header);
118 static jb_err client_accept_language (struct client_state *csp, char **header);
119 static jb_err client_if_none_match (struct client_state *csp, char **header);
120 static jb_err crunch_client_header (struct client_state *csp, char **header);
121 static jb_err client_x_filter (struct client_state *csp, char **header);
122 static jb_err client_range (struct client_state *csp, char **header);
123 static jb_err client_expect (struct client_state *csp, char **header);
124 static jb_err server_set_cookie (struct client_state *csp, char **header);
125 static jb_err server_connection (struct client_state *csp, char **header);
126 static jb_err server_content_type (struct client_state *csp, char **header);
127 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
128 static jb_err server_content_md5 (struct client_state *csp, char **header);
129 static jb_err server_content_encoding (struct client_state *csp, char **header);
130 static jb_err server_transfer_coding (struct client_state *csp, char **header);
131 static jb_err server_http (struct client_state *csp, char **header);
132 static jb_err crunch_server_header (struct client_state *csp, char **header);
133 static jb_err server_last_modified (struct client_state *csp, char **header);
134 static jb_err server_content_disposition(struct client_state *csp, char **header);
136 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
139 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
140 static jb_err server_save_content_length(struct client_state *csp, char **header);
141 static jb_err server_keep_alive(struct client_state *csp, char **header);
142 static jb_err server_proxy_connection(struct client_state *csp, char **header);
143 static jb_err client_keep_alive(struct client_state *csp, char **header);
144 static jb_err client_proxy_connection(struct client_state *csp, char **header);
145 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
147 static jb_err client_save_content_length(struct client_state *csp, char **header);
148 static jb_err client_host_adder (struct client_state *csp);
149 static jb_err client_xtra_adder (struct client_state *csp);
150 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
151 static jb_err client_connection_header_adder(struct client_state *csp);
152 static jb_err server_connection_adder(struct client_state *csp);
153 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
154 static jb_err server_proxy_connection_adder(struct client_state *csp);
155 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
156 static jb_err proxy_authentication(struct client_state *csp, char **header);
158 static jb_err create_forged_referrer(char **header, const char *hostport);
159 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
160 static jb_err handle_conditional_hide_referrer_parameter(char **header,
161 const char *host, const int parameter_conditional_block);
162 static void create_content_length_header(unsigned long long content_length,
163 char *header, size_t buffer_length);
166 * List of functions to run on a list of headers.
170 /** The header prefix to match */
173 /** The length of the prefix to match */
176 /** The function to apply to this line */
177 const parser_func_ptr parser;
180 static const struct parsers client_patterns[] = {
181 { "referer:", 8, client_referrer },
182 { "user-agent:", 11, client_uagent },
183 { "ua-", 3, client_ua },
184 { "from:", 5, client_from },
185 { "cookie:", 7, client_send_cookie },
186 { "x-forwarded-for:", 16, client_x_forwarded },
187 { "Accept-Encoding:", 16, client_accept_encoding },
188 { "TE:", 3, client_te },
189 { "Host:", 5, client_host },
190 { "if-modified-since:", 18, client_if_modified_since },
191 { "Content-Length:", 15, client_save_content_length },
192 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
193 { "Keep-Alive:", 11, client_keep_alive },
194 { "Proxy-Connection:", 17, client_proxy_connection },
196 { "Keep-Alive:", 11, crumble },
197 { "Proxy-Connection:", 17, crumble },
199 { "connection:", 11, client_connection },
200 { "max-forwards:", 13, client_max_forwards },
201 { "Accept-Language:", 16, client_accept_language },
202 { "if-none-match:", 14, client_if_none_match },
203 { "Range:", 6, client_range },
204 { "Request-Range:", 14, client_range },
205 { "If-Range:", 9, client_range },
206 { "X-Filter:", 9, client_x_filter },
207 { "Proxy-Authorization:", 20, proxy_authentication },
209 { "Transfer-Encoding:", 18, client_transfer_encoding },
211 { "Expect:", 7, client_expect },
212 { "*", 0, crunch_client_header },
213 { "*", 0, filter_header },
217 static const struct parsers server_patterns[] = {
218 { "HTTP/", 5, server_http },
219 { "set-cookie:", 11, server_set_cookie },
220 { "connection:", 11, server_connection },
221 { "Content-Type:", 13, server_content_type },
222 { "Content-MD5:", 12, server_content_md5 },
223 { "Content-Encoding:", 17, server_content_encoding },
224 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
225 { "Content-Length:", 15, server_save_content_length },
226 { "Keep-Alive:", 11, server_keep_alive },
227 { "Proxy-Connection:", 17, server_proxy_connection },
229 { "Keep-Alive:", 11, crumble },
230 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
231 { "Transfer-Encoding:", 18, server_transfer_coding },
232 { "content-disposition:", 20, server_content_disposition },
233 { "Last-Modified:", 14, server_last_modified },
234 { "Proxy-Authenticate:", 19, proxy_authentication },
235 { "*", 0, crunch_server_header },
236 { "*", 0, filter_header },
240 static const add_header_func_ptr add_client_headers[] = {
242 client_x_forwarded_for_adder,
244 client_connection_header_adder,
248 static const add_header_func_ptr add_server_headers[] = {
249 server_connection_adder,
250 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
251 server_proxy_connection_adder,
252 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
256 /*********************************************************************
258 * Function : flush_iob
260 * Description : Write any pending "buffered" content.
263 * 1 : fd = file descriptor of the socket to read
264 * 2 : iob = The I/O buffer to flush, usually csp->iob.
265 * 3 : delay = Number of milliseconds to delay the writes
267 * Returns : On success, the number of bytes written are returned (zero
268 * indicates nothing was written). On error, -1 is returned,
269 * and errno is set appropriately. If count is zero and the
270 * file descriptor refers to a regular file, 0 will be
271 * returned without causing any other effect. For a special
272 * file, the results are not portable.
274 *********************************************************************/
275 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
277 long len = iob->eod - iob->cur;
284 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
288 iob->eod = iob->cur = iob->buf;
294 /*********************************************************************
296 * Function : add_to_iob
298 * Description : Add content to the buffer, expanding the
299 * buffer if necessary.
302 * 1 : iob = Destination buffer.
303 * 2 : buffer_limit = Limit to which the destination may grow
304 * 3 : src = holds the content to be added
305 * 4 : n = number of bytes to be added
307 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
308 * or buffer limit reached.
310 *********************************************************************/
311 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
313 size_t used, offset, need;
316 if (n <= 0) return JB_ERR_OK;
318 used = (size_t)(iob->eod - iob->buf);
319 offset = (size_t)(iob->cur - iob->buf);
320 need = used + (size_t)n + 1;
323 * If the buffer can't hold the new data, extend it first.
324 * Use the next power of two if possible, else use the actual need.
326 if (need > buffer_limit)
328 log_error(LOG_LEVEL_INFO,
329 "Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
331 return JB_ERR_MEMORY;
334 if (need > iob->size)
336 size_t want = iob->size ? iob->size : 512;
343 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
347 else if (NULL != (p = (char *)realloc(iob->buf, need)))
353 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
354 return JB_ERR_MEMORY;
357 /* Update the iob pointers */
358 iob->cur = p + offset;
363 /* copy the new data into the iob buffer */
364 memcpy(iob->eod, src, (size_t)n);
366 /* point to the end of the data */
369 /* null terminate == cheap insurance */
377 /*********************************************************************
379 * Function : clear_iob
381 * Description : Frees the memory allocated for an I/O buffer and
382 * resets the structure.
385 * 1 : iob = I/O buffer to clear.
389 *********************************************************************/
390 void clear_iob(struct iob *iob)
393 memset(iob, '\0', sizeof(*iob));
398 #ifdef FEATURE_BROTLI
399 /*********************************************************************
401 * Function : decompress_iob_with_brotli
403 * Description : Decompress buffered page using Brotli.
406 * 1 : csp = Current client state (buffers, headers, etc...)
408 * Returns : JB_ERR_OK on success,
409 * JB_ERR_MEMORY if out-of-memory limit reached, and
410 * JB_ERR_COMPRESS if error decompressing buffer.
412 *********************************************************************/
413 static jb_err decompress_iob_with_brotli(struct client_state *csp)
415 BrotliDecoderResult result;
416 char *decoded_buffer;
418 size_t decoded_buffer_size;
420 enum { MAX_COMPRESSION_FACTOR = 15 };
422 encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
424 * The BrotliDecoderDecompress() api is a bit unfortunate
425 * and requires the caller to reserve enough memory for
426 * the decompressed content. Hopefully reserving
427 * MAX_COMPRESSION_FACTOR times the original size is
428 * sufficient. If not, BrotliDecoderDecompress() will fail.
430 decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
432 if (decoded_buffer_size > csp->config->buffer_limit)
434 log_error(LOG_LEVEL_ERROR,
435 "Buffer limit reached before decompressing iob with Brotli");
436 return JB_ERR_MEMORY;
439 decoded_buffer = malloc(decoded_buffer_size);
440 if (decoded_buffer == NULL)
442 log_error(LOG_LEVEL_ERROR,
443 "Failed to allocate %lu bytes for Brotli decompression",
444 decoded_buffer_size);
445 return JB_ERR_MEMORY;
448 decoded_size = decoded_buffer_size;
449 result = BrotliDecoderDecompress(encoded_size,
450 (const uint8_t *)csp->iob->cur, &decoded_size,
451 (uint8_t *)decoded_buffer);
452 if (result == BROTLI_DECODER_RESULT_SUCCESS)
455 * Update the iob, since the decompression was successful.
457 freez(csp->iob->buf);
458 csp->iob->buf = decoded_buffer;
459 csp->iob->cur = csp->iob->buf;
460 csp->iob->eod = csp->iob->cur + decoded_size;
461 csp->iob->size = decoded_buffer_size;
463 log_error(LOG_LEVEL_RE_FILTER,
464 "Decompression successful. Old size: %lu, new size: %lu.",
465 encoded_size, decoded_size);
471 log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
472 freez(decoded_buffer);
474 return JB_ERR_COMPRESS;
479 /*********************************************************************
481 * Function : decompress_iob
483 * Description : Decompress buffered page, expanding the
484 * buffer as necessary. csp->iob->cur
485 * should point to the the beginning of the
486 * compressed data block.
489 * 1 : csp = Current client state (buffers, headers, etc...)
491 * Returns : JB_ERR_OK on success,
492 * JB_ERR_MEMORY if out-of-memory limit reached, and
493 * JB_ERR_COMPRESS if error decompressing buffer.
495 *********************************************************************/
496 jb_err decompress_iob(struct client_state *csp)
498 char *buf; /* new, uncompressed buffer */
499 char *cur; /* Current iob position (to keep the original
500 * iob->cur unmodified if we return early) */
501 size_t bufsize; /* allocated size of the new buffer */
502 size_t old_size; /* Content size before decompression */
503 size_t skip_size; /* Number of bytes at the beginning of the iob
504 that we should NOT decompress. */
505 int status; /* return status of the inflate() call */
506 z_stream zstr; /* used by calls to zlib */
509 assert(csp->iob->cur - csp->iob->buf >= 0);
510 assert(csp->iob->eod - csp->iob->cur >= 0);
512 assert(csp->iob->cur - csp->iob->buf > 0);
513 assert(csp->iob->eod - csp->iob->cur > 0);
516 bufsize = csp->iob->size;
517 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
518 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
522 if (bufsize < (size_t)10)
525 * This is to protect the parsing of gzipped data,
526 * but it should(?) be valid for deflated data also.
528 log_error(LOG_LEVEL_ERROR,
529 "Insufficient data to start decompression. Bytes in buffer: %ld",
530 csp->iob->eod - csp->iob->cur);
531 return JB_ERR_COMPRESS;
534 #ifdef FEATURE_BROTLI
535 if (csp->content_type & CT_BROTLI)
537 return decompress_iob_with_brotli(csp);
541 if (csp->content_type & CT_GZIP)
544 * Our task is slightly complicated by the facts that data
545 * compressed by gzip does not include a zlib header, and
546 * that there is no easily accessible interface in zlib to
547 * handle a gzip header. We strip off the gzip header by
548 * hand, and later inform zlib not to expect a header.
552 * Strip off the gzip header. Please see RFC 1952 for more
553 * explanation of the appropriate fields.
555 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
556 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
557 || (*cur++ != Z_DEFLATED))
559 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
560 return JB_ERR_COMPRESS;
565 if (flags & GZIP_FLAG_RESERVED_BITS)
567 /* The gzip header has reserved bits set; bail out. */
568 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
569 return JB_ERR_COMPRESS;
573 * Skip mtime (4 bytes), extra flags (1 byte)
574 * and OS type (1 byte).
578 /* Skip extra fields if necessary. */
579 if (flags & GZIP_FLAG_EXTRA_FIELDS)
582 * Skip a given number of bytes, specified
583 * as a 16-bit little-endian value.
585 * XXX: this code is untested and should probably be removed.
589 skip_bytes += *cur++ << 8;
592 * The number of bytes to skip should be positive
593 * and we'd like to stay in the buffer.
595 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
597 log_error(LOG_LEVEL_ERROR,
598 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
600 return JB_ERR_COMPRESS;
602 log_error(LOG_LEVEL_INFO,
603 "Skipping %d bytes for gzip compression. Does this sound right?",
608 /* Skip the filename if necessary. */
609 if (flags & GZIP_FLAG_FILE_NAME)
611 /* A null-terminated string is supposed to follow. */
612 while (*cur++ && (cur < csp->iob->eod));
615 /* Skip the comment if necessary. */
616 if (flags & GZIP_FLAG_COMMENT)
618 /* A null-terminated string is supposed to follow. */
619 while (*cur++ && (cur < csp->iob->eod));
622 /* Skip the CRC if necessary. */
623 if (flags & GZIP_FLAG_CHECKSUM)
628 if (cur >= csp->iob->eod)
631 * If the current position pointer reached or passed
632 * the buffer end, we were obviously tricked to skip
635 log_error(LOG_LEVEL_ERROR,
636 "Malformed gzip header detected. Aborting decompression.");
637 return JB_ERR_COMPRESS;
641 else if (csp->content_type & CT_DEFLATE)
644 * In theory (that is, according to RFC 1950), deflate-compressed
645 * data should begin with a two-byte zlib header and have an
646 * adler32 checksum at the end. It seems that in practice only
647 * the raw compressed data is sent. Note that this means that
648 * we are not RFC 1950-compliant here, but the advantage is that
649 * this actually works. :)
651 * We add a dummy null byte to tell zlib where the data ends,
652 * and later inform it not to expect a header.
654 * Fortunately, add_to_iob() has thoughtfully null-terminated
655 * the buffer; we can just increment the end pointer to include
662 log_error(LOG_LEVEL_ERROR,
663 "Unable to determine compression format for decompression");
664 return JB_ERR_COMPRESS;
667 /* Set up the fields required by zlib. */
668 zstr.next_in = (Bytef *)cur;
669 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
670 zstr.zalloc = Z_NULL;
672 zstr.opaque = Z_NULL;
675 * Passing -MAX_WBITS to inflateInit2 tells the library
676 * that there is no zlib header.
678 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
680 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
681 return JB_ERR_COMPRESS;
685 * Next, we allocate new storage for the inflated data.
686 * We don't modify the existing iob yet, so in case there
687 * is error in decompression we can recover gracefully.
689 buf = zalloc(bufsize);
692 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
693 return JB_ERR_MEMORY;
696 assert(bufsize >= skip_size);
697 memcpy(buf, csp->iob->buf, skip_size);
698 zstr.avail_out = (uInt)(bufsize - skip_size);
699 zstr.next_out = (Bytef *)buf + skip_size;
701 /* Try to decompress the whole stream in one shot. */
702 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
704 /* We need to allocate more memory for the output buffer. */
706 char *tmpbuf; /* used for realloc'ing the buffer */
707 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
709 if (0 == zstr.avail_in)
712 * If zlib wants more data then there's a problem, because
713 * the complete compressed file should have been buffered.
715 log_error(LOG_LEVEL_ERROR,
716 "Unexpected end of compressed iob. Using what we got so far.");
721 * If we reached the buffer limit and still didn't have enough
722 * memory, just give up. Due to the ceiling enforced by the next
723 * if block we could actually check for equality here, but as it
724 * can be easily mistaken for a bug we don't.
726 if (bufsize >= csp->config->buffer_limit)
728 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
731 return JB_ERR_MEMORY;
734 /* Try doubling the buffer size each time. */
737 /* Don't exceed the buffer limit. */
738 if (bufsize > csp->config->buffer_limit)
740 bufsize = csp->config->buffer_limit;
743 /* Try to allocate the new buffer. */
744 tmpbuf = realloc(buf, bufsize);
747 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
750 return JB_ERR_MEMORY;
754 char *oldnext_out = (char *)zstr.next_out;
757 * Update the fields for inflate() to use the new
758 * buffer, which may be in a location different from
761 zstr.avail_out += (uInt)(bufsize - oldbufsize);
762 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
765 * Compare with an uglier method of calculating these values
766 * that doesn't require the extra oldbufsize variable.
768 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
769 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
775 if (Z_STREAM_ERROR == inflateEnd(&zstr))
777 log_error(LOG_LEVEL_ERROR,
778 "Inconsistent stream state after decompression: %s", zstr.msg);
780 * XXX: Intentionally no return.
782 * According to zlib.h, Z_STREAM_ERROR is returned
783 * "if the stream state was inconsistent".
785 * I assume in this case inflate()'s status
786 * would also be something different than Z_STREAM_END
787 * so this check should be redundant, but lets see.
791 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
794 * We failed to decompress the stream and it's
795 * not simply because of missing data.
797 log_error(LOG_LEVEL_ERROR,
798 "Unexpected error while decompressing to the buffer (iob): %s",
800 return JB_ERR_COMPRESS;
804 * Finally, we can actually update the iob, since the
805 * decompression was successful. First, free the old
808 freez(csp->iob->buf);
810 /* Now, update the iob to use the new buffer. */
812 csp->iob->cur = csp->iob->buf + skip_size;
813 csp->iob->eod = (char *)zstr.next_out;
814 csp->iob->size = bufsize;
817 * Make sure the new uncompressed iob obeys some minimal
818 * consistency conditions.
820 if ((csp->iob->buf <= csp->iob->cur)
821 && (csp->iob->cur <= csp->iob->eod)
822 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
824 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
825 if (new_size > (size_t)0)
827 log_error(LOG_LEVEL_RE_FILTER,
828 "Decompression successful. Old size: %lu, new size: %lu.",
833 /* zlib thinks this is OK, so let's do the same. */
834 log_error(LOG_LEVEL_RE_FILTER,
835 "Decompression didn't result in any content.");
840 /* It seems that zlib did something weird. */
841 log_error(LOG_LEVEL_ERROR, "Inconsistent buffer after decompression");
842 return JB_ERR_COMPRESS;
848 #endif /* defined(FEATURE_ZLIB) */
851 /*********************************************************************
853 * Function : normalize_lws
855 * Description : Reduces unquoted linear whitespace in headers to
856 * a single space in accordance with RFC 7230 3.2.4.
857 * This simplifies parsing and filtering later on.
860 * 1 : header = A header with linear whitespace to reduce.
864 *********************************************************************/
865 static void normalize_lws(char *header)
871 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
875 while (privoxy_isspace(*q))
879 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
885 log_error(LOG_LEVEL_HEADER,
886 "Converting tab to space in '%s'", header);
891 char *end_of_token = strstr(p+1, "\"");
893 if (NULL != end_of_token)
895 /* Don't mess with quoted text. */
900 log_error(LOG_LEVEL_HEADER,
901 "Ignoring single quote in '%s'", header);
907 p = strchr(header, ':');
908 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
911 * There's still space before the colon.
919 /*********************************************************************
921 * Function : get_header
923 * Description : This (odd) routine will parse the csp->iob
924 * to get the next complete header.
927 * 1 : iob = The I/O buffer to parse, usually csp->iob.
929 * Returns : Any one of the following:
931 * 1) a pointer to a dynamically allocated string that contains a header line
932 * 2) NULL indicating that the end of the header was reached
933 * 3) "" indicating that the end of the iob was reached before finding
934 * a complete header line.
936 *********************************************************************/
937 char *get_header(struct iob *iob)
941 header = get_header_line(iob);
943 if ((header == NULL) || (*header == '\0'))
946 * No complete header read yet, tell the client.
951 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
954 * Header spans multiple lines, append the next one.
956 char *continued_header;
958 continued_header = get_header_line(iob);
959 if ((continued_header == NULL) || (*continued_header == '\0'))
962 * No complete header read yet, return what we got.
963 * XXX: Should "unread" header instead.
965 log_error(LOG_LEVEL_INFO,
966 "Failed to read a multi-line header properly: '%s'",
971 if (JB_ERR_OK != string_join(&header, continued_header))
973 log_error(LOG_LEVEL_FATAL,
974 "Out of memory while appending multiple headers.");
978 /* XXX: remove before next stable release. */
979 log_error(LOG_LEVEL_HEADER,
980 "Merged multiple header lines to: '%s'",
985 normalize_lws(header);
992 /*********************************************************************
994 * Function : get_header_line
996 * Description : This (odd) routine will parse the csp->iob
997 * to get the next header line.
1000 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1002 * Returns : Any one of the following:
1004 * 1) a pointer to a dynamically allocated string that contains a header line
1005 * 2) NULL indicating that the end of the header was reached
1006 * 3) "" indicating that the end of the iob was reached before finding
1007 * a complete header line.
1009 *********************************************************************/
1010 static char *get_header_line(struct iob *iob)
1014 if ((iob->cur == NULL)
1015 || ((p = strchr(iob->cur, '\n')) == NULL))
1017 return(""); /* couldn't find a complete header */
1022 ret = strdup(iob->cur);
1025 /* FIXME No way to handle error properly */
1026 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1028 assert(ret != NULL);
1032 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1034 /* is this a blank line (i.e. the end of the header) ? */
1046 /*********************************************************************
1048 * Function : get_header_value
1050 * Description : Get the value of a given header from a chained list
1051 * of header lines or return NULL if no such header is
1052 * present in the list.
1055 * 1 : header_list = pointer to list
1056 * 2 : header_name = string with name of header to look for.
1057 * Trailing colon required, capitalization
1060 * Returns : NULL if not found, else value of header
1062 *********************************************************************/
1063 char *get_header_value(const struct list *header_list, const char *header_name)
1065 struct list_entry *cur_entry;
1069 assert(header_list);
1070 assert(header_name);
1071 length = strlen(header_name);
1073 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1077 if (!strncmpic(cur_entry->str, header_name, length))
1080 * Found: return pointer to start of value
1082 ret = cur_entry->str + length;
1083 while (*ret && privoxy_isspace(*ret)) ret++;
1097 /*********************************************************************
1099 * Function : scan_headers
1101 * Description : Scans headers, applies tags and updates action bits.
1104 * 1 : csp = Current client state (buffers, headers, etc...)
1106 * Returns : JB_ERR_OK
1108 *********************************************************************/
1109 static jb_err scan_headers(struct client_state *csp)
1111 struct list_entry *h; /* Header */
1112 jb_err err = JB_ERR_OK;
1114 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1116 /* Header crunch()ed in previous run? -> ignore */
1117 if (h->str == NULL) continue;
1118 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1119 err = header_tagger(csp, h->str);
1126 /*********************************************************************
1128 * Function : enforce_header_order
1130 * Description : Enforces a given header order.
1133 * 1 : headers = List of headers to order.
1134 * 2 : ordered_headers = List of ordered header names.
1138 *********************************************************************/
1139 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1141 struct list_entry *sorted_header;
1142 struct list new_headers[1];
1143 struct list_entry *header;
1145 init_list(new_headers);
1147 /* The request line is always the first "header" */
1149 assert(NULL != headers->first->str);
1150 enlist(new_headers, headers->first->str);
1151 freez(headers->first->str)
1153 /* Enlist the specified headers in the given order */
1155 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1156 sorted_header = sorted_header->next)
1158 const size_t sorted_header_length = strlen(sorted_header->str);
1159 for (header = headers->first; header != NULL; header = header->next)
1161 /* Header enlisted in previous run? -> ignore */
1162 if (header->str == NULL) continue;
1164 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1165 && (header->str[sorted_header_length] == ':'))
1167 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1168 if (JB_ERR_OK != enlist(new_headers, header->str))
1170 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1177 /* Enlist the rest of the headers behind the ordered ones */
1178 for (header = headers->first; header != NULL; header = header->next)
1180 /* Header enlisted in previous run? -> ignore */
1181 if (header->str == NULL) continue;
1183 log_error(LOG_LEVEL_HEADER,
1184 "Enlisting left-over header %s", header->str);
1185 if (JB_ERR_OK != enlist(new_headers, header->str))
1187 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1192 list_remove_all(headers);
1193 list_duplicate(headers, new_headers);
1194 list_remove_all(new_headers);
1200 /*********************************************************************
1204 * Description : add, delete or modify lines in the HTTP header streams.
1205 * On entry, it receives a linked list of headers space
1206 * that was allocated dynamically (both the list nodes
1207 * and the header contents).
1209 * As a side effect it frees the space used by the original
1213 * 1 : csp = Current client state (buffers, headers, etc...)
1214 * 2 : filter_server_headers = Boolean to switch between
1215 * server and header filtering.
1217 * Returns : JB_ERR_OK in case off success, or
1218 * JB_ERR_MEMORY on some out-of-memory errors, or
1219 * JB_ERR_PARSE in case of fatal parse errors.
1221 *********************************************************************/
1222 jb_err sed(struct client_state *csp, int filter_server_headers)
1224 /* XXX: use more descriptive names. */
1225 struct list_entry *p;
1226 const struct parsers *v;
1227 const add_header_func_ptr *f;
1228 jb_err err = JB_ERR_OK;
1232 if (filter_server_headers)
1234 v = server_patterns;
1235 f = add_server_headers;
1236 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1240 v = client_patterns;
1241 f = add_client_headers;
1242 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1245 while (v->str != NULL)
1247 for (p = csp->headers->first; p != NULL; p = p->next)
1249 /* Header crunch()ed in previous run? -> ignore */
1250 if (p->str == NULL) continue;
1252 /* Does the current parser handle this header? */
1253 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1254 (v->len == CHECK_EVERY_HEADER_REMAINING))
1256 err = v->parser(csp, &(p->str));
1257 if (err != JB_ERR_OK)
1266 /* place additional headers on the csp->headers list */
1267 while ((err == JB_ERR_OK) && (*f))
1273 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1275 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1282 #ifdef FEATURE_HTTPS_INSPECTION
1283 /*********************************************************************
1285 * Function : sed_https
1287 * Description : add, delete or modify lines in the HTTPS client
1288 * header streams. Wrapper around sed().
1291 * 1 : csp = Current client state (buffers, headers, etc...)
1293 * Returns : JB_ERR_OK in case off success, or
1294 * JB_ERR_MEMORY on some out-of-memory errors, or
1295 * JB_ERR_PARSE in case of fatal parse errors.
1297 *********************************************************************/
1298 jb_err sed_https(struct client_state *csp)
1301 struct list headers;
1304 * Temporarily replace csp->headers with csp->https_headers
1305 * to trick sed() into filtering the https headers.
1307 headers.first = csp->headers->first;
1308 headers.last = csp->headers->last;
1309 csp->headers->first = csp->https_headers->first;
1310 csp->headers->last = csp->https_headers->last;
1313 * Start with fresh tags. Already existing tags may
1314 * be set again. This is necessary to overrule
1315 * URL-based patterns.
1317 destroy_list(csp->tags);
1320 * We want client header filters and taggers
1321 * so temporarily remove the flag.
1323 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1324 err = sed(csp, FILTER_CLIENT_HEADERS);
1325 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1328 * Update the last header which may have changed
1329 * due to header additions,
1331 csp->https_headers->last = csp->headers->last;
1333 csp->headers->first = headers.first;
1334 csp->headers->last = headers.last;
1338 #endif /* def FEATURE_HTTPS_INSPECTION */
1341 /*********************************************************************
1343 * Function : update_server_headers
1345 * Description : Updates server headers after the body has been modified.
1348 * 1 : csp = Current client state (buffers, headers, etc...)
1350 * Returns : JB_ERR_OK in case off success, or
1351 * JB_ERR_MEMORY on out-of-memory error.
1353 *********************************************************************/
1354 jb_err update_server_headers(struct client_state *csp)
1356 jb_err err = JB_ERR_OK;
1358 static const struct parsers server_patterns_light[] = {
1359 { "Content-Length:", 15, server_adjust_content_length },
1360 { "Transfer-Encoding:", 18, server_transfer_coding },
1362 { "Content-Encoding:", 17, server_adjust_content_encoding },
1363 #endif /* def FEATURE_ZLIB */
1367 if (strncmpic(csp->http->cmd, "HEAD", 4))
1369 const struct parsers *v;
1370 struct list_entry *p;
1372 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1374 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1376 /* Header crunch()ed in previous run? -> ignore */
1377 if (p->str == NULL) continue;
1379 /* Does the current parser handle this header? */
1380 if (strncmpic(p->str, v->str, v->len) == 0)
1382 err = v->parser(csp, (char **)&(p->str));
1388 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1389 if ((JB_ERR_OK == err)
1390 && (csp->flags & CSP_FLAG_MODIFIED)
1391 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1392 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1396 create_content_length_header(csp->content_length, header, sizeof(header));
1397 err = enlist(csp->headers, header);
1398 if (JB_ERR_OK == err)
1400 log_error(LOG_LEVEL_HEADER,
1401 "Content modified with no Content-Length header set. "
1402 "Created: %s.", header);
1403 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1406 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1408 #ifdef FEATURE_COMPRESSION
1409 if ((JB_ERR_OK == err)
1410 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1412 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1413 if (JB_ERR_OK == err)
1415 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1424 /*********************************************************************
1426 * Function : header_tagger
1428 * Description : Executes all text substitutions from applying
1429 * tag actions and saves the result as tag.
1431 * XXX: Shares enough code with filter_header() and
1432 * pcrs_filter_response() to warrant some helper functions.
1435 * 1 : csp = Current client state (buffers, headers, etc...)
1436 * 2 : header = Header that is used as tagger input
1438 * Returns : JB_ERR_OK on success and always succeeds
1440 *********************************************************************/
1441 static jb_err header_tagger(struct client_state *csp, char *header)
1443 enum filter_type wanted_filter_type;
1444 int multi_action_index;
1447 struct re_filterfile_spec *b;
1448 struct list_entry *tag_name;
1450 const size_t header_length = strlen(header);
1452 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1454 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1455 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1459 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1460 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1463 if (list_is_empty(csp->action->multi[multi_action_index])
1464 || filters_available(csp) == FALSE)
1466 /* Return early if no taggers apply or if none are available. */
1470 /* Execute all applying taggers */
1471 for (tag_name = csp->action->multi[multi_action_index]->first;
1472 NULL != tag_name; tag_name = tag_name->next)
1474 char *modified_tag = NULL;
1476 size_t size = header_length;
1479 b = get_filter(csp, tag_name->str, wanted_filter_type);
1485 joblist = b->joblist;
1487 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1489 if (NULL == joblist)
1491 log_error(LOG_LEVEL_RE_FILTER,
1492 "Tagger %s has empty joblist. Nothing to do.", b->name);
1496 /* execute their pcrs_joblist on the header. */
1497 for (job = joblist; NULL != job; job = job->next)
1499 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1503 /* Success, continue with the modified version. */
1512 /* Tagger doesn't match */
1515 /* Regex failure, log it but continue anyway. */
1516 assert(NULL != header);
1517 log_error(LOG_LEVEL_ERROR,
1518 "Problems with tagger \'%s\' and header \'%s\': %s",
1519 b->name, header, pcrs_strerror(hits));
1521 freez(modified_tag);
1525 if (b->dynamic) pcrs_free_joblist(joblist);
1527 /* If this tagger matched */
1533 * There is no technical limitation which makes
1534 * it impossible to use empty tags, but I assume
1535 * no one would do it intentionally.
1538 log_error(LOG_LEVEL_INFO,
1539 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1543 if (!list_contains_item(csp->tags, tag))
1545 if (JB_ERR_OK != enlist(csp->tags, tag))
1547 log_error(LOG_LEVEL_ERROR,
1548 "Insufficient memory to add tag \'%s\', "
1549 "based on tagger \'%s\' and header \'%s\'",
1550 tag, b->name, header);
1554 char *action_message;
1556 * update the action bits right away, to make
1557 * tagging based on tags set by earlier taggers
1558 * of the same kind possible.
1560 if (update_action_bits_for_tag(csp, tag))
1562 action_message = "Action bits updated accordingly.";
1566 action_message = "No action bits update necessary.";
1569 log_error(LOG_LEVEL_HEADER,
1570 "Tagger \'%s\' added tag \'%s\'. %s",
1571 b->name, tag, action_message);
1576 /* XXX: Is this log-worthy? */
1577 log_error(LOG_LEVEL_HEADER,
1578 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1588 /* here begins the family of parser functions that reformat header lines */
1590 /*********************************************************************
1592 * Function : filter_header
1594 * Description : Executes all text substitutions from all applying
1595 * +(server|client)-header-filter actions on the header.
1596 * Most of the code was copied from pcrs_filter_response,
1597 * including the rather short variable names
1600 * 1 : csp = Current client state (buffers, headers, etc...)
1601 * 2 : header = On input, pointer to header to modify.
1602 * On output, pointer to the modified header, or NULL
1603 * to remove the header. This function frees the
1604 * original string if necessary.
1606 * Returns : JB_ERR_OK on success and always succeeds
1608 *********************************************************************/
1609 static jb_err filter_header(struct client_state *csp, char **header)
1613 size_t size = strlen(*header);
1615 char *newheader = NULL;
1618 struct re_filterfile_spec *b;
1619 struct list_entry *filtername;
1621 enum filter_type wanted_filter_type;
1622 int multi_action_index;
1624 if (csp->flags & CSP_FLAG_NO_FILTERING)
1629 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1631 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1632 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1636 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1637 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1640 if (list_is_empty(csp->action->multi[multi_action_index])
1641 || filters_available(csp) == FALSE)
1643 /* Return early if no filters apply or if none are available. */
1647 /* Execute all applying header filters */
1648 for (filtername = csp->action->multi[multi_action_index]->first;
1649 filtername != NULL; filtername = filtername->next)
1651 int current_hits = 0;
1654 b = get_filter(csp, filtername->str, wanted_filter_type);
1660 joblist = b->joblist;
1662 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1664 if (NULL == joblist)
1666 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1670 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %lu) with \'%s\' ...",
1671 *header, size, b->name);
1673 /* Apply all jobs from the joblist */
1674 for (job = joblist; NULL != job; job = job->next)
1676 matches = pcrs_execute(job, *header, size, &newheader, &size);
1679 current_hits += matches;
1680 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1682 *header = newheader;
1684 else if (0 == matches)
1686 /* Filter doesn't change header */
1692 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1693 *header, b->name, pcrs_strerror(matches));
1694 if (newheader != NULL)
1696 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1702 if (b->dynamic) pcrs_free_joblist(joblist);
1704 log_error(LOG_LEVEL_RE_FILTER,
1705 "... produced %d hits (new size %lu).", current_hits, size);
1706 hits += current_hits;
1710 * Additionally checking for hits is important because if
1711 * the continue hack is triggered, server headers can
1712 * arrive empty to separate multiple heads from each other.
1714 if ((0 == size) && hits)
1716 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1724 /*********************************************************************
1726 * Function : server_connection
1728 * Description : Makes sure a proper "Connection:" header is
1729 * set and signals connection_header_adder to
1733 * 1 : csp = Current client state (buffers, headers, etc...)
1734 * 2 : header = On input, pointer to header to modify.
1735 * On output, pointer to the modified header, or NULL
1736 * to remove the header. This function frees the
1737 * original string if necessary.
1739 * Returns : JB_ERR_OK on success.
1741 *********************************************************************/
1742 static jb_err server_connection(struct client_state *csp, char **header)
1744 if (!strcmpic(*header, "Connection: keep-alive")
1745 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1746 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1750 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1751 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1753 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1756 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1758 log_error(LOG_LEVEL_HEADER,
1759 "Keeping the server header '%s' around.", *header);
1762 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1764 char *old_header = *header;
1766 *header = strdup_or_die("Connection: close");
1767 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1772 /* Signal server_connection_adder() to return early. */
1773 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1779 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1780 /*********************************************************************
1782 * Function : server_keep_alive
1784 * Description : Stores the server's keep alive timeout.
1787 * 1 : csp = Current client state (buffers, headers, etc...)
1788 * 2 : header = On input, pointer to header to modify.
1789 * On output, pointer to the modified header, or NULL
1790 * to remove the header. This function frees the
1791 * original string if necessary.
1793 * Returns : JB_ERR_OK.
1795 *********************************************************************/
1796 static jb_err server_keep_alive(struct client_state *csp, char **header)
1798 unsigned int keep_alive_timeout;
1799 const char *timeout_position = strstr(*header, "timeout=");
1801 if ((NULL == timeout_position)
1802 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1804 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1808 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1810 log_error(LOG_LEVEL_HEADER,
1811 "Reducing keep-alive timeout from %u to %u.",
1812 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1813 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1817 /* XXX: Is this log worthy? */
1818 log_error(LOG_LEVEL_HEADER,
1819 "Server keep-alive timeout is %u. Sticking with %u.",
1820 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1822 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1831 /*********************************************************************
1833 * Function : server_proxy_connection
1835 * Description : Figures out whether or not we should add a
1836 * Proxy-Connection header.
1839 * 1 : csp = Current client state (buffers, headers, etc...)
1840 * 2 : header = On input, pointer to header to modify.
1841 * On output, pointer to the modified header, or NULL
1842 * to remove the header. This function frees the
1843 * original string if necessary.
1845 * Returns : JB_ERR_OK.
1847 *********************************************************************/
1848 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1850 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1853 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1856 /*********************************************************************
1858 * Function : proxy_authentication
1860 * Description : Removes headers that are relevant for proxy
1861 * authentication unless forwarding them has
1862 * been explicitly requested.
1865 * 1 : csp = Current client state (buffers, headers, etc...)
1866 * 2 : header = On input, pointer to header to modify.
1867 * On output, pointer to the modified header, or NULL
1868 * to remove the header. This function frees the
1869 * original string if necessary.
1871 * Returns : JB_ERR_OK.
1873 *********************************************************************/
1874 static jb_err proxy_authentication(struct client_state *csp, char **header)
1876 if ((csp->config->feature_flags &
1877 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1878 log_error(LOG_LEVEL_HEADER,
1879 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1886 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1887 /*********************************************************************
1889 * Function : client_keep_alive
1891 * Description : Stores the client's keep alive timeout.
1894 * 1 : csp = Current client state (buffers, headers, etc...)
1895 * 2 : header = On input, pointer to header to modify.
1896 * On output, pointer to the modified header, or NULL
1897 * to remove the header. This function frees the
1898 * original string if necessary.
1900 * Returns : JB_ERR_OK.
1902 *********************************************************************/
1903 static jb_err client_keep_alive(struct client_state *csp, char **header)
1905 unsigned int keep_alive_timeout;
1906 char *timeout_position;
1908 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1910 log_error(LOG_LEVEL_HEADER,
1911 "keep-alive support is disabled. Crunching: %s.", *header);
1916 /* Check for parameter-less format "Keep-Alive: 100" */
1917 timeout_position = strstr(*header, ": ");
1918 if ((NULL == timeout_position)
1919 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1921 /* Assume parameter format "Keep-Alive: timeout=100" */
1922 timeout_position = strstr(*header, "timeout=");
1923 if ((NULL == timeout_position)
1924 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1926 log_error(LOG_LEVEL_HEADER,
1927 "Couldn't parse: '%s'. Using default timeout %u",
1928 *header, csp->config->keep_alive_timeout);
1935 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1937 log_error(LOG_LEVEL_HEADER,
1938 "Reducing keep-alive timeout from %u to %u.",
1939 csp->config->keep_alive_timeout, keep_alive_timeout);
1940 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1944 /* XXX: Is this log worthy? */
1945 log_error(LOG_LEVEL_HEADER,
1946 "Client keep-alive timeout is %u. Sticking with %u.",
1947 keep_alive_timeout, csp->config->keep_alive_timeout);
1953 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1956 /*********************************************************************
1958 * Function : get_content_length
1960 * Description : Gets the content length specified in a
1961 * Content-Length header.
1964 * 1 : header_value = The Content-Length header value.
1965 * 2 : length = Storage to return the value.
1967 * Returns : JB_ERR_OK on success, or
1968 * JB_ERR_PARSE if no value is recognized.
1970 *********************************************************************/
1971 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1974 #if SIZEOF_LONG_LONG < 8
1975 #error sizeof(unsigned long long) too small
1977 if (1 != sscanf(header_value, "%I64u", length))
1979 if (1 != sscanf(header_value, "%llu", length))
1982 return JB_ERR_PARSE;
1989 /*********************************************************************
1991 * Function : client_save_content_length
1993 * Description : Save the Content-Length sent by the client.
1996 * 1 : csp = Current client state (buffers, headers, etc...)
1997 * 2 : header = On input, pointer to header to modify.
1998 * On output, pointer to the modified header, or NULL
1999 * to remove the header. This function frees the
2000 * original string if necessary.
2002 * Returns : JB_ERR_OK on success, or
2003 * JB_ERR_MEMORY on out-of-memory error.
2005 *********************************************************************/
2006 static jb_err client_save_content_length(struct client_state *csp, char **header)
2008 unsigned long long content_length = 0;
2009 const char *header_value;
2011 assert(*(*header+14) == ':');
2013 header_value = *header + 15;
2014 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2016 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2021 csp->expected_client_content_length = content_length;
2028 /*********************************************************************
2030 * Function : client_connection
2032 * Description : Makes sure a proper "Connection:" header is
2033 * set and signals connection_header_adder
2037 * 1 : csp = Current client state (buffers, headers, etc...)
2038 * 2 : header = On input, pointer to header to modify.
2039 * On output, pointer to the modified header, or NULL
2040 * to remove the header. This function frees the
2041 * original string if necessary.
2043 * Returns : JB_ERR_OK on success.
2045 *********************************************************************/
2046 static jb_err client_connection(struct client_state *csp, char **header)
2048 static const char connection_close[] = "Connection: close";
2050 if (!strcmpic(*header, connection_close))
2052 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2053 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2054 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2055 #ifdef FEATURE_HTTPS_INSPECTION
2056 && !client_use_ssl(csp)
2060 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2062 log_error(LOG_LEVEL_HEADER,
2063 "Removing \'%s\' to imply keep-alive.", *header);
2066 * While we imply keep-alive to the server,
2067 * we have to remember that the client didn't.
2069 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2073 char *old_header = *header;
2075 *header = strdup_or_die("Connection: keep-alive");
2076 log_error(LOG_LEVEL_HEADER,
2077 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2083 log_error(LOG_LEVEL_HEADER,
2084 "Keeping the client header '%s' around. "
2085 "The connection will not be kept alive.",
2087 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2090 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2091 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2093 log_error(LOG_LEVEL_HEADER,
2094 "Keeping the client header '%s' around. "
2095 "The server connection will be kept alive if possible.",
2097 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2098 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2102 char *old_header = *header;
2104 *header = strdup_or_die(connection_close);
2105 log_error(LOG_LEVEL_HEADER,
2106 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2110 /* Signal client_connection_header_adder() to return early. */
2111 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2117 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2118 /*********************************************************************
2120 * Function : client_proxy_connection
2122 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2123 * appropriate and removes the Proxy-Connection
2127 * 1 : csp = Current client state (buffers, headers, etc...)
2128 * 2 : header = On input, pointer to header to modify.
2129 * On output, pointer to the modified header, or NULL
2130 * to remove the header. This function frees the
2131 * original string if necessary.
2133 * Returns : JB_ERR_OK
2135 *********************************************************************/
2136 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2138 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2139 && (csp->http->ssl == 0)
2140 && (NULL == strstr(*header, "close")))
2142 log_error(LOG_LEVEL_HEADER,
2143 "The client connection can be kept alive due to: %s", *header);
2144 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2146 crumble(csp, header);
2150 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2153 /*********************************************************************
2155 * Function : client_transfer_encoding
2157 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2158 * the request body is "chunked"
2160 * XXX: Currently not called through sed() as we
2161 * need the flag earlier on. Should be fixed.
2164 * 1 : csp = Current client state (buffers, headers, etc...)
2165 * 2 : header = On input, pointer to header to modify.
2166 * On output, pointer to the modified header, or NULL
2167 * to remove the header. This function frees the
2168 * original string if necessary.
2170 * Returns : JB_ERR_OK on success, or
2172 *********************************************************************/
2173 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2175 if (strstr(*header, "chunked"))
2177 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2178 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2185 /*********************************************************************
2187 * Function : client_expect
2189 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2190 * if the Expect header value is unsupported.
2192 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2193 * MAY and a RFC 2616 (obsolete) MUST.
2196 * 1 : csp = Current client state (buffers, headers, etc...)
2197 * 2 : header = On input, pointer to header to modify.
2198 * On output, pointer to the modified header, or NULL
2199 * to remove the header. This function frees the
2200 * original string if necessary.
2202 * Returns : JB_ERR_OK on success, or
2204 *********************************************************************/
2205 jb_err client_expect(struct client_state *csp, char **header)
2207 if (0 != strcmpic(*header, "Expect: 100-continue"))
2209 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2210 log_error(LOG_LEVEL_HEADER,
2211 "Unsupported client expectaction: %s", *header);
2219 /*********************************************************************
2221 * Function : crumble
2223 * Description : This is called if a header matches a pattern to "crunch"
2226 * 1 : csp = Current client state (buffers, headers, etc...)
2227 * 2 : header = On input, pointer to header to modify.
2228 * On output, pointer to the modified header, or NULL
2229 * to remove the header. This function frees the
2230 * original string if necessary.
2232 * Returns : JB_ERR_OK on success, or
2233 * JB_ERR_MEMORY on out-of-memory error.
2235 *********************************************************************/
2236 static jb_err crumble(struct client_state *csp, char **header)
2239 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2245 /*********************************************************************
2247 * Function : crunch_server_header
2249 * Description : Crunch server header if it matches a string supplied by the
2250 * user. Called from `sed'.
2253 * 1 : csp = Current client state (buffers, headers, etc...)
2254 * 2 : header = On input, pointer to header to modify.
2255 * On output, pointer to the modified header, or NULL
2256 * to remove the header. This function frees the
2257 * original string if necessary.
2259 * Returns : JB_ERR_OK on success and always succeeds
2261 *********************************************************************/
2262 static jb_err crunch_server_header(struct client_state *csp, char **header)
2264 const char *crunch_pattern;
2266 /* Do we feel like crunching? */
2267 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2269 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2271 /* Is the current header the lucky one? */
2272 if (strstr(*header, crunch_pattern))
2274 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2283 /*********************************************************************
2285 * Function : server_content_type
2287 * Description : Set the content-type for filterable types (text/.*,
2288 * .*xml.*, .*script.* and image/gif) unless filtering has been
2289 * forbidden (CT_TABOO) while parsing earlier headers.
2290 * NOTE: Since text/plain is commonly used by web servers
2291 * for files whose correct type is unknown, we don't
2292 * set CT_TEXT for it.
2295 * 1 : csp = Current client state (buffers, headers, etc...)
2296 * 2 : header = On input, pointer to header to modify.
2297 * On output, pointer to the modified header, or NULL
2298 * to remove the header. This function frees the
2299 * original string if necessary.
2301 * Returns : JB_ERR_OK on success, or
2302 * JB_ERR_MEMORY on out-of-memory error.
2304 *********************************************************************/
2305 static jb_err server_content_type(struct client_state *csp, char **header)
2307 /* Remove header if it isn't the first Content-Type header */
2308 if ((csp->content_type & CT_DECLARED))
2310 if (content_filters_enabled(csp->action))
2313 * Making sure the client interprets the content the same way
2314 * Privoxy did is only relevant if Privoxy modified it.
2316 * Checking for this is "hard" as it's not yet known when
2317 * this function is called, thus go shopping and and just
2318 * check if Privoxy could filter it.
2320 * The main thing is that we don't mess with the headers
2321 * unless the user signalled that it's acceptable.
2323 log_error(LOG_LEVEL_HEADER,
2324 "Multiple Content-Type headers detected. "
2325 "Removing and ignoring: %s",
2333 * Signal that the Content-Type has been set.
2335 csp->content_type |= CT_DECLARED;
2337 if (!(csp->content_type & CT_TABOO))
2340 * XXX: The assumption that text/plain is a sign of
2341 * binary data seems to be somewhat unreasonable nowadays
2342 * and should be dropped after 3.0.8 is out.
2344 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2345 || strstr(*header, "xml")
2346 || strstr(*header, "script"))
2348 csp->content_type |= CT_TEXT;
2350 else if (strstr(*header, "image/gif"))
2352 csp->content_type |= CT_GIF;
2357 * Are we messing with the content type?
2359 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2362 * Make sure the user doesn't accidentally
2363 * change the content type of binary documents.
2365 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2369 *header = strdup_or_die("Content-Type: ");
2371 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2372 if (JB_ERR_OK != err)
2374 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2375 return JB_ERR_MEMORY;
2377 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2381 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2382 "It doesn't look like a content type that should be filtered. "
2383 "Enable force-text-mode if you know what you're doing.", *header);
2391 /*********************************************************************
2393 * Function : server_transfer_coding
2395 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2396 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2397 * - Remove header if body was chunked but has been
2398 * de-chunked for filtering.
2401 * 1 : csp = Current client state (buffers, headers, etc...)
2402 * 2 : header = On input, pointer to header to modify.
2403 * On output, pointer to the modified header, or NULL
2404 * to remove the header. This function frees the
2405 * original string if necessary.
2407 * Returns : JB_ERR_OK on success, or
2408 * JB_ERR_MEMORY on out-of-memory error.
2410 *********************************************************************/
2411 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2414 * Turn off pcrs and gif filtering if body compressed
2416 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2420 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2422 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2423 csp->http->cmd, *header);
2424 #endif /* def FEATURE_ZLIB */
2425 csp->content_type = CT_TABOO;
2429 * Raise flag if body chunked
2431 if (strstr(*header, "chunked"))
2433 csp->flags |= CSP_FLAG_CHUNKED;
2436 * If the body was modified, it has been de-chunked first
2437 * and the header must be removed.
2439 * FIXME: If there is more than one transfer encoding,
2440 * only the "chunked" part should be removed here.
2442 if (csp->flags & CSP_FLAG_MODIFIED)
2444 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2453 /*********************************************************************
2455 * Function : server_content_encoding
2457 * Description : Used to check if the content is compressed, and if
2458 * FEATURE_ZLIB is disabled, filtering is disabled as
2461 * If FEATURE_ZLIB is enabled and the compression type
2462 * supported, the content is marked for decompression.
2464 * XXX: Doesn't properly deal with multiple or with
2465 * unsupported but unknown encodings.
2466 * Is case-sensitive but shouldn't be.
2469 * 1 : csp = Current client state (buffers, headers, etc...)
2470 * 2 : header = On input, pointer to header to modify.
2471 * On output, pointer to the modified header, or NULL
2472 * to remove the header. This function frees the
2473 * original string if necessary.
2475 * Returns : JB_ERR_OK on success, or
2476 * JB_ERR_MEMORY on out-of-memory error.
2478 *********************************************************************/
2479 static jb_err server_content_encoding(struct client_state *csp, char **header)
2482 if (strstr(*header, "sdch"))
2485 * Shared Dictionary Compression over HTTP isn't supported,
2486 * filtering it anyway is pretty much guaranteed to mess up
2489 csp->content_type |= CT_TABOO;
2492 * Log a warning if the user expects the content to be filtered.
2494 if (content_filters_enabled(csp->action))
2496 log_error(LOG_LEVEL_INFO,
2497 "SDCH-compressed content detected, content filtering disabled. "
2498 "Consider suppressing SDCH offers made by the client.");
2501 else if (strstr(*header, "gzip"))
2503 /* Mark for gzip decompression */
2504 csp->content_type |= CT_GZIP;
2506 else if (strstr(*header, "deflate"))
2508 /* Mark for zlib decompression */
2509 csp->content_type |= CT_DEFLATE;
2511 else if (strstr(*header, "br"))
2513 #ifdef FEATURE_BROTLI
2514 /* Mark for Brotli decompression */
2515 csp->content_type |= CT_BROTLI;
2517 csp->content_type |= CT_TABOO;
2520 else if (strstr(*header, "compress"))
2523 * We can't decompress this; therefore we can't filter
2526 csp->content_type |= CT_TABOO;
2528 #else /* !defined(FEATURE_ZLIB) */
2530 * XXX: Using a black list here isn't the right approach.
2532 * In case of SDCH, building with zlib support isn't
2535 if (strstr(*header, "gzip") ||
2536 strstr(*header, "compress") ||
2537 strstr(*header, "deflate") ||
2538 strstr(*header, "sdch"))
2541 * Body is compressed, turn off pcrs and gif filtering.
2543 csp->content_type |= CT_TABOO;
2546 * Log a warning if the user expects the content to be filtered.
2548 if (content_filters_enabled(csp->action))
2550 log_error(LOG_LEVEL_INFO,
2551 "Compressed content detected, content filtering disabled. "
2552 "Consider recompiling Privoxy with zlib support or "
2553 "enable the prevent-compression action.");
2556 #endif /* defined(FEATURE_ZLIB) */
2564 /*********************************************************************
2566 * Function : server_adjust_content_encoding
2568 * Description : Remove the Content-Encoding header if the
2569 * decompression was successful and the content
2570 * has been modified.
2573 * 1 : csp = Current client state (buffers, headers, etc...)
2574 * 2 : header = On input, pointer to header to modify.
2575 * On output, pointer to the modified header, or NULL
2576 * to remove the header. This function frees the
2577 * original string if necessary.
2579 * Returns : JB_ERR_OK on success, or
2580 * JB_ERR_MEMORY on out-of-memory error.
2582 *********************************************************************/
2583 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2585 if ((csp->flags & CSP_FLAG_MODIFIED)
2586 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2587 #ifdef FEATURE_BROTLI
2588 || (csp->content_type & CT_BROTLI)
2594 * We successfully decompressed the content,
2595 * and have to clean the header now, so the
2596 * client no longer expects compressed data.
2598 * XXX: There is a difference between cleaning
2599 * and removing it completely.
2601 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2608 #endif /* defined(FEATURE_ZLIB) */
2611 /*********************************************************************
2613 * Function : server_adjust_content_length
2615 * Description : Adjust Content-Length header if we modified
2619 * 1 : csp = Current client state (buffers, headers, etc...)
2620 * 2 : header = On input, pointer to header to modify.
2621 * On output, pointer to the modified header, or NULL
2622 * to remove the header. This function frees the
2623 * original string if necessary.
2625 * Returns : JB_ERR_OK on success, or
2626 * JB_ERR_MEMORY on out-of-memory error.
2628 *********************************************************************/
2629 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2631 /* Regenerate header if the content was modified. */
2632 if (csp->flags & CSP_FLAG_MODIFIED)
2634 const size_t header_length = 50;
2636 *header = malloc(header_length);
2637 if (*header == NULL)
2639 return JB_ERR_MEMORY;
2641 create_content_length_header(csp->content_length, *header, header_length);
2642 log_error(LOG_LEVEL_HEADER,
2643 "Adjusted Content-Length to %llu", csp->content_length);
2650 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2651 /*********************************************************************
2653 * Function : server_save_content_length
2655 * Description : Save the Content-Length sent by the server.
2658 * 1 : csp = Current client state (buffers, headers, etc...)
2659 * 2 : header = On input, pointer to header to modify.
2660 * On output, pointer to the modified header, or NULL
2661 * to remove the header. This function frees the
2662 * original string if necessary.
2664 * Returns : JB_ERR_OK on success, or
2665 * JB_ERR_MEMORY on out-of-memory error.
2667 *********************************************************************/
2668 static jb_err server_save_content_length(struct client_state *csp, char **header)
2670 unsigned long long content_length = 0;
2671 const char *header_value;
2673 assert(*(*header+14) == ':');
2675 header_value = *header + 15;
2676 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2678 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2683 csp->expected_content_length = content_length;
2684 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2685 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2690 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2693 /*********************************************************************
2695 * Function : server_content_md5
2697 * Description : Crumble any Content-MD5 headers if the document was
2698 * modified. FIXME: Should we re-compute instead?
2701 * 1 : csp = Current client state (buffers, headers, etc...)
2702 * 2 : header = On input, pointer to header to modify.
2703 * On output, pointer to the modified header, or NULL
2704 * to remove the header. This function frees the
2705 * original string if necessary.
2707 * Returns : JB_ERR_OK on success, or
2708 * JB_ERR_MEMORY on out-of-memory error.
2710 *********************************************************************/
2711 static jb_err server_content_md5(struct client_state *csp, char **header)
2713 if (csp->flags & CSP_FLAG_MODIFIED)
2715 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2723 /*********************************************************************
2725 * Function : server_content_disposition
2727 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2728 * Called from `sed'.
2731 * 1 : csp = Current client state (buffers, headers, etc...)
2732 * 2 : header = On input, pointer to header to modify.
2733 * On output, pointer to the modified header, or NULL
2734 * to remove the header. This function frees the
2735 * original string if necessary.
2737 * Returns : JB_ERR_OK on success, or
2738 * JB_ERR_MEMORY on out-of-memory error.
2740 *********************************************************************/
2741 static jb_err server_content_disposition(struct client_state *csp, char **header)
2746 * Are we messing with the Content-Disposition header?
2748 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2754 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2756 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2759 * Blocking content-disposition header
2761 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2768 * Replacing Content-Disposition header
2771 *header = strdup("Content-Disposition: ");
2772 string_append(header, newval);
2774 if (*header != NULL)
2776 log_error(LOG_LEVEL_HEADER,
2777 "Content-Disposition header crunched and replaced with: %s", *header);
2780 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2784 /*********************************************************************
2786 * Function : server_last_modified
2788 * Description : Changes Last-Modified header to the actual date
2789 * to help hide-if-modified-since.
2790 * Called from `sed'.
2793 * 1 : csp = Current client state (buffers, headers, etc...)
2794 * 2 : header = On input, pointer to header to modify.
2795 * On output, pointer to the modified header, or NULL
2796 * to remove the header. This function frees the
2797 * original string if necessary.
2799 * Returns : JB_ERR_OK on success, or
2800 * JB_ERR_MEMORY on out-of-memory error.
2802 *********************************************************************/
2803 static jb_err server_last_modified(struct client_state *csp, char **header)
2806 time_t last_modified;
2810 * Are we messing with the Last-Modified header?
2812 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2818 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2820 if (0 == strcmpic(newval, "block"))
2823 * Blocking Last-Modified header. Useless but why not.
2825 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2829 else if (0 == strcmpic(newval, "reset-to-request-time"))
2832 * Setting Last-Modified Header to now.
2835 get_http_time(0, buf, sizeof(buf));
2837 *header = strdup("Last-Modified: ");
2838 string_append(header, buf);
2840 if (*header == NULL)
2842 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2846 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2849 else if (0 == strcmpic(newval, "randomize"))
2851 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2853 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2855 log_error(LOG_LEVEL_HEADER,
2856 "Couldn't parse time in %s (crunching!)", *header);
2862 struct tm *timeptr = NULL;
2867 rtime = (long int)difftime(now, last_modified);
2870 long int days, hours, minutes, seconds;
2871 const int negative_delta = (rtime < 0);
2876 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2878 rtime = pick_from_range(rtime);
2883 last_modified += rtime;
2884 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2885 if ((NULL == timeptr) || !strftime(newheader,
2886 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2888 log_error(LOG_LEVEL_ERROR,
2889 "Randomizing '%s' failed. Crunching the header without replacement.",
2895 *header = strdup("Last-Modified: ");
2896 string_append(header, newheader);
2898 if (*header == NULL)
2900 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2901 return JB_ERR_MEMORY;
2904 days = rtime / (3600 * 24);
2905 hours = rtime / 3600 % 24;
2906 minutes = rtime / 60 % 60;
2907 seconds = rtime % 60;
2909 log_error(LOG_LEVEL_HEADER,
2910 "Randomized: %s (added %ld da%s %ld hou%s %ld minut%s %ld second%s",
2911 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2912 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2916 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2925 /*********************************************************************
2927 * Function : client_accept_encoding
2929 * Description : Rewrite the client's Accept-Encoding header so that
2930 * if doesn't allow compression, if the action applies.
2931 * Note: For HTTP/1.0 the absence of the header is enough.
2934 * 1 : csp = Current client state (buffers, headers, etc...)
2935 * 2 : header = On input, pointer to header to modify.
2936 * On output, pointer to the modified header, or NULL
2937 * to remove the header. This function frees the
2938 * original string if necessary.
2940 * Returns : JB_ERR_OK on success, or
2941 * JB_ERR_MEMORY on out-of-memory error.
2943 *********************************************************************/
2944 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2946 #ifdef FEATURE_COMPRESSION
2947 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2948 && strstr(*header, "deflate"))
2950 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2953 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2955 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2963 /*********************************************************************
2965 * Function : client_te
2967 * Description : Rewrite the client's TE header so that
2968 * if doesn't allow compression, if the action applies.
2971 * 1 : csp = Current client state (buffers, headers, etc...)
2972 * 2 : header = On input, pointer to header to modify.
2973 * On output, pointer to the modified header, or NULL
2974 * to remove the header. This function frees the
2975 * original string if necessary.
2977 * Returns : JB_ERR_OK on success, or
2978 * JB_ERR_MEMORY on out-of-memory error.
2980 *********************************************************************/
2981 static jb_err client_te(struct client_state *csp, char **header)
2983 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2986 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2993 /*********************************************************************
2995 * Function : client_referrer
2997 * Description : Handle the "referer" config setting properly.
2998 * Called from `sed'.
3001 * 1 : csp = Current client state (buffers, headers, etc...)
3002 * 2 : header = On input, pointer to header to modify.
3003 * On output, pointer to the modified header, or NULL
3004 * to remove the header. This function frees the
3005 * original string if necessary.
3007 * Returns : JB_ERR_OK on success, or
3008 * JB_ERR_MEMORY on out-of-memory error.
3010 *********************************************************************/
3011 static jb_err client_referrer(struct client_state *csp, char **header)
3013 const char *parameter;
3014 /* booleans for parameters we have to check multiple times */
3015 int parameter_conditional_block;
3016 int parameter_conditional_forge;
3018 #ifdef FEATURE_FORCE_LOAD
3020 * Since the referrer can include the prefix even
3021 * if the request itself is non-forced, we must
3022 * clean it unconditionally.
3024 * XXX: strclean is too broad
3026 strclean(*header, FORCE_PREFIX);
3027 #endif /* def FEATURE_FORCE_LOAD */
3029 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3031 /* Nothing left to do */
3035 parameter = csp->action->string[ACTION_STRING_REFERER];
3036 assert(parameter != NULL);
3037 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3038 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3040 if (!parameter_conditional_block && !parameter_conditional_forge)
3043 * As conditional-block and conditional-forge are the only
3044 * parameters that rely on the original referrer, we can
3045 * remove it now for all the others.
3050 if (0 == strcmpic(parameter, "block"))
3052 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3055 else if (parameter_conditional_block || parameter_conditional_forge)
3057 return handle_conditional_hide_referrer_parameter(header,
3058 csp->http->hostport, parameter_conditional_block);
3060 else if (0 == strcmpic(parameter, "forge"))
3062 return create_forged_referrer(header, csp->http->hostport);
3066 /* interpret parameter as user-supplied referer to fake */
3067 return create_fake_referrer(header, parameter);
3072 /*********************************************************************
3074 * Function : client_accept_language
3076 * Description : Handle the "Accept-Language" config setting properly.
3077 * Called from `sed'.
3080 * 1 : csp = Current client state (buffers, headers, etc...)
3081 * 2 : header = On input, pointer to header to modify.
3082 * On output, pointer to the modified header, or NULL
3083 * to remove the header. This function frees the
3084 * original string if necessary.
3086 * Returns : JB_ERR_OK on success, or
3087 * JB_ERR_MEMORY on out-of-memory error.
3089 *********************************************************************/
3090 static jb_err client_accept_language(struct client_state *csp, char **header)
3095 * Are we messing with the Accept-Language?
3097 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3099 /*I don't think so*/
3103 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3105 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3108 * Blocking Accept-Language header
3110 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3117 * Replacing Accept-Language header
3120 *header = strdup("Accept-Language: ");
3121 string_append(header, newval);
3123 if (*header == NULL)
3125 log_error(LOG_LEVEL_ERROR,
3126 "Insufficient memory. Accept-Language header crunched without replacement.");
3130 log_error(LOG_LEVEL_HEADER,
3131 "Accept-Language header crunched and replaced with: %s", *header);
3134 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3138 /*********************************************************************
3140 * Function : crunch_client_header
3142 * Description : Crunch client header if it matches a string supplied by the
3143 * user. Called from `sed'.
3146 * 1 : csp = Current client state (buffers, headers, etc...)
3147 * 2 : header = On input, pointer to header to modify.
3148 * On output, pointer to the modified header, or NULL
3149 * to remove the header. This function frees the
3150 * original string if necessary.
3152 * Returns : JB_ERR_OK on success and always succeeds
3154 *********************************************************************/
3155 static jb_err crunch_client_header(struct client_state *csp, char **header)
3157 const char *crunch_pattern;
3159 /* Do we feel like crunching? */
3160 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3162 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3164 /* Is the current header the lucky one? */
3165 if (strstr(*header, crunch_pattern))
3167 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3175 /*********************************************************************
3177 * Function : client_uagent
3179 * Description : Handle the "user-agent" config setting properly
3180 * and remember its original value to enable browser
3181 * bug workarounds. Called from `sed'.
3184 * 1 : csp = Current client state (buffers, headers, etc...)
3185 * 2 : header = On input, pointer to header to modify.
3186 * On output, pointer to the modified header, or NULL
3187 * to remove the header. This function frees the
3188 * original string if necessary.
3190 * Returns : JB_ERR_OK on success, or
3191 * JB_ERR_MEMORY on out-of-memory error.
3193 *********************************************************************/
3194 static jb_err client_uagent(struct client_state *csp, char **header)
3198 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3203 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3210 *header = strdup("User-Agent: ");
3211 string_append(header, newval);
3213 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3215 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3219 /*********************************************************************
3221 * Function : client_ua
3223 * Description : Handle "ua-" headers properly. Called from `sed'.
3226 * 1 : csp = Current client state (buffers, headers, etc...)
3227 * 2 : header = On input, pointer to header to modify.
3228 * On output, pointer to the modified header, or NULL
3229 * to remove the header. This function frees the
3230 * original string if necessary.
3232 * Returns : JB_ERR_OK on success, or
3233 * JB_ERR_MEMORY on out-of-memory error.
3235 *********************************************************************/
3236 static jb_err client_ua(struct client_state *csp, char **header)
3238 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3240 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3248 /*********************************************************************
3250 * Function : client_from
3252 * Description : Handle the "from" config setting properly.
3253 * Called from `sed'.
3256 * 1 : csp = Current client state (buffers, headers, etc...)
3257 * 2 : header = On input, pointer to header to modify.
3258 * On output, pointer to the modified header, or NULL
3259 * to remove the header. This function frees the
3260 * original string if necessary.
3262 * Returns : JB_ERR_OK on success, or
3263 * JB_ERR_MEMORY on out-of-memory error.
3265 *********************************************************************/
3266 static jb_err client_from(struct client_state *csp, char **header)
3270 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3277 newval = csp->action->string[ACTION_STRING_FROM];
3280 * Are we blocking the e-mail address?
3282 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3284 log_error(LOG_LEVEL_HEADER, "crunched From!");
3288 log_error(LOG_LEVEL_HEADER, " modified");
3290 *header = strdup("From: ");
3291 string_append(header, newval);
3293 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3297 /*********************************************************************
3299 * Function : client_send_cookie
3301 * Description : Crunches the "cookie" header if necessary.
3302 * Called from `sed'.
3304 * XXX: Stupid name, doesn't send squat.
3307 * 1 : csp = Current client state (buffers, headers, etc...)
3308 * 2 : header = On input, pointer to header to modify.
3309 * On output, pointer to the modified header, or NULL
3310 * to remove the header. This function frees the
3311 * original string if necessary.
3313 * Returns : JB_ERR_OK on success, or
3314 * JB_ERR_MEMORY on out-of-memory error.
3316 *********************************************************************/
3317 static jb_err client_send_cookie(struct client_state *csp, char **header)
3319 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3321 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3329 /*********************************************************************
3331 * Function : client_x_forwarded
3333 * Description : Handle the "x-forwarded-for" config setting properly,
3334 * also used in the add_client_headers list. Called from `sed'.
3337 * 1 : csp = Current client state (buffers, headers, etc...)
3338 * 2 : header = On input, pointer to header to modify.
3339 * On output, pointer to the modified header, or NULL
3340 * to remove the header. This function frees the
3341 * original string if necessary.
3343 * Returns : JB_ERR_OK on success, or
3344 * JB_ERR_MEMORY on out-of-memory error.
3346 *********************************************************************/
3347 jb_err client_x_forwarded(struct client_state *csp, char **header)
3349 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3351 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3353 if (0 == strcmpic(parameter, "block"))
3356 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3358 else if (0 == strcmpic(parameter, "add"))
3360 string_append(header, ", ");
3361 string_append(header, csp->ip_addr_str);
3363 if (*header == NULL)
3365 return JB_ERR_MEMORY;
3367 log_error(LOG_LEVEL_HEADER,
3368 "Appended client IP address to %s", *header);
3369 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3373 log_error(LOG_LEVEL_FATAL,
3374 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3382 /*********************************************************************
3384 * Function : client_max_forwards
3386 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3387 * from the value of the Max-Forwards header field.
3390 * 1 : csp = Current client state (buffers, headers, etc...)
3391 * 2 : header = On input, pointer to header to modify.
3392 * On output, pointer to the modified header, or NULL
3393 * to remove the header. This function frees the
3394 * original string if necessary.
3396 * Returns : JB_ERR_OK on success, or
3397 * JB_ERR_MEMORY on out-of-memory error.
3399 *********************************************************************/
3400 static jb_err client_max_forwards(struct client_state *csp, char **header)
3404 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3405 (0 == strcmpic(csp->http->gpc, "options")))
3407 assert(*(*header+12) == ':');
3408 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3410 if (max_forwards > 0)
3412 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3413 log_error(LOG_LEVEL_HEADER,
3414 "Max-Forwards value for %s request reduced to %d.",
3415 csp->http->gpc, max_forwards);
3417 else if (max_forwards < 0)
3419 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3425 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3434 /*********************************************************************
3436 * Function : client_host
3438 * Description : If the request URI did not contain host and
3439 * port information, parse and evaluate the Host
3443 * 1 : csp = Current client state (buffers, headers, etc...)
3444 * 2 : header = On input, pointer to header to modify.
3445 * On output, pointer to the modified header, or NULL
3446 * to remove the header. This function frees the
3447 * original string if necessary.
3449 * Returns : JB_ERR_OK on success, or
3450 * JB_ERR_MEMORY on out-of-memory error.
3452 *********************************************************************/
3453 static jb_err client_host(struct client_state *csp, char **header)
3457 if (strlen(*header) < 7)
3459 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3464 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3465 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3468 p = strdup_or_die((*header)+6);
3470 q = strdup_or_die(p);
3472 freez(csp->http->hostport);
3473 csp->http->hostport = p;
3474 freez(csp->http->host);
3475 csp->http->host = q;
3476 q = strchr(csp->http->host, ':');
3479 /* Terminate hostname and evaluate port string */
3481 csp->http->port = atoi(q);
3485 csp->http->port = csp->http->ssl ? 443 : 80;
3488 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3489 csp->http->hostport, csp->http->host, csp->http->port);
3492 /* Signal client_host_adder() to return right away */
3493 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3499 /*********************************************************************
3501 * Function : client_if_modified_since
3503 * Description : Remove or modify the If-Modified-Since header.
3506 * 1 : csp = Current client state (buffers, headers, etc...)
3507 * 2 : header = On input, pointer to header to modify.
3508 * On output, pointer to the modified header, or NULL
3509 * to remove the header. This function frees the
3510 * original string if necessary.
3512 * Returns : JB_ERR_OK on success, or
3513 * JB_ERR_MEMORY on out-of-memory error.
3515 *********************************************************************/
3516 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3520 struct tm *timeptr = NULL;
3525 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3528 * The client got an error message because of a temporary problem,
3529 * the problem is gone and the client now tries to revalidate our
3530 * error message on the real server. The revalidation would always
3531 * end with the transmission of the whole document and there is
3532 * no need to expose the bogus If-Modified-Since header.
3534 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3537 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3539 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3541 if ((0 == strcmpic(newval, "block")))
3543 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3546 else /* add random value */
3548 if (JB_ERR_OK != parse_time_header(*header, &tm))
3550 log_error(LOG_LEVEL_HEADER,
3551 "Couldn't parse time in %s (crunching!)", *header);
3556 long int hours, minutes, seconds;
3557 long int rtime = strtol(newval, &endptr, 0);
3558 const int negative_range = (rtime < 0);
3562 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %ld minut%s)",
3563 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3569 rtime = pick_from_range(rtime);
3573 log_error(LOG_LEVEL_ERROR,
3574 "Random range is 0. Assuming time transformation test.");
3576 tm += rtime * (negative_range ? -1 : 1);
3577 timeptr = privoxy_gmtime_r(&tm, &gmt);
3578 if ((NULL == timeptr) || !strftime(newheader,
3579 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3581 log_error(LOG_LEVEL_ERROR,
3582 "Randomizing '%s' failed. Crunching the header without replacement.",
3588 *header = strdup("If-Modified-Since: ");
3589 string_append(header, newheader);
3591 if (*header == NULL)
3593 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3594 return JB_ERR_MEMORY;
3597 hours = rtime / 3600;
3598 minutes = rtime / 60 % 60;
3599 seconds = rtime % 60;
3601 log_error(LOG_LEVEL_HEADER,
3602 "Randomized: %s (%s %ld hou%s %ld minut%s %ld second%s",
3603 *header, (negative_range) ? "subtracted" : "added", hours,
3604 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3605 seconds, (seconds == 1) ? ")" : "s)");
3614 /*********************************************************************
3616 * Function : client_if_none_match
3618 * Description : Remove the If-None-Match header.
3621 * 1 : csp = Current client state (buffers, headers, etc...)
3622 * 2 : header = On input, pointer to header to modify.
3623 * On output, pointer to the modified header, or NULL
3624 * to remove the header. This function frees the
3625 * original string if necessary.
3627 * Returns : JB_ERR_OK on success, or
3628 * JB_ERR_MEMORY on out-of-memory error.
3630 *********************************************************************/
3631 static jb_err client_if_none_match(struct client_state *csp, char **header)
3633 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3635 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3643 /*********************************************************************
3645 * Function : client_x_filter
3647 * Description : Disables filtering if the client set "X-Filter: No".
3648 * Called from `sed'.
3651 * 1 : csp = Current client state (buffers, headers, etc...)
3652 * 2 : header = On input, pointer to header to modify.
3653 * On output, pointer to the modified header, or NULL
3654 * to remove the header. This function frees the
3655 * original string if necessary.
3657 * Returns : JB_ERR_OK on success
3659 *********************************************************************/
3660 jb_err client_x_filter(struct client_state *csp, char **header)
3662 if (0 == strcmpic(*header, "X-Filter: No"))
3664 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3666 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3670 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3672 log_error(LOG_LEVEL_HEADER,
3673 "force-text-mode overruled the client's request to fetch without filtering!");
3677 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3678 csp->flags |= CSP_FLAG_NO_FILTERING;
3679 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3681 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3689 /*********************************************************************
3691 * Function : client_range
3693 * Description : Removes Range, Request-Range and If-Range headers if
3694 * content filtering is enabled and the range doesn't
3697 * If the client's version of the document has been
3698 * altered by Privoxy, the server could interpret the
3699 * range differently than the client intended in which
3700 * case the user could end up with corrupted content.
3702 * If the range starts at byte 0 this isn't an issue
3703 * so the header can pass. Partial requests like this
3704 * are used to render preview images for videos without
3705 * downloading the whole video.
3707 * While HTTP doesn't require that range requests are
3708 * honoured and the client could simply abort the download
3709 * after receiving a sufficient amount of data, various
3710 * clients don't handle complete responses to range
3711 * requests gracefully and emit misleading error messages
3715 * 1 : csp = Current client state (buffers, headers, etc...)
3716 * 2 : header = On input, pointer to header to modify.
3717 * On output, pointer to the modified header, or NULL
3718 * to remove the header. This function frees the
3719 * original string if necessary.
3721 * Returns : JB_ERR_OK
3723 *********************************************************************/
3724 static jb_err client_range(struct client_state *csp, char **header)
3726 if (content_filters_enabled(csp->action)
3727 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3729 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3730 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3737 /* the following functions add headers directly to the header list */
3739 /*********************************************************************
3741 * Function : client_host_adder
3743 * Description : Adds the Host: header field if it is missing.
3744 * Called from `sed'.
3747 * 1 : csp = Current client state (buffers, headers, etc...)
3749 * Returns : JB_ERR_OK on success, or
3750 * JB_ERR_MEMORY on out-of-memory error.
3752 *********************************************************************/
3753 static jb_err client_host_adder(struct client_state *csp)
3758 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3760 /* Header already set by the client, nothing to do. */
3764 if (!csp->http->hostport || !*(csp->http->hostport))
3766 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3767 return JB_ERR_PARSE;
3771 * remove 'user:pass@' from 'proto://user:pass@host'
3773 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3779 p = csp->http->hostport;
3782 /* XXX: Just add it, we already made sure that it will be unique */
3783 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3784 err = enlist_unique_header(csp->headers, "Host", p);
3790 /*********************************************************************
3792 * Function : client_xtra_adder
3794 * Description : Used in the add_client_headers list. Called from `sed'.
3797 * 1 : csp = Current client state (buffers, headers, etc...)
3799 * Returns : JB_ERR_OK on success, or
3800 * JB_ERR_MEMORY on out-of-memory error.
3802 *********************************************************************/
3803 static jb_err client_xtra_adder(struct client_state *csp)
3805 struct list_entry *lst;
3808 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3809 lst ; lst = lst->next)
3811 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3812 err = enlist(csp->headers, lst->str);
3824 /*********************************************************************
3826 * Function : client_x_forwarded_for_adder
3828 * Description : Used in the add_client_headers list. Called from `sed'.
3831 * 1 : csp = Current client state (buffers, headers, etc...)
3833 * Returns : JB_ERR_OK on success, or
3834 * JB_ERR_MEMORY on out-of-memory error.
3836 *********************************************************************/
3837 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3839 char *header = NULL;
3842 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3843 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3844 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3847 * If we aren't adding X-Forwarded-For headers,
3848 * or we already appended an existing X-Forwarded-For
3849 * header, there's nothing left to do here.
3854 header = strdup("X-Forwarded-For: ");
3855 string_append(&header, csp->ip_addr_str);
3859 return JB_ERR_MEMORY;
3862 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3863 err = enlist(csp->headers, header);
3870 /*********************************************************************
3872 * Function : server_connection_adder
3874 * Description : Adds an appropriate "Connection:" header to csp->headers
3875 * unless the header was already present. Called from `sed'.
3878 * 1 : csp = Current client state (buffers, headers, etc...)
3880 * Returns : JB_ERR_OK on success, or
3881 * JB_ERR_MEMORY on out-of-memory error.
3883 *********************************************************************/
3884 static jb_err server_connection_adder(struct client_state *csp)
3886 const unsigned int flags = csp->flags;
3887 const char *response_status_line = csp->headers->first->str;
3888 static const char connection_close[] = "Connection: close";
3890 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3891 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3897 * XXX: if we downgraded the response, this check will fail.
3899 if ((csp->config->feature_flags &
3900 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3901 && (NULL != response_status_line)
3902 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3903 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3904 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3908 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3909 "without Connection header implies keep-alive.");
3910 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3914 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3916 return enlist(csp->headers, connection_close);
3920 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3921 /*********************************************************************
3923 * Function : server_proxy_connection_adder
3925 * Description : Adds a "Proxy-Connection: keep-alive" header to
3926 * csp->headers when appropriate.
3929 * 1 : csp = Current client state (buffers, headers, etc...)
3931 * Returns : JB_ERR_OK on success, or
3932 * JB_ERR_MEMORY on out-of-memory error.
3934 *********************************************************************/
3935 static jb_err server_proxy_connection_adder(struct client_state *csp)
3937 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3938 jb_err err = JB_ERR_OK;
3940 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3941 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3942 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3943 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3944 || (csp->flags & CSP_FLAG_CHUNKED))
3945 #ifdef FEATURE_HTTPS_INSPECTION
3946 && !client_use_ssl(csp)
3951 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3952 err = enlist(csp->headers, proxy_connection_header);
3957 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3960 /*********************************************************************
3962 * Function : client_connection_header_adder
3964 * Description : Adds a proper "Connection:" header to csp->headers
3965 * unless the header was already present or it's a
3966 * CONNECT request. Called from `sed'.
3969 * 1 : csp = Current client state (buffers, headers, etc...)
3971 * Returns : JB_ERR_OK on success, or
3972 * JB_ERR_MEMORY on out-of-memory error.
3974 *********************************************************************/
3975 static jb_err client_connection_header_adder(struct client_state *csp)
3977 static const char connection_close[] = "Connection: close";
3979 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3980 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3986 * In case of CONNECT requests "Connection: close" is implied,
3987 * but actually setting the header has been reported to cause
3988 * problems with some forwarding proxies that close the
3989 * connection prematurely.
3991 if (csp->http->ssl != 0)
3996 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3997 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3998 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3999 && !strcmpic(csp->http->version, "HTTP/1.1"))
4001 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4004 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4006 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4008 return enlist(csp->headers, connection_close);
4012 /*********************************************************************
4014 * Function : server_http
4016 * Description : - Save the HTTP Status into csp->http->status
4017 * - Set CT_TABOO to prevent filtering if the answer
4018 * is a partial range (HTTP status 206)
4019 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4021 * - Normalize the HTTP-version.
4024 * 1 : csp = Current client state (buffers, headers, etc...)
4025 * 2 : header = On input, pointer to header to modify.
4026 * On output, pointer to the modified header, or NULL
4027 * to remove the header. This function frees the
4028 * original string if necessary.
4030 * Returns : JB_ERR_OK on success, or
4031 * JB_ERR_PARSE on fatal parse errors.
4033 *********************************************************************/
4034 static jb_err server_http(struct client_state *csp, char **header)
4036 char *reason_phrase = NULL;
4037 char *new_response_line;
4040 unsigned int major_version;
4041 unsigned int minor_version;
4043 /* Get the reason phrase which start after the second whitespace */
4044 p = strchr(*header, ' ');
4048 reason_phrase = strchr(p, ' ');
4051 if (reason_phrase != NULL)
4057 log_error(LOG_LEVEL_ERROR,
4058 "Response line lacks reason phrase: %s", *header);
4062 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4063 &minor_version, &(csp->http->status)))
4065 log_error(LOG_LEVEL_ERROR,
4066 "Failed to parse the response line: %s", *header);
4067 return JB_ERR_PARSE;
4070 if (csp->http->status == 206)
4072 csp->content_type = CT_TABOO;
4075 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4078 * According to RFC 7230 2.6 intermediaries MUST send
4079 * their own HTTP-version in forwarded messages.
4081 log_error(LOG_LEVEL_ERROR,
4082 "Unsupported HTTP version. Downgrading to 1.1.");
4087 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4089 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4093 /* Rebuild response line. */
4094 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4095 new_response_line = malloc_or_die(length);
4097 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4098 major_version, minor_version, csp->http->status, reason_phrase);
4100 if (0 != strcmp(*header, new_response_line))
4102 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4103 *header, new_response_line);
4107 *header = new_response_line;
4112 /*********************************************************************
4114 * Function : add_cooky_expiry_date
4116 * Description : Adds a cookie expiry date to a string.
4119 * 1 : cookie = On input, pointer to cookie to modify.
4120 * On output, pointer to the modified header.
4121 * The original string is freed.
4122 * 2 : lifetime = Seconds the cookie should be valid
4126 *********************************************************************/
4127 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4130 struct tm *timeptr = NULL;
4131 time_t expiry_date = time(NULL) + lifetime;
4134 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4135 if (NULL == timeptr)
4137 log_error(LOG_LEVEL_FATAL,
4138 "Failed to get the time in add_cooky_expiry_date()");
4140 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4141 if (JB_ERR_OK != string_append(cookie, tmp))
4143 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4148 /*********************************************************************
4150 * Function : server_set_cookie
4152 * Description : Handle the server "cookie" header properly.
4153 * Crunch, accept or rewrite it to a session cookie.
4154 * Called from `sed'.
4157 * 1 : csp = Current client state (buffers, headers, etc...)
4158 * 2 : header = On input, pointer to header to modify.
4159 * On output, pointer to the modified header, or NULL
4160 * to remove the header. This function frees the
4161 * original string if necessary.
4163 * Returns : JB_ERR_OK on success, or
4164 * JB_ERR_MEMORY on out-of-memory error.
4166 *********************************************************************/
4167 static jb_err server_set_cookie(struct client_state *csp, char **header)
4169 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4171 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4174 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4175 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4179 long cookie_lifetime = 0;
4182 NO_EXPIRY_DATE_SPECIFIED,
4183 EXPIRY_DATE_ACCEPTABLE,
4184 EXPIRY_DATE_UNACCEPTABLE
4185 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4187 /* A variable to store the tag we're working on */
4190 /* Skip "Set-Cookie:" (11 characters) in header */
4191 cur_tag = *header + 11;
4193 /* skip whitespace between "Set-Cookie:" and value */
4194 while (*cur_tag && privoxy_isspace(*cur_tag))
4201 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4203 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4205 cookie_lifetime = strtol(param, NULL, 0);
4206 if (cookie_lifetime < 0)
4208 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4210 cookie_lifetime *= 60;
4213 /* Loop through each tag in the cookie */
4217 char *next_tag = strchr(cur_tag, ';');
4218 if (next_tag != NULL)
4220 /* Skip the ';' character itself */
4223 /* skip whitespace ";" and start of tag */
4224 while (*next_tag && privoxy_isspace(*next_tag))
4231 /* "Next tag" is the end of the string */
4232 next_tag = cur_tag + strlen(cur_tag);
4236 * Check the expiration date to see
4237 * if the cookie is still valid, if yes,
4238 * rewrite it to a session cookie.
4240 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4242 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4244 if ((expiration_date[0] == '"')
4245 && (expiration_date[1] != '\0'))
4248 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4249 * that the expiration date isn't supposed to be quoted,
4250 * but some servers do it anyway.
4255 /* Did we detect the date properly? */
4256 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4259 * Nope, treat it as if it was still valid.
4261 * XXX: Should we remove the whole cookie instead?
4263 log_error(LOG_LEVEL_ERROR,
4264 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4265 string_move(cur_tag, next_tag);
4266 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4271 * Yes. Check if the cookie is still valid.
4273 * If the cookie is already expired it's probably
4274 * a delete cookie and even if it isn't, the browser
4275 * will discard it anyway.
4279 * XXX: timegm() isn't available on some AmigaOS
4280 * versions and our replacement doesn't work.
4282 * Our options are to either:
4284 * - disable session-cookies-only completely if timegm
4287 * - to simply remove all expired tags, like it has
4288 * been done until Privoxy 3.0.6 and to live with
4289 * the consequence that it can cause login/logout
4290 * problems on servers that don't validate their
4291 * input properly, or
4293 * - to replace it with mktime in which
4294 * case there is a slight chance of valid cookies
4295 * passing as already expired.
4297 * This is the way it's currently done and it's not
4298 * as bad as it sounds. If the missing GMT offset is
4299 * enough to change the result of the expiration check
4300 * the cookie will be only valid for a few hours
4301 * anyway, which in many cases will be shorter
4302 * than a browser session.
4304 if (cookie_time < now)
4306 log_error(LOG_LEVEL_HEADER,
4307 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4308 /* Just in case some clown sets more then one expiration date */
4310 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4312 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4314 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4315 "Its lifetime is below the limit.", *header);
4316 /* Just in case some clown sets more then one expiration date */
4318 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4323 * Still valid, delete expiration date by copying
4324 * the rest of the string over it.
4326 string_move(cur_tag, next_tag);
4328 /* That changed the header, need to issue a log message */
4329 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4332 * Note that the next tag has now been moved to *cur_tag,
4333 * so we do not need to update the cur_tag pointer.
4341 /* Move on to next cookie tag */
4346 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4348 assert(NULL != *header);
4349 if (cookie_lifetime != 0)
4351 add_cookie_expiry_date(header, cookie_lifetime);
4352 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4354 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4356 log_error(LOG_LEVEL_HEADER,
4357 "Cookie rewritten to a temporary one: %s", *header);
4366 #ifdef FEATURE_FORCE_LOAD
4367 /*********************************************************************
4369 * Function : strclean
4371 * Description : In-Situ-Eliminate all occurrences of substring in
4375 * 1 : string = string to clean
4376 * 2 : substring = substring to eliminate
4378 * Returns : Number of eliminations
4380 *********************************************************************/
4381 int strclean(char *string, const char *substring)
4387 len = strlen(substring);
4389 while((pos = strstr(string, substring)) != NULL)
4396 while (*p++ != '\0');
4403 #endif /* def FEATURE_FORCE_LOAD */
4406 /*********************************************************************
4408 * Function : parse_header_time
4410 * Description : Parses time formats used in HTTP header strings
4411 * to get the numerical respresentation.
4414 * 1 : header_time = HTTP header time as string.
4415 * 2 : result = storage for header_time in seconds
4417 * Returns : JB_ERR_OK if the time format was recognized, or
4418 * JB_ERR_PARSE otherwise.
4420 *********************************************************************/
4421 static jb_err parse_header_time(const char *header_time, time_t *result)
4425 * Checking for two-digit years first in an
4426 * attempt to work around GNU libc's strptime()
4427 * reporting negative year values when using %Y.
4429 static const char time_formats[][22] = {
4430 /* Tue, 02-Jun-37 20:00:00 */
4431 "%a, %d-%b-%y %H:%M:%S",
4432 /* Tue, 02 Jun 2037 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 /* Tuesday, 02-Jun-2037 20:00:00 */
4437 "%A, %d-%b-%Y %H:%M:%S",
4438 /* Tuesday Jun 02 20:00:00 2037 */
4439 "%A %b %d %H:%M:%S %Y"
4443 for (i = 0; i < SZ(time_formats); i++)
4446 * Zero out gmt to prevent time zone offsets.
4447 * Documented to be required for GNU libc.
4449 memset(&gmt, 0, sizeof(gmt));
4451 if (NULL != strptime(header_time, time_formats[i], &gmt))
4453 /* Sanity check for GNU libc. */
4454 if (gmt.tm_year < 0)
4456 log_error(LOG_LEVEL_HEADER,
4457 "Failed to parse '%s' using '%s'. Moving on.",
4458 header_time, time_formats[i]);
4461 *result = timegm(&gmt);
4463 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4465 * Verify that parsing the date recreated from the first
4466 * parse operation gets the previous result. If it doesn't,
4467 * either strptime() or strftime() are malfunctioning.
4469 * We could string-compare the recreated date with the original
4470 * header date, but this leads to false positives as strptime()
4471 * may let %a accept all day formats while strftime() will only
4475 char recreated_date[100];
4480 tm = privoxy_gmtime_r(result, &storage);
4481 if (!strftime(recreated_date, sizeof(recreated_date),
4482 time_formats[i], tm))
4484 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4485 header_time, time_formats[i]);
4488 memset(&gmt, 0, sizeof(gmt));
4489 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4491 log_error(LOG_LEVEL_ERROR,
4492 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4493 recreated_date, time_formats[i], header_time);
4496 result2 = timegm(&gmt);
4497 if (*result != result2)
4499 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4500 "Format: '%s'. In: '%s', out: '%s'. %ld != %ld. Rejecting.",
4501 time_formats[i], header_time, recreated_date, *result, result2);
4511 return JB_ERR_PARSE;
4515 /*********************************************************************
4517 * Function : parse_time_header
4519 * Description : Parses the time in an HTTP time header to get
4520 * the numerical respresentation.
4523 * 1 : header = HTTP header with a time value
4524 * 2 : result = storage for header_time in seconds
4526 * Returns : JB_ERR_OK if the time format was recognized, or
4527 * JB_ERR_PARSE otherwise.
4529 *********************************************************************/
4530 static jb_err parse_time_header(const char *header, time_t *result)
4532 const char *header_time;
4534 header_time = strchr(header, ':');
4537 * Currently this can't happen as all callers are called
4538 * through sed() which requires a header name followed by
4541 assert(header_time != NULL);
4544 if (*header_time == ' ')
4549 return parse_header_time(header_time, result);
4554 /*********************************************************************
4556 * Function : get_destination_from_headers
4558 * Description : Parse the "Host:" header to get the request's destination.
4559 * Only needed if the client's request was forcefully
4560 * redirected into Privoxy.
4562 * Code mainly copied from client_host() which is currently
4563 * run too late for this purpose.
4566 * 1 : headers = List of headers (one of them hopefully being
4567 * the "Host:" header)
4568 * 2 : http = storage for the result (host, port and hostport).
4570 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4571 * JB_ERR_PARSE if the host header couldn't be found,
4572 * JB_ERR_OK otherwise.
4574 *********************************************************************/
4575 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4581 host = get_header_value(headers, "Host:");
4585 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4586 return JB_ERR_PARSE;
4589 p = strdup_or_die(host);
4591 q = strdup_or_die(p);
4593 freez(http->hostport);
4597 q = strchr(http->host, ':');
4600 /* Terminate hostname and evaluate port string */
4602 http->port = atoi(q);
4609 /* Rebuild request URL */
4611 http->url = strdup("http://");
4612 string_append(&http->url, http->hostport);
4613 string_append(&http->url, http->path);
4614 if (http->url == NULL)
4616 return JB_ERR_MEMORY;
4619 log_error(LOG_LEVEL_HEADER,
4620 "Destination extracted from \"Host\" header. New request URL: %s",
4624 * Regenerate request line in "proxy format"
4625 * to make rewrites more convenient.
4627 assert(http->cmd != NULL);
4629 http->cmd = strdup_or_die(http->gpc);
4630 string_append(&http->cmd, " ");
4631 string_append(&http->cmd, http->url);
4632 string_append(&http->cmd, " ");
4633 string_append(&http->cmd, http->version);
4634 if (http->cmd == NULL)
4636 return JB_ERR_MEMORY;
4644 #ifdef FEATURE_HTTPS_INSPECTION
4645 /*********************************************************************
4647 * Function : get_destination_from_https_headers
4649 * Description : Parse the previously encrypted "Host:" header to
4650 * get the request's destination.
4653 * 1 : headers = List of headers (one of them hopefully being
4654 * the "Host:" header)
4655 * 2 : http = storage for the result (host, port and hostport).
4657 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4658 * JB_ERR_PARSE if the host header couldn't be found,
4659 * JB_ERR_OK otherwise.
4661 *********************************************************************/
4662 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4668 host = get_header_value(headers, "Host:");
4672 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4673 return JB_ERR_PARSE;
4676 p = strdup_or_die(host);
4678 q = strdup_or_die(p);
4680 freez(http->hostport);
4684 q = strchr(http->host, ':');
4687 /* Terminate hostname and evaluate port string */
4689 http->port = atoi(q);
4696 /* Rebuild request URL */
4698 http->url = strdup_or_die(http->path);
4700 log_error(LOG_LEVEL_HEADER,
4701 "Destination extracted from \"Host\" header. New request URL: %s",
4705 * Regenerate request line in "proxy format"
4706 * to make rewrites more convenient.
4708 assert(http->cmd != NULL);
4710 http->cmd = strdup_or_die(http->gpc);
4711 string_append(&http->cmd, " ");
4712 string_append(&http->cmd, http->url);
4713 string_append(&http->cmd, " ");
4714 string_append(&http->cmd, http->version);
4715 if (http->cmd == NULL)
4717 return JB_ERR_MEMORY;
4723 #endif /* def FEATURE_HTTPS_INSPECTION */
4726 /*********************************************************************
4728 * Function : create_forged_referrer
4730 * Description : Helper for client_referrer to forge a referer as
4731 * 'http://hostname[:port]/' to fool stupid
4732 * checks for in-site links
4735 * 1 : header = Pointer to header pointer
4736 * 2 : hostport = Host and optionally port as string
4738 * Returns : JB_ERR_OK in case of success, or
4739 * JB_ERR_MEMORY in case of memory problems.
4741 *********************************************************************/
4742 static jb_err create_forged_referrer(char **header, const char *hostport)
4744 assert(NULL == *header);
4746 *header = strdup("Referer: http://");
4747 string_append(header, hostport);
4748 string_append(header, "/");
4750 if (NULL == *header)
4752 return JB_ERR_MEMORY;
4755 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4762 /*********************************************************************
4764 * Function : create_fake_referrer
4766 * Description : Helper for client_referrer to create a fake referrer
4767 * based on a string supplied by the user.
4770 * 1 : header = Pointer to header pointer
4771 * 2 : hosthost = Referrer to fake
4773 * Returns : JB_ERR_OK in case of success, or
4774 * JB_ERR_MEMORY in case of memory problems.
4776 *********************************************************************/
4777 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4779 assert(NULL == *header);
4781 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4783 log_error(LOG_LEVEL_HEADER,
4784 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4786 *header = strdup("Referer: ");
4787 string_append(header, fake_referrer);
4789 if (NULL == *header)
4791 return JB_ERR_MEMORY;
4794 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4801 /*********************************************************************
4803 * Function : handle_conditional_hide_referrer_parameter
4805 * Description : Helper for client_referrer to crunch or forge
4806 * the referrer header if the host has changed.
4809 * 1 : header = Pointer to header pointer
4810 * 2 : host = The target host (may include the port)
4811 * 3 : parameter_conditional_block = Boolean to signal
4812 * if we're in conditional-block mode. If not set,
4813 * we're in conditional-forge mode.
4815 * Returns : JB_ERR_OK in case of success, or
4816 * JB_ERR_MEMORY in case of memory problems.
4818 *********************************************************************/
4819 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4820 const char *host, const int parameter_conditional_block)
4822 char *referer = strdup_or_die(*header);
4823 const size_t hostlength = strlen(host);
4824 const char *referer_url = NULL;
4826 /* referer begins with 'Referer: http[s]://' */
4827 if ((hostlength+17) < strlen(referer))
4830 * Shorten referer to make sure the referer is blocked
4831 * if www.example.org/www.example.com-shall-see-the-referer/
4832 * links to www.example.com/
4834 referer[hostlength+17] = '\0';
4836 referer_url = strstr(referer, "http://");
4837 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4839 /* Host has changed, Referer is invalid or a https URL. */
4840 if (parameter_conditional_block)
4842 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4849 return create_forged_referrer(header, host);
4859 /*********************************************************************
4861 * Function : create_content_length_header
4863 * Description : Creates a Content-Length header.
4866 * 1 : content_length = The content length to be used in the header.
4867 * 2 : header = Allocated space to safe the header.
4868 * 3 : buffer_length = The length of the allocated space.
4872 *********************************************************************/
4873 static void create_content_length_header(unsigned long long content_length,
4874 char *header, size_t buffer_length)
4877 #if SIZEOF_LONG_LONG < 8
4878 #error sizeof(unsigned long long) too small
4880 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4882 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4887 /*********************************************************************
4889 * Function : get_expected_content_length
4891 * Description : Figures out the content length from a list of headers.
4894 * 1 : headers = List of headers
4896 * Returns : Number of bytes to expect
4898 *********************************************************************/
4899 unsigned long long get_expected_content_length(struct list *headers)
4901 const char *content_length_header;
4902 unsigned long long content_length = 0;
4904 content_length_header = get_header_value(headers, "Content-Length:");
4905 if (content_length_header != NULL)
4907 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4909 log_error(LOG_LEVEL_ERROR,
4910 "Failed to get the Content-Length in %s", content_length_header);
4911 /* XXX: The header will be removed later on */
4916 return content_length;