1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2021 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
61 #define GZIP_FLAG_CHECKSUM 0x02
62 #define GZIP_FLAG_EXTRA_FIELDS 0x04
63 #define GZIP_FLAG_FILE_NAME 0x08
64 #define GZIP_FLAG_COMMENT 0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
68 #include <brotli/decode.h>
77 #ifdef FEATURE_PTHREAD
79 /* jcc.h is for mutex semapores only */
80 #endif /* def FEATURE_PTHREAD */
85 #include "jbsockets.h"
90 #ifdef FEATURE_HTTPS_INSPECTION
98 static char *get_header_line(struct iob *iob);
99 static jb_err scan_headers(struct client_state *csp);
100 static jb_err header_tagger(struct client_state *csp, char *header);
101 static jb_err parse_header_time(const char *header_time, time_t *result);
102 static jb_err parse_time_header(const char *header, time_t *result);
104 static jb_err crumble (struct client_state *csp, char **header);
105 static jb_err filter_header (struct client_state *csp, char **header);
106 static jb_err client_connection (struct client_state *csp, char **header);
107 static jb_err client_referrer (struct client_state *csp, char **header);
108 static jb_err client_uagent (struct client_state *csp, char **header);
109 static jb_err client_ua (struct client_state *csp, char **header);
110 static jb_err client_from (struct client_state *csp, char **header);
111 static jb_err client_send_cookie (struct client_state *csp, char **header);
112 static jb_err client_x_forwarded (struct client_state *csp, char **header);
113 static jb_err client_accept_encoding (struct client_state *csp, char **header);
114 static jb_err client_te (struct client_state *csp, char **header);
115 static jb_err client_max_forwards (struct client_state *csp, char **header);
116 static jb_err client_host (struct client_state *csp, char **header);
117 static jb_err client_if_modified_since (struct client_state *csp, char **header);
118 static jb_err client_accept_language (struct client_state *csp, char **header);
119 static jb_err client_if_none_match (struct client_state *csp, char **header);
120 static jb_err crunch_client_header (struct client_state *csp, char **header);
121 static jb_err client_x_filter (struct client_state *csp, char **header);
122 static jb_err client_range (struct client_state *csp, char **header);
123 static jb_err client_expect (struct client_state *csp, char **header);
124 static jb_err server_set_cookie (struct client_state *csp, char **header);
125 static jb_err server_connection (struct client_state *csp, char **header);
126 static jb_err server_content_type (struct client_state *csp, char **header);
127 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
128 static jb_err server_content_md5 (struct client_state *csp, char **header);
129 static jb_err server_content_encoding (struct client_state *csp, char **header);
130 static jb_err server_transfer_coding (struct client_state *csp, char **header);
131 static jb_err server_http (struct client_state *csp, char **header);
132 static jb_err crunch_server_header (struct client_state *csp, char **header);
133 static jb_err server_last_modified (struct client_state *csp, char **header);
134 static jb_err server_content_disposition(struct client_state *csp, char **header);
136 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
139 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
140 static jb_err server_save_content_length(struct client_state *csp, char **header);
141 static jb_err server_keep_alive(struct client_state *csp, char **header);
142 static jb_err server_proxy_connection(struct client_state *csp, char **header);
143 static jb_err client_keep_alive(struct client_state *csp, char **header);
144 static jb_err client_proxy_connection(struct client_state *csp, char **header);
145 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
147 static jb_err client_save_content_length(struct client_state *csp, char **header);
148 static jb_err client_host_adder (struct client_state *csp);
149 static jb_err client_xtra_adder (struct client_state *csp);
150 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
151 static jb_err client_connection_header_adder(struct client_state *csp);
152 static jb_err server_connection_adder(struct client_state *csp);
153 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
154 static jb_err server_proxy_connection_adder(struct client_state *csp);
155 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
156 static jb_err proxy_authentication(struct client_state *csp, char **header);
158 static jb_err create_forged_referrer(char **header, const char *hostport);
159 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
160 static jb_err handle_conditional_hide_referrer_parameter(char **header,
161 const char *host, const int parameter_conditional_block);
162 static void create_content_length_header(unsigned long long content_length,
163 char *header, size_t buffer_length);
166 * List of functions to run on a list of headers.
170 /** The header prefix to match */
173 /** The length of the prefix to match */
176 /** The function to apply to this line */
177 const parser_func_ptr parser;
180 static const struct parsers client_patterns[] = {
181 { "referer:", 8, client_referrer },
182 { "user-agent:", 11, client_uagent },
183 { "ua-", 3, client_ua },
184 { "from:", 5, client_from },
185 { "cookie:", 7, client_send_cookie },
186 { "x-forwarded-for:", 16, client_x_forwarded },
187 { "Accept-Encoding:", 16, client_accept_encoding },
188 { "TE:", 3, client_te },
189 { "Host:", 5, client_host },
190 { "if-modified-since:", 18, client_if_modified_since },
191 { "Content-Length:", 15, client_save_content_length },
192 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
193 { "Keep-Alive:", 11, client_keep_alive },
194 { "Proxy-Connection:", 17, client_proxy_connection },
196 { "Keep-Alive:", 11, crumble },
197 { "Proxy-Connection:", 17, crumble },
199 { "connection:", 11, client_connection },
200 { "max-forwards:", 13, client_max_forwards },
201 { "Accept-Language:", 16, client_accept_language },
202 { "if-none-match:", 14, client_if_none_match },
203 { "Range:", 6, client_range },
204 { "Request-Range:", 14, client_range },
205 { "If-Range:", 9, client_range },
206 { "X-Filter:", 9, client_x_filter },
207 { "Proxy-Authorization:", 20, proxy_authentication },
209 { "Transfer-Encoding:", 18, client_transfer_encoding },
211 { "Expect:", 7, client_expect },
212 { "*", 0, crunch_client_header },
213 { "*", 0, filter_header },
217 static const struct parsers server_patterns[] = {
218 { "HTTP/", 5, server_http },
219 { "set-cookie:", 11, server_set_cookie },
220 { "connection:", 11, server_connection },
221 { "Content-Type:", 13, server_content_type },
222 { "Content-MD5:", 12, server_content_md5 },
223 { "Content-Encoding:", 17, server_content_encoding },
224 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
225 { "Content-Length:", 15, server_save_content_length },
226 { "Keep-Alive:", 11, server_keep_alive },
227 { "Proxy-Connection:", 17, server_proxy_connection },
229 { "Keep-Alive:", 11, crumble },
230 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
231 { "Transfer-Encoding:", 18, server_transfer_coding },
232 { "content-disposition:", 20, server_content_disposition },
233 { "Last-Modified:", 14, server_last_modified },
234 { "Proxy-Authenticate:", 19, proxy_authentication },
235 { "*", 0, crunch_server_header },
236 { "*", 0, filter_header },
240 static const add_header_func_ptr add_client_headers[] = {
242 client_x_forwarded_for_adder,
244 client_connection_header_adder,
248 static const add_header_func_ptr add_server_headers[] = {
249 server_connection_adder,
250 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
251 server_proxy_connection_adder,
252 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
256 /*********************************************************************
258 * Function : flush_iob
260 * Description : Write any pending "buffered" content.
263 * 1 : fd = file descriptor of the socket to read
264 * 2 : iob = The I/O buffer to flush, usually csp->iob.
265 * 3 : delay = Number of milliseconds to delay the writes
267 * Returns : On success, the number of bytes written are returned (zero
268 * indicates nothing was written). On error, -1 is returned,
269 * and errno is set appropriately. If count is zero and the
270 * file descriptor refers to a regular file, 0 will be
271 * returned without causing any other effect. For a special
272 * file, the results are not portable.
274 *********************************************************************/
275 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
277 long len = iob->eod - iob->cur;
284 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
288 iob->eod = iob->cur = iob->buf;
294 /*********************************************************************
296 * Function : can_add_to_iob
298 * Description : Checks if the given number of bytes can be added to the given iob
299 * without exceeding the given buffer limit.
302 * 1 : iob = Destination buffer.
303 * 2 : buffer_limit = Limit to which the destination may grow
304 * 3 : n = number of bytes to be added
306 * Returns : TRUE if the given iob can handle given number of bytes
307 * FALSE buffer limit will be exceeded
309 *********************************************************************/
310 int can_add_to_iob(const struct iob *iob, const size_t buffer_limit, size_t n)
312 return ((size_t)(iob->eod - iob->buf) + n + 1) > buffer_limit ? FALSE : TRUE;
315 /*********************************************************************
317 * Function : add_to_iob
319 * Description : Add content to the buffer, expanding the
320 * buffer if necessary.
323 * 1 : iob = Destination buffer.
324 * 2 : buffer_limit = Limit to which the destination may grow
325 * 3 : src = holds the content to be added
326 * 4 : n = number of bytes to be added
328 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
329 * or buffer limit reached.
331 *********************************************************************/
332 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, const char *src, long n)
334 size_t used, offset, need;
337 if (n <= 0) return JB_ERR_OK;
339 used = (size_t)(iob->eod - iob->buf);
340 offset = (size_t)(iob->cur - iob->buf);
341 need = used + (size_t)n + 1;
344 * If the buffer can't hold the new data, extend it first.
345 * Use the next power of two if possible, else use the actual need.
347 if (need > buffer_limit)
349 log_error(LOG_LEVEL_INFO,
350 "Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
352 return JB_ERR_MEMORY;
355 if (need > iob->size)
357 size_t want = iob->size ? iob->size : 512;
364 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
368 else if (NULL != (p = (char *)realloc(iob->buf, need)))
374 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
375 return JB_ERR_MEMORY;
378 /* Update the iob pointers */
379 iob->cur = p + offset;
384 /* copy the new data into the iob buffer */
385 memcpy(iob->eod, src, (size_t)n);
387 /* point to the end of the data */
390 /* null terminate == cheap insurance */
398 /*********************************************************************
400 * Function : clear_iob
402 * Description : Frees the memory allocated for an I/O buffer and
403 * resets the structure.
406 * 1 : iob = I/O buffer to clear.
410 *********************************************************************/
411 void clear_iob(struct iob *iob)
414 memset(iob, '\0', sizeof(*iob));
419 #ifdef FEATURE_BROTLI
420 /*********************************************************************
422 * Function : decompress_iob_with_brotli
424 * Description : Decompress buffered page using Brotli.
427 * 1 : csp = Current client state (buffers, headers, etc...)
429 * Returns : JB_ERR_OK on success,
430 * JB_ERR_MEMORY if out-of-memory limit reached, and
431 * JB_ERR_COMPRESS if error decompressing buffer.
433 *********************************************************************/
434 static jb_err decompress_iob_with_brotli(struct client_state *csp)
436 BrotliDecoderResult result;
437 char *decoded_buffer;
439 size_t decoded_buffer_size;
441 enum { MAX_COMPRESSION_FACTOR = 15 };
443 encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
445 * The BrotliDecoderDecompress() api is a bit unfortunate
446 * and requires the caller to reserve enough memory for
447 * the decompressed content. Hopefully reserving
448 * MAX_COMPRESSION_FACTOR times the original size is
449 * sufficient. If not, BrotliDecoderDecompress() will fail.
451 decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
453 if (decoded_buffer_size > csp->config->buffer_limit)
455 log_error(LOG_LEVEL_ERROR,
456 "Buffer limit reached before decompressing iob with Brotli");
457 return JB_ERR_MEMORY;
460 decoded_buffer = malloc(decoded_buffer_size);
461 if (decoded_buffer == NULL)
463 log_error(LOG_LEVEL_ERROR,
464 "Failed to allocate %lu bytes for Brotli decompression",
465 decoded_buffer_size);
466 return JB_ERR_MEMORY;
469 decoded_size = decoded_buffer_size;
470 result = BrotliDecoderDecompress(encoded_size,
471 (const uint8_t *)csp->iob->cur, &decoded_size,
472 (uint8_t *)decoded_buffer);
473 if (result == BROTLI_DECODER_RESULT_SUCCESS)
476 * Update the iob, since the decompression was successful.
478 freez(csp->iob->buf);
479 csp->iob->buf = decoded_buffer;
480 csp->iob->cur = csp->iob->buf;
481 csp->iob->eod = csp->iob->cur + decoded_size;
482 csp->iob->size = decoded_buffer_size;
484 log_error(LOG_LEVEL_RE_FILTER,
485 "Decompression successful. Old size: %lu, new size: %lu.",
486 encoded_size, decoded_size);
492 log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
493 freez(decoded_buffer);
495 return JB_ERR_COMPRESS;
500 /*********************************************************************
502 * Function : decompress_iob
504 * Description : Decompress buffered page, expanding the
505 * buffer as necessary. csp->iob->cur
506 * should point to the the beginning of the
507 * compressed data block.
510 * 1 : csp = Current client state (buffers, headers, etc...)
512 * Returns : JB_ERR_OK on success,
513 * JB_ERR_MEMORY if out-of-memory limit reached, and
514 * JB_ERR_COMPRESS if error decompressing buffer.
516 *********************************************************************/
517 jb_err decompress_iob(struct client_state *csp)
519 char *buf; /* new, uncompressed buffer */
520 char *cur; /* Current iob position (to keep the original
521 * iob->cur unmodified if we return early) */
522 size_t bufsize; /* allocated size of the new buffer */
523 size_t old_size; /* Content size before decompression */
524 size_t skip_size; /* Number of bytes at the beginning of the iob
525 that we should NOT decompress. */
526 int status; /* return status of the inflate() call */
527 z_stream zstr; /* used by calls to zlib */
530 assert(csp->iob->cur - csp->iob->buf >= 0);
531 assert(csp->iob->eod - csp->iob->cur >= 0);
533 assert(csp->iob->cur - csp->iob->buf > 0);
534 assert(csp->iob->eod - csp->iob->cur > 0);
537 bufsize = csp->iob->size;
538 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
539 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
543 if (old_size < (size_t)10)
546 * This is to protect the parsing of gzipped data,
547 * but it should(?) be valid for deflated data also.
549 log_error(LOG_LEVEL_ERROR,
550 "Insufficient data to start decompression. Bytes in buffer: %ld",
551 csp->iob->eod - csp->iob->cur);
552 return JB_ERR_COMPRESS;
555 #ifdef FEATURE_BROTLI
556 if (csp->content_type & CT_BROTLI)
558 return decompress_iob_with_brotli(csp);
562 if (csp->content_type & CT_GZIP)
565 * Our task is slightly complicated by the facts that data
566 * compressed by gzip does not include a zlib header, and
567 * that there is no easily accessible interface in zlib to
568 * handle a gzip header. We strip off the gzip header by
569 * hand, and later inform zlib not to expect a header.
573 * Strip off the gzip header. Please see RFC 1952 for more
574 * explanation of the appropriate fields.
576 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
577 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
578 || (*cur++ != Z_DEFLATED))
580 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
581 return JB_ERR_COMPRESS;
586 if (flags & GZIP_FLAG_RESERVED_BITS)
588 /* The gzip header has reserved bits set; bail out. */
589 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
590 return JB_ERR_COMPRESS;
594 * Skip mtime (4 bytes), extra flags (1 byte)
595 * and OS type (1 byte).
599 /* Skip extra fields if necessary. */
600 if (flags & GZIP_FLAG_EXTRA_FIELDS)
603 * Skip a given number of bytes, specified
604 * as a 16-bit little-endian value.
606 * XXX: this code is untested and should probably be removed.
610 skip_bytes += *cur++ << 8;
613 * The number of bytes to skip should be positive
614 * and we'd like to stay in the buffer.
616 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
618 log_error(LOG_LEVEL_ERROR,
619 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
621 return JB_ERR_COMPRESS;
623 log_error(LOG_LEVEL_INFO,
624 "Skipping %d bytes for gzip compression. Does this sound right?",
629 /* Skip the filename if necessary. */
630 if (flags & GZIP_FLAG_FILE_NAME)
632 /* A null-terminated string is supposed to follow. */
633 while (*cur++ && (cur < csp->iob->eod));
636 /* Skip the comment if necessary. */
637 if (flags & GZIP_FLAG_COMMENT)
639 /* A null-terminated string is supposed to follow. */
640 while (*cur++ && (cur < csp->iob->eod));
643 /* Skip the CRC if necessary. */
644 if (flags & GZIP_FLAG_CHECKSUM)
649 if (cur >= csp->iob->eod)
652 * If the current position pointer reached or passed
653 * the buffer end, we were obviously tricked to skip
656 log_error(LOG_LEVEL_ERROR,
657 "Malformed gzip header detected. Aborting decompression.");
658 return JB_ERR_COMPRESS;
662 else if (csp->content_type & CT_DEFLATE)
665 * In theory (that is, according to RFC 1950), deflate-compressed
666 * data should begin with a two-byte zlib header and have an
667 * adler32 checksum at the end. It seems that in practice only
668 * the raw compressed data is sent. Note that this means that
669 * we are not RFC 1950-compliant here, but the advantage is that
670 * this actually works. :)
672 * We add a dummy null byte to tell zlib where the data ends,
673 * and later inform it not to expect a header.
675 * Fortunately, add_to_iob() has thoughtfully null-terminated
676 * the buffer; we can just increment the end pointer to include
683 log_error(LOG_LEVEL_ERROR,
684 "Unable to determine compression format for decompression");
685 return JB_ERR_COMPRESS;
688 /* Set up the fields required by zlib. */
689 zstr.next_in = (Bytef *)cur;
690 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
691 zstr.zalloc = Z_NULL;
693 zstr.opaque = Z_NULL;
696 * Passing -MAX_WBITS to inflateInit2 tells the library
697 * that there is no zlib header.
699 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
701 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
702 return JB_ERR_COMPRESS;
706 * Next, we allocate new storage for the inflated data.
707 * We don't modify the existing iob yet, so in case there
708 * is error in decompression we can recover gracefully.
710 buf = zalloc(bufsize);
713 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
714 return JB_ERR_MEMORY;
717 assert(bufsize >= skip_size);
718 memcpy(buf, csp->iob->buf, skip_size);
719 zstr.avail_out = (uInt)(bufsize - skip_size);
720 zstr.next_out = (Bytef *)buf + skip_size;
722 /* Try to decompress the whole stream in one shot. */
723 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
725 /* We need to allocate more memory for the output buffer. */
727 char *tmpbuf; /* used for realloc'ing the buffer */
728 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
730 if (0 == zstr.avail_in)
733 * If zlib wants more data then there's a problem, because
734 * the complete compressed file should have been buffered.
736 log_error(LOG_LEVEL_ERROR,
737 "Unexpected end of compressed iob. Using what we got so far.");
742 * If we reached the buffer limit and still didn't have enough
743 * memory, just give up. Due to the ceiling enforced by the next
744 * if block we could actually check for equality here, but as it
745 * can be easily mistaken for a bug we don't.
747 if (bufsize >= csp->config->buffer_limit)
749 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
752 return JB_ERR_MEMORY;
755 /* Try doubling the buffer size each time. */
758 /* Don't exceed the buffer limit. */
759 if (bufsize > csp->config->buffer_limit)
761 bufsize = csp->config->buffer_limit;
764 /* Try to allocate the new buffer. */
765 tmpbuf = realloc(buf, bufsize);
768 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
771 return JB_ERR_MEMORY;
775 char *oldnext_out = (char *)zstr.next_out;
778 * Update the fields for inflate() to use the new
779 * buffer, which may be in a location different from
782 zstr.avail_out += (uInt)(bufsize - oldbufsize);
783 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
786 * Compare with an uglier method of calculating these values
787 * that doesn't require the extra oldbufsize variable.
789 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
790 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
796 if (Z_STREAM_ERROR == inflateEnd(&zstr))
798 log_error(LOG_LEVEL_ERROR,
799 "Inconsistent stream state after decompression: %s", zstr.msg);
801 * XXX: Intentionally no return.
803 * According to zlib.h, Z_STREAM_ERROR is returned
804 * "if the stream state was inconsistent".
806 * I assume in this case inflate()'s status
807 * would also be something different than Z_STREAM_END
808 * so this check should be redundant, but lets see.
812 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
815 * We failed to decompress the stream and it's
816 * not simply because of missing data.
818 log_error(LOG_LEVEL_ERROR,
819 "Unexpected error while decompressing to the buffer (iob): %s",
822 return JB_ERR_COMPRESS;
826 * Finally, we can actually update the iob, since the
827 * decompression was successful. First, free the old
830 freez(csp->iob->buf);
832 /* Now, update the iob to use the new buffer. */
834 csp->iob->cur = csp->iob->buf + skip_size;
835 csp->iob->eod = (char *)zstr.next_out;
836 csp->iob->size = bufsize;
839 * Make sure the new uncompressed iob obeys some minimal
840 * consistency conditions.
842 if ((csp->iob->buf <= csp->iob->cur)
843 && (csp->iob->cur <= csp->iob->eod)
844 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
846 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
847 if (new_size > (size_t)0)
849 log_error(LOG_LEVEL_RE_FILTER,
850 "Decompression successful. Old size: %lu, new size: %lu.",
855 /* zlib thinks this is OK, so let's do the same. */
856 log_error(LOG_LEVEL_RE_FILTER,
857 "Decompression didn't result in any content.");
862 /* It seems that zlib did something weird. */
863 log_error(LOG_LEVEL_ERROR, "Inconsistent buffer after decompression");
864 return JB_ERR_COMPRESS;
870 #endif /* defined(FEATURE_ZLIB) */
873 /*********************************************************************
875 * Function : normalize_lws
877 * Description : Reduces unquoted linear whitespace in headers to
878 * a single space in accordance with RFC 7230 3.2.4.
879 * This simplifies parsing and filtering later on.
882 * 1 : header = A header with linear whitespace to reduce.
886 *********************************************************************/
887 static void normalize_lws(char *header)
893 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
897 while (privoxy_isspace(*q))
901 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
907 log_error(LOG_LEVEL_HEADER,
908 "Converting tab to space in '%s'", header);
913 char *end_of_token = strstr(p+1, "\"");
915 if (NULL != end_of_token)
917 /* Don't mess with quoted text. */
922 log_error(LOG_LEVEL_HEADER,
923 "Ignoring single quote in '%s'", header);
929 p = strchr(header, ':');
930 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
933 * There's still space before the colon.
941 /*********************************************************************
943 * Function : get_header
945 * Description : This (odd) routine will parse the csp->iob
946 * to get the next complete header.
949 * 1 : iob = The I/O buffer to parse, usually csp->iob.
951 * Returns : Any one of the following:
953 * 1) a pointer to a dynamically allocated string that contains a header line
954 * 2) NULL indicating that the end of the header was reached
955 * 3) "" indicating that the end of the iob was reached before finding
956 * a complete header line.
958 *********************************************************************/
959 char *get_header(struct iob *iob)
963 header = get_header_line(iob);
965 if ((header == NULL) || (*header == '\0'))
968 * No complete header read yet, tell the client.
973 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
976 * Header spans multiple lines, append the next one.
978 char *continued_header;
980 continued_header = get_header_line(iob);
981 if ((continued_header == NULL) || (*continued_header == '\0'))
984 * No complete header read yet, return what we got.
985 * XXX: Should "unread" header instead.
987 log_error(LOG_LEVEL_INFO,
988 "Failed to read a multi-line header properly: '%s'",
993 if (JB_ERR_OK != string_join(&header, continued_header))
995 log_error(LOG_LEVEL_FATAL,
996 "Out of memory while appending multiple headers.");
1000 /* XXX: remove before next stable release. */
1001 log_error(LOG_LEVEL_HEADER,
1002 "Merged multiple header lines to: '%s'",
1007 normalize_lws(header);
1014 /*********************************************************************
1016 * Function : get_header_line
1018 * Description : This (odd) routine will parse the csp->iob
1019 * to get the next header line.
1022 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1024 * Returns : Any one of the following:
1026 * 1) a pointer to a dynamically allocated string that contains a header line
1027 * 2) NULL indicating that the end of the header was reached
1028 * 3) "" indicating that the end of the iob was reached before finding
1029 * a complete header line.
1031 *********************************************************************/
1032 static char *get_header_line(struct iob *iob)
1036 if ((iob->cur == NULL)
1037 || ((p = strchr(iob->cur, '\n')) == NULL))
1039 return(""); /* couldn't find a complete header */
1044 ret = strdup(iob->cur);
1047 /* FIXME No way to handle error properly */
1048 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1050 assert(ret != NULL);
1054 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1056 /* is this a blank line (i.e. the end of the header) ? */
1068 /*********************************************************************
1070 * Function : get_header_value
1072 * Description : Get the value of a given header from a chained list
1073 * of header lines or return NULL if no such header is
1074 * present in the list.
1077 * 1 : header_list = pointer to list
1078 * 2 : header_name = string with name of header to look for.
1079 * Trailing colon required, capitalization
1082 * Returns : NULL if not found, else value of header
1084 *********************************************************************/
1085 char *get_header_value(const struct list *header_list, const char *header_name)
1087 struct list_entry *cur_entry;
1091 assert(header_list);
1092 assert(header_name);
1093 length = strlen(header_name);
1095 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1099 if (!strncmpic(cur_entry->str, header_name, length))
1102 * Found: return pointer to start of value
1104 ret = cur_entry->str + length;
1105 while (*ret && privoxy_isspace(*ret)) ret++;
1119 /*********************************************************************
1121 * Function : scan_headers
1123 * Description : Scans headers, applies tags and updates action bits.
1126 * 1 : csp = Current client state (buffers, headers, etc...)
1128 * Returns : JB_ERR_OK
1130 *********************************************************************/
1131 static jb_err scan_headers(struct client_state *csp)
1133 struct list_entry *h; /* Header */
1134 jb_err err = JB_ERR_OK;
1136 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1138 /* Header crunch()ed in previous run? -> ignore */
1139 if (h->str == NULL) continue;
1140 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1141 err = header_tagger(csp, h->str);
1148 /*********************************************************************
1150 * Function : enforce_header_order
1152 * Description : Enforces a given header order.
1155 * 1 : headers = List of headers to order.
1156 * 2 : ordered_headers = List of ordered header names.
1160 *********************************************************************/
1161 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1163 struct list_entry *sorted_header;
1164 struct list new_headers[1];
1165 struct list_entry *header;
1167 init_list(new_headers);
1169 /* The request line is always the first "header" */
1171 assert(NULL != headers->first->str);
1172 enlist(new_headers, headers->first->str);
1173 freez(headers->first->str)
1175 /* Enlist the specified headers in the given order */
1177 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1178 sorted_header = sorted_header->next)
1180 const size_t sorted_header_length = strlen(sorted_header->str);
1181 for (header = headers->first; header != NULL; header = header->next)
1183 /* Header enlisted in previous run? -> ignore */
1184 if (header->str == NULL) continue;
1186 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1187 && (header->str[sorted_header_length] == ':'))
1189 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1190 if (JB_ERR_OK != enlist(new_headers, header->str))
1192 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1199 /* Enlist the rest of the headers behind the ordered ones */
1200 for (header = headers->first; header != NULL; header = header->next)
1202 /* Header enlisted in previous run? -> ignore */
1203 if (header->str == NULL) continue;
1205 log_error(LOG_LEVEL_HEADER,
1206 "Enlisting left-over header %s", header->str);
1207 if (JB_ERR_OK != enlist(new_headers, header->str))
1209 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1214 list_remove_all(headers);
1215 headers->first = new_headers->first;
1216 headers->last = new_headers->last;
1222 /*********************************************************************
1226 * Description : add, delete or modify lines in the HTTP header streams.
1227 * On entry, it receives a linked list of headers space
1228 * that was allocated dynamically (both the list nodes
1229 * and the header contents).
1231 * As a side effect it frees the space used by the original
1235 * 1 : csp = Current client state (buffers, headers, etc...)
1236 * 2 : filter_server_headers = Boolean to switch between
1237 * server and header filtering.
1239 * Returns : JB_ERR_OK in case off success, or
1240 * JB_ERR_MEMORY on some out-of-memory errors, or
1241 * JB_ERR_PARSE in case of fatal parse errors.
1243 *********************************************************************/
1244 jb_err sed(struct client_state *csp, int filter_server_headers)
1246 /* XXX: use more descriptive names. */
1247 struct list_entry *p;
1248 const struct parsers *v;
1249 const add_header_func_ptr *f;
1250 jb_err err = JB_ERR_OK;
1254 if (filter_server_headers)
1256 v = server_patterns;
1257 f = add_server_headers;
1258 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1262 v = client_patterns;
1263 f = add_client_headers;
1264 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1267 while (v->str != NULL)
1269 for (p = csp->headers->first; p != NULL; p = p->next)
1271 /* Header crunch()ed in previous run? -> ignore */
1272 if (p->str == NULL) continue;
1274 /* Does the current parser handle this header? */
1275 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1276 (v->len == CHECK_EVERY_HEADER_REMAINING))
1278 err = v->parser(csp, &(p->str));
1279 if (err != JB_ERR_OK)
1288 /* place additional headers on the csp->headers list */
1289 while ((err == JB_ERR_OK) && (*f))
1295 if (!filter_server_headers &&
1296 !list_is_empty(csp->config->ordered_client_headers) &&
1297 csp->headers->first->str != NULL)
1299 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1306 #ifdef FEATURE_HTTPS_INSPECTION
1307 /*********************************************************************
1309 * Function : sed_https
1311 * Description : add, delete or modify lines in the HTTPS client
1312 * header streams. Wrapper around sed().
1315 * 1 : csp = Current client state (buffers, headers, etc...)
1317 * Returns : JB_ERR_OK in case off success, or
1318 * JB_ERR_MEMORY on some out-of-memory errors, or
1319 * JB_ERR_PARSE in case of fatal parse errors.
1321 *********************************************************************/
1322 jb_err sed_https(struct client_state *csp)
1325 struct list headers;
1328 * Temporarily replace csp->headers with csp->https_headers
1329 * to trick sed() into filtering the https headers.
1331 headers.first = csp->headers->first;
1332 headers.last = csp->headers->last;
1333 csp->headers->first = csp->https_headers->first;
1334 csp->headers->last = csp->https_headers->last;
1337 * Start with fresh tags. Already existing tags may
1338 * be set again. This is necessary to overrule
1339 * URL-based patterns.
1341 destroy_list(csp->tags);
1344 * We want client header filters and taggers
1345 * so temporarily remove the flag.
1347 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1348 err = sed(csp, FILTER_CLIENT_HEADERS);
1349 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1352 * Update the https headers list which may have
1353 * been modified due to header additions or header
1356 csp->https_headers->first = csp->headers->first;
1357 csp->https_headers->last = csp->headers->last;
1359 csp->headers->first = headers.first;
1360 csp->headers->last = headers.last;
1364 #endif /* def FEATURE_HTTPS_INSPECTION */
1367 /*********************************************************************
1369 * Function : update_server_headers
1371 * Description : Updates server headers after the body has been modified.
1374 * 1 : csp = Current client state (buffers, headers, etc...)
1376 * Returns : JB_ERR_OK in case off success, or
1377 * JB_ERR_MEMORY on out-of-memory error.
1379 *********************************************************************/
1380 jb_err update_server_headers(struct client_state *csp)
1382 jb_err err = JB_ERR_OK;
1384 static const struct parsers server_patterns_light[] = {
1385 { "Content-Length:", 15, server_adjust_content_length },
1386 { "Transfer-Encoding:", 18, server_transfer_coding },
1388 { "Content-Encoding:", 17, server_adjust_content_encoding },
1389 #endif /* def FEATURE_ZLIB */
1393 if (strncmpic(csp->http->cmd, "HEAD", 4))
1395 const struct parsers *v;
1396 struct list_entry *p;
1398 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1400 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1402 /* Header crunch()ed in previous run? -> ignore */
1403 if (p->str == NULL) continue;
1405 /* Does the current parser handle this header? */
1406 if (strncmpic(p->str, v->str, v->len) == 0)
1408 err = v->parser(csp, (char **)&(p->str));
1414 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1415 if ((JB_ERR_OK == err)
1416 && (csp->flags & CSP_FLAG_MODIFIED)
1417 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1418 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1422 create_content_length_header(csp->content_length, header, sizeof(header));
1423 err = enlist(csp->headers, header);
1424 if (JB_ERR_OK == err)
1426 log_error(LOG_LEVEL_HEADER,
1427 "Content modified with no Content-Length header set. "
1428 "Created: %s.", header);
1429 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1432 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1434 #ifdef FEATURE_COMPRESSION
1435 if ((JB_ERR_OK == err)
1436 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1438 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1439 if (JB_ERR_OK == err)
1441 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1450 /*********************************************************************
1452 * Function : header_tagger
1454 * Description : Executes all text substitutions from applying
1455 * tag actions and saves the result as tag.
1457 * XXX: Shares enough code with filter_header() and
1458 * pcrs_filter_response() to warrant some helper functions.
1461 * 1 : csp = Current client state (buffers, headers, etc...)
1462 * 2 : header = Header that is used as tagger input
1464 * Returns : JB_ERR_OK on success and always succeeds
1466 *********************************************************************/
1467 static jb_err header_tagger(struct client_state *csp, char *header)
1469 enum filter_type wanted_filter_type;
1470 int multi_action_index;
1473 struct re_filterfile_spec *b;
1474 struct list_entry *tag_name;
1476 const size_t header_length = strlen(header);
1478 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1480 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1481 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1485 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1486 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1489 if (list_is_empty(csp->action->multi[multi_action_index])
1490 || filters_available(csp) == FALSE)
1492 /* Return early if no taggers apply or if none are available. */
1496 /* Execute all applying taggers */
1497 for (tag_name = csp->action->multi[multi_action_index]->first;
1498 NULL != tag_name; tag_name = tag_name->next)
1500 char *modified_tag = NULL;
1502 size_t size = header_length;
1505 b = get_filter(csp, tag_name->str, wanted_filter_type);
1511 joblist = b->joblist;
1513 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1515 if (NULL == joblist)
1517 log_error(LOG_LEVEL_TAGGING,
1518 "Tagger %s has empty joblist. Nothing to do.", b->name);
1522 /* execute their pcrs_joblist on the header. */
1523 for (job = joblist; NULL != job; job = job->next)
1525 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1529 /* Success, continue with the modified version. */
1538 /* Tagger doesn't match */
1541 /* Regex failure, log it but continue anyway. */
1542 assert(NULL != header);
1543 log_error(LOG_LEVEL_ERROR,
1544 "Problems with tagger \'%s\' and header \'%s\': %s",
1545 b->name, header, pcrs_strerror(hits));
1547 freez(modified_tag);
1551 if (b->dynamic) pcrs_free_joblist(joblist);
1553 /* If this tagger matched */
1559 * There is no technical limitation which makes
1560 * it impossible to use empty tags, but I assume
1561 * no one would do it intentionally.
1564 log_error(LOG_LEVEL_TAGGING,
1565 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1569 if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
1571 log_error(LOG_LEVEL_TAGGING,
1572 "Tagger \'%s\' didn't add tag \'%s\': suppressed",
1578 if (!list_contains_item(csp->tags, tag))
1580 if (JB_ERR_OK != enlist(csp->tags, tag))
1582 log_error(LOG_LEVEL_ERROR,
1583 "Insufficient memory to add tag \'%s\', "
1584 "based on tagger \'%s\' and header \'%s\'",
1585 tag, b->name, header);
1589 char *action_message;
1591 * update the action bits right away, to make
1592 * tagging based on tags set by earlier taggers
1593 * of the same kind possible.
1595 if (update_action_bits_for_tag(csp, tag))
1597 action_message = "Action bits updated accordingly.";
1601 action_message = "No action bits update necessary.";
1604 log_error(LOG_LEVEL_TAGGING,
1605 "Tagger \'%s\' added tag \'%s\'. %s",
1606 b->name, tag, action_message);
1611 /* XXX: Is this log-worthy? */
1612 log_error(LOG_LEVEL_TAGGING,
1613 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1623 /* here begins the family of parser functions that reformat header lines */
1625 /*********************************************************************
1627 * Function : filter_header
1629 * Description : Executes all text substitutions from all applying
1630 * +(server|client)-header-filter actions on the header.
1631 * Most of the code was copied from pcrs_filter_response,
1632 * including the rather short variable names
1635 * 1 : csp = Current client state (buffers, headers, etc...)
1636 * 2 : header = On input, pointer to header to modify.
1637 * On output, pointer to the modified header, or NULL
1638 * to remove the header. This function frees the
1639 * original string if necessary.
1641 * Returns : JB_ERR_OK on success and always succeeds
1643 *********************************************************************/
1644 static jb_err filter_header(struct client_state *csp, char **header)
1648 size_t size = strlen(*header);
1650 char *newheader = NULL;
1653 struct re_filterfile_spec *b;
1654 struct list_entry *filtername;
1656 enum filter_type wanted_filter_type;
1657 int multi_action_index;
1659 if (csp->flags & CSP_FLAG_NO_FILTERING)
1664 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1666 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1667 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1671 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1672 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1675 if (list_is_empty(csp->action->multi[multi_action_index])
1676 || filters_available(csp) == FALSE)
1678 /* Return early if no filters apply or if none are available. */
1682 /* Execute all applying header filters */
1683 for (filtername = csp->action->multi[multi_action_index]->first;
1684 filtername != NULL; filtername = filtername->next)
1686 int current_hits = 0;
1689 b = get_filter(csp, filtername->str, wanted_filter_type);
1695 joblist = b->joblist;
1697 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1699 if (NULL == joblist)
1701 log_error(LOG_LEVEL_RE_FILTER,
1702 "Filter %s has empty joblist. Nothing to do.", b->name);
1706 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %lu) with \'%s\' ...",
1707 *header, size, b->name);
1709 /* Apply all jobs from the joblist */
1710 for (job = joblist; NULL != job; job = job->next)
1712 matches = pcrs_execute(job, *header, size, &newheader, &size);
1715 current_hits += matches;
1716 log_error(LOG_LEVEL_HEADER,
1717 "Transforming \"%s\" to \"%s\"", *header, newheader);
1719 *header = newheader;
1721 else if (0 == matches)
1723 /* Filter doesn't change header */
1729 log_error(LOG_LEVEL_ERROR,
1730 "Filtering \'%s\' with \'%s\' didn't work out: %s",
1731 *header, b->name, pcrs_strerror(matches));
1732 if (newheader != NULL)
1734 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1740 if (b->dynamic) pcrs_free_joblist(joblist);
1742 log_error(LOG_LEVEL_RE_FILTER,
1743 "... produced %d hits (new size %lu).", current_hits, size);
1744 hits += current_hits;
1748 * Additionally checking for hits is important because if
1749 * the continue hack is triggered, server headers can
1750 * arrive empty to separate multiple heads from each other.
1752 if ((0 == size) && hits)
1754 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1762 /*********************************************************************
1764 * Function : server_connection
1766 * Description : Makes sure a proper "Connection:" header is
1767 * set and signals connection_header_adder to
1771 * 1 : csp = Current client state (buffers, headers, etc...)
1772 * 2 : header = On input, pointer to header to modify.
1773 * On output, pointer to the modified header, or NULL
1774 * to remove the header. This function frees the
1775 * original string if necessary.
1777 * Returns : JB_ERR_OK on success.
1779 *********************************************************************/
1780 static jb_err server_connection(struct client_state *csp, char **header)
1782 if (!strcmpic(*header, "Connection: keep-alive")
1783 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1784 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1788 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1789 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1791 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1794 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1796 log_error(LOG_LEVEL_HEADER,
1797 "Keeping the server header '%s' around.", *header);
1800 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1802 char *old_header = *header;
1804 *header = strdup_or_die("Connection: close");
1805 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1810 /* Signal server_connection_adder() to return early. */
1811 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1817 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1818 /*********************************************************************
1820 * Function : server_keep_alive
1822 * Description : Stores the server's keep alive timeout.
1825 * 1 : csp = Current client state (buffers, headers, etc...)
1826 * 2 : header = On input, pointer to header to modify.
1827 * On output, pointer to the modified header, or NULL
1828 * to remove the header. This function frees the
1829 * original string if necessary.
1831 * Returns : JB_ERR_OK.
1833 *********************************************************************/
1834 static jb_err server_keep_alive(struct client_state *csp, char **header)
1836 unsigned int keep_alive_timeout;
1837 const char *timeout_position = strstr(*header, "timeout=");
1839 if ((NULL == timeout_position)
1840 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1842 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1846 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1848 log_error(LOG_LEVEL_HEADER,
1849 "Reducing keep-alive timeout from %u to %u.",
1850 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1851 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1855 /* XXX: Is this log worthy? */
1856 log_error(LOG_LEVEL_HEADER,
1857 "Server keep-alive timeout is %u. Sticking with %u.",
1858 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1860 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1869 /*********************************************************************
1871 * Function : server_proxy_connection
1873 * Description : Figures out whether or not we should add a
1874 * Proxy-Connection header.
1877 * 1 : csp = Current client state (buffers, headers, etc...)
1878 * 2 : header = On input, pointer to header to modify.
1879 * On output, pointer to the modified header, or NULL
1880 * to remove the header. This function frees the
1881 * original string if necessary.
1883 * Returns : JB_ERR_OK.
1885 *********************************************************************/
1886 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1888 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1891 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1894 /*********************************************************************
1896 * Function : proxy_authentication
1898 * Description : Removes headers that are relevant for proxy
1899 * authentication unless forwarding them has
1900 * been explicitly requested.
1903 * 1 : csp = Current client state (buffers, headers, etc...)
1904 * 2 : header = On input, pointer to header to modify.
1905 * On output, pointer to the modified header, or NULL
1906 * to remove the header. This function frees the
1907 * original string if necessary.
1909 * Returns : JB_ERR_OK.
1911 *********************************************************************/
1912 static jb_err proxy_authentication(struct client_state *csp, char **header)
1914 if ((csp->config->feature_flags &
1915 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1916 log_error(LOG_LEVEL_HEADER,
1917 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1924 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1925 /*********************************************************************
1927 * Function : client_keep_alive
1929 * Description : Stores the client's keep alive timeout.
1932 * 1 : csp = Current client state (buffers, headers, etc...)
1933 * 2 : header = On input, pointer to header to modify.
1934 * On output, pointer to the modified header, or NULL
1935 * to remove the header. This function frees the
1936 * original string if necessary.
1938 * Returns : JB_ERR_OK.
1940 *********************************************************************/
1941 static jb_err client_keep_alive(struct client_state *csp, char **header)
1943 unsigned int keep_alive_timeout;
1944 char *timeout_position;
1946 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1948 log_error(LOG_LEVEL_HEADER,
1949 "keep-alive support is disabled. Crunching: %s.", *header);
1954 /* Check for parameter-less format "Keep-Alive: 100" */
1955 timeout_position = strstr(*header, ": ");
1956 if ((NULL == timeout_position)
1957 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1959 /* Assume parameter format "Keep-Alive: timeout=100" */
1960 timeout_position = strstr(*header, "timeout=");
1961 if ((NULL == timeout_position)
1962 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1964 log_error(LOG_LEVEL_HEADER,
1965 "Couldn't parse: '%s'. Using default timeout %u",
1966 *header, csp->config->keep_alive_timeout);
1973 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1975 log_error(LOG_LEVEL_HEADER,
1976 "Reducing keep-alive timeout from %u to %u.",
1977 csp->config->keep_alive_timeout, keep_alive_timeout);
1978 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1982 /* XXX: Is this log worthy? */
1983 log_error(LOG_LEVEL_HEADER,
1984 "Client keep-alive timeout is %u. Sticking with %u.",
1985 keep_alive_timeout, csp->config->keep_alive_timeout);
1991 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1994 /*********************************************************************
1996 * Function : get_content_length
1998 * Description : Gets the content length specified in a
1999 * Content-Length header.
2002 * 1 : header_value = The Content-Length header value.
2003 * 2 : length = Storage to return the value.
2005 * Returns : JB_ERR_OK on success, or
2006 * JB_ERR_PARSE if no value is recognized.
2008 *********************************************************************/
2009 static jb_err get_content_length(const char *header_value, unsigned long long *length)
2012 #if SIZEOF_LONG_LONG < 8
2013 #error sizeof(unsigned long long) too small
2015 if (1 != sscanf(header_value, "%I64u", length))
2017 if (1 != sscanf(header_value, "%llu", length))
2020 return JB_ERR_PARSE;
2027 /*********************************************************************
2029 * Function : client_save_content_length
2031 * Description : Save the Content-Length sent by the client.
2034 * 1 : csp = Current client state (buffers, headers, etc...)
2035 * 2 : header = pointer to the Content-Length header
2037 * Returns : JB_ERR_OK on success, or
2038 * JB_ERR_MEMORY on out-of-memory error.
2040 *********************************************************************/
2041 static jb_err client_save_content_length(struct client_state *csp, char **header)
2043 unsigned long long content_length = 0;
2044 const char *header_value;
2046 assert(*(*header+14) == ':');
2048 header_value = *header + 15;
2049 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2051 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2056 csp->expected_client_content_length = content_length;
2063 /*********************************************************************
2065 * Function : client_connection
2067 * Description : Makes sure a proper "Connection:" header is
2068 * set and signals connection_header_adder
2072 * 1 : csp = Current client state (buffers, headers, etc...)
2073 * 2 : header = On input, pointer to header to modify.
2074 * On output, pointer to the modified header, or NULL
2075 * to remove the header. This function frees the
2076 * original string if necessary.
2078 * Returns : JB_ERR_OK on success.
2080 *********************************************************************/
2081 static jb_err client_connection(struct client_state *csp, char **header)
2083 static const char connection_close[] = "Connection: close";
2085 if (!strcmpic(*header, connection_close))
2087 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2088 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2089 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2090 #ifdef FEATURE_HTTPS_INSPECTION
2091 && !client_use_ssl(csp)
2095 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2097 log_error(LOG_LEVEL_HEADER,
2098 "Removing \'%s\' to imply keep-alive.", *header);
2101 * While we imply keep-alive to the server,
2102 * we have to remember that the client didn't.
2104 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2108 char *old_header = *header;
2110 *header = strdup_or_die("Connection: keep-alive");
2111 log_error(LOG_LEVEL_HEADER,
2112 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2118 log_error(LOG_LEVEL_HEADER,
2119 "Keeping the client header '%s' around. "
2120 "The connection will not be kept alive.",
2122 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2125 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2126 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2128 log_error(LOG_LEVEL_HEADER,
2129 "Keeping the client header '%s' around. "
2130 "The server connection will be kept alive if possible.",
2132 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2133 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2137 char *old_header = *header;
2139 *header = strdup_or_die(connection_close);
2140 log_error(LOG_LEVEL_HEADER,
2141 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2145 /* Signal client_connection_header_adder() to return early. */
2146 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2152 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2153 /*********************************************************************
2155 * Function : client_proxy_connection
2157 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2158 * appropriate and removes the Proxy-Connection
2162 * 1 : csp = Current client state (buffers, headers, etc...)
2163 * 2 : header = On input, pointer to header to modify.
2164 * On output, pointer to the modified header, or NULL
2165 * to remove the header. This function frees the
2166 * original string if necessary.
2168 * Returns : JB_ERR_OK
2170 *********************************************************************/
2171 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2173 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2174 && (csp->http->ssl == 0)
2175 && (NULL == strstr(*header, "close")))
2177 log_error(LOG_LEVEL_HEADER,
2178 "The client connection can be kept alive due to: %s", *header);
2179 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2181 crumble(csp, header);
2185 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2188 /*********************************************************************
2190 * Function : client_transfer_encoding
2192 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2193 * the request body is "chunked"
2195 * XXX: Currently not called through sed() as we
2196 * need the flag earlier on. Should be fixed.
2199 * 1 : csp = Current client state (buffers, headers, etc...)
2200 * 2 : header = On input, pointer to header to modify.
2201 * On output, pointer to the modified header, or NULL
2202 * to remove the header. This function frees the
2203 * original string if necessary.
2205 * Returns : JB_ERR_OK on success, or
2207 *********************************************************************/
2208 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2210 if (strstr(*header, "chunked"))
2212 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2213 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2220 /*********************************************************************
2222 * Function : client_expect
2224 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2225 * if the Expect header value is unsupported.
2227 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2228 * MAY and a RFC 2616 (obsolete) MUST.
2231 * 1 : csp = Current client state (buffers, headers, etc...)
2232 * 2 : header = On input, pointer to header to modify.
2233 * On output, pointer to the modified header, or NULL
2234 * to remove the header. This function frees the
2235 * original string if necessary.
2237 * Returns : JB_ERR_OK on success, or
2239 *********************************************************************/
2240 jb_err client_expect(struct client_state *csp, char **header)
2242 if (0 != strcmpic(*header, "Expect: 100-continue"))
2244 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2245 log_error(LOG_LEVEL_HEADER,
2246 "Unsupported client expectaction: %s", *header);
2254 /*********************************************************************
2256 * Function : crumble
2258 * Description : This is called if a header matches a pattern to "crunch"
2261 * 1 : csp = Current client state (buffers, headers, etc...)
2262 * 2 : header = On input, pointer to header to modify.
2263 * On output, pointer to the modified header, or NULL
2264 * to remove the header. This function frees the
2265 * original string if necessary.
2267 * Returns : JB_ERR_OK on success, or
2268 * JB_ERR_MEMORY on out-of-memory error.
2270 *********************************************************************/
2271 static jb_err crumble(struct client_state *csp, char **header)
2274 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2280 /*********************************************************************
2282 * Function : crunch_server_header
2284 * Description : Crunch server header if it matches a string supplied by the
2285 * user. Called from `sed'.
2288 * 1 : csp = Current client state (buffers, headers, etc...)
2289 * 2 : header = On input, pointer to header to modify.
2290 * On output, pointer to the modified header, or NULL
2291 * to remove the header. This function frees the
2292 * original string if necessary.
2294 * Returns : JB_ERR_OK on success and always succeeds
2296 *********************************************************************/
2297 static jb_err crunch_server_header(struct client_state *csp, char **header)
2299 const char *crunch_pattern;
2301 /* Do we feel like crunching? */
2302 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2304 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2306 /* Is the current header the lucky one? */
2307 if (strstr(*header, crunch_pattern))
2309 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2318 /*********************************************************************
2320 * Function : server_content_type
2322 * Description : Set the content-type for filterable types (text/.*,
2323 * .*xml.*, .*script.* and image/gif) unless filtering has been
2324 * forbidden (CT_TABOO) while parsing earlier headers.
2325 * NOTE: Since text/plain is commonly used by web servers
2326 * for files whose correct type is unknown, we don't
2327 * set CT_TEXT for it.
2330 * 1 : csp = Current client state (buffers, headers, etc...)
2331 * 2 : header = On input, pointer to header to modify.
2332 * On output, pointer to the modified header, or NULL
2333 * to remove the header. This function frees the
2334 * original string if necessary.
2336 * Returns : JB_ERR_OK on success, or
2337 * JB_ERR_MEMORY on out-of-memory error.
2339 *********************************************************************/
2340 static jb_err server_content_type(struct client_state *csp, char **header)
2342 /* Remove header if it isn't the first Content-Type header */
2343 if ((csp->content_type & CT_DECLARED))
2345 if (content_filters_enabled(csp->action))
2348 * Making sure the client interprets the content the same way
2349 * Privoxy did is only relevant if Privoxy modified it.
2351 * Checking for this is "hard" as it's not yet known when
2352 * this function is called, thus go shopping and and just
2353 * check if Privoxy could filter it.
2355 * The main thing is that we don't mess with the headers
2356 * unless the user signalled that it's acceptable.
2358 log_error(LOG_LEVEL_HEADER,
2359 "Multiple Content-Type headers detected. "
2360 "Removing and ignoring: %s",
2368 * Signal that the Content-Type has been set.
2370 csp->content_type |= CT_DECLARED;
2372 if (!(csp->content_type & CT_TABOO))
2375 * XXX: The assumption that text/plain is a sign of
2376 * binary data seems to be somewhat unreasonable nowadays
2377 * and should be dropped after 3.0.8 is out.
2379 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2380 || strstr(*header, "xml")
2381 || strstr(*header, "script"))
2383 csp->content_type |= CT_TEXT;
2385 else if (strstr(*header, "image/gif"))
2387 csp->content_type |= CT_GIF;
2392 * Are we messing with the content type?
2394 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2397 * Make sure the user doesn't accidentally
2398 * change the content type of binary documents.
2400 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2404 *header = strdup_or_die("Content-Type: ");
2406 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2407 if (JB_ERR_OK != err)
2409 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2410 return JB_ERR_MEMORY;
2412 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2416 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2417 "It doesn't look like a content type that should be filtered. "
2418 "Enable force-text-mode if you know what you're doing.", *header);
2426 /*********************************************************************
2428 * Function : server_transfer_coding
2430 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2431 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2432 * - Remove header if body was chunked but has been
2433 * de-chunked for filtering.
2436 * 1 : csp = Current client state (buffers, headers, etc...)
2437 * 2 : header = On input, pointer to header to modify.
2438 * On output, pointer to the modified header, or NULL
2439 * to remove the header. This function frees the
2440 * original string if necessary.
2442 * Returns : JB_ERR_OK on success, or
2443 * JB_ERR_MEMORY on out-of-memory error.
2445 *********************************************************************/
2446 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2449 * Turn off pcrs and gif filtering if body compressed
2451 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2455 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2457 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2458 csp->http->cmd, *header);
2459 #endif /* def FEATURE_ZLIB */
2460 csp->content_type = CT_TABOO;
2464 * Raise flag if body chunked
2466 if (strstr(*header, "chunked"))
2468 csp->flags |= CSP_FLAG_CHUNKED;
2471 * If the body was modified, it has been de-chunked first
2472 * and the header must be removed.
2474 * FIXME: If there is more than one transfer encoding,
2475 * only the "chunked" part should be removed here.
2477 if (csp->flags & CSP_FLAG_MODIFIED)
2479 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2488 /*********************************************************************
2490 * Function : server_content_encoding
2492 * Description : Used to check if the content is compressed, and if
2493 * FEATURE_ZLIB is disabled, filtering is disabled as
2496 * If FEATURE_ZLIB is enabled and the compression type
2497 * supported, the content is marked for decompression.
2499 * XXX: Doesn't properly deal with multiple or with
2500 * unsupported but unknown encodings.
2501 * Is case-sensitive but shouldn't be.
2504 * 1 : csp = Current client state (buffers, headers, etc...)
2505 * 2 : header = On input, pointer to header to modify.
2506 * On output, pointer to the modified header, or NULL
2507 * to remove the header. This function frees the
2508 * original string if necessary.
2510 * Returns : JB_ERR_OK on success, or
2511 * JB_ERR_MEMORY on out-of-memory error.
2513 *********************************************************************/
2514 static jb_err server_content_encoding(struct client_state *csp, char **header)
2517 if (strstr(*header, "sdch"))
2520 * Shared Dictionary Compression over HTTP isn't supported,
2521 * filtering it anyway is pretty much guaranteed to mess up
2524 csp->content_type |= CT_TABOO;
2527 * Log a warning if the user expects the content to be filtered.
2529 if (content_filters_enabled(csp->action))
2531 log_error(LOG_LEVEL_INFO,
2532 "SDCH-compressed content detected, content filtering disabled. "
2533 "Consider suppressing SDCH offers made by the client.");
2536 else if (strstr(*header, "gzip"))
2538 /* Mark for gzip decompression */
2539 csp->content_type |= CT_GZIP;
2541 else if (strstr(*header, "deflate"))
2543 /* Mark for zlib decompression */
2544 csp->content_type |= CT_DEFLATE;
2546 else if (strstr(*header, "br"))
2548 #ifdef FEATURE_BROTLI
2549 /* Mark for Brotli decompression */
2550 csp->content_type |= CT_BROTLI;
2552 csp->content_type |= CT_TABOO;
2555 else if (strstr(*header, "compress"))
2558 * We can't decompress this; therefore we can't filter
2561 csp->content_type |= CT_TABOO;
2563 #else /* !defined(FEATURE_ZLIB) */
2565 * XXX: Using a black list here isn't the right approach.
2567 * In case of SDCH, building with zlib support isn't
2570 if (strstr(*header, "gzip") ||
2571 strstr(*header, "compress") ||
2572 strstr(*header, "deflate") ||
2573 strstr(*header, "sdch"))
2576 * Body is compressed, turn off pcrs and gif filtering.
2578 csp->content_type |= CT_TABOO;
2581 * Log a warning if the user expects the content to be filtered.
2583 if (content_filters_enabled(csp->action))
2585 log_error(LOG_LEVEL_INFO,
2586 "Compressed content detected, content filtering disabled. "
2587 "Consider recompiling Privoxy with zlib support or "
2588 "enable the prevent-compression action.");
2591 #endif /* defined(FEATURE_ZLIB) */
2599 /*********************************************************************
2601 * Function : server_adjust_content_encoding
2603 * Description : Remove the Content-Encoding header if the
2604 * decompression was successful and the content
2605 * has been modified.
2608 * 1 : csp = Current client state (buffers, headers, etc...)
2609 * 2 : header = On input, pointer to header to modify.
2610 * On output, pointer to the modified header, or NULL
2611 * to remove the header. This function frees the
2612 * original string if necessary.
2614 * Returns : JB_ERR_OK on success, or
2615 * JB_ERR_MEMORY on out-of-memory error.
2617 *********************************************************************/
2618 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2620 if ((csp->flags & CSP_FLAG_MODIFIED)
2621 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2622 #ifdef FEATURE_BROTLI
2623 || (csp->content_type & CT_BROTLI)
2629 * We successfully decompressed the content,
2630 * and have to clean the header now, so the
2631 * client no longer expects compressed data.
2633 * XXX: There is a difference between cleaning
2634 * and removing it completely.
2636 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2643 #endif /* defined(FEATURE_ZLIB) */
2646 /*********************************************************************
2648 * Function : header_adjust_content_length
2650 * Description : Replace given header with new Content-Length header.
2653 * 1 : header = On input, pointer to header to modify.
2654 * On output, pointer to the modified header, or NULL
2655 * to remove the header. This function frees the
2656 * original string if necessary.
2657 * 2 : content_length = content length value to set
2659 * Returns : JB_ERR_OK on success, or
2660 * JB_ERR_MEMORY on out-of-memory error.
2662 *********************************************************************/
2663 jb_err header_adjust_content_length(char **header, size_t content_length)
2665 const size_t header_length = 50;
2667 *header = malloc(header_length);
2668 if (*header == NULL)
2670 return JB_ERR_MEMORY;
2672 create_content_length_header(content_length, *header, header_length);
2677 /*********************************************************************
2679 * Function : server_adjust_content_length
2681 * Description : Adjust Content-Length header if we modified
2685 * 1 : csp = Current client state (buffers, headers, etc...)
2686 * 2 : header = On input, pointer to header to modify.
2687 * On output, pointer to the modified header, or NULL
2688 * to remove the header. This function frees the
2689 * original string if necessary.
2691 * Returns : JB_ERR_OK on success, or
2692 * JB_ERR_MEMORY on out-of-memory error.
2694 *********************************************************************/
2695 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2697 /* Regenerate header if the content was modified. */
2698 if (csp->flags & CSP_FLAG_MODIFIED)
2700 if (JB_ERR_OK != header_adjust_content_length(header, csp->content_length))
2702 return JB_ERR_MEMORY;
2704 log_error(LOG_LEVEL_HEADER,
2705 "Adjusted Content-Length to %llu", csp->content_length);
2712 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2713 /*********************************************************************
2715 * Function : server_save_content_length
2717 * Description : Save the Content-Length sent by the server.
2720 * 1 : csp = Current client state (buffers, headers, etc...)
2721 * 2 : header = On input, pointer to header to modify.
2722 * On output, pointer to the modified header, or NULL
2723 * to remove the header. This function frees the
2724 * original string if necessary.
2726 * Returns : JB_ERR_OK on success, or
2727 * JB_ERR_MEMORY on out-of-memory error.
2729 *********************************************************************/
2730 static jb_err server_save_content_length(struct client_state *csp, char **header)
2732 unsigned long long content_length = 0;
2733 const char *header_value;
2735 assert(*(*header+14) == ':');
2737 header_value = *header + 15;
2738 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2740 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2745 csp->expected_content_length = content_length;
2746 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2747 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2752 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2755 /*********************************************************************
2757 * Function : server_content_md5
2759 * Description : Crumble any Content-MD5 headers if the document was
2760 * modified. FIXME: Should we re-compute instead?
2763 * 1 : csp = Current client state (buffers, headers, etc...)
2764 * 2 : header = On input, pointer to header to modify.
2765 * On output, pointer to the modified header, or NULL
2766 * to remove the header. This function frees the
2767 * original string if necessary.
2769 * Returns : JB_ERR_OK on success, or
2770 * JB_ERR_MEMORY on out-of-memory error.
2772 *********************************************************************/
2773 static jb_err server_content_md5(struct client_state *csp, char **header)
2775 if (csp->flags & CSP_FLAG_MODIFIED)
2777 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2785 /*********************************************************************
2787 * Function : server_content_disposition
2789 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
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_content_disposition(struct client_state *csp, char **header)
2808 * Are we messing with the Content-Disposition header?
2810 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2816 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2818 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2821 * Blocking content-disposition header
2823 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2830 * Replacing Content-Disposition header
2833 *header = strdup("Content-Disposition: ");
2834 string_append(header, newval);
2836 if (*header != NULL)
2838 log_error(LOG_LEVEL_HEADER,
2839 "Content-Disposition header crunched and replaced with: %s", *header);
2842 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2846 /*********************************************************************
2848 * Function : server_last_modified
2850 * Description : Changes Last-Modified header to the actual date
2851 * to help hide-if-modified-since.
2852 * Called from `sed'.
2855 * 1 : csp = Current client state (buffers, headers, etc...)
2856 * 2 : header = On input, pointer to header to modify.
2857 * On output, pointer to the modified header, or NULL
2858 * to remove the header. This function frees the
2859 * original string if necessary.
2861 * Returns : JB_ERR_OK on success, or
2862 * JB_ERR_MEMORY on out-of-memory error.
2864 *********************************************************************/
2865 static jb_err server_last_modified(struct client_state *csp, char **header)
2868 time_t last_modified;
2872 * Are we messing with the Last-Modified header?
2874 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2880 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2882 if (0 == strcmpic(newval, "block"))
2885 * Blocking Last-Modified header. Useless but why not.
2887 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2891 else if (0 == strcmpic(newval, "reset-to-request-time"))
2894 * Setting Last-Modified Header to now.
2897 get_http_time(0, buf, sizeof(buf));
2899 *header = strdup("Last-Modified: ");
2900 string_append(header, buf);
2902 if (*header == NULL)
2904 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2908 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2911 else if (0 == strcmpic(newval, "randomize"))
2913 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2915 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2917 log_error(LOG_LEVEL_HEADER,
2918 "Couldn't parse time in %s (crunching!)", *header);
2924 struct tm *timeptr = NULL;
2929 rtime = (long int)difftime(now, last_modified);
2932 long int days, hours, minutes, seconds;
2933 const int negative_delta = (rtime < 0);
2938 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2940 rtime = pick_from_range(rtime);
2945 last_modified += rtime;
2946 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2947 if ((NULL == timeptr) || !strftime(newheader,
2948 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2950 log_error(LOG_LEVEL_ERROR,
2951 "Randomizing '%s' failed. Crunching the header without replacement.",
2957 *header = strdup("Last-Modified: ");
2958 string_append(header, newheader);
2960 if (*header == NULL)
2962 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2963 return JB_ERR_MEMORY;
2966 days = rtime / (3600 * 24);
2967 hours = rtime / 3600 % 24;
2968 minutes = rtime / 60 % 60;
2969 seconds = rtime % 60;
2971 log_error(LOG_LEVEL_HEADER,
2972 "Randomized: %s (added %ld da%s %ld hou%s %ld minut%s %ld second%s",
2973 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2974 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2978 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2987 /*********************************************************************
2989 * Function : client_accept_encoding
2991 * Description : Rewrite the client's Accept-Encoding header so that
2992 * if doesn't allow compression, if the action applies.
2993 * Note: For HTTP/1.0 the absence of the header is enough.
2996 * 1 : csp = Current client state (buffers, headers, etc...)
2997 * 2 : header = On input, pointer to header to modify.
2998 * On output, pointer to the modified header, or NULL
2999 * to remove the header. This function frees the
3000 * original string if necessary.
3002 * Returns : JB_ERR_OK on success, or
3003 * JB_ERR_MEMORY on out-of-memory error.
3005 *********************************************************************/
3006 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3008 #ifdef FEATURE_COMPRESSION
3009 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
3010 && strstr(*header, "deflate"))
3012 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
3015 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3017 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3025 /*********************************************************************
3027 * Function : client_te
3029 * Description : Rewrite the client's TE header so that
3030 * if doesn't allow compression, if the action applies.
3033 * 1 : csp = Current client state (buffers, headers, etc...)
3034 * 2 : header = On input, pointer to header to modify.
3035 * On output, pointer to the modified header, or NULL
3036 * to remove the header. This function frees the
3037 * original string if necessary.
3039 * Returns : JB_ERR_OK on success, or
3040 * JB_ERR_MEMORY on out-of-memory error.
3042 *********************************************************************/
3043 static jb_err client_te(struct client_state *csp, char **header)
3045 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3048 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3055 /*********************************************************************
3057 * Function : client_referrer
3059 * Description : Handle the "referer" config setting properly.
3060 * Called from `sed'.
3063 * 1 : csp = Current client state (buffers, headers, etc...)
3064 * 2 : header = On input, pointer to header to modify.
3065 * On output, pointer to the modified header, or NULL
3066 * to remove the header. This function frees the
3067 * original string if necessary.
3069 * Returns : JB_ERR_OK on success, or
3070 * JB_ERR_MEMORY on out-of-memory error.
3072 *********************************************************************/
3073 static jb_err client_referrer(struct client_state *csp, char **header)
3075 const char *parameter;
3076 /* booleans for parameters we have to check multiple times */
3077 int parameter_conditional_block;
3078 int parameter_conditional_forge;
3080 #ifdef FEATURE_FORCE_LOAD
3082 * Since the referrer can include the prefix even
3083 * if the request itself is non-forced, we must
3084 * clean it unconditionally.
3086 * XXX: strclean is too broad
3088 strclean(*header, FORCE_PREFIX);
3089 #endif /* def FEATURE_FORCE_LOAD */
3091 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3093 /* Nothing left to do */
3097 parameter = csp->action->string[ACTION_STRING_REFERER];
3098 assert(parameter != NULL);
3099 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3100 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3102 if (!parameter_conditional_block && !parameter_conditional_forge)
3105 * As conditional-block and conditional-forge are the only
3106 * parameters that rely on the original referrer, we can
3107 * remove it now for all the others.
3112 if (0 == strcmpic(parameter, "block"))
3114 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3117 else if (parameter_conditional_block || parameter_conditional_forge)
3119 return handle_conditional_hide_referrer_parameter(header,
3120 csp->http->hostport, parameter_conditional_block);
3122 else if (0 == strcmpic(parameter, "forge"))
3124 return create_forged_referrer(header, csp->http->hostport);
3128 /* interpret parameter as user-supplied referer to fake */
3129 return create_fake_referrer(header, parameter);
3134 /*********************************************************************
3136 * Function : client_accept_language
3138 * Description : Handle the "Accept-Language" config setting properly.
3139 * Called from `sed'.
3142 * 1 : csp = Current client state (buffers, headers, etc...)
3143 * 2 : header = On input, pointer to header to modify.
3144 * On output, pointer to the modified header, or NULL
3145 * to remove the header. This function frees the
3146 * original string if necessary.
3148 * Returns : JB_ERR_OK on success, or
3149 * JB_ERR_MEMORY on out-of-memory error.
3151 *********************************************************************/
3152 static jb_err client_accept_language(struct client_state *csp, char **header)
3157 * Are we messing with the Accept-Language?
3159 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3161 /*I don't think so*/
3165 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3167 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3170 * Blocking Accept-Language header
3172 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3179 * Replacing Accept-Language header
3182 *header = strdup("Accept-Language: ");
3183 string_append(header, newval);
3185 if (*header == NULL)
3187 log_error(LOG_LEVEL_ERROR,
3188 "Insufficient memory. Accept-Language header crunched without replacement.");
3192 log_error(LOG_LEVEL_HEADER,
3193 "Accept-Language header crunched and replaced with: %s", *header);
3196 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3200 /*********************************************************************
3202 * Function : crunch_client_header
3204 * Description : Crunch client header if it matches a string supplied by the
3205 * user. Called from `sed'.
3208 * 1 : csp = Current client state (buffers, headers, etc...)
3209 * 2 : header = On input, pointer to header to modify.
3210 * On output, pointer to the modified header, or NULL
3211 * to remove the header. This function frees the
3212 * original string if necessary.
3214 * Returns : JB_ERR_OK on success and always succeeds
3216 *********************************************************************/
3217 static jb_err crunch_client_header(struct client_state *csp, char **header)
3219 const char *crunch_pattern;
3221 /* Do we feel like crunching? */
3222 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3224 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3226 /* Is the current header the lucky one? */
3227 if (strstr(*header, crunch_pattern))
3229 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3237 /*********************************************************************
3239 * Function : client_uagent
3241 * Description : Handle the "user-agent" config setting properly
3242 * and remember its original value to enable browser
3243 * bug workarounds. Called from `sed'.
3246 * 1 : csp = Current client state (buffers, headers, etc...)
3247 * 2 : header = On input, pointer to header to modify.
3248 * On output, pointer to the modified header, or NULL
3249 * to remove the header. This function frees the
3250 * original string if necessary.
3252 * Returns : JB_ERR_OK on success, or
3253 * JB_ERR_MEMORY on out-of-memory error.
3255 *********************************************************************/
3256 static jb_err client_uagent(struct client_state *csp, char **header)
3260 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3265 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3272 *header = strdup("User-Agent: ");
3273 string_append(header, newval);
3275 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3277 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3281 /*********************************************************************
3283 * Function : client_ua
3285 * Description : Handle "ua-" headers properly. Called from `sed'.
3288 * 1 : csp = Current client state (buffers, headers, etc...)
3289 * 2 : header = On input, pointer to header to modify.
3290 * On output, pointer to the modified header, or NULL
3291 * to remove the header. This function frees the
3292 * original string if necessary.
3294 * Returns : JB_ERR_OK on success, or
3295 * JB_ERR_MEMORY on out-of-memory error.
3297 *********************************************************************/
3298 static jb_err client_ua(struct client_state *csp, char **header)
3300 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3302 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3310 /*********************************************************************
3312 * Function : client_from
3314 * Description : Handle the "from" config setting properly.
3315 * Called from `sed'.
3318 * 1 : csp = Current client state (buffers, headers, etc...)
3319 * 2 : header = On input, pointer to header to modify.
3320 * On output, pointer to the modified header, or NULL
3321 * to remove the header. This function frees the
3322 * original string if necessary.
3324 * Returns : JB_ERR_OK on success, or
3325 * JB_ERR_MEMORY on out-of-memory error.
3327 *********************************************************************/
3328 static jb_err client_from(struct client_state *csp, char **header)
3332 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3339 newval = csp->action->string[ACTION_STRING_FROM];
3342 * Are we blocking the e-mail address?
3344 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3346 log_error(LOG_LEVEL_HEADER, "crunched From!");
3350 log_error(LOG_LEVEL_HEADER, " modified");
3352 *header = strdup("From: ");
3353 string_append(header, newval);
3355 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3359 /*********************************************************************
3361 * Function : client_send_cookie
3363 * Description : Crunches the "cookie" header if necessary.
3364 * Called from `sed'.
3366 * XXX: Stupid name, doesn't send squat.
3369 * 1 : csp = Current client state (buffers, headers, etc...)
3370 * 2 : header = On input, pointer to header to modify.
3371 * On output, pointer to the modified header, or NULL
3372 * to remove the header. This function frees the
3373 * original string if necessary.
3375 * Returns : JB_ERR_OK on success, or
3376 * JB_ERR_MEMORY on out-of-memory error.
3378 *********************************************************************/
3379 static jb_err client_send_cookie(struct client_state *csp, char **header)
3381 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3383 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3391 /*********************************************************************
3393 * Function : client_x_forwarded
3395 * Description : Handle the "x-forwarded-for" config setting properly,
3396 * also used in the add_client_headers list. Called from `sed'.
3399 * 1 : csp = Current client state (buffers, headers, etc...)
3400 * 2 : header = On input, pointer to header to modify.
3401 * On output, pointer to the modified header, or NULL
3402 * to remove the header. This function frees the
3403 * original string if necessary.
3405 * Returns : JB_ERR_OK on success, or
3406 * JB_ERR_MEMORY on out-of-memory error.
3408 *********************************************************************/
3409 jb_err client_x_forwarded(struct client_state *csp, char **header)
3411 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3413 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3415 if (0 == strcmpic(parameter, "block"))
3418 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3420 else if (0 == strcmpic(parameter, "add"))
3422 string_append(header, ", ");
3423 string_append(header, csp->ip_addr_str);
3425 if (*header == NULL)
3427 return JB_ERR_MEMORY;
3429 log_error(LOG_LEVEL_HEADER,
3430 "Appended client IP address to %s", *header);
3431 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3435 log_error(LOG_LEVEL_FATAL,
3436 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3444 /*********************************************************************
3446 * Function : client_max_forwards
3448 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3449 * from the value of the Max-Forwards header field.
3452 * 1 : csp = Current client state (buffers, headers, etc...)
3453 * 2 : header = On input, pointer to header to modify.
3454 * On output, pointer to the modified header, or NULL
3455 * to remove the header. This function frees the
3456 * original string if necessary.
3458 * Returns : JB_ERR_OK on success, or
3459 * JB_ERR_MEMORY on out-of-memory error.
3461 *********************************************************************/
3462 static jb_err client_max_forwards(struct client_state *csp, char **header)
3466 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3467 (0 == strcmpic(csp->http->gpc, "options")))
3469 assert(*(*header+12) == ':');
3470 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3472 if (max_forwards > 0)
3474 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3475 log_error(LOG_LEVEL_HEADER,
3476 "Max-Forwards value for %s request reduced to %d.",
3477 csp->http->gpc, max_forwards);
3479 else if (max_forwards < 0)
3481 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3487 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3496 /*********************************************************************
3498 * Function : client_host
3500 * Description : If the request URI did not contain host and
3501 * port information, parse and evaluate the Host
3505 * 1 : csp = Current client state (buffers, headers, etc...)
3506 * 2 : header = On input, pointer to header to modify.
3507 * On output, pointer to the modified header, or NULL
3508 * to remove the header. This function frees the
3509 * original string if necessary.
3511 * Returns : JB_ERR_OK on success, or
3512 * JB_ERR_MEMORY on out-of-memory error.
3514 *********************************************************************/
3515 static jb_err client_host(struct client_state *csp, char **header)
3519 if (strlen(*header) < 7)
3521 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3526 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3527 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3530 p = strdup_or_die((*header)+6);
3532 q = strdup_or_die(p);
3534 freez(csp->http->hostport);
3535 csp->http->hostport = p;
3536 freez(csp->http->host);
3537 csp->http->host = q;
3538 q = strchr(csp->http->host, ':');
3541 /* Terminate hostname and evaluate port string */
3543 csp->http->port = atoi(q);
3547 csp->http->port = csp->http->ssl ? 443 : 80;
3550 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3551 csp->http->hostport, csp->http->host, csp->http->port);
3554 /* Signal client_host_adder() to return right away */
3555 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3561 /*********************************************************************
3563 * Function : client_if_modified_since
3565 * Description : Remove or modify the If-Modified-Since header.
3568 * 1 : csp = Current client state (buffers, headers, etc...)
3569 * 2 : header = On input, pointer to header to modify.
3570 * On output, pointer to the modified header, or NULL
3571 * to remove the header. This function frees the
3572 * original string if necessary.
3574 * Returns : JB_ERR_OK on success, or
3575 * JB_ERR_MEMORY on out-of-memory error.
3577 *********************************************************************/
3578 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3582 struct tm *timeptr = NULL;
3587 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3590 * The client got an error message because of a temporary problem,
3591 * the problem is gone and the client now tries to revalidate our
3592 * error message on the real server. The revalidation would always
3593 * end with the transmission of the whole document and there is
3594 * no need to expose the bogus If-Modified-Since header.
3596 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3599 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3601 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3603 if ((0 == strcmpic(newval, "block")))
3605 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3608 else /* add random value */
3610 if (JB_ERR_OK != parse_time_header(*header, &tm))
3612 log_error(LOG_LEVEL_HEADER,
3613 "Couldn't parse time in %s (crunching!)", *header);
3618 long int hours, minutes, seconds;
3619 long int rtime = strtol(newval, &endptr, 0);
3620 const int negative_range = (rtime < 0);
3624 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %ld minut%s)",
3625 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3631 rtime = pick_from_range(rtime);
3635 log_error(LOG_LEVEL_ERROR,
3636 "Random range is 0. Assuming time transformation test.");
3638 tm += rtime * (negative_range ? -1 : 1);
3639 timeptr = privoxy_gmtime_r(&tm, &gmt);
3640 if ((NULL == timeptr) || !strftime(newheader,
3641 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3643 log_error(LOG_LEVEL_ERROR,
3644 "Randomizing '%s' failed. Crunching the header without replacement.",
3650 *header = strdup("If-Modified-Since: ");
3651 string_append(header, newheader);
3653 if (*header == NULL)
3655 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3656 return JB_ERR_MEMORY;
3659 hours = rtime / 3600;
3660 minutes = rtime / 60 % 60;
3661 seconds = rtime % 60;
3663 log_error(LOG_LEVEL_HEADER,
3664 "Randomized: %s (%s %ld hou%s %ld minut%s %ld second%s",
3665 *header, (negative_range) ? "subtracted" : "added", hours,
3666 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3667 seconds, (seconds == 1) ? ")" : "s)");
3676 /*********************************************************************
3678 * Function : client_if_none_match
3680 * Description : Remove the If-None-Match header.
3683 * 1 : csp = Current client state (buffers, headers, etc...)
3684 * 2 : header = On input, pointer to header to modify.
3685 * On output, pointer to the modified header, or NULL
3686 * to remove the header. This function frees the
3687 * original string if necessary.
3689 * Returns : JB_ERR_OK on success, or
3690 * JB_ERR_MEMORY on out-of-memory error.
3692 *********************************************************************/
3693 static jb_err client_if_none_match(struct client_state *csp, char **header)
3695 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3697 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3705 /*********************************************************************
3707 * Function : client_x_filter
3709 * Description : Disables filtering if the client set "X-Filter: No".
3710 * Called from `sed'.
3713 * 1 : csp = Current client state (buffers, headers, etc...)
3714 * 2 : header = On input, pointer to header to modify.
3715 * On output, pointer to the modified header, or NULL
3716 * to remove the header. This function frees the
3717 * original string if necessary.
3719 * Returns : JB_ERR_OK on success
3721 *********************************************************************/
3722 jb_err client_x_filter(struct client_state *csp, char **header)
3724 if (0 == strcmpic(*header, "X-Filter: No"))
3726 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3728 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3732 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3734 log_error(LOG_LEVEL_HEADER,
3735 "force-text-mode overruled the client's request to fetch without filtering!");
3739 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3740 csp->flags |= CSP_FLAG_NO_FILTERING;
3741 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3743 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3751 /*********************************************************************
3753 * Function : client_range
3755 * Description : Removes Range, Request-Range and If-Range headers if
3756 * content filtering is enabled and the range doesn't
3759 * If the client's version of the document has been
3760 * altered by Privoxy, the server could interpret the
3761 * range differently than the client intended in which
3762 * case the user could end up with corrupted content.
3764 * If the range starts at byte 0 this isn't an issue
3765 * so the header can pass. Partial requests like this
3766 * are used to render preview images for videos without
3767 * downloading the whole video.
3769 * While HTTP doesn't require that range requests are
3770 * honoured and the client could simply abort the download
3771 * after receiving a sufficient amount of data, various
3772 * clients don't handle complete responses to range
3773 * requests gracefully and emit misleading error messages
3777 * 1 : csp = Current client state (buffers, headers, etc...)
3778 * 2 : header = On input, pointer to header to modify.
3779 * On output, pointer to the modified header, or NULL
3780 * to remove the header. This function frees the
3781 * original string if necessary.
3783 * Returns : JB_ERR_OK
3785 *********************************************************************/
3786 static jb_err client_range(struct client_state *csp, char **header)
3788 if (content_filters_enabled(csp->action)
3789 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3791 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3792 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3799 /* the following functions add headers directly to the header list */
3801 /*********************************************************************
3803 * Function : client_host_adder
3805 * Description : Adds the Host: header field if it is missing.
3806 * Called from `sed'.
3809 * 1 : csp = Current client state (buffers, headers, etc...)
3811 * Returns : JB_ERR_OK on success, or
3812 * JB_ERR_MEMORY on out-of-memory error.
3814 *********************************************************************/
3815 static jb_err client_host_adder(struct client_state *csp)
3820 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3822 /* Header already set by the client, nothing to do. */
3826 if (!csp->http->hostport || !*(csp->http->hostport))
3828 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3829 return JB_ERR_PARSE;
3833 * remove 'user:pass@' from 'proto://user:pass@host'
3835 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3841 p = csp->http->hostport;
3844 /* XXX: Just add it, we already made sure that it will be unique */
3845 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3846 err = enlist_unique_header(csp->headers, "Host", p);
3852 /*********************************************************************
3854 * Function : client_xtra_adder
3856 * Description : Used in the add_client_headers list. Called from `sed'.
3859 * 1 : csp = Current client state (buffers, headers, etc...)
3861 * Returns : JB_ERR_OK on success, or
3862 * JB_ERR_MEMORY on out-of-memory error.
3864 *********************************************************************/
3865 static jb_err client_xtra_adder(struct client_state *csp)
3867 struct list_entry *lst;
3870 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3871 lst ; lst = lst->next)
3873 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3874 err = enlist(csp->headers, lst->str);
3886 /*********************************************************************
3888 * Function : client_x_forwarded_for_adder
3890 * Description : Used in the add_client_headers list. Called from `sed'.
3893 * 1 : csp = Current client state (buffers, headers, etc...)
3895 * Returns : JB_ERR_OK on success, or
3896 * JB_ERR_MEMORY on out-of-memory error.
3898 *********************************************************************/
3899 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3901 char *header = NULL;
3904 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3905 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3906 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3909 * If we aren't adding X-Forwarded-For headers,
3910 * or we already appended an existing X-Forwarded-For
3911 * header, there's nothing left to do here.
3916 header = strdup("X-Forwarded-For: ");
3917 string_append(&header, csp->ip_addr_str);
3921 return JB_ERR_MEMORY;
3924 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3925 err = enlist(csp->headers, header);
3932 /*********************************************************************
3934 * Function : server_connection_adder
3936 * Description : Adds an appropriate "Connection:" header to csp->headers
3937 * unless the header was already present. Called from `sed'.
3940 * 1 : csp = Current client state (buffers, headers, etc...)
3942 * Returns : JB_ERR_OK on success, or
3943 * JB_ERR_MEMORY on out-of-memory error.
3945 *********************************************************************/
3946 static jb_err server_connection_adder(struct client_state *csp)
3948 const unsigned int flags = csp->flags;
3949 const char *response_status_line = csp->headers->first->str;
3950 static const char connection_close[] = "Connection: close";
3952 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3953 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3959 * XXX: if we downgraded the response, this check will fail.
3961 if ((csp->config->feature_flags &
3962 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3963 && (NULL != response_status_line)
3964 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3965 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3966 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3970 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3971 "without Connection header implies keep-alive.");
3972 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3976 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3978 return enlist(csp->headers, connection_close);
3982 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3983 /*********************************************************************
3985 * Function : server_proxy_connection_adder
3987 * Description : Adds a "Proxy-Connection: keep-alive" header to
3988 * csp->headers when appropriate.
3991 * 1 : csp = Current client state (buffers, headers, etc...)
3993 * Returns : JB_ERR_OK on success, or
3994 * JB_ERR_MEMORY on out-of-memory error.
3996 *********************************************************************/
3997 static jb_err server_proxy_connection_adder(struct client_state *csp)
3999 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
4000 jb_err err = JB_ERR_OK;
4002 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4003 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4004 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
4005 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4006 || (csp->flags & CSP_FLAG_CHUNKED))
4007 #ifdef FEATURE_HTTPS_INSPECTION
4008 && !client_use_ssl(csp)
4013 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
4014 err = enlist(csp->headers, proxy_connection_header);
4019 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4022 /*********************************************************************
4024 * Function : client_connection_header_adder
4026 * Description : Adds a proper "Connection:" header to csp->headers
4027 * unless the header was already present or it's a
4028 * CONNECT request. Called from `sed'.
4031 * 1 : csp = Current client state (buffers, headers, etc...)
4033 * Returns : JB_ERR_OK on success, or
4034 * JB_ERR_MEMORY on out-of-memory error.
4036 *********************************************************************/
4037 static jb_err client_connection_header_adder(struct client_state *csp)
4039 static const char connection_close[] = "Connection: close";
4041 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4042 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4048 * In case of CONNECT requests "Connection: close" is implied,
4049 * but actually setting the header has been reported to cause
4050 * problems with some forwarding proxies that close the
4051 * connection prematurely.
4053 if (csp->http->ssl != 0)
4058 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4059 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4060 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4061 && !strcmpic(csp->http->version, "HTTP/1.1"))
4063 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4066 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4068 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4070 return enlist(csp->headers, connection_close);
4074 /*********************************************************************
4076 * Function : server_http
4078 * Description : - Save the HTTP Status into csp->http->status
4079 * - Set CT_TABOO to prevent filtering if the answer
4080 * is a partial range (HTTP status 206)
4081 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4083 * - Normalize the HTTP-version.
4086 * 1 : csp = Current client state (buffers, headers, etc...)
4087 * 2 : header = On input, pointer to header to modify.
4088 * On output, pointer to the modified header, or NULL
4089 * to remove the header. This function frees the
4090 * original string if necessary.
4092 * Returns : JB_ERR_OK on success, or
4093 * JB_ERR_PARSE on fatal parse errors.
4095 *********************************************************************/
4096 static jb_err server_http(struct client_state *csp, char **header)
4098 char *reason_phrase = NULL;
4099 char *new_response_line;
4102 unsigned int major_version;
4103 unsigned int minor_version;
4105 /* Get the reason phrase which start after the second whitespace */
4106 p = strchr(*header, ' ');
4110 reason_phrase = strchr(p, ' ');
4113 if (reason_phrase != NULL)
4119 log_error(LOG_LEVEL_ERROR,
4120 "Response line lacks reason phrase: %s", *header);
4124 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4125 &minor_version, &(csp->http->status)))
4127 log_error(LOG_LEVEL_ERROR,
4128 "Failed to parse the response line: %s", *header);
4129 return JB_ERR_PARSE;
4132 if (csp->http->status == 101 ||
4133 csp->http->status == 206)
4135 csp->content_type = CT_TABOO;
4138 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4141 * According to RFC 7230 2.6 intermediaries MUST send
4142 * their own HTTP-version in forwarded messages.
4144 log_error(LOG_LEVEL_ERROR,
4145 "Unsupported HTTP version. Downgrading to 1.1.");
4150 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4152 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4156 /* Rebuild response line. */
4157 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4158 new_response_line = malloc_or_die(length);
4160 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4161 major_version, minor_version, csp->http->status, reason_phrase);
4163 if (0 != strcmp(*header, new_response_line))
4165 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4166 *header, new_response_line);
4170 *header = new_response_line;
4175 /*********************************************************************
4177 * Function : add_cooky_expiry_date
4179 * Description : Adds a cookie expiry date to a string.
4182 * 1 : cookie = On input, pointer to cookie to modify.
4183 * On output, pointer to the modified header.
4184 * The original string is freed.
4185 * 2 : lifetime = Seconds the cookie should be valid
4189 *********************************************************************/
4190 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4193 struct tm *timeptr = NULL;
4194 time_t expiry_date = time(NULL) + lifetime;
4197 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4198 if (NULL == timeptr)
4200 log_error(LOG_LEVEL_FATAL,
4201 "Failed to get the time in add_cooky_expiry_date()");
4203 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4204 if (JB_ERR_OK != string_append(cookie, tmp))
4206 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4211 /*********************************************************************
4213 * Function : server_set_cookie
4215 * Description : Handle the server "cookie" header properly.
4216 * Crunch, accept or rewrite it to a session cookie.
4217 * Called from `sed'.
4220 * 1 : csp = Current client state (buffers, headers, etc...)
4221 * 2 : header = On input, pointer to header to modify.
4222 * On output, pointer to the modified header, or NULL
4223 * to remove the header. This function frees the
4224 * original string if necessary.
4226 * Returns : JB_ERR_OK on success, or
4227 * JB_ERR_MEMORY on out-of-memory error.
4229 *********************************************************************/
4230 static jb_err server_set_cookie(struct client_state *csp, char **header)
4232 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4234 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4237 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4238 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4242 long cookie_lifetime = 0;
4245 NO_EXPIRY_DATE_SPECIFIED,
4246 EXPIRY_DATE_ACCEPTABLE,
4247 EXPIRY_DATE_UNACCEPTABLE
4248 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4250 /* A variable to store the tag we're working on */
4253 /* Skip "Set-Cookie:" (11 characters) in header */
4254 cur_tag = *header + 11;
4256 /* skip whitespace between "Set-Cookie:" and value */
4257 while (*cur_tag && privoxy_isspace(*cur_tag))
4264 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4266 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4268 cookie_lifetime = strtol(param, NULL, 0);
4269 if (cookie_lifetime < 0)
4271 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4273 cookie_lifetime *= 60;
4276 /* Loop through each tag in the cookie */
4280 char *next_tag = strchr(cur_tag, ';');
4281 if (next_tag != NULL)
4283 /* Skip the ';' character itself */
4286 /* skip whitespace ";" and start of tag */
4287 while (*next_tag && privoxy_isspace(*next_tag))
4294 /* "Next tag" is the end of the string */
4295 next_tag = cur_tag + strlen(cur_tag);
4299 * Check the expiration date to see
4300 * if the cookie is still valid, if yes,
4301 * rewrite it to a session cookie.
4303 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4305 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4307 if ((expiration_date[0] == '"')
4308 && (expiration_date[1] != '\0'))
4311 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4312 * that the expiration date isn't supposed to be quoted,
4313 * but some servers do it anyway.
4318 /* Did we detect the date properly? */
4319 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4322 * Nope, treat it as if it was still valid.
4324 * XXX: Should we remove the whole cookie instead?
4326 log_error(LOG_LEVEL_ERROR,
4327 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4328 string_move(cur_tag, next_tag);
4329 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4334 * Yes. Check if the cookie is still valid.
4336 * If the cookie is already expired it's probably
4337 * a delete cookie and even if it isn't, the browser
4338 * will discard it anyway.
4342 * XXX: timegm() isn't available on some AmigaOS
4343 * versions and our replacement doesn't work.
4345 * Our options are to either:
4347 * - disable session-cookies-only completely if timegm
4350 * - to simply remove all expired tags, like it has
4351 * been done until Privoxy 3.0.6 and to live with
4352 * the consequence that it can cause login/logout
4353 * problems on servers that don't validate their
4354 * input properly, or
4356 * - to replace it with mktime in which
4357 * case there is a slight chance of valid cookies
4358 * passing as already expired.
4360 * This is the way it's currently done and it's not
4361 * as bad as it sounds. If the missing GMT offset is
4362 * enough to change the result of the expiration check
4363 * the cookie will be only valid for a few hours
4364 * anyway, which in many cases will be shorter
4365 * than a browser session.
4367 if (cookie_time < now)
4369 log_error(LOG_LEVEL_HEADER,
4370 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4371 /* Just in case some clown sets more then one expiration date */
4373 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4375 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4377 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4378 "Its lifetime is below the limit.", *header);
4379 /* Just in case some clown sets more then one expiration date */
4381 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4386 * Still valid, delete expiration date by copying
4387 * the rest of the string over it.
4389 string_move(cur_tag, next_tag);
4391 /* That changed the header, need to issue a log message */
4392 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4395 * Note that the next tag has now been moved to *cur_tag,
4396 * so we do not need to update the cur_tag pointer.
4404 /* Move on to next cookie tag */
4409 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4411 assert(NULL != *header);
4412 if (cookie_lifetime != 0)
4414 add_cookie_expiry_date(header, cookie_lifetime);
4415 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4417 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4419 log_error(LOG_LEVEL_HEADER,
4420 "Cookie rewritten to a temporary one: %s", *header);
4429 #ifdef FEATURE_FORCE_LOAD
4430 /*********************************************************************
4432 * Function : strclean
4434 * Description : In-Situ-Eliminate all occurrences of substring in
4438 * 1 : string = string to clean
4439 * 2 : substring = substring to eliminate
4441 * Returns : Number of eliminations
4443 *********************************************************************/
4444 int strclean(char *string, const char *substring)
4450 len = strlen(substring);
4452 while((pos = strstr(string, substring)) != NULL)
4459 while (*p++ != '\0');
4466 #endif /* def FEATURE_FORCE_LOAD */
4469 /*********************************************************************
4471 * Function : parse_header_time
4473 * Description : Parses time formats used in HTTP header strings
4474 * to get the numerical respresentation.
4477 * 1 : header_time = HTTP header time as string.
4478 * 2 : result = storage for header_time in seconds
4480 * Returns : JB_ERR_OK if the time format was recognized, or
4481 * JB_ERR_PARSE otherwise.
4483 *********************************************************************/
4484 static jb_err parse_header_time(const char *header_time, time_t *result)
4488 * Checking for two-digit years first in an
4489 * attempt to work around GNU libc's strptime()
4490 * reporting negative year values when using %Y.
4492 static const char time_formats[][22] = {
4493 /* Tue, 02-Jun-37 20:00:00 */
4494 "%a, %d-%b-%y %H:%M:%S",
4495 /* Tue, 02 Jun 2037 20:00:00 */
4496 "%a, %d %b %Y %H:%M:%S",
4497 /* Tue, 02-Jun-2037 20:00:00 */
4498 "%a, %d-%b-%Y %H:%M:%S",
4499 /* Tuesday, 02-Jun-2037 20:00:00 */
4500 "%A, %d-%b-%Y %H:%M:%S",
4501 /* Tuesday Jun 02 20:00:00 2037 */
4502 "%A %b %d %H:%M:%S %Y"
4506 for (i = 0; i < SZ(time_formats); i++)
4509 * Zero out gmt to prevent time zone offsets.
4510 * Documented to be required for GNU libc.
4512 memset(&gmt, 0, sizeof(gmt));
4514 if (NULL != strptime(header_time, time_formats[i], &gmt))
4516 /* Sanity check for GNU libc. */
4517 if (gmt.tm_year < 0)
4519 log_error(LOG_LEVEL_HEADER,
4520 "Failed to parse '%s' using '%s'. Moving on.",
4521 header_time, time_formats[i]);
4524 *result = timegm(&gmt);
4526 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4528 * Verify that parsing the date recreated from the first
4529 * parse operation gets the previous result. If it doesn't,
4530 * either strptime() or strftime() are malfunctioning.
4532 * We could string-compare the recreated date with the original
4533 * header date, but this leads to false positives as strptime()
4534 * may let %a accept all day formats while strftime() will only
4538 char recreated_date[100];
4543 tm = privoxy_gmtime_r(result, &storage);
4544 if (!strftime(recreated_date, sizeof(recreated_date),
4545 time_formats[i], tm))
4547 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4548 header_time, time_formats[i]);
4551 memset(&gmt, 0, sizeof(gmt));
4552 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4554 log_error(LOG_LEVEL_ERROR,
4555 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4556 recreated_date, time_formats[i], header_time);
4559 result2 = timegm(&gmt);
4560 if (*result != result2)
4562 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4563 "Format: '%s'. In: '%s', out: '%s'. %ld != %ld. Rejecting.",
4564 time_formats[i], header_time, recreated_date, *result, result2);
4574 return JB_ERR_PARSE;
4578 /*********************************************************************
4580 * Function : parse_time_header
4582 * Description : Parses the time in an HTTP time header to get
4583 * the numerical respresentation.
4586 * 1 : header = HTTP header with a time value
4587 * 2 : result = storage for header_time in seconds
4589 * Returns : JB_ERR_OK if the time format was recognized, or
4590 * JB_ERR_PARSE otherwise.
4592 *********************************************************************/
4593 static jb_err parse_time_header(const char *header, time_t *result)
4595 const char *header_time;
4597 header_time = strchr(header, ':');
4600 * Currently this can't happen as all callers are called
4601 * through sed() which requires a header name followed by
4604 assert(header_time != NULL);
4607 if (*header_time == ' ')
4612 return parse_header_time(header_time, result);
4617 /*********************************************************************
4619 * Function : get_destination_from_headers
4621 * Description : Parse the "Host:" header to get the request's destination.
4622 * Only needed if the client's request was forcefully
4623 * redirected into Privoxy.
4625 * Code mainly copied from client_host() which is currently
4626 * run too late for this purpose.
4629 * 1 : headers = List of headers (one of them hopefully being
4630 * the "Host:" header)
4631 * 2 : http = storage for the result (host, port and hostport).
4633 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4634 * JB_ERR_PARSE if the host header couldn't be found,
4635 * JB_ERR_OK otherwise.
4637 *********************************************************************/
4638 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4644 host = get_header_value(headers, "Host:");
4648 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4649 return JB_ERR_PARSE;
4652 p = string_tolower(host);
4655 return JB_ERR_MEMORY;
4658 q = strdup_or_die(p);
4660 freez(http->hostport);
4664 q = strchr(http->host, ':');
4667 /* Terminate hostname and evaluate port string */
4669 http->port = atoi(q);
4676 /* Rebuild request URL */
4678 http->url = strdup("http://");
4679 string_append(&http->url, http->hostport);
4680 string_append(&http->url, http->path);
4681 if (http->url == NULL)
4683 return JB_ERR_MEMORY;
4686 log_error(LOG_LEVEL_HEADER,
4687 "Destination extracted from \"Host\" header. New request URL: %s",
4691 * Regenerate request line in "proxy format"
4692 * to make rewrites more convenient.
4694 assert(http->cmd != NULL);
4696 http->cmd = strdup_or_die(http->gpc);
4697 string_append(&http->cmd, " ");
4698 string_append(&http->cmd, http->url);
4699 string_append(&http->cmd, " ");
4700 string_append(&http->cmd, http->version);
4701 if (http->cmd == NULL)
4703 return JB_ERR_MEMORY;
4711 #ifdef FEATURE_HTTPS_INSPECTION
4712 /*********************************************************************
4714 * Function : get_destination_from_https_headers
4716 * Description : Parse the previously encrypted "Host:" header to
4717 * get the request's destination.
4720 * 1 : headers = List of headers (one of them hopefully being
4721 * the "Host:" header)
4722 * 2 : http = storage for the result (host, port and hostport).
4724 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4725 * JB_ERR_PARSE if the host header couldn't be found,
4726 * JB_ERR_OK otherwise.
4728 *********************************************************************/
4729 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4735 host = get_header_value(headers, "Host:");
4739 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4740 return JB_ERR_PARSE;
4743 p = string_tolower(host);
4746 return JB_ERR_MEMORY;
4749 q = strdup_or_die(p);
4751 freez(http->hostport);
4755 q = strchr(http->host, ':');
4758 /* Terminate hostname and evaluate port string */
4760 http->port = atoi(q);
4767 /* Rebuild request URL */
4769 http->url = strdup_or_die(http->path);
4771 log_error(LOG_LEVEL_HEADER,
4772 "Destination extracted from \"Host\" header. New request URL: %s",
4776 * Regenerate request line in "proxy format"
4777 * to make rewrites more convenient.
4779 assert(http->cmd != NULL);
4781 http->cmd = strdup_or_die(http->gpc);
4782 string_append(&http->cmd, " ");
4783 string_append(&http->cmd, http->url);
4784 string_append(&http->cmd, " ");
4785 string_append(&http->cmd, http->version);
4786 if (http->cmd == NULL)
4788 return JB_ERR_MEMORY;
4794 #endif /* def FEATURE_HTTPS_INSPECTION */
4797 /*********************************************************************
4799 * Function : create_forged_referrer
4801 * Description : Helper for client_referrer to forge a referer as
4802 * 'http://hostname[:port]/' to fool stupid
4803 * checks for in-site links
4806 * 1 : header = Pointer to header pointer
4807 * 2 : hostport = Host and optionally port as string
4809 * Returns : JB_ERR_OK in case of success, or
4810 * JB_ERR_MEMORY in case of memory problems.
4812 *********************************************************************/
4813 static jb_err create_forged_referrer(char **header, const char *hostport)
4815 assert(NULL == *header);
4817 *header = strdup("Referer: http://");
4818 string_append(header, hostport);
4819 string_append(header, "/");
4821 if (NULL == *header)
4823 return JB_ERR_MEMORY;
4826 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4833 /*********************************************************************
4835 * Function : create_fake_referrer
4837 * Description : Helper for client_referrer to create a fake referrer
4838 * based on a string supplied by the user.
4841 * 1 : header = Pointer to header pointer
4842 * 2 : hosthost = Referrer to fake
4844 * Returns : JB_ERR_OK in case of success, or
4845 * JB_ERR_MEMORY in case of memory problems.
4847 *********************************************************************/
4848 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4850 assert(NULL == *header);
4852 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4854 log_error(LOG_LEVEL_HEADER,
4855 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4857 *header = strdup("Referer: ");
4858 string_append(header, fake_referrer);
4860 if (NULL == *header)
4862 return JB_ERR_MEMORY;
4865 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4872 /*********************************************************************
4874 * Function : handle_conditional_hide_referrer_parameter
4876 * Description : Helper for client_referrer to crunch or forge
4877 * the referrer header if the host has changed.
4880 * 1 : header = Pointer to header pointer
4881 * 2 : host = The target host (may include the port)
4882 * 3 : parameter_conditional_block = Boolean to signal
4883 * if we're in conditional-block mode. If not set,
4884 * we're in conditional-forge mode.
4886 * Returns : JB_ERR_OK in case of success, or
4887 * JB_ERR_MEMORY in case of memory problems.
4889 *********************************************************************/
4890 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4891 const char *host, const int parameter_conditional_block)
4893 char *referer = strdup_or_die(*header);
4894 const size_t hostlength = strlen(host);
4895 const char *referer_url = NULL;
4897 /* referer begins with 'Referer: http[s]://' */
4898 if ((hostlength+17) < strlen(referer))
4901 * Shorten referer to make sure the referer is blocked
4902 * if www.example.org/www.example.com-shall-see-the-referer/
4903 * links to www.example.com/
4905 referer[hostlength+17] = '\0';
4907 referer_url = strstr(referer, "http://");
4908 if (NULL == referer_url)
4910 referer_url = strstr(referer, "https://");
4912 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4914 /* Host has changed, Referer is invalid or a https URL. */
4915 if (parameter_conditional_block)
4917 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4924 return create_forged_referrer(header, host);
4934 /*********************************************************************
4936 * Function : create_content_length_header
4938 * Description : Creates a Content-Length header.
4941 * 1 : content_length = The content length to be used in the header.
4942 * 2 : header = Allocated space to safe the header.
4943 * 3 : buffer_length = The length of the allocated space.
4947 *********************************************************************/
4948 static void create_content_length_header(unsigned long long content_length,
4949 char *header, size_t buffer_length)
4952 #if SIZEOF_LONG_LONG < 8
4953 #error sizeof(unsigned long long) too small
4955 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4957 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4962 /*********************************************************************
4964 * Function : get_expected_content_length
4966 * Description : Figures out the content length from a list of headers.
4969 * 1 : headers = List of headers
4971 * Returns : Number of bytes to expect
4973 *********************************************************************/
4974 unsigned long long get_expected_content_length(struct list *headers)
4976 const char *content_length_header;
4977 unsigned long long content_length = 0;
4979 content_length_header = get_header_value(headers, "Content-Length:");
4980 if (content_length_header != NULL)
4982 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4984 log_error(LOG_LEVEL_ERROR,
4985 "Failed to get the Content-Length in %s", content_length_header);
4986 /* XXX: The header will be removed later on */
4991 return content_length;