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,
581 "Invalid gzip header when decompressing.");
582 return JB_ERR_COMPRESS;
587 if (flags & GZIP_FLAG_RESERVED_BITS)
589 /* The gzip header has reserved bits set; bail out. */
590 log_error(LOG_LEVEL_ERROR,
591 "Invalid gzip header flags when decompressing.");
592 return JB_ERR_COMPRESS;
596 * Skip mtime (4 bytes), extra flags (1 byte)
597 * and OS type (1 byte).
601 /* Skip extra fields if necessary. */
602 if (flags & GZIP_FLAG_EXTRA_FIELDS)
605 * Skip a given number of bytes, specified
606 * as a 16-bit little-endian value.
608 * XXX: this code is untested and should probably be removed.
612 if (cur + 2 >= csp->iob->eod)
614 log_error(LOG_LEVEL_ERROR,
615 "gzip extra field flag set but insufficient data available.");
616 return JB_ERR_COMPRESS;
620 skip_bytes += (unsigned char)*cur++ << 8;
623 * The number of bytes to skip should be positive
624 * and we'd like to stay in the buffer.
626 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
628 log_error(LOG_LEVEL_ERROR,
629 "Unreasonable amount of bytes to skip (%d). "
630 "Stopping decompression.",
632 return JB_ERR_COMPRESS;
634 log_error(LOG_LEVEL_INFO,
635 "Skipping %d bytes for gzip compression. "
636 "Does this sound right?",
641 /* Skip the filename if necessary. */
642 if (flags & GZIP_FLAG_FILE_NAME)
644 /* A null-terminated string is supposed to follow. */
645 while ((cur < csp->iob->eod) && *cur++);
648 /* Skip the comment if necessary. */
649 if (flags & GZIP_FLAG_COMMENT)
651 /* A null-terminated string is supposed to follow. */
652 while ((cur < csp->iob->eod) && *cur++);
655 /* Skip the CRC if necessary. */
656 if (flags & GZIP_FLAG_CHECKSUM)
661 if (cur >= csp->iob->eod)
664 * If the current position pointer reached or passed
665 * the buffer end, we were obviously tricked to skip
668 log_error(LOG_LEVEL_ERROR,
669 "Malformed gzip header detected. Aborting decompression.");
670 return JB_ERR_COMPRESS;
674 else if (csp->content_type & CT_DEFLATE)
677 * In theory (that is, according to RFC 1950), deflate-compressed
678 * data should begin with a two-byte zlib header and have an
679 * adler32 checksum at the end. It seems that in practice only
680 * the raw compressed data is sent. Note that this means that
681 * we are not RFC 1950-compliant here, but the advantage is that
682 * this actually works. :)
684 * We add a dummy null byte to tell zlib where the data ends,
685 * and later inform it not to expect a header.
687 * Fortunately, add_to_iob() has thoughtfully null-terminated
688 * the buffer; we can just increment the end pointer to include
695 log_error(LOG_LEVEL_ERROR,
696 "Unable to determine compression format for decompression.");
697 return JB_ERR_COMPRESS;
700 /* Set up the fields required by zlib. */
701 zstr.next_in = (Bytef *)cur;
702 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
703 zstr.zalloc = Z_NULL;
705 zstr.opaque = Z_NULL;
708 * Passing -MAX_WBITS to inflateInit2 tells the library
709 * that there is no zlib header.
711 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
713 log_error(LOG_LEVEL_ERROR, "Error initializing decompression.");
714 return JB_ERR_COMPRESS;
718 * Next, we allocate new storage for the inflated data.
719 * We don't modify the existing iob yet, so in case there
720 * is an error in decompression we can recover gracefully.
722 buf = zalloc(bufsize);
725 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob.");
726 return JB_ERR_MEMORY;
729 assert(bufsize >= skip_size);
730 memcpy(buf, csp->iob->buf, skip_size);
731 zstr.avail_out = (uInt)(bufsize - skip_size);
732 zstr.next_out = (Bytef *)buf + skip_size;
734 /* Try to decompress the whole stream in one shot. */
735 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
737 /* We need to allocate more memory for the output buffer. */
739 char *tmpbuf; /* used for realloc'ing the buffer */
740 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
742 if (0 == zstr.avail_in)
745 * If zlib wants more data then there's a problem, because
746 * the complete compressed file should have been buffered.
748 log_error(LOG_LEVEL_ERROR,
749 "Unexpected end of compressed iob. Using what we got so far.");
754 * If we reached the buffer limit and still didn't have enough
755 * memory, just give up. Due to the ceiling enforced by the next
756 * if block we could actually check for equality here, but as it
757 * can be easily mistaken for a bug we don't.
759 if (bufsize >= csp->config->buffer_limit)
761 log_error(LOG_LEVEL_ERROR,
762 "Buffer limit reached while decompressing iob.");
765 return JB_ERR_MEMORY;
768 /* Try doubling the buffer size each time. */
771 /* Don't exceed the buffer limit. */
772 if (bufsize > csp->config->buffer_limit)
774 bufsize = csp->config->buffer_limit;
777 /* Try to allocate the new buffer. */
778 tmpbuf = realloc(buf, bufsize);
781 log_error(LOG_LEVEL_ERROR,
782 "Out of memory decompressing iob.");
785 return JB_ERR_MEMORY;
790 char *oldnext_out = (char *)zstr.next_out;
793 * Update the fields for inflate() to use the new
794 * buffer, which may be in a location different from
797 zstr.avail_out += (uInt)(bufsize - oldbufsize);
798 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
801 * Compare with an uglier method of calculating these values
802 * that doesn't require the extra oldbufsize variable.
804 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
805 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
811 if (Z_STREAM_ERROR == inflateEnd(&zstr))
813 log_error(LOG_LEVEL_ERROR,
814 "Inconsistent stream state after decompression: %s", zstr.msg);
816 * XXX: Intentionally no return.
818 * According to zlib.h, Z_STREAM_ERROR is returned
819 * "if the stream state was inconsistent".
821 * I assume in this case inflate()'s status
822 * would also be something different than Z_STREAM_END
823 * so this check should be redundant, but lets see.
827 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
830 * We failed to decompress the stream and it's
831 * not simply because of missing data.
833 log_error(LOG_LEVEL_ERROR,
834 "Unexpected error while decompressing to the buffer (iob): %s",
837 return JB_ERR_COMPRESS;
841 * Finally, we can actually update the iob, since the
842 * decompression was successful. First, free the old
845 freez(csp->iob->buf);
847 /* Now, update the iob to use the new buffer. */
849 csp->iob->cur = csp->iob->buf + skip_size;
850 csp->iob->eod = (char *)zstr.next_out;
851 csp->iob->size = bufsize;
854 * Make sure the new uncompressed iob obeys some minimal
855 * consistency conditions.
857 if ((csp->iob->buf <= csp->iob->cur)
858 && (csp->iob->cur <= csp->iob->eod)
859 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
861 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
862 if (new_size > (size_t)0)
864 log_error(LOG_LEVEL_RE_FILTER,
865 "Decompression successful. Old size: %lu, new size: %lu.",
870 /* zlib thinks this is OK, so let's do the same. */
871 log_error(LOG_LEVEL_RE_FILTER,
872 "Decompression didn't result in any content.");
877 /* It seems that zlib did something weird. */
878 log_error(LOG_LEVEL_ERROR,
879 "Inconsistent buffer after decompression.");
880 return JB_ERR_COMPRESS;
886 #endif /* defined(FEATURE_ZLIB) */
889 /*********************************************************************
891 * Function : normalize_lws
893 * Description : Reduces unquoted linear whitespace in headers to
894 * a single space in accordance with RFC 7230 3.2.4.
895 * This simplifies parsing and filtering later on.
898 * 1 : header = A header with linear whitespace to reduce.
902 *********************************************************************/
903 static void normalize_lws(char *header)
906 int reducing_white_space_message_logged = 0;
910 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
914 while (privoxy_isspace(*q))
918 if (!reducing_white_space_message_logged)
920 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
921 reducing_white_space_message_logged = 1;
928 log_error(LOG_LEVEL_HEADER,
929 "Converting tab to space in '%s'", header);
934 char *end_of_token = strstr(p+1, "\"");
936 if (NULL != end_of_token)
938 /* Don't mess with quoted text. */
943 log_error(LOG_LEVEL_HEADER,
944 "Ignoring single quote in '%s'", header);
950 p = strchr(header, ':');
951 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
954 * There's still space before the colon.
962 /*********************************************************************
964 * Function : get_header
966 * Description : This (odd) routine will parse the csp->iob
967 * to get the next complete header.
970 * 1 : iob = The I/O buffer to parse, usually csp->iob.
972 * Returns : Any one of the following:
974 * 1) a pointer to a dynamically allocated string that contains a header line
975 * 2) NULL indicating that the end of the header was reached
976 * 3) "" indicating that the end of the iob was reached before finding
977 * a complete header line.
979 *********************************************************************/
980 char *get_header(struct iob *iob)
984 header = get_header_line(iob);
986 if ((header == NULL) || (*header == '\0'))
989 * No complete header read yet, tell the client.
994 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
997 * Header spans multiple lines, append the next one.
999 char *continued_header;
1001 continued_header = get_header_line(iob);
1002 if ((continued_header == NULL) || (*continued_header == '\0'))
1005 * No complete header read yet, return what we got.
1006 * XXX: Should "unread" header instead.
1008 log_error(LOG_LEVEL_INFO,
1009 "Failed to read a multi-line header properly: '%s'",
1014 if (JB_ERR_OK != string_join(&header, continued_header))
1016 log_error(LOG_LEVEL_FATAL,
1017 "Out of memory while appending multiple headers.");
1021 /* XXX: remove before next stable release. */
1022 log_error(LOG_LEVEL_HEADER,
1023 "Merged multiple header lines to: '%s'",
1028 normalize_lws(header);
1035 /*********************************************************************
1037 * Function : get_header_line
1039 * Description : This (odd) routine will parse the csp->iob
1040 * to get the next header line.
1043 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1045 * Returns : Any one of the following:
1047 * 1) a pointer to a dynamically allocated string that contains a header line
1048 * 2) NULL indicating that the end of the header was reached
1049 * 3) "" indicating that the end of the iob was reached before finding
1050 * a complete header line.
1052 *********************************************************************/
1053 static char *get_header_line(struct iob *iob)
1057 if ((iob->cur == NULL)
1058 || ((p = strchr(iob->cur, '\n')) == NULL))
1060 return(""); /* couldn't find a complete header */
1065 ret = strdup(iob->cur);
1068 /* FIXME No way to handle error properly */
1069 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1071 assert(ret != NULL);
1075 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1077 /* is this a blank line (i.e. the end of the header) ? */
1089 /*********************************************************************
1091 * Function : get_header_value
1093 * Description : Get the value of a given header from a chained list
1094 * of header lines or return NULL if no such header is
1095 * present in the list.
1098 * 1 : header_list = pointer to list
1099 * 2 : header_name = string with name of header to look for.
1100 * Trailing colon required, capitalization
1103 * Returns : NULL if not found, else value of header
1105 *********************************************************************/
1106 char *get_header_value(const struct list *header_list, const char *header_name)
1108 struct list_entry *cur_entry;
1112 assert(header_list);
1113 assert(header_name);
1114 length = strlen(header_name);
1116 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1120 if (!strncmpic(cur_entry->str, header_name, length))
1123 * Found: return pointer to start of value
1125 ret = cur_entry->str + length;
1126 while (*ret && privoxy_isspace(*ret)) ret++;
1140 /*********************************************************************
1142 * Function : scan_headers
1144 * Description : Scans headers, applies tags and updates action bits.
1147 * 1 : csp = Current client state (buffers, headers, etc...)
1149 * Returns : JB_ERR_OK
1151 *********************************************************************/
1152 static jb_err scan_headers(struct client_state *csp)
1154 struct list_entry *h; /* Header */
1155 jb_err err = JB_ERR_OK;
1157 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1159 /* Header crunch()ed in previous run? -> ignore */
1160 if (h->str == NULL) continue;
1161 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1162 err = header_tagger(csp, h->str);
1169 /*********************************************************************
1171 * Function : enforce_header_order
1173 * Description : Enforces a given header order.
1176 * 1 : headers = List of headers to order.
1177 * 2 : ordered_headers = List of ordered header names.
1181 *********************************************************************/
1182 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1184 struct list_entry *sorted_header;
1185 struct list new_headers[1];
1186 struct list_entry *header;
1188 init_list(new_headers);
1190 /* The request line is always the first "header" */
1192 assert(NULL != headers->first->str);
1193 enlist(new_headers, headers->first->str);
1194 freez(headers->first->str)
1196 /* Enlist the specified headers in the given order */
1198 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1199 sorted_header = sorted_header->next)
1201 const size_t sorted_header_length = strlen(sorted_header->str);
1202 for (header = headers->first; header != NULL; header = header->next)
1204 /* Header enlisted in previous run? -> ignore */
1205 if (header->str == NULL) continue;
1207 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1208 && (header->str[sorted_header_length] == ':'))
1210 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1211 if (JB_ERR_OK != enlist(new_headers, header->str))
1213 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1220 /* Enlist the rest of the headers behind the ordered ones */
1221 for (header = headers->first; header != NULL; header = header->next)
1223 /* Header enlisted in previous run? -> ignore */
1224 if (header->str == NULL) continue;
1226 log_error(LOG_LEVEL_HEADER,
1227 "Enlisting left-over header %s", header->str);
1228 if (JB_ERR_OK != enlist(new_headers, header->str))
1230 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1235 list_remove_all(headers);
1236 headers->first = new_headers->first;
1237 headers->last = new_headers->last;
1243 /*********************************************************************
1247 * Description : add, delete or modify lines in the HTTP header streams.
1248 * On entry, it receives a linked list of headers space
1249 * that was allocated dynamically (both the list nodes
1250 * and the header contents).
1252 * As a side effect it frees the space used by the original
1256 * 1 : csp = Current client state (buffers, headers, etc...)
1257 * 2 : filter_server_headers = Boolean to switch between
1258 * server and header filtering.
1260 * Returns : JB_ERR_OK in case off success, or
1261 * JB_ERR_MEMORY on some out-of-memory errors, or
1262 * JB_ERR_PARSE in case of fatal parse errors.
1264 *********************************************************************/
1265 jb_err sed(struct client_state *csp, int filter_server_headers)
1267 /* XXX: use more descriptive names. */
1268 struct list_entry *p;
1269 const struct parsers *v;
1270 const add_header_func_ptr *f;
1271 jb_err err = JB_ERR_OK;
1275 if (filter_server_headers)
1277 v = server_patterns;
1278 f = add_server_headers;
1279 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1283 v = client_patterns;
1284 f = add_client_headers;
1285 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1288 while (v->str != NULL)
1290 for (p = csp->headers->first; p != NULL; p = p->next)
1292 /* Header crunch()ed in previous run? -> ignore */
1293 if (p->str == NULL) continue;
1295 /* Does the current parser handle this header? */
1296 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1297 (v->len == CHECK_EVERY_HEADER_REMAINING))
1299 err = v->parser(csp, &(p->str));
1300 if (err != JB_ERR_OK)
1309 if (filter_server_headers &&
1310 (csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET) &&
1311 (csp->flags & CSP_FLAG_CHUNKED))
1313 /* RFC 2616 4.4 3 */
1314 log_error(LOG_LEVEL_HEADER, "Ignoring the Content-Length header "
1315 "sent by the server as the response is chunk-encoded.");
1316 csp->flags &= ~CSP_FLAG_CONTENT_LENGTH_SET;
1317 csp->expected_content_length = 0;
1320 /* place additional headers on the csp->headers list */
1321 while ((err == JB_ERR_OK) && (*f))
1327 if (!filter_server_headers &&
1328 !list_is_empty(csp->config->ordered_client_headers) &&
1329 csp->headers->first->str != NULL)
1331 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1338 #ifdef FEATURE_HTTPS_INSPECTION
1339 /*********************************************************************
1341 * Function : sed_https
1343 * Description : add, delete or modify lines in the HTTPS client
1344 * header streams. Wrapper around sed().
1347 * 1 : csp = Current client state (buffers, headers, etc...)
1349 * Returns : JB_ERR_OK in case off success, or
1350 * JB_ERR_MEMORY on some out-of-memory errors, or
1351 * JB_ERR_PARSE in case of fatal parse errors.
1353 *********************************************************************/
1354 jb_err sed_https(struct client_state *csp)
1357 struct list headers;
1360 * Temporarily replace csp->headers with csp->https_headers
1361 * to trick sed() into filtering the https headers.
1363 headers.first = csp->headers->first;
1364 headers.last = csp->headers->last;
1365 csp->headers->first = csp->https_headers->first;
1366 csp->headers->last = csp->https_headers->last;
1369 * Start with fresh tags. Already existing tags may
1370 * be set again. This is necessary to overrule
1371 * URL-based patterns.
1373 destroy_list(csp->tags);
1376 * We want client header filters and taggers
1377 * so temporarily remove the flag.
1379 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1380 err = sed(csp, FILTER_CLIENT_HEADERS);
1381 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1384 * Update the https headers list which may have
1385 * been modified due to header additions or header
1388 csp->https_headers->first = csp->headers->first;
1389 csp->https_headers->last = csp->headers->last;
1391 csp->headers->first = headers.first;
1392 csp->headers->last = headers.last;
1396 #endif /* def FEATURE_HTTPS_INSPECTION */
1399 /*********************************************************************
1401 * Function : update_server_headers
1403 * Description : Updates server headers after the body has been modified.
1406 * 1 : csp = Current client state (buffers, headers, etc...)
1408 * Returns : JB_ERR_OK in case off success, or
1409 * JB_ERR_MEMORY on out-of-memory error.
1411 *********************************************************************/
1412 jb_err update_server_headers(struct client_state *csp)
1414 jb_err err = JB_ERR_OK;
1416 static const struct parsers server_patterns_light[] = {
1417 { "Content-Length:", 15, server_adjust_content_length },
1418 { "Transfer-Encoding:", 18, server_transfer_coding },
1420 { "Content-Encoding:", 17, server_adjust_content_encoding },
1421 #endif /* def FEATURE_ZLIB */
1425 if (strncmpic(csp->http->cmd, "HEAD", 4))
1427 const struct parsers *v;
1428 struct list_entry *p;
1430 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1432 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1434 /* Header crunch()ed in previous run? -> ignore */
1435 if (p->str == NULL) continue;
1437 /* Does the current parser handle this header? */
1438 if (strncmpic(p->str, v->str, v->len) == 0)
1440 err = v->parser(csp, (char **)&(p->str));
1446 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1447 if ((JB_ERR_OK == err)
1448 && (csp->flags & CSP_FLAG_MODIFIED)
1449 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1450 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1454 create_content_length_header(csp->content_length, header, sizeof(header));
1455 err = enlist(csp->headers, header);
1456 if (JB_ERR_OK == err)
1458 log_error(LOG_LEVEL_HEADER,
1459 "Content modified with no Content-Length header set. "
1460 "Created: %s.", header);
1461 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1464 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1466 #ifdef FEATURE_COMPRESSION
1467 if ((JB_ERR_OK == err)
1468 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1470 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1471 if (JB_ERR_OK == err)
1473 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1482 /*********************************************************************
1484 * Function : header_tagger
1486 * Description : Executes all text substitutions from applying
1487 * tag actions and saves the result as tag.
1489 * XXX: Shares enough code with filter_header() and
1490 * pcrs_filter_response() to warrant some helper functions.
1493 * 1 : csp = Current client state (buffers, headers, etc...)
1494 * 2 : header = Header that is used as tagger input
1496 * Returns : JB_ERR_OK on success and always succeeds
1498 *********************************************************************/
1499 static jb_err header_tagger(struct client_state *csp, char *header)
1501 enum filter_type wanted_filter_type;
1502 int multi_action_index;
1505 struct re_filterfile_spec *b;
1506 struct list_entry *tag_name;
1508 const size_t header_length = strlen(header);
1510 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1512 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1513 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1517 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1518 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1521 if (list_is_empty(csp->action->multi[multi_action_index])
1522 || filters_available(csp) == FALSE)
1524 /* Return early if no taggers apply or if none are available. */
1528 /* Execute all applying taggers */
1529 for (tag_name = csp->action->multi[multi_action_index]->first;
1530 NULL != tag_name; tag_name = tag_name->next)
1532 char *modified_tag = NULL;
1534 size_t size = header_length;
1537 b = get_filter(csp, tag_name->str, wanted_filter_type);
1543 joblist = b->joblist;
1545 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1547 if (NULL == joblist)
1549 log_error(LOG_LEVEL_TAGGING,
1550 "Tagger %s has empty joblist. Nothing to do.", b->name);
1554 /* execute their pcrs_joblist on the header. */
1555 for (job = joblist; NULL != job; job = job->next)
1557 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1561 /* Success, continue with the modified version. */
1570 /* Tagger doesn't match */
1573 /* Regex failure, log it but continue anyway. */
1574 assert(NULL != header);
1575 log_error(LOG_LEVEL_ERROR,
1576 "Problems with tagger \'%s\' and header \'%s\': %s",
1577 b->name, header, pcrs_strerror(hits));
1579 freez(modified_tag);
1583 if (b->dynamic) pcrs_free_joblist(joblist);
1585 /* If this tagger matched */
1591 * There is no technical limitation which makes
1592 * it impossible to use empty tags, but I assume
1593 * no one would do it intentionally.
1596 log_error(LOG_LEVEL_TAGGING,
1597 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1601 if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
1603 log_error(LOG_LEVEL_TAGGING,
1604 "Tagger \'%s\' didn't add tag \'%s\': suppressed",
1610 if (!list_contains_item(csp->tags, tag))
1612 if (JB_ERR_OK != enlist(csp->tags, tag))
1614 log_error(LOG_LEVEL_ERROR,
1615 "Insufficient memory to add tag \'%s\', "
1616 "based on tagger \'%s\' and header \'%s\'",
1617 tag, b->name, header);
1621 char *action_message;
1623 * update the action bits right away, to make
1624 * tagging based on tags set by earlier taggers
1625 * of the same kind possible.
1627 if (update_action_bits_for_tag(csp, tag))
1629 action_message = "Action bits updated accordingly.";
1633 action_message = "No action bits update necessary.";
1636 log_error(LOG_LEVEL_TAGGING,
1637 "Tagger \'%s\' added tag \'%s\'. %s",
1638 b->name, tag, action_message);
1643 /* XXX: Is this log-worthy? */
1644 log_error(LOG_LEVEL_TAGGING,
1645 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1655 /* here begins the family of parser functions that reformat header lines */
1657 /*********************************************************************
1659 * Function : filter_header
1661 * Description : Executes all text substitutions from all applying
1662 * +(server|client)-header-filter actions on the header.
1663 * Most of the code was copied from pcrs_filter_response,
1664 * including the rather short variable names
1667 * 1 : csp = Current client state (buffers, headers, etc...)
1668 * 2 : header = On input, pointer to header to modify.
1669 * On output, pointer to the modified header, or NULL
1670 * to remove the header. This function frees the
1671 * original string if necessary.
1673 * Returns : JB_ERR_OK on success and always succeeds
1675 *********************************************************************/
1676 static jb_err filter_header(struct client_state *csp, char **header)
1680 size_t size = strlen(*header);
1682 char *newheader = NULL;
1685 struct re_filterfile_spec *b;
1686 struct list_entry *filtername;
1688 enum filter_type wanted_filter_type;
1689 int multi_action_index;
1691 if (csp->flags & CSP_FLAG_NO_FILTERING)
1696 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1698 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1699 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1703 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1704 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1707 if (list_is_empty(csp->action->multi[multi_action_index])
1708 || filters_available(csp) == FALSE)
1710 /* Return early if no filters apply or if none are available. */
1714 /* Execute all applying header filters */
1715 for (filtername = csp->action->multi[multi_action_index]->first;
1716 filtername != NULL; filtername = filtername->next)
1718 int current_hits = 0;
1721 b = get_filter(csp, filtername->str, wanted_filter_type);
1727 joblist = b->joblist;
1729 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1731 if (NULL == joblist)
1733 log_error(LOG_LEVEL_RE_FILTER,
1734 "Filter %s has empty joblist. Nothing to do.", b->name);
1738 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %lu) with \'%s\' ...",
1739 *header, size, b->name);
1741 /* Apply all jobs from the joblist */
1742 for (job = joblist; NULL != job; job = job->next)
1744 matches = pcrs_execute(job, *header, size, &newheader, &size);
1747 current_hits += matches;
1748 log_error(LOG_LEVEL_HEADER,
1749 "Transforming \"%s\" to \"%s\"", *header, newheader);
1751 *header = newheader;
1753 else if (0 == matches)
1755 /* Filter doesn't change header */
1761 log_error(LOG_LEVEL_ERROR,
1762 "Filtering \'%s\' with \'%s\' didn't work out: %s",
1763 *header, b->name, pcrs_strerror(matches));
1764 if (newheader != NULL)
1766 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1772 if (b->dynamic) pcrs_free_joblist(joblist);
1774 log_error(LOG_LEVEL_RE_FILTER,
1775 "... produced %d hits (new size %lu).", current_hits, size);
1776 hits += current_hits;
1780 * Additionally checking for hits is important because if
1781 * the continue hack is triggered, server headers can
1782 * arrive empty to separate multiple heads from each other.
1784 if ((0 == size) && hits)
1786 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1794 /*********************************************************************
1796 * Function : server_connection
1798 * Description : Makes sure a proper "Connection:" header is
1799 * set and signals connection_header_adder to
1803 * 1 : csp = Current client state (buffers, headers, etc...)
1804 * 2 : header = On input, pointer to header to modify.
1805 * On output, pointer to the modified header, or NULL
1806 * to remove the header. This function frees the
1807 * original string if necessary.
1809 * Returns : JB_ERR_OK on success.
1811 *********************************************************************/
1812 static jb_err server_connection(struct client_state *csp, char **header)
1814 if (!strcmpic(*header, "Connection: keep-alive")
1815 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1816 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1820 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1821 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1823 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1826 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1828 log_error(LOG_LEVEL_HEADER,
1829 "Keeping the server header '%s' around.", *header);
1832 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1834 char *old_header = *header;
1836 *header = strdup_or_die("Connection: close");
1837 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1842 /* Signal server_connection_adder() to return early. */
1843 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1849 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1850 /*********************************************************************
1852 * Function : server_keep_alive
1854 * Description : Stores the server's keep alive timeout.
1857 * 1 : csp = Current client state (buffers, headers, etc...)
1858 * 2 : header = On input, pointer to header to modify.
1859 * On output, pointer to the modified header, or NULL
1860 * to remove the header. This function frees the
1861 * original string if necessary.
1863 * Returns : JB_ERR_OK.
1865 *********************************************************************/
1866 static jb_err server_keep_alive(struct client_state *csp, char **header)
1868 unsigned int keep_alive_timeout;
1869 const char *timeout_position = strstr(*header, "timeout=");
1871 if ((NULL == timeout_position)
1872 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1874 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1878 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1880 log_error(LOG_LEVEL_HEADER,
1881 "Reducing keep-alive timeout from %u to %u.",
1882 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1883 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1887 /* XXX: Is this log worthy? */
1888 log_error(LOG_LEVEL_HEADER,
1889 "Server keep-alive timeout is %u. Sticking with %u.",
1890 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1892 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1901 /*********************************************************************
1903 * Function : server_proxy_connection
1905 * Description : Figures out whether or not we should add a
1906 * Proxy-Connection header.
1909 * 1 : csp = Current client state (buffers, headers, etc...)
1910 * 2 : header = On input, pointer to header to modify.
1911 * On output, pointer to the modified header, or NULL
1912 * to remove the header. This function frees the
1913 * original string if necessary.
1915 * Returns : JB_ERR_OK.
1917 *********************************************************************/
1918 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1920 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1923 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1926 /*********************************************************************
1928 * Function : proxy_authentication
1930 * Description : Removes headers that are relevant for proxy
1931 * authentication unless forwarding them has
1932 * been explicitly requested.
1935 * 1 : csp = Current client state (buffers, headers, etc...)
1936 * 2 : header = On input, pointer to header to modify.
1937 * On output, pointer to the modified header, or NULL
1938 * to remove the header. This function frees the
1939 * original string if necessary.
1941 * Returns : JB_ERR_OK.
1943 *********************************************************************/
1944 static jb_err proxy_authentication(struct client_state *csp, char **header)
1946 if ((csp->config->feature_flags &
1947 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1948 log_error(LOG_LEVEL_HEADER,
1949 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1956 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1957 /*********************************************************************
1959 * Function : client_keep_alive
1961 * Description : Stores the client's keep alive timeout.
1964 * 1 : csp = Current client state (buffers, headers, etc...)
1965 * 2 : header = On input, pointer to header to modify.
1966 * On output, pointer to the modified header, or NULL
1967 * to remove the header. This function frees the
1968 * original string if necessary.
1970 * Returns : JB_ERR_OK.
1972 *********************************************************************/
1973 static jb_err client_keep_alive(struct client_state *csp, char **header)
1975 unsigned int keep_alive_timeout;
1976 char *timeout_position;
1978 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1980 log_error(LOG_LEVEL_HEADER,
1981 "keep-alive support is disabled. Crunching: %s.", *header);
1986 /* Check for parameter-less format "Keep-Alive: 100" */
1987 timeout_position = strstr(*header, ": ");
1988 if ((NULL == timeout_position)
1989 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1991 /* Assume parameter format "Keep-Alive: timeout=100" */
1992 timeout_position = strstr(*header, "timeout=");
1993 if ((NULL == timeout_position)
1994 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1996 log_error(LOG_LEVEL_HEADER,
1997 "Couldn't parse: '%s'. Using default timeout %u",
1998 *header, csp->config->keep_alive_timeout);
2005 if (keep_alive_timeout < csp->config->keep_alive_timeout)
2007 log_error(LOG_LEVEL_HEADER,
2008 "Reducing keep-alive timeout from %u to %u.",
2009 csp->config->keep_alive_timeout, keep_alive_timeout);
2010 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
2014 /* XXX: Is this log worthy? */
2015 log_error(LOG_LEVEL_HEADER,
2016 "Client keep-alive timeout is %u. Sticking with %u.",
2017 keep_alive_timeout, csp->config->keep_alive_timeout);
2023 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2026 /*********************************************************************
2028 * Function : get_content_length
2030 * Description : Gets the content length specified in a
2031 * Content-Length header.
2034 * 1 : header_value = The Content-Length header value.
2035 * 2 : length = Storage to return the value.
2037 * Returns : JB_ERR_OK on success, or
2038 * JB_ERR_PARSE if no value is recognized.
2040 *********************************************************************/
2041 static jb_err get_content_length(const char *header_value, unsigned long long *length)
2044 #if SIZEOF_LONG_LONG < 8
2045 #error sizeof(unsigned long long) too small
2047 if (1 != sscanf(header_value, "%I64u", length))
2049 if (1 != sscanf(header_value, "%llu", length))
2052 return JB_ERR_PARSE;
2059 /*********************************************************************
2061 * Function : client_save_content_length
2063 * Description : Save the Content-Length sent by the client.
2066 * 1 : csp = Current client state (buffers, headers, etc...)
2067 * 2 : header = pointer to the Content-Length header
2069 * Returns : JB_ERR_OK on success, or
2070 * JB_ERR_MEMORY on out-of-memory error.
2072 *********************************************************************/
2073 static jb_err client_save_content_length(struct client_state *csp, char **header)
2075 unsigned long long content_length = 0;
2076 const char *header_value;
2078 assert(*(*header+14) == ':');
2080 header_value = *header + 15;
2081 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2083 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2088 csp->expected_client_content_length = content_length;
2095 /*********************************************************************
2097 * Function : client_connection
2099 * Description : Makes sure a proper "Connection:" header is
2100 * set and signals connection_header_adder
2104 * 1 : csp = Current client state (buffers, headers, etc...)
2105 * 2 : header = On input, pointer to header to modify.
2106 * On output, pointer to the modified header, or NULL
2107 * to remove the header. This function frees the
2108 * original string if necessary.
2110 * Returns : JB_ERR_OK on success.
2112 *********************************************************************/
2113 static jb_err client_connection(struct client_state *csp, char **header)
2115 static const char connection_close[] = "Connection: close";
2117 if (!strcmpic(*header, connection_close))
2119 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2120 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2121 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2122 #ifdef FEATURE_HTTPS_INSPECTION
2123 && !client_use_ssl(csp)
2127 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2129 log_error(LOG_LEVEL_HEADER,
2130 "Removing \'%s\' to imply keep-alive.", *header);
2133 * While we imply keep-alive to the server,
2134 * we have to remember that the client didn't.
2136 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2140 char *old_header = *header;
2142 *header = strdup_or_die("Connection: keep-alive");
2143 log_error(LOG_LEVEL_HEADER,
2144 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2150 log_error(LOG_LEVEL_HEADER,
2151 "Keeping the client header '%s' around. "
2152 "The connection will not be kept alive.",
2154 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2157 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2158 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2160 log_error(LOG_LEVEL_HEADER,
2161 "Keeping the client header '%s' around. "
2162 "The server connection will be kept alive if possible.",
2164 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2165 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2169 char *old_header = *header;
2171 *header = strdup_or_die(connection_close);
2172 log_error(LOG_LEVEL_HEADER,
2173 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2177 /* Signal client_connection_header_adder() to return early. */
2178 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2184 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2185 /*********************************************************************
2187 * Function : client_proxy_connection
2189 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2190 * appropriate and removes the Proxy-Connection
2194 * 1 : csp = Current client state (buffers, headers, etc...)
2195 * 2 : header = On input, pointer to header to modify.
2196 * On output, pointer to the modified header, or NULL
2197 * to remove the header. This function frees the
2198 * original string if necessary.
2200 * Returns : JB_ERR_OK
2202 *********************************************************************/
2203 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2205 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2206 && (csp->http->ssl == 0)
2207 && (NULL == strstr(*header, "close")))
2209 log_error(LOG_LEVEL_HEADER,
2210 "The client connection can be kept alive due to: %s", *header);
2211 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2213 crumble(csp, header);
2217 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2220 /*********************************************************************
2222 * Function : client_transfer_encoding
2224 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2225 * the request body is "chunked"
2227 * XXX: Currently not called through sed() as we
2228 * need the flag earlier on. Should be fixed.
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_transfer_encoding(struct client_state *csp, char **header)
2242 if (strstr(*header, "chunked"))
2244 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2245 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2252 /*********************************************************************
2254 * Function : client_expect
2256 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2257 * if the Expect header value is unsupported.
2259 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2260 * MAY and a RFC 2616 (obsolete) MUST.
2263 * 1 : csp = Current client state (buffers, headers, etc...)
2264 * 2 : header = On input, pointer to header to modify.
2265 * On output, pointer to the modified header, or NULL
2266 * to remove the header. This function frees the
2267 * original string if necessary.
2269 * Returns : JB_ERR_OK on success, or
2271 *********************************************************************/
2272 jb_err client_expect(struct client_state *csp, char **header)
2274 if (0 != strcmpic(*header, "Expect: 100-continue"))
2276 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2277 log_error(LOG_LEVEL_HEADER,
2278 "Unsupported client expectaction: %s", *header);
2286 /*********************************************************************
2288 * Function : crumble
2290 * Description : This is called if a header matches a pattern to "crunch"
2293 * 1 : csp = Current client state (buffers, headers, etc...)
2294 * 2 : header = On input, pointer to header to modify.
2295 * On output, pointer to the modified header, or NULL
2296 * to remove the header. This function frees the
2297 * original string if necessary.
2299 * Returns : JB_ERR_OK on success, or
2300 * JB_ERR_MEMORY on out-of-memory error.
2302 *********************************************************************/
2303 static jb_err crumble(struct client_state *csp, char **header)
2306 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2312 /*********************************************************************
2314 * Function : crunch_server_header
2316 * Description : Crunch server header if it matches a string supplied by the
2317 * user. Called from `sed'.
2320 * 1 : csp = Current client state (buffers, headers, etc...)
2321 * 2 : header = On input, pointer to header to modify.
2322 * On output, pointer to the modified header, or NULL
2323 * to remove the header. This function frees the
2324 * original string if necessary.
2326 * Returns : JB_ERR_OK on success and always succeeds
2328 *********************************************************************/
2329 static jb_err crunch_server_header(struct client_state *csp, char **header)
2331 const char *crunch_pattern;
2333 /* Do we feel like crunching? */
2334 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2336 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2338 /* Is the current header the lucky one? */
2339 if (strstr(*header, crunch_pattern))
2341 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2350 /*********************************************************************
2352 * Function : server_content_type
2354 * Description : Set the content-type for filterable types (text/.*,
2355 * .*xml.*, .*script.* and image/gif) unless filtering has been
2356 * forbidden (CT_TABOO) while parsing earlier headers.
2357 * NOTE: Since text/plain is commonly used by web servers
2358 * for files whose correct type is unknown, we don't
2359 * set CT_TEXT for it.
2362 * 1 : csp = Current client state (buffers, headers, etc...)
2363 * 2 : header = On input, pointer to header to modify.
2364 * On output, pointer to the modified header, or NULL
2365 * to remove the header. This function frees the
2366 * original string if necessary.
2368 * Returns : JB_ERR_OK on success, or
2369 * JB_ERR_MEMORY on out-of-memory error.
2371 *********************************************************************/
2372 static jb_err server_content_type(struct client_state *csp, char **header)
2374 /* Remove header if it isn't the first Content-Type header */
2375 if ((csp->content_type & CT_DECLARED))
2377 if (content_filters_enabled(csp->action))
2380 * Making sure the client interprets the content the same way
2381 * Privoxy did is only relevant if Privoxy modified it.
2383 * Checking for this is "hard" as it's not yet known when
2384 * this function is called, thus go shopping and and just
2385 * check if Privoxy could filter it.
2387 * The main thing is that we don't mess with the headers
2388 * unless the user signalled that it's acceptable.
2390 log_error(LOG_LEVEL_HEADER,
2391 "Multiple Content-Type headers detected. "
2392 "Removing and ignoring: %s",
2400 * Signal that the Content-Type has been set.
2402 csp->content_type |= CT_DECLARED;
2404 if (!(csp->content_type & CT_TABOO))
2407 * XXX: The assumption that text/plain is a sign of
2408 * binary data seems to be somewhat unreasonable nowadays
2409 * and should be dropped after 3.0.8 is out.
2411 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2412 || strstr(*header, "xml")
2413 || strstr(*header, "script"))
2415 csp->content_type |= CT_TEXT;
2417 else if (strstr(*header, "image/gif"))
2419 csp->content_type |= CT_GIF;
2424 * Are we messing with the content type?
2426 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2429 * Make sure the user doesn't accidentally
2430 * change the content type of binary documents.
2432 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2436 *header = strdup_or_die("Content-Type: ");
2438 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2439 if (JB_ERR_OK != err)
2441 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2442 return JB_ERR_MEMORY;
2444 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2448 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2449 "It doesn't look like a content type that should be filtered. "
2450 "Enable force-text-mode if you know what you're doing.", *header);
2458 /*********************************************************************
2460 * Function : server_transfer_coding
2462 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2463 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2464 * - Remove header if body was chunked but has been
2465 * de-chunked for filtering.
2468 * 1 : csp = Current client state (buffers, headers, etc...)
2469 * 2 : header = On input, pointer to header to modify.
2470 * On output, pointer to the modified header, or NULL
2471 * to remove the header. This function frees the
2472 * original string if necessary.
2474 * Returns : JB_ERR_OK on success, or
2475 * JB_ERR_MEMORY on out-of-memory error.
2477 *********************************************************************/
2478 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2481 * Turn off pcrs and gif filtering if body compressed
2483 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2487 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2489 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2490 csp->http->cmd, *header);
2491 #endif /* def FEATURE_ZLIB */
2492 csp->content_type = CT_TABOO;
2496 * Raise flag if body chunked
2498 if (strstr(*header, "chunked"))
2500 csp->flags |= CSP_FLAG_CHUNKED;
2503 * If the body was modified, it has been de-chunked first
2504 * and the header must be removed.
2506 * FIXME: If there is more than one transfer encoding,
2507 * only the "chunked" part should be removed here.
2509 if (csp->flags & CSP_FLAG_MODIFIED)
2511 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2520 /*********************************************************************
2522 * Function : server_content_encoding
2524 * Description : Used to check if the content is compressed, and if
2525 * FEATURE_ZLIB is disabled, filtering is disabled as
2528 * If FEATURE_ZLIB is enabled and the compression type
2529 * supported, the content is marked for decompression.
2531 * XXX: Doesn't properly deal with multiple or with
2532 * unsupported but unknown encodings.
2533 * Is case-sensitive but shouldn't be.
2536 * 1 : csp = Current client state (buffers, headers, etc...)
2537 * 2 : header = On input, pointer to header to modify.
2538 * On output, pointer to the modified header, or NULL
2539 * to remove the header. This function frees the
2540 * original string if necessary.
2542 * Returns : JB_ERR_OK on success, or
2543 * JB_ERR_MEMORY on out-of-memory error.
2545 *********************************************************************/
2546 static jb_err server_content_encoding(struct client_state *csp, char **header)
2549 if (strstr(*header, "sdch"))
2552 * Shared Dictionary Compression over HTTP isn't supported,
2553 * filtering it anyway is pretty much guaranteed to mess up
2556 csp->content_type |= CT_TABOO;
2559 * Log a warning if the user expects the content to be filtered.
2561 if (content_filters_enabled(csp->action))
2563 log_error(LOG_LEVEL_INFO,
2564 "SDCH-compressed content detected, content filtering disabled. "
2565 "Consider suppressing SDCH offers made by the client.");
2568 else if (strstr(*header, "gzip"))
2570 /* Mark for gzip decompression */
2571 csp->content_type |= CT_GZIP;
2573 else if (strstr(*header, "deflate"))
2575 /* Mark for zlib decompression */
2576 csp->content_type |= CT_DEFLATE;
2578 else if (strstr(*header, "br"))
2580 #ifdef FEATURE_BROTLI
2581 /* Mark for Brotli decompression */
2582 csp->content_type |= CT_BROTLI;
2584 csp->content_type |= CT_TABOO;
2587 else if (strstr(*header, "compress"))
2590 * We can't decompress this; therefore we can't filter
2593 csp->content_type |= CT_TABOO;
2595 #else /* !defined(FEATURE_ZLIB) */
2597 * XXX: Using a black list here isn't the right approach.
2599 * In case of SDCH, building with zlib support isn't
2602 if (strstr(*header, "gzip") ||
2603 strstr(*header, "compress") ||
2604 strstr(*header, "deflate") ||
2605 strstr(*header, "sdch"))
2608 * Body is compressed, turn off pcrs and gif filtering.
2610 csp->content_type |= CT_TABOO;
2613 * Log a warning if the user expects the content to be filtered.
2615 if (content_filters_enabled(csp->action))
2617 log_error(LOG_LEVEL_INFO,
2618 "Compressed content detected, content filtering disabled. "
2619 "Consider recompiling Privoxy with zlib support or "
2620 "enable the prevent-compression action.");
2623 #endif /* defined(FEATURE_ZLIB) */
2631 /*********************************************************************
2633 * Function : server_adjust_content_encoding
2635 * Description : Remove the Content-Encoding header if the
2636 * decompression was successful and the content
2637 * has been modified.
2640 * 1 : csp = Current client state (buffers, headers, etc...)
2641 * 2 : header = On input, pointer to header to modify.
2642 * On output, pointer to the modified header, or NULL
2643 * to remove the header. This function frees the
2644 * original string if necessary.
2646 * Returns : JB_ERR_OK on success, or
2647 * JB_ERR_MEMORY on out-of-memory error.
2649 *********************************************************************/
2650 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2652 if ((csp->flags & CSP_FLAG_MODIFIED)
2653 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2654 #ifdef FEATURE_BROTLI
2655 || (csp->content_type & CT_BROTLI)
2661 * We successfully decompressed the content,
2662 * and have to clean the header now, so the
2663 * client no longer expects compressed data.
2665 * XXX: There is a difference between cleaning
2666 * and removing it completely.
2668 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2675 #endif /* defined(FEATURE_ZLIB) */
2678 /*********************************************************************
2680 * Function : header_adjust_content_length
2682 * Description : Replace given header with new Content-Length header.
2685 * 1 : header = On input, pointer to header to modify.
2686 * On output, pointer to the modified header, or NULL
2687 * to remove the header. This function frees the
2688 * original string if necessary.
2689 * 2 : content_length = content length value to set
2691 * Returns : JB_ERR_OK on success, or
2692 * JB_ERR_MEMORY on out-of-memory error.
2694 *********************************************************************/
2695 jb_err header_adjust_content_length(char **header, size_t content_length)
2697 const size_t header_length = 50;
2699 *header = malloc(header_length);
2700 if (*header == NULL)
2702 return JB_ERR_MEMORY;
2704 create_content_length_header(content_length, *header, header_length);
2709 /*********************************************************************
2711 * Function : server_adjust_content_length
2713 * Description : Adjust Content-Length header if we modified
2717 * 1 : csp = Current client state (buffers, headers, etc...)
2718 * 2 : header = On input, pointer to header to modify.
2719 * On output, pointer to the modified header, or NULL
2720 * to remove the header. This function frees the
2721 * original string if necessary.
2723 * Returns : JB_ERR_OK on success, or
2724 * JB_ERR_MEMORY on out-of-memory error.
2726 *********************************************************************/
2727 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2729 /* Regenerate header if the content was modified. */
2730 if (csp->flags & CSP_FLAG_MODIFIED)
2732 if (JB_ERR_OK != header_adjust_content_length(header, csp->content_length))
2734 return JB_ERR_MEMORY;
2736 log_error(LOG_LEVEL_HEADER,
2737 "Adjusted Content-Length to %llu", csp->content_length);
2744 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2745 /*********************************************************************
2747 * Function : server_save_content_length
2749 * Description : Save the Content-Length sent by the server.
2752 * 1 : csp = Current client state (buffers, headers, etc...)
2753 * 2 : header = On input, pointer to header to modify.
2754 * On output, pointer to the modified header, or NULL
2755 * to remove the header. This function frees the
2756 * original string if necessary.
2758 * Returns : JB_ERR_OK on success, or
2759 * JB_ERR_MEMORY on out-of-memory error.
2761 *********************************************************************/
2762 static jb_err server_save_content_length(struct client_state *csp, char **header)
2764 unsigned long long content_length = 0;
2765 const char *header_value;
2767 assert(*(*header+14) == ':');
2769 header_value = *header + 15;
2770 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2772 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2777 csp->expected_content_length = content_length;
2778 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2779 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2784 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2787 /*********************************************************************
2789 * Function : server_content_md5
2791 * Description : Crumble any Content-MD5 headers if the document was
2792 * modified. FIXME: Should we re-compute instead?
2795 * 1 : csp = Current client state (buffers, headers, etc...)
2796 * 2 : header = On input, pointer to header to modify.
2797 * On output, pointer to the modified header, or NULL
2798 * to remove the header. This function frees the
2799 * original string if necessary.
2801 * Returns : JB_ERR_OK on success, or
2802 * JB_ERR_MEMORY on out-of-memory error.
2804 *********************************************************************/
2805 static jb_err server_content_md5(struct client_state *csp, char **header)
2807 if (csp->flags & CSP_FLAG_MODIFIED)
2809 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2817 /*********************************************************************
2819 * Function : server_content_disposition
2821 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2822 * Called from `sed'.
2825 * 1 : csp = Current client state (buffers, headers, etc...)
2826 * 2 : header = On input, pointer to header to modify.
2827 * On output, pointer to the modified header, or NULL
2828 * to remove the header. This function frees the
2829 * original string if necessary.
2831 * Returns : JB_ERR_OK on success, or
2832 * JB_ERR_MEMORY on out-of-memory error.
2834 *********************************************************************/
2835 static jb_err server_content_disposition(struct client_state *csp, char **header)
2840 * Are we messing with the Content-Disposition header?
2842 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2848 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2850 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2853 * Blocking content-disposition header
2855 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2862 * Replacing Content-Disposition header
2865 *header = strdup("Content-Disposition: ");
2866 string_append(header, newval);
2868 if (*header != NULL)
2870 log_error(LOG_LEVEL_HEADER,
2871 "Content-Disposition header crunched and replaced with: %s", *header);
2874 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2878 /*********************************************************************
2880 * Function : server_last_modified
2882 * Description : Changes Last-Modified header to the actual date
2883 * to help hide-if-modified-since.
2884 * Called from `sed'.
2887 * 1 : csp = Current client state (buffers, headers, etc...)
2888 * 2 : header = On input, pointer to header to modify.
2889 * On output, pointer to the modified header, or NULL
2890 * to remove the header. This function frees the
2891 * original string if necessary.
2893 * Returns : JB_ERR_OK on success, or
2894 * JB_ERR_MEMORY on out-of-memory error.
2896 *********************************************************************/
2897 static jb_err server_last_modified(struct client_state *csp, char **header)
2900 time_t last_modified;
2904 * Are we messing with the Last-Modified header?
2906 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2912 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2914 if (0 == strcmpic(newval, "block"))
2917 * Blocking Last-Modified header. Useless but why not.
2919 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2923 else if (0 == strcmpic(newval, "reset-to-request-time"))
2926 * Setting Last-Modified Header to now.
2929 get_http_time(0, buf, sizeof(buf));
2931 *header = strdup("Last-Modified: ");
2932 string_append(header, buf);
2934 if (*header == NULL)
2936 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2940 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2943 else if (0 == strcmpic(newval, "randomize"))
2945 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2947 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2949 log_error(LOG_LEVEL_HEADER,
2950 "Couldn't parse time in %s (crunching!)", *header);
2956 struct tm *timeptr = NULL;
2961 rtime = (long int)difftime(now, last_modified);
2964 long int days, hours, minutes, seconds;
2965 const int negative_delta = (rtime < 0);
2970 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2972 rtime = pick_from_range(rtime);
2977 last_modified += rtime;
2978 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2979 if ((NULL == timeptr) || !strftime(newheader,
2980 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2982 log_error(LOG_LEVEL_ERROR,
2983 "Randomizing '%s' failed. Crunching the header without replacement.",
2989 *header = strdup("Last-Modified: ");
2990 string_append(header, newheader);
2992 if (*header == NULL)
2994 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2995 return JB_ERR_MEMORY;
2998 days = rtime / (3600 * 24);
2999 hours = rtime / 3600 % 24;
3000 minutes = rtime / 60 % 60;
3001 seconds = rtime % 60;
3003 log_error(LOG_LEVEL_HEADER,
3004 "Randomized: %s (added %ld da%s %ld hou%s %ld minut%s %ld second%s",
3005 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3006 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3010 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3019 /*********************************************************************
3021 * Function : client_accept_encoding
3023 * Description : Rewrite the client's Accept-Encoding header so that
3024 * if doesn't allow compression, if the action applies.
3025 * Note: For HTTP/1.0 the absence of the header is enough.
3028 * 1 : csp = Current client state (buffers, headers, etc...)
3029 * 2 : header = On input, pointer to header to modify.
3030 * On output, pointer to the modified header, or NULL
3031 * to remove the header. This function frees the
3032 * original string if necessary.
3034 * Returns : JB_ERR_OK on success, or
3035 * JB_ERR_MEMORY on out-of-memory error.
3037 *********************************************************************/
3038 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3040 #ifdef FEATURE_COMPRESSION
3041 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
3042 && strstr(*header, "deflate"))
3044 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
3047 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3049 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3057 /*********************************************************************
3059 * Function : client_te
3061 * Description : Rewrite the client's TE header so that
3062 * if doesn't allow compression, if the action applies.
3065 * 1 : csp = Current client state (buffers, headers, etc...)
3066 * 2 : header = On input, pointer to header to modify.
3067 * On output, pointer to the modified header, or NULL
3068 * to remove the header. This function frees the
3069 * original string if necessary.
3071 * Returns : JB_ERR_OK on success, or
3072 * JB_ERR_MEMORY on out-of-memory error.
3074 *********************************************************************/
3075 static jb_err client_te(struct client_state *csp, char **header)
3077 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3080 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3087 /*********************************************************************
3089 * Function : client_referrer
3091 * Description : Handle the "referer" config setting properly.
3092 * Called from `sed'.
3095 * 1 : csp = Current client state (buffers, headers, etc...)
3096 * 2 : header = On input, pointer to header to modify.
3097 * On output, pointer to the modified header, or NULL
3098 * to remove the header. This function frees the
3099 * original string if necessary.
3101 * Returns : JB_ERR_OK on success, or
3102 * JB_ERR_MEMORY on out-of-memory error.
3104 *********************************************************************/
3105 static jb_err client_referrer(struct client_state *csp, char **header)
3107 const char *parameter;
3108 /* booleans for parameters we have to check multiple times */
3109 int parameter_conditional_block;
3110 int parameter_conditional_forge;
3112 #ifdef FEATURE_FORCE_LOAD
3114 * Since the referrer can include the prefix even
3115 * if the request itself is non-forced, we must
3116 * clean it unconditionally.
3118 * XXX: strclean is too broad
3120 strclean(*header, FORCE_PREFIX);
3121 #endif /* def FEATURE_FORCE_LOAD */
3123 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3125 /* Nothing left to do */
3129 parameter = csp->action->string[ACTION_STRING_REFERER];
3130 assert(parameter != NULL);
3131 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3132 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3134 if (!parameter_conditional_block && !parameter_conditional_forge)
3137 * As conditional-block and conditional-forge are the only
3138 * parameters that rely on the original referrer, we can
3139 * remove it now for all the others.
3144 if (0 == strcmpic(parameter, "block"))
3146 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3149 else if (parameter_conditional_block || parameter_conditional_forge)
3151 return handle_conditional_hide_referrer_parameter(header,
3152 csp->http->hostport, parameter_conditional_block);
3154 else if (0 == strcmpic(parameter, "forge"))
3156 return create_forged_referrer(header, csp->http->hostport);
3160 /* interpret parameter as user-supplied referer to fake */
3161 return create_fake_referrer(header, parameter);
3166 /*********************************************************************
3168 * Function : client_accept_language
3170 * Description : Handle the "Accept-Language" config setting properly.
3171 * Called from `sed'.
3174 * 1 : csp = Current client state (buffers, headers, etc...)
3175 * 2 : header = On input, pointer to header to modify.
3176 * On output, pointer to the modified header, or NULL
3177 * to remove the header. This function frees the
3178 * original string if necessary.
3180 * Returns : JB_ERR_OK on success, or
3181 * JB_ERR_MEMORY on out-of-memory error.
3183 *********************************************************************/
3184 static jb_err client_accept_language(struct client_state *csp, char **header)
3189 * Are we messing with the Accept-Language?
3191 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3193 /*I don't think so*/
3197 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3199 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3202 * Blocking Accept-Language header
3204 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3211 * Replacing Accept-Language header
3214 *header = strdup("Accept-Language: ");
3215 string_append(header, newval);
3217 if (*header == NULL)
3219 log_error(LOG_LEVEL_ERROR,
3220 "Insufficient memory. Accept-Language header crunched without replacement.");
3224 log_error(LOG_LEVEL_HEADER,
3225 "Accept-Language header crunched and replaced with: %s", *header);
3228 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3232 /*********************************************************************
3234 * Function : crunch_client_header
3236 * Description : Crunch client header if it matches a string supplied by the
3237 * user. Called from `sed'.
3240 * 1 : csp = Current client state (buffers, headers, etc...)
3241 * 2 : header = On input, pointer to header to modify.
3242 * On output, pointer to the modified header, or NULL
3243 * to remove the header. This function frees the
3244 * original string if necessary.
3246 * Returns : JB_ERR_OK on success and always succeeds
3248 *********************************************************************/
3249 static jb_err crunch_client_header(struct client_state *csp, char **header)
3251 const char *crunch_pattern;
3253 /* Do we feel like crunching? */
3254 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3256 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3258 /* Is the current header the lucky one? */
3259 if (strstr(*header, crunch_pattern))
3261 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3269 /*********************************************************************
3271 * Function : client_uagent
3273 * Description : Handle the "user-agent" config setting properly
3274 * and remember its original value to enable browser
3275 * bug workarounds. Called from `sed'.
3278 * 1 : csp = Current client state (buffers, headers, etc...)
3279 * 2 : header = On input, pointer to header to modify.
3280 * On output, pointer to the modified header, or NULL
3281 * to remove the header. This function frees the
3282 * original string if necessary.
3284 * Returns : JB_ERR_OK on success, or
3285 * JB_ERR_MEMORY on out-of-memory error.
3287 *********************************************************************/
3288 static jb_err client_uagent(struct client_state *csp, char **header)
3292 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3297 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3304 *header = strdup("User-Agent: ");
3305 string_append(header, newval);
3307 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3309 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3313 /*********************************************************************
3315 * Function : client_ua
3317 * Description : Handle "ua-" headers properly. Called from `sed'.
3320 * 1 : csp = Current client state (buffers, headers, etc...)
3321 * 2 : header = On input, pointer to header to modify.
3322 * On output, pointer to the modified header, or NULL
3323 * to remove the header. This function frees the
3324 * original string if necessary.
3326 * Returns : JB_ERR_OK on success, or
3327 * JB_ERR_MEMORY on out-of-memory error.
3329 *********************************************************************/
3330 static jb_err client_ua(struct client_state *csp, char **header)
3332 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3334 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3342 /*********************************************************************
3344 * Function : client_from
3346 * Description : Handle the "from" config setting properly.
3347 * Called from `sed'.
3350 * 1 : csp = Current client state (buffers, headers, etc...)
3351 * 2 : header = On input, pointer to header to modify.
3352 * On output, pointer to the modified header, or NULL
3353 * to remove the header. This function frees the
3354 * original string if necessary.
3356 * Returns : JB_ERR_OK on success, or
3357 * JB_ERR_MEMORY on out-of-memory error.
3359 *********************************************************************/
3360 static jb_err client_from(struct client_state *csp, char **header)
3364 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3371 newval = csp->action->string[ACTION_STRING_FROM];
3374 * Are we blocking the e-mail address?
3376 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3378 log_error(LOG_LEVEL_HEADER, "crunched From!");
3382 log_error(LOG_LEVEL_HEADER, " modified");
3384 *header = strdup("From: ");
3385 string_append(header, newval);
3387 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3391 /*********************************************************************
3393 * Function : client_send_cookie
3395 * Description : Crunches the "cookie" header if necessary.
3396 * Called from `sed'.
3398 * XXX: Stupid name, doesn't send squat.
3401 * 1 : csp = Current client state (buffers, headers, etc...)
3402 * 2 : header = On input, pointer to header to modify.
3403 * On output, pointer to the modified header, or NULL
3404 * to remove the header. This function frees the
3405 * original string if necessary.
3407 * Returns : JB_ERR_OK on success, or
3408 * JB_ERR_MEMORY on out-of-memory error.
3410 *********************************************************************/
3411 static jb_err client_send_cookie(struct client_state *csp, char **header)
3413 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3415 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3423 /*********************************************************************
3425 * Function : client_x_forwarded
3427 * Description : Handle the "x-forwarded-for" config setting properly,
3428 * also used in the add_client_headers list. Called from `sed'.
3431 * 1 : csp = Current client state (buffers, headers, etc...)
3432 * 2 : header = On input, pointer to header to modify.
3433 * On output, pointer to the modified header, or NULL
3434 * to remove the header. This function frees the
3435 * original string if necessary.
3437 * Returns : JB_ERR_OK on success, or
3438 * JB_ERR_MEMORY on out-of-memory error.
3440 *********************************************************************/
3441 jb_err client_x_forwarded(struct client_state *csp, char **header)
3443 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3445 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3447 if (0 == strcmpic(parameter, "block"))
3450 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3452 else if (0 == strcmpic(parameter, "add"))
3454 string_append(header, ", ");
3455 string_append(header, csp->ip_addr_str);
3457 if (*header == NULL)
3459 return JB_ERR_MEMORY;
3461 log_error(LOG_LEVEL_HEADER,
3462 "Appended client IP address to %s", *header);
3463 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3467 log_error(LOG_LEVEL_FATAL,
3468 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3476 /*********************************************************************
3478 * Function : client_max_forwards
3480 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3481 * from the value of the Max-Forwards header field.
3484 * 1 : csp = Current client state (buffers, headers, etc...)
3485 * 2 : header = On input, pointer to header to modify.
3486 * On output, pointer to the modified header, or NULL
3487 * to remove the header. This function frees the
3488 * original string if necessary.
3490 * Returns : JB_ERR_OK on success, or
3491 * JB_ERR_MEMORY on out-of-memory error.
3493 *********************************************************************/
3494 static jb_err client_max_forwards(struct client_state *csp, char **header)
3498 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3499 (0 == strcmpic(csp->http->gpc, "options")))
3501 assert(*(*header+12) == ':');
3502 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3504 if (max_forwards > 0)
3506 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3507 log_error(LOG_LEVEL_HEADER,
3508 "Max-Forwards value for %s request reduced to %d.",
3509 csp->http->gpc, max_forwards);
3511 else if (max_forwards < 0)
3513 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3519 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3528 /*********************************************************************
3530 * Function : client_host
3532 * Description : If the request URI did not contain host and
3533 * port information, parse and evaluate the Host
3537 * 1 : csp = Current client state (buffers, headers, etc...)
3538 * 2 : header = On input, pointer to header to modify.
3539 * On output, pointer to the modified header, or NULL
3540 * to remove the header. This function frees the
3541 * original string if necessary.
3543 * Returns : JB_ERR_OK on success, or
3544 * JB_ERR_MEMORY on out-of-memory error.
3546 *********************************************************************/
3547 static jb_err client_host(struct client_state *csp, char **header)
3551 if (strlen(*header) < 7)
3553 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3558 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3559 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3562 p = strdup_or_die((*header)+6);
3564 q = strdup_or_die(p);
3566 freez(csp->http->hostport);
3567 csp->http->hostport = p;
3568 freez(csp->http->host);
3569 csp->http->host = q;
3570 q = strchr(csp->http->host, ':');
3573 /* Terminate hostname and evaluate port string */
3575 csp->http->port = atoi(q);
3579 csp->http->port = csp->http->ssl ? 443 : 80;
3582 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3583 csp->http->hostport, csp->http->host, csp->http->port);
3586 /* Signal client_host_adder() to return right away */
3587 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3593 /*********************************************************************
3595 * Function : client_if_modified_since
3597 * Description : Remove or modify the If-Modified-Since header.
3600 * 1 : csp = Current client state (buffers, headers, etc...)
3601 * 2 : header = On input, pointer to header to modify.
3602 * On output, pointer to the modified header, or NULL
3603 * to remove the header. This function frees the
3604 * original string if necessary.
3606 * Returns : JB_ERR_OK on success, or
3607 * JB_ERR_MEMORY on out-of-memory error.
3609 *********************************************************************/
3610 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3614 struct tm *timeptr = NULL;
3619 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3622 * The client got an error message because of a temporary problem,
3623 * the problem is gone and the client now tries to revalidate our
3624 * error message on the real server. The revalidation would always
3625 * end with the transmission of the whole document and there is
3626 * no need to expose the bogus If-Modified-Since header.
3628 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3631 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3633 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3635 if ((0 == strcmpic(newval, "block")))
3637 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3640 else /* add random value */
3642 if (JB_ERR_OK != parse_time_header(*header, &tm))
3644 log_error(LOG_LEVEL_HEADER,
3645 "Couldn't parse time in %s (crunching!)", *header);
3650 long int hours, minutes, seconds;
3651 long int rtime = strtol(newval, &endptr, 0);
3652 const int negative_range = (rtime < 0);
3656 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %ld minut%s)",
3657 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3663 rtime = pick_from_range(rtime);
3667 log_error(LOG_LEVEL_ERROR,
3668 "Random range is 0. Assuming time transformation test.");
3670 tm += rtime * (negative_range ? -1 : 1);
3671 timeptr = privoxy_gmtime_r(&tm, &gmt);
3672 if ((NULL == timeptr) || !strftime(newheader,
3673 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3675 log_error(LOG_LEVEL_ERROR,
3676 "Randomizing '%s' failed. Crunching the header without replacement.",
3682 *header = strdup("If-Modified-Since: ");
3683 string_append(header, newheader);
3685 if (*header == NULL)
3687 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3688 return JB_ERR_MEMORY;
3691 hours = rtime / 3600;
3692 minutes = rtime / 60 % 60;
3693 seconds = rtime % 60;
3695 log_error(LOG_LEVEL_HEADER,
3696 "Randomized: %s (%s %ld hou%s %ld minut%s %ld second%s",
3697 *header, (negative_range) ? "subtracted" : "added", hours,
3698 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3699 seconds, (seconds == 1) ? ")" : "s)");
3708 /*********************************************************************
3710 * Function : client_if_none_match
3712 * Description : Remove the If-None-Match header.
3715 * 1 : csp = Current client state (buffers, headers, etc...)
3716 * 2 : header = On input, pointer to header to modify.
3717 * On output, pointer to the modified header, or NULL
3718 * to remove the header. This function frees the
3719 * original string if necessary.
3721 * Returns : JB_ERR_OK on success, or
3722 * JB_ERR_MEMORY on out-of-memory error.
3724 *********************************************************************/
3725 static jb_err client_if_none_match(struct client_state *csp, char **header)
3727 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3729 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3737 /*********************************************************************
3739 * Function : client_x_filter
3741 * Description : Disables filtering if the client set "X-Filter: No".
3742 * Called from `sed'.
3745 * 1 : csp = Current client state (buffers, headers, etc...)
3746 * 2 : header = On input, pointer to header to modify.
3747 * On output, pointer to the modified header, or NULL
3748 * to remove the header. This function frees the
3749 * original string if necessary.
3751 * Returns : JB_ERR_OK on success
3753 *********************************************************************/
3754 jb_err client_x_filter(struct client_state *csp, char **header)
3756 if (0 == strcmpic(*header, "X-Filter: No"))
3758 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3760 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3764 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3766 log_error(LOG_LEVEL_HEADER,
3767 "force-text-mode overruled the client's request to fetch without filtering!");
3771 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3772 csp->flags |= CSP_FLAG_NO_FILTERING;
3773 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3775 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3783 /*********************************************************************
3785 * Function : client_range
3787 * Description : Removes Range, Request-Range and If-Range headers if
3788 * content filtering is enabled and the range doesn't
3791 * If the client's version of the document has been
3792 * altered by Privoxy, the server could interpret the
3793 * range differently than the client intended in which
3794 * case the user could end up with corrupted content.
3796 * If the range starts at byte 0 this isn't an issue
3797 * so the header can pass. Partial requests like this
3798 * are used to render preview images for videos without
3799 * downloading the whole video.
3801 * While HTTP doesn't require that range requests are
3802 * honoured and the client could simply abort the download
3803 * after receiving a sufficient amount of data, various
3804 * clients don't handle complete responses to range
3805 * requests gracefully and emit misleading error messages
3809 * 1 : csp = Current client state (buffers, headers, etc...)
3810 * 2 : header = On input, pointer to header to modify.
3811 * On output, pointer to the modified header, or NULL
3812 * to remove the header. This function frees the
3813 * original string if necessary.
3815 * Returns : JB_ERR_OK
3817 *********************************************************************/
3818 static jb_err client_range(struct client_state *csp, char **header)
3820 if (content_filters_enabled(csp->action)
3821 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3823 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3824 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3831 /* the following functions add headers directly to the header list */
3833 /*********************************************************************
3835 * Function : client_host_adder
3837 * Description : Adds the Host: header field if it is missing.
3838 * Called from `sed'.
3841 * 1 : csp = Current client state (buffers, headers, etc...)
3843 * Returns : JB_ERR_OK on success, or
3844 * JB_ERR_MEMORY on out-of-memory error.
3846 *********************************************************************/
3847 static jb_err client_host_adder(struct client_state *csp)
3852 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3854 /* Header already set by the client, nothing to do. */
3858 if (!csp->http->hostport || !*(csp->http->hostport))
3860 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3861 return JB_ERR_PARSE;
3865 * remove 'user:pass@' from 'proto://user:pass@host'
3867 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3873 p = csp->http->hostport;
3876 /* XXX: Just add it, we already made sure that it will be unique */
3877 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3878 err = enlist_unique_header(csp->headers, "Host", p);
3884 /*********************************************************************
3886 * Function : client_xtra_adder
3888 * Description : Used in the add_client_headers list. Called from `sed'.
3891 * 1 : csp = Current client state (buffers, headers, etc...)
3893 * Returns : JB_ERR_OK on success, or
3894 * JB_ERR_MEMORY on out-of-memory error.
3896 *********************************************************************/
3897 static jb_err client_xtra_adder(struct client_state *csp)
3899 struct list_entry *lst;
3902 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3903 lst ; lst = lst->next)
3905 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3906 err = enlist(csp->headers, lst->str);
3918 /*********************************************************************
3920 * Function : client_x_forwarded_for_adder
3922 * Description : Used in the add_client_headers list. Called from `sed'.
3925 * 1 : csp = Current client state (buffers, headers, etc...)
3927 * Returns : JB_ERR_OK on success, or
3928 * JB_ERR_MEMORY on out-of-memory error.
3930 *********************************************************************/
3931 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3933 char *header = NULL;
3936 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3937 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3938 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3941 * If we aren't adding X-Forwarded-For headers,
3942 * or we already appended an existing X-Forwarded-For
3943 * header, there's nothing left to do here.
3948 header = strdup("X-Forwarded-For: ");
3949 string_append(&header, csp->ip_addr_str);
3953 return JB_ERR_MEMORY;
3956 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3957 err = enlist(csp->headers, header);
3964 /*********************************************************************
3966 * Function : server_connection_adder
3968 * Description : Adds an appropriate "Connection:" header to csp->headers
3969 * unless the header was already present. Called from `sed'.
3972 * 1 : csp = Current client state (buffers, headers, etc...)
3974 * Returns : JB_ERR_OK on success, or
3975 * JB_ERR_MEMORY on out-of-memory error.
3977 *********************************************************************/
3978 static jb_err server_connection_adder(struct client_state *csp)
3980 const unsigned int flags = csp->flags;
3981 const char *response_status_line = csp->headers->first->str;
3982 static const char connection_close[] = "Connection: close";
3984 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3985 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3991 * XXX: if we downgraded the response, this check will fail.
3993 if ((csp->config->feature_flags &
3994 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3995 && (NULL != response_status_line)
3996 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3997 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3998 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4002 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
4003 "without Connection header implies keep-alive.");
4004 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
4008 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4010 return enlist(csp->headers, connection_close);
4014 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4015 /*********************************************************************
4017 * Function : server_proxy_connection_adder
4019 * Description : Adds a "Proxy-Connection: keep-alive" header to
4020 * csp->headers when appropriate.
4023 * 1 : csp = Current client state (buffers, headers, etc...)
4025 * Returns : JB_ERR_OK on success, or
4026 * JB_ERR_MEMORY on out-of-memory error.
4028 *********************************************************************/
4029 static jb_err server_proxy_connection_adder(struct client_state *csp)
4031 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
4032 jb_err err = JB_ERR_OK;
4034 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4035 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4036 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
4037 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4038 || (csp->flags & CSP_FLAG_CHUNKED))
4039 #ifdef FEATURE_HTTPS_INSPECTION
4040 && !client_use_ssl(csp)
4045 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
4046 err = enlist(csp->headers, proxy_connection_header);
4051 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4054 /*********************************************************************
4056 * Function : client_connection_header_adder
4058 * Description : Adds a proper "Connection:" header to csp->headers
4059 * unless the header was already present or it's a
4060 * CONNECT request. Called from `sed'.
4063 * 1 : csp = Current client state (buffers, headers, etc...)
4065 * Returns : JB_ERR_OK on success, or
4066 * JB_ERR_MEMORY on out-of-memory error.
4068 *********************************************************************/
4069 static jb_err client_connection_header_adder(struct client_state *csp)
4071 static const char connection_close[] = "Connection: close";
4073 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4074 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4080 * In case of CONNECT requests "Connection: close" is implied,
4081 * but actually setting the header has been reported to cause
4082 * problems with some forwarding proxies that close the
4083 * connection prematurely.
4085 if (csp->http->ssl != 0)
4090 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4091 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4092 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4093 && !strcmpic(csp->http->version, "HTTP/1.1"))
4095 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4098 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4100 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4102 return enlist(csp->headers, connection_close);
4106 /*********************************************************************
4108 * Function : server_http
4110 * Description : - Save the HTTP Status into csp->http->status
4111 * - Set CT_TABOO to prevent filtering if the answer
4112 * is a partial range (HTTP status 206)
4113 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4115 * - Normalize the HTTP-version.
4118 * 1 : csp = Current client state (buffers, headers, etc...)
4119 * 2 : header = On input, pointer to header to modify.
4120 * On output, pointer to the modified header, or NULL
4121 * to remove the header. This function frees the
4122 * original string if necessary.
4124 * Returns : JB_ERR_OK on success, or
4125 * JB_ERR_PARSE on fatal parse errors.
4127 *********************************************************************/
4128 static jb_err server_http(struct client_state *csp, char **header)
4130 char *reason_phrase = NULL;
4131 char *new_response_line;
4134 unsigned int major_version;
4135 unsigned int minor_version;
4137 /* Get the reason phrase which start after the second whitespace */
4138 p = strchr(*header, ' ');
4142 reason_phrase = strchr(p, ' ');
4145 if (reason_phrase != NULL)
4151 log_error(LOG_LEVEL_ERROR,
4152 "Response line lacks reason phrase: %s", *header);
4156 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4157 &minor_version, &(csp->http->status)))
4159 log_error(LOG_LEVEL_ERROR,
4160 "Failed to parse the response line: %s", *header);
4161 return JB_ERR_PARSE;
4164 if (csp->http->status == 101 ||
4165 csp->http->status == 206)
4167 csp->content_type = CT_TABOO;
4170 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4173 * According to RFC 7230 2.6 intermediaries MUST send
4174 * their own HTTP-version in forwarded messages.
4176 log_error(LOG_LEVEL_ERROR,
4177 "Unsupported HTTP version. Downgrading to 1.1.");
4182 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4184 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4188 /* Rebuild response line. */
4189 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4190 new_response_line = malloc_or_die(length);
4192 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4193 major_version, minor_version, csp->http->status, reason_phrase);
4195 if (0 != strcmp(*header, new_response_line))
4197 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4198 *header, new_response_line);
4202 *header = new_response_line;
4207 /*********************************************************************
4209 * Function : add_cooky_expiry_date
4211 * Description : Adds a cookie expiry date to a string.
4214 * 1 : cookie = On input, pointer to cookie to modify.
4215 * On output, pointer to the modified header.
4216 * The original string is freed.
4217 * 2 : lifetime = Seconds the cookie should be valid
4221 *********************************************************************/
4222 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4225 struct tm *timeptr = NULL;
4226 time_t expiry_date = time(NULL) + lifetime;
4229 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4230 if (NULL == timeptr)
4232 log_error(LOG_LEVEL_FATAL,
4233 "Failed to get the time in add_cooky_expiry_date()");
4235 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4236 if (JB_ERR_OK != string_append(cookie, tmp))
4238 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4243 /*********************************************************************
4245 * Function : server_set_cookie
4247 * Description : Handle the server "cookie" header properly.
4248 * Crunch, accept or rewrite it to a session cookie.
4249 * Called from `sed'.
4252 * 1 : csp = Current client state (buffers, headers, etc...)
4253 * 2 : header = On input, pointer to header to modify.
4254 * On output, pointer to the modified header, or NULL
4255 * to remove the header. This function frees the
4256 * original string if necessary.
4258 * Returns : JB_ERR_OK on success, or
4259 * JB_ERR_MEMORY on out-of-memory error.
4261 *********************************************************************/
4262 static jb_err server_set_cookie(struct client_state *csp, char **header)
4264 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4266 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4269 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4270 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4274 long cookie_lifetime = 0;
4277 NO_EXPIRY_DATE_SPECIFIED,
4278 EXPIRY_DATE_ACCEPTABLE,
4279 EXPIRY_DATE_UNACCEPTABLE
4280 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4282 /* A variable to store the tag we're working on */
4285 /* Skip "Set-Cookie:" (11 characters) in header */
4286 cur_tag = *header + 11;
4288 /* skip whitespace between "Set-Cookie:" and value */
4289 while (*cur_tag && privoxy_isspace(*cur_tag))
4296 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4298 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4300 cookie_lifetime = strtol(param, NULL, 0);
4301 if (cookie_lifetime < 0)
4303 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4305 cookie_lifetime *= 60;
4308 /* Loop through each tag in the cookie */
4312 char *next_tag = strchr(cur_tag, ';');
4313 if (next_tag != NULL)
4315 /* Skip the ';' character itself */
4318 /* skip whitespace ";" and start of tag */
4319 while (*next_tag && privoxy_isspace(*next_tag))
4326 /* "Next tag" is the end of the string */
4327 next_tag = cur_tag + strlen(cur_tag);
4331 * Check the expiration date to see
4332 * if the cookie is still valid, if yes,
4333 * rewrite it to a session cookie.
4335 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4337 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4339 if ((expiration_date[0] == '"')
4340 && (expiration_date[1] != '\0'))
4343 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4344 * that the expiration date isn't supposed to be quoted,
4345 * but some servers do it anyway.
4350 /* Did we detect the date properly? */
4351 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4354 * Nope, treat it as if it was still valid.
4356 * XXX: Should we remove the whole cookie instead?
4358 log_error(LOG_LEVEL_ERROR,
4359 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4360 string_move(cur_tag, next_tag);
4361 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4366 * Yes. Check if the cookie is still valid.
4368 * If the cookie is already expired it's probably
4369 * a delete cookie and even if it isn't, the browser
4370 * will discard it anyway.
4374 * XXX: timegm() isn't available on some AmigaOS
4375 * versions and our replacement doesn't work.
4377 * Our options are to either:
4379 * - disable session-cookies-only completely if timegm
4382 * - to simply remove all expired tags, like it has
4383 * been done until Privoxy 3.0.6 and to live with
4384 * the consequence that it can cause login/logout
4385 * problems on servers that don't validate their
4386 * input properly, or
4388 * - to replace it with mktime in which
4389 * case there is a slight chance of valid cookies
4390 * passing as already expired.
4392 * This is the way it's currently done and it's not
4393 * as bad as it sounds. If the missing GMT offset is
4394 * enough to change the result of the expiration check
4395 * the cookie will be only valid for a few hours
4396 * anyway, which in many cases will be shorter
4397 * than a browser session.
4399 if (cookie_time < now)
4401 log_error(LOG_LEVEL_HEADER,
4402 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4403 /* Just in case some clown sets more then one expiration date */
4405 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4407 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4409 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4410 "Its lifetime is below the limit.", *header);
4411 /* Just in case some clown sets more then one expiration date */
4413 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4418 * Still valid, delete expiration date by copying
4419 * the rest of the string over it.
4421 string_move(cur_tag, next_tag);
4423 /* That changed the header, need to issue a log message */
4424 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4427 * Note that the next tag has now been moved to *cur_tag,
4428 * so we do not need to update the cur_tag pointer.
4436 /* Move on to next cookie tag */
4441 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4443 assert(NULL != *header);
4444 if (cookie_lifetime != 0)
4446 add_cookie_expiry_date(header, cookie_lifetime);
4447 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4449 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4451 log_error(LOG_LEVEL_HEADER,
4452 "Cookie rewritten to a temporary one: %s", *header);
4461 #ifdef FEATURE_FORCE_LOAD
4462 /*********************************************************************
4464 * Function : strclean
4466 * Description : In-Situ-Eliminate all occurrences of substring in
4470 * 1 : string = string to clean
4471 * 2 : substring = substring to eliminate
4473 * Returns : Number of eliminations
4475 *********************************************************************/
4476 int strclean(char *string, const char *substring)
4482 len = strlen(substring);
4484 while((pos = strstr(string, substring)) != NULL)
4491 while (*p++ != '\0');
4498 #endif /* def FEATURE_FORCE_LOAD */
4501 /*********************************************************************
4503 * Function : parse_header_time
4505 * Description : Parses time formats used in HTTP header strings
4506 * to get the numerical respresentation.
4509 * 1 : header_time = HTTP header time as string.
4510 * 2 : result = storage for header_time in seconds
4512 * Returns : JB_ERR_OK if the time format was recognized, or
4513 * JB_ERR_PARSE otherwise.
4515 *********************************************************************/
4516 static jb_err parse_header_time(const char *header_time, time_t *result)
4520 * Checking for two-digit years first in an
4521 * attempt to work around GNU libc's strptime()
4522 * reporting negative year values when using %Y.
4524 static const char time_formats[][22] = {
4525 /* Tue, 02-Jun-37 20:00:00 */
4526 "%a, %d-%b-%y %H:%M:%S",
4527 /* Tue, 02 Jun 2037 20:00:00 */
4528 "%a, %d %b %Y %H:%M:%S",
4529 /* Tue, 02-Jun-2037 20:00:00 */
4530 "%a, %d-%b-%Y %H:%M:%S",
4531 /* Tuesday, 02-Jun-2037 20:00:00 */
4532 "%A, %d-%b-%Y %H:%M:%S",
4533 /* Tuesday Jun 02 20:00:00 2037 */
4534 "%A %b %d %H:%M:%S %Y"
4538 for (i = 0; i < SZ(time_formats); i++)
4541 * Zero out gmt to prevent time zone offsets.
4542 * Documented to be required for GNU libc.
4544 memset(&gmt, 0, sizeof(gmt));
4546 if (NULL != strptime(header_time, time_formats[i], &gmt))
4548 /* Sanity check for GNU libc. */
4549 if (gmt.tm_year < 0)
4551 log_error(LOG_LEVEL_HEADER,
4552 "Failed to parse '%s' using '%s'. Moving on.",
4553 header_time, time_formats[i]);
4556 *result = timegm(&gmt);
4558 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4560 * Verify that parsing the date recreated from the first
4561 * parse operation gets the previous result. If it doesn't,
4562 * either strptime() or strftime() are malfunctioning.
4564 * We could string-compare the recreated date with the original
4565 * header date, but this leads to false positives as strptime()
4566 * may let %a accept all day formats while strftime() will only
4570 char recreated_date[100];
4575 tm = privoxy_gmtime_r(result, &storage);
4576 if (!strftime(recreated_date, sizeof(recreated_date),
4577 time_formats[i], tm))
4579 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4580 header_time, time_formats[i]);
4583 memset(&gmt, 0, sizeof(gmt));
4584 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4586 log_error(LOG_LEVEL_ERROR,
4587 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4588 recreated_date, time_formats[i], header_time);
4591 result2 = timegm(&gmt);
4592 if (*result != result2)
4594 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4595 "Format: '%s'. In: '%s', out: '%s'. %ld != %ld. Rejecting.",
4596 time_formats[i], header_time, recreated_date, *result, result2);
4606 return JB_ERR_PARSE;
4610 /*********************************************************************
4612 * Function : parse_time_header
4614 * Description : Parses the time in an HTTP time header to get
4615 * the numerical respresentation.
4618 * 1 : header = HTTP header with a time value
4619 * 2 : result = storage for header_time in seconds
4621 * Returns : JB_ERR_OK if the time format was recognized, or
4622 * JB_ERR_PARSE otherwise.
4624 *********************************************************************/
4625 static jb_err parse_time_header(const char *header, time_t *result)
4627 const char *header_time;
4629 header_time = strchr(header, ':');
4632 * Currently this can't happen as all callers are called
4633 * through sed() which requires a header name followed by
4636 if (header_time == NULL)
4638 return JB_ERR_PARSE;
4642 if (*header_time == ' ')
4647 return parse_header_time(header_time, result);
4652 /*********************************************************************
4654 * Function : get_destination_from_headers
4656 * Description : Parse the "Host:" header to get the request's destination.
4657 * Only needed if the client's request was forcefully
4658 * redirected into Privoxy.
4660 * Code mainly copied from client_host() which is currently
4661 * run too late for this purpose.
4664 * 1 : headers = List of headers (one of them hopefully being
4665 * the "Host:" header)
4666 * 2 : http = storage for the result (host, port and hostport).
4668 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4669 * JB_ERR_PARSE if the host header couldn't be found,
4670 * JB_ERR_OK otherwise.
4672 *********************************************************************/
4673 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4679 host = get_header_value(headers, "Host:");
4683 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4684 return JB_ERR_PARSE;
4687 p = string_tolower(host);
4690 return JB_ERR_MEMORY;
4693 q = strdup_or_die(p);
4695 freez(http->hostport);
4699 q = strchr(http->host, ':');
4702 /* Terminate hostname and evaluate port string */
4704 http->port = atoi(q);
4711 /* Rebuild request URL */
4713 http->url = strdup("http://");
4714 string_append(&http->url, http->hostport);
4715 string_append(&http->url, http->path);
4716 if (http->url == NULL)
4718 return JB_ERR_MEMORY;
4721 log_error(LOG_LEVEL_HEADER,
4722 "Destination extracted from \"Host\" header. New request URL: %s",
4726 * Regenerate request line in "proxy format"
4727 * to make rewrites more convenient.
4729 assert(http->cmd != NULL);
4731 http->cmd = strdup_or_die(http->gpc);
4732 string_append(&http->cmd, " ");
4733 string_append(&http->cmd, http->url);
4734 string_append(&http->cmd, " ");
4735 string_append(&http->cmd, http->version);
4736 if (http->cmd == NULL)
4738 return JB_ERR_MEMORY;
4746 #ifdef FEATURE_HTTPS_INSPECTION
4747 /*********************************************************************
4749 * Function : get_destination_from_https_headers
4751 * Description : Parse the previously encrypted "Host:" header to
4752 * get the request's destination.
4755 * 1 : headers = List of headers (one of them hopefully being
4756 * the "Host:" header)
4757 * 2 : http = storage for the result (host, port and hostport).
4759 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4760 * JB_ERR_PARSE if the host header couldn't be found,
4761 * JB_ERR_OK otherwise.
4763 *********************************************************************/
4764 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4770 host = get_header_value(headers, "Host:");
4774 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4775 return JB_ERR_PARSE;
4778 p = string_tolower(host);
4781 return JB_ERR_MEMORY;
4784 q = strdup_or_die(p);
4786 freez(http->hostport);
4790 q = strchr(http->host, ':');
4793 /* Terminate hostname and evaluate port string */
4795 http->port = atoi(q);
4802 /* Rebuild request URL */
4804 http->url = strdup_or_die(http->path);
4806 log_error(LOG_LEVEL_HEADER,
4807 "Destination extracted from \"Host\" header. New request URL: %s",
4811 * Regenerate request line in "proxy format"
4812 * to make rewrites more convenient.
4814 assert(http->cmd != NULL);
4816 http->cmd = strdup_or_die(http->gpc);
4817 string_append(&http->cmd, " ");
4818 string_append(&http->cmd, http->url);
4819 string_append(&http->cmd, " ");
4820 string_append(&http->cmd, http->version);
4821 if (http->cmd == NULL)
4823 return JB_ERR_MEMORY;
4829 #endif /* def FEATURE_HTTPS_INSPECTION */
4832 /*********************************************************************
4834 * Function : create_forged_referrer
4836 * Description : Helper for client_referrer to forge a referer as
4837 * 'http://hostname[:port]/' to fool stupid
4838 * checks for in-site links
4841 * 1 : header = Pointer to header pointer
4842 * 2 : hostport = Host and optionally port as string
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_forged_referrer(char **header, const char *hostport)
4850 assert(NULL == *header);
4852 *header = strdup("Referer: http://");
4853 string_append(header, hostport);
4854 string_append(header, "/");
4856 if (NULL == *header)
4858 return JB_ERR_MEMORY;
4861 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4868 /*********************************************************************
4870 * Function : create_fake_referrer
4872 * Description : Helper for client_referrer to create a fake referrer
4873 * based on a string supplied by the user.
4876 * 1 : header = Pointer to header pointer
4877 * 2 : hosthost = Referrer to fake
4879 * Returns : JB_ERR_OK in case of success, or
4880 * JB_ERR_MEMORY in case of memory problems.
4882 *********************************************************************/
4883 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4885 assert(NULL == *header);
4887 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4889 log_error(LOG_LEVEL_HEADER,
4890 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4892 *header = strdup("Referer: ");
4893 string_append(header, fake_referrer);
4895 if (NULL == *header)
4897 return JB_ERR_MEMORY;
4900 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4907 /*********************************************************************
4909 * Function : handle_conditional_hide_referrer_parameter
4911 * Description : Helper for client_referrer to crunch or forge
4912 * the referrer header if the host has changed.
4915 * 1 : header = Pointer to header pointer
4916 * 2 : host = The target host (may include the port)
4917 * 3 : parameter_conditional_block = Boolean to signal
4918 * if we're in conditional-block mode. If not set,
4919 * we're in conditional-forge mode.
4921 * Returns : JB_ERR_OK in case of success, or
4922 * JB_ERR_MEMORY in case of memory problems.
4924 *********************************************************************/
4925 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4926 const char *host, const int parameter_conditional_block)
4928 char *referer = strdup_or_die(*header);
4929 const size_t hostlength = strlen(host);
4930 const char *referer_url = NULL;
4932 /* referer begins with 'Referer: http[s]://' */
4933 if ((hostlength+17) < strlen(referer))
4936 * Shorten referer to make sure the referer is blocked
4937 * if www.example.org/www.example.com-shall-see-the-referer/
4938 * links to www.example.com/
4940 referer[hostlength+17] = '\0';
4942 referer_url = strstr(referer, "http://");
4943 if (NULL == referer_url)
4945 referer_url = strstr(referer, "https://");
4947 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4949 /* Host has changed, Referer is invalid or a https URL. */
4950 if (parameter_conditional_block)
4952 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4959 return create_forged_referrer(header, host);
4969 /*********************************************************************
4971 * Function : create_content_length_header
4973 * Description : Creates a Content-Length header.
4976 * 1 : content_length = The content length to be used in the header.
4977 * 2 : header = Allocated space to safe the header.
4978 * 3 : buffer_length = The length of the allocated space.
4982 *********************************************************************/
4983 static void create_content_length_header(unsigned long long content_length,
4984 char *header, size_t buffer_length)
4987 #if SIZEOF_LONG_LONG < 8
4988 #error sizeof(unsigned long long) too small
4990 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4992 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4997 /*********************************************************************
4999 * Function : get_expected_content_length
5001 * Description : Figures out the content length from a list of headers.
5004 * 1 : headers = List of headers
5006 * Returns : Number of bytes to expect
5008 *********************************************************************/
5009 unsigned long long get_expected_content_length(struct list *headers)
5011 const char *content_length_header;
5012 unsigned long long content_length = 0;
5014 content_length_header = get_header_value(headers, "Content-Length:");
5015 if (content_length_header != NULL)
5017 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
5019 log_error(LOG_LEVEL_ERROR,
5020 "Failed to get the Content-Length in %s", content_length_header);
5021 /* XXX: The header will be removed later on */
5026 return content_length;