1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2020 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
61 #define GZIP_FLAG_CHECKSUM 0x02
62 #define GZIP_FLAG_EXTRA_FIELDS 0x04
63 #define GZIP_FLAG_FILE_NAME 0x08
64 #define GZIP_FLAG_COMMENT 0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
68 #include <brotli/decode.h>
71 #if !defined(_WIN32) && !defined(__OS2__)
77 #ifdef FEATURE_PTHREAD
79 /* jcc.h is for mutex semapores only */
80 #endif /* def FEATURE_PTHREAD */
85 #include "jbsockets.h"
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
99 static jb_err parse_time_header(const char *header, time_t *result);
101 static jb_err crumble (struct client_state *csp, char **header);
102 static jb_err filter_header (struct client_state *csp, char **header);
103 static jb_err client_connection (struct client_state *csp, char **header);
104 static jb_err client_referrer (struct client_state *csp, char **header);
105 static jb_err client_uagent (struct client_state *csp, char **header);
106 static jb_err client_ua (struct client_state *csp, char **header);
107 static jb_err client_from (struct client_state *csp, char **header);
108 static jb_err client_send_cookie (struct client_state *csp, char **header);
109 static jb_err client_x_forwarded (struct client_state *csp, char **header);
110 static jb_err client_accept_encoding (struct client_state *csp, char **header);
111 static jb_err client_te (struct client_state *csp, char **header);
112 static jb_err client_max_forwards (struct client_state *csp, char **header);
113 static jb_err client_host (struct client_state *csp, char **header);
114 static jb_err client_if_modified_since (struct client_state *csp, char **header);
115 static jb_err client_accept_language (struct client_state *csp, char **header);
116 static jb_err client_if_none_match (struct client_state *csp, char **header);
117 static jb_err crunch_client_header (struct client_state *csp, char **header);
118 static jb_err client_x_filter (struct client_state *csp, char **header);
119 static jb_err client_range (struct client_state *csp, char **header);
120 static jb_err client_expect (struct client_state *csp, char **header);
121 static jb_err server_set_cookie (struct client_state *csp, char **header);
122 static jb_err server_connection (struct client_state *csp, char **header);
123 static jb_err server_content_type (struct client_state *csp, char **header);
124 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
125 static jb_err server_content_md5 (struct client_state *csp, char **header);
126 static jb_err server_content_encoding (struct client_state *csp, char **header);
127 static jb_err server_transfer_coding (struct client_state *csp, char **header);
128 static jb_err server_http (struct client_state *csp, char **header);
129 static jb_err crunch_server_header (struct client_state *csp, char **header);
130 static jb_err server_last_modified (struct client_state *csp, char **header);
131 static jb_err server_content_disposition(struct client_state *csp, char **header);
133 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
136 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
137 static jb_err server_save_content_length(struct client_state *csp, char **header);
138 static jb_err server_keep_alive(struct client_state *csp, char **header);
139 static jb_err server_proxy_connection(struct client_state *csp, char **header);
140 static jb_err client_keep_alive(struct client_state *csp, char **header);
141 static jb_err client_save_content_length(struct client_state *csp, char **header);
142 static jb_err client_proxy_connection(struct client_state *csp, char **header);
143 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
145 static jb_err client_host_adder (struct client_state *csp);
146 static jb_err client_xtra_adder (struct client_state *csp);
147 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
148 static jb_err client_connection_header_adder(struct client_state *csp);
149 static jb_err server_connection_adder(struct client_state *csp);
150 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
151 static jb_err server_proxy_connection_adder(struct client_state *csp);
152 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
153 static jb_err proxy_authentication(struct client_state *csp, char **header);
155 static jb_err create_forged_referrer(char **header, const char *hostport);
156 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
157 static jb_err handle_conditional_hide_referrer_parameter(char **header,
158 const char *host, const int parameter_conditional_block);
159 static void create_content_length_header(unsigned long long content_length,
160 char *header, size_t buffer_length);
163 * List of functions to run on a list of headers.
167 /** The header prefix to match */
170 /** The length of the prefix to match */
173 /** The function to apply to this line */
174 const parser_func_ptr parser;
177 static const struct parsers client_patterns[] = {
178 { "referer:", 8, client_referrer },
179 { "user-agent:", 11, client_uagent },
180 { "ua-", 3, client_ua },
181 { "from:", 5, client_from },
182 { "cookie:", 7, client_send_cookie },
183 { "x-forwarded-for:", 16, client_x_forwarded },
184 { "Accept-Encoding:", 16, client_accept_encoding },
185 { "TE:", 3, client_te },
186 { "Host:", 5, client_host },
187 { "if-modified-since:", 18, client_if_modified_since },
188 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
189 { "Keep-Alive:", 11, client_keep_alive },
190 { "Content-Length:", 15, client_save_content_length },
191 { "Proxy-Connection:", 17, client_proxy_connection },
193 { "Keep-Alive:", 11, crumble },
194 { "Proxy-Connection:", 17, crumble },
196 { "connection:", 11, client_connection },
197 { "max-forwards:", 13, client_max_forwards },
198 { "Accept-Language:", 16, client_accept_language },
199 { "if-none-match:", 14, client_if_none_match },
200 { "Range:", 6, client_range },
201 { "Request-Range:", 14, client_range },
202 { "If-Range:", 9, client_range },
203 { "X-Filter:", 9, client_x_filter },
204 { "Proxy-Authorization:", 20, proxy_authentication },
206 { "Transfer-Encoding:", 18, client_transfer_encoding },
208 { "Expect:", 7, client_expect },
209 { "*", 0, crunch_client_header },
210 { "*", 0, filter_header },
214 static const struct parsers server_patterns[] = {
215 { "HTTP/", 5, server_http },
216 { "set-cookie:", 11, server_set_cookie },
217 { "connection:", 11, server_connection },
218 { "Content-Type:", 13, server_content_type },
219 { "Content-MD5:", 12, server_content_md5 },
220 { "Content-Encoding:", 17, server_content_encoding },
221 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
222 { "Content-Length:", 15, server_save_content_length },
223 { "Keep-Alive:", 11, server_keep_alive },
224 { "Proxy-Connection:", 17, server_proxy_connection },
226 { "Keep-Alive:", 11, crumble },
227 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
228 { "Transfer-Encoding:", 18, server_transfer_coding },
229 { "content-disposition:", 20, server_content_disposition },
230 { "Last-Modified:", 14, server_last_modified },
231 { "Proxy-Authenticate:", 19, proxy_authentication },
232 { "*", 0, crunch_server_header },
233 { "*", 0, filter_header },
237 static const add_header_func_ptr add_client_headers[] = {
239 client_x_forwarded_for_adder,
241 client_connection_header_adder,
245 static const add_header_func_ptr add_server_headers[] = {
246 server_connection_adder,
247 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
248 server_proxy_connection_adder,
249 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
253 /*********************************************************************
255 * Function : flush_iob
257 * Description : Write any pending "buffered" content.
260 * 1 : fd = file descriptor of the socket to read
261 * 2 : iob = The I/O buffer to flush, usually csp->iob.
262 * 3 : delay = Number of milliseconds to delay the writes
264 * Returns : On success, the number of bytes written are returned (zero
265 * indicates nothing was written). On error, -1 is returned,
266 * and errno is set appropriately. If count is zero and the
267 * file descriptor refers to a regular file, 0 will be
268 * returned without causing any other effect. For a special
269 * file, the results are not portable.
271 *********************************************************************/
272 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
274 long len = iob->eod - iob->cur;
281 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
285 iob->eod = iob->cur = iob->buf;
291 /*********************************************************************
293 * Function : add_to_iob
295 * Description : Add content to the buffer, expanding the
296 * buffer if necessary.
299 * 1 : iob = Destination buffer.
300 * 2 : buffer_limit = Limit to which the destination may grow
301 * 3 : src = holds the content to be added
302 * 4 : n = number of bytes to be added
304 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
305 * or buffer limit reached.
307 *********************************************************************/
308 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
310 size_t used, offset, need;
313 if (n <= 0) return JB_ERR_OK;
315 used = (size_t)(iob->eod - iob->buf);
316 offset = (size_t)(iob->cur - iob->buf);
317 need = used + (size_t)n + 1;
320 * If the buffer can't hold the new data, extend it first.
321 * Use the next power of two if possible, else use the actual need.
323 if (need > buffer_limit)
325 log_error(LOG_LEVEL_INFO,
326 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
328 return JB_ERR_MEMORY;
331 if (need > iob->size)
333 size_t want = iob->size ? iob->size : 512;
340 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
344 else if (NULL != (p = (char *)realloc(iob->buf, need)))
350 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
351 return JB_ERR_MEMORY;
354 /* Update the iob pointers */
355 iob->cur = p + offset;
360 /* copy the new data into the iob buffer */
361 memcpy(iob->eod, src, (size_t)n);
363 /* point to the end of the data */
366 /* null terminate == cheap insurance */
374 /*********************************************************************
376 * Function : clear_iob
378 * Description : Frees the memory allocated for an I/O buffer and
379 * resets the structure.
382 * 1 : iob = I/O buffer to clear.
384 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
385 * or buffer limit reached.
387 *********************************************************************/
388 void clear_iob(struct iob *iob)
391 memset(iob, '\0', sizeof(*iob));
396 #ifdef FEATURE_BROTLI
397 /*********************************************************************
399 * Function : decompress_iob_with_brotli
401 * Description : Decompress buffered page using Brotli.
404 * 1 : csp = Current client state (buffers, headers, etc...)
406 * Returns : JB_ERR_OK on success,
407 * JB_ERR_MEMORY if out-of-memory limit reached, and
408 * JB_ERR_COMPRESS if error decompressing buffer.
410 *********************************************************************/
411 static jb_err decompress_iob_with_brotli(struct client_state *csp)
413 BrotliDecoderResult result;
414 char *decoded_buffer;
416 size_t decoded_buffer_size;
418 enum { MAX_COMPRESSION_FACTOR = 15 };
420 encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
422 * The BrotliDecoderDecompress() api is a bit unfortunate
423 * and requires the caller to reserve enough memory for
424 * the decompressed content. Hopefully reserving
425 * MAX_COMPRESSION_FACTOR times the original size is
426 * sufficient. If not, BrotliDecoderDecompress() will fail.
428 decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
430 if (decoded_buffer_size > csp->config->buffer_limit)
432 log_error(LOG_LEVEL_ERROR,
433 "Buffer limit reached before decompressing iob with Brotli");
434 return JB_ERR_MEMORY;
437 decoded_buffer = malloc(decoded_buffer_size);
438 if (decoded_buffer == NULL)
440 log_error(LOG_LEVEL_ERROR,
441 "Failed to allocate %d bytes for Brotli decompression",
442 decoded_buffer_size);
443 return JB_ERR_MEMORY;
446 decoded_size = decoded_buffer_size;
447 result = BrotliDecoderDecompress(encoded_size,
448 (const uint8_t *)csp->iob->cur, &decoded_size,
449 (uint8_t *)decoded_buffer);
450 if (result == BROTLI_DECODER_RESULT_SUCCESS)
453 * Update the iob, since the decompression was successful.
455 freez(csp->iob->buf);
456 csp->iob->buf = decoded_buffer;
457 csp->iob->cur = csp->iob->buf;
458 csp->iob->eod = csp->iob->cur + decoded_size;
459 csp->iob->size = decoded_buffer_size;
461 log_error(LOG_LEVEL_RE_FILTER,
462 "Decompression successful. Old size: %d, new size: %d.",
463 encoded_size, decoded_size);
469 log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
470 freez(decoded_buffer);
472 return JB_ERR_COMPRESS;
477 /*********************************************************************
479 * Function : decompress_iob
481 * Description : Decompress buffered page, expanding the
482 * buffer as necessary. csp->iob->cur
483 * should point to the the beginning of the
484 * compressed data block.
487 * 1 : csp = Current client state (buffers, headers, etc...)
489 * Returns : JB_ERR_OK on success,
490 * JB_ERR_MEMORY if out-of-memory limit reached, and
491 * JB_ERR_COMPRESS if error decompressing buffer.
493 *********************************************************************/
494 jb_err decompress_iob(struct client_state *csp)
496 char *buf; /* new, uncompressed buffer */
497 char *cur; /* Current iob position (to keep the original
498 * iob->cur unmodified if we return early) */
499 size_t bufsize; /* allocated size of the new buffer */
500 size_t old_size; /* Content size before decompression */
501 size_t skip_size; /* Number of bytes at the beginning of the iob
502 that we should NOT decompress. */
503 int status; /* return status of the inflate() call */
504 z_stream zstr; /* used by calls to zlib */
507 assert(csp->iob->cur - csp->iob->buf >= 0);
508 assert(csp->iob->eod - csp->iob->cur >= 0);
510 assert(csp->iob->cur - csp->iob->buf > 0);
511 assert(csp->iob->eod - csp->iob->cur > 0);
514 bufsize = csp->iob->size;
515 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
516 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
520 if (bufsize < (size_t)10)
523 * This is to protect the parsing of gzipped data,
524 * but it should(?) be valid for deflated data also.
526 log_error(LOG_LEVEL_ERROR,
527 "Insufficient data to start decompression. Bytes in buffer: %d",
528 csp->iob->eod - csp->iob->cur);
529 return JB_ERR_COMPRESS;
532 #ifdef FEATURE_BROTLI
533 if (csp->content_type & CT_BROTLI)
535 return decompress_iob_with_brotli(csp);
539 if (csp->content_type & CT_GZIP)
542 * Our task is slightly complicated by the facts that data
543 * compressed by gzip does not include a zlib header, and
544 * that there is no easily accessible interface in zlib to
545 * handle a gzip header. We strip off the gzip header by
546 * hand, and later inform zlib not to expect a header.
550 * Strip off the gzip header. Please see RFC 1952 for more
551 * explanation of the appropriate fields.
553 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
554 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
555 || (*cur++ != Z_DEFLATED))
557 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
558 return JB_ERR_COMPRESS;
563 if (flags & GZIP_FLAG_RESERVED_BITS)
565 /* The gzip header has reserved bits set; bail out. */
566 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
567 return JB_ERR_COMPRESS;
571 * Skip mtime (4 bytes), extra flags (1 byte)
572 * and OS type (1 byte).
576 /* Skip extra fields if necessary. */
577 if (flags & GZIP_FLAG_EXTRA_FIELDS)
580 * Skip a given number of bytes, specified
581 * as a 16-bit little-endian value.
583 * XXX: this code is untested and should probably be removed.
587 skip_bytes += *cur++ << 8;
590 * The number of bytes to skip should be positive
591 * and we'd like to stay in the buffer.
593 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
595 log_error(LOG_LEVEL_ERROR,
596 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
598 return JB_ERR_COMPRESS;
600 log_error(LOG_LEVEL_INFO,
601 "Skipping %d bytes for gzip compression. Does this sound right?",
606 /* Skip the filename if necessary. */
607 if (flags & GZIP_FLAG_FILE_NAME)
609 /* A null-terminated string is supposed to follow. */
610 while (*cur++ && (cur < csp->iob->eod));
613 /* Skip the comment if necessary. */
614 if (flags & GZIP_FLAG_COMMENT)
616 /* A null-terminated string is supposed to follow. */
617 while (*cur++ && (cur < csp->iob->eod));
620 /* Skip the CRC if necessary. */
621 if (flags & GZIP_FLAG_CHECKSUM)
626 if (cur >= csp->iob->eod)
629 * If the current position pointer reached or passed
630 * the buffer end, we were obviously tricked to skip
633 log_error(LOG_LEVEL_ERROR,
634 "Malformed gzip header detected. Aborting decompression.");
635 return JB_ERR_COMPRESS;
639 else if (csp->content_type & CT_DEFLATE)
642 * In theory (that is, according to RFC 1950), deflate-compressed
643 * data should begin with a two-byte zlib header and have an
644 * adler32 checksum at the end. It seems that in practice only
645 * the raw compressed data is sent. Note that this means that
646 * we are not RFC 1950-compliant here, but the advantage is that
647 * this actually works. :)
649 * We add a dummy null byte to tell zlib where the data ends,
650 * and later inform it not to expect a header.
652 * Fortunately, add_to_iob() has thoughtfully null-terminated
653 * the buffer; we can just increment the end pointer to include
660 log_error(LOG_LEVEL_ERROR,
661 "Unable to determine compression format for decompression");
662 return JB_ERR_COMPRESS;
665 /* Set up the fields required by zlib. */
666 zstr.next_in = (Bytef *)cur;
667 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
668 zstr.zalloc = Z_NULL;
670 zstr.opaque = Z_NULL;
673 * Passing -MAX_WBITS to inflateInit2 tells the library
674 * that there is no zlib header.
676 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
678 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
679 return JB_ERR_COMPRESS;
683 * Next, we allocate new storage for the inflated data.
684 * We don't modify the existing iob yet, so in case there
685 * is error in decompression we can recover gracefully.
687 buf = zalloc(bufsize);
690 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
691 return JB_ERR_MEMORY;
694 assert(bufsize >= skip_size);
695 memcpy(buf, csp->iob->buf, skip_size);
696 zstr.avail_out = (uInt)(bufsize - skip_size);
697 zstr.next_out = (Bytef *)buf + skip_size;
699 /* Try to decompress the whole stream in one shot. */
700 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
702 /* We need to allocate more memory for the output buffer. */
704 char *tmpbuf; /* used for realloc'ing the buffer */
705 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
707 if (0 == zstr.avail_in)
710 * If zlib wants more data then there's a problem, because
711 * the complete compressed file should have been buffered.
713 log_error(LOG_LEVEL_ERROR,
714 "Unexpected end of compressed iob. Using what we got so far.");
719 * If we reached the buffer limit and still didn't have enough
720 * memory, just give up. Due to the ceiling enforced by the next
721 * if block we could actually check for equality here, but as it
722 * can be easily mistaken for a bug we don't.
724 if (bufsize >= csp->config->buffer_limit)
726 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
728 return JB_ERR_MEMORY;
731 /* Try doubling the buffer size each time. */
734 /* Don't exceed the buffer limit. */
735 if (bufsize > csp->config->buffer_limit)
737 bufsize = csp->config->buffer_limit;
740 /* Try to allocate the new buffer. */
741 tmpbuf = realloc(buf, bufsize);
744 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
746 return JB_ERR_MEMORY;
750 char *oldnext_out = (char *)zstr.next_out;
753 * Update the fields for inflate() to use the new
754 * buffer, which may be in a location different from
757 zstr.avail_out += (uInt)(bufsize - oldbufsize);
758 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
761 * Compare with an uglier method of calculating these values
762 * that doesn't require the extra oldbufsize variable.
764 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
765 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
771 if (Z_STREAM_ERROR == inflateEnd(&zstr))
773 log_error(LOG_LEVEL_ERROR,
774 "Inconsistent stream state after decompression: %s", zstr.msg);
776 * XXX: Intentionally no return.
778 * According to zlib.h, Z_STREAM_ERROR is returned
779 * "if the stream state was inconsistent".
781 * I assume in this case inflate()'s status
782 * would also be something different than Z_STREAM_END
783 * so this check should be redundant, but lets see.
787 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
790 * We failed to decompress the stream and it's
791 * not simply because of missing data.
793 log_error(LOG_LEVEL_ERROR,
794 "Unexpected error while decompressing to the buffer (iob): %s",
796 return JB_ERR_COMPRESS;
800 * Finally, we can actually update the iob, since the
801 * decompression was successful. First, free the old
804 freez(csp->iob->buf);
806 /* Now, update the iob to use the new buffer. */
808 csp->iob->cur = csp->iob->buf + skip_size;
809 csp->iob->eod = (char *)zstr.next_out;
810 csp->iob->size = bufsize;
813 * Make sure the new uncompressed iob obeys some minimal
814 * consistency conditions.
816 if ((csp->iob->buf <= csp->iob->cur)
817 && (csp->iob->cur <= csp->iob->eod)
818 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
820 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
821 if (new_size > (size_t)0)
823 log_error(LOG_LEVEL_RE_FILTER,
824 "Decompression successful. Old size: %d, new size: %d.",
829 /* zlib thinks this is OK, so let's do the same. */
830 log_error(LOG_LEVEL_RE_FILTER,
831 "Decompression didn't result in any content.");
836 /* It seems that zlib did something weird. */
837 log_error(LOG_LEVEL_ERROR,
838 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
839 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
840 csp->iob->eod, csp->iob->buf + csp->iob->size);
841 return JB_ERR_COMPRESS;
847 #endif /* defined(FEATURE_ZLIB) */
850 /*********************************************************************
852 * Function : normalize_lws
854 * Description : Reduces unquoted linear whitespace in headers to
855 * a single space in accordance with RFC 7230 3.2.4.
856 * This simplifies parsing and filtering later on.
859 * 1 : header = A header with linear whitespace to reduce.
863 *********************************************************************/
864 static void normalize_lws(char *header)
870 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
874 while (privoxy_isspace(*q))
878 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
884 log_error(LOG_LEVEL_HEADER,
885 "Converting tab to space in '%s'", header);
890 char *end_of_token = strstr(p+1, "\"");
892 if (NULL != end_of_token)
894 /* Don't mess with quoted text. */
899 log_error(LOG_LEVEL_HEADER,
900 "Ignoring single quote in '%s'", header);
906 p = strchr(header, ':');
907 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
910 * There's still space before the colon.
918 /*********************************************************************
920 * Function : get_header
922 * Description : This (odd) routine will parse the csp->iob
923 * to get the next complete header.
926 * 1 : iob = The I/O buffer to parse, usually csp->iob.
928 * Returns : Any one of the following:
930 * 1) a pointer to a dynamically allocated string that contains a header line
931 * 2) NULL indicating that the end of the header was reached
932 * 3) "" indicating that the end of the iob was reached before finding
933 * a complete header line.
935 *********************************************************************/
936 char *get_header(struct iob *iob)
940 header = get_header_line(iob);
942 if ((header == NULL) || (*header == '\0'))
945 * No complete header read yet, tell the client.
950 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
953 * Header spans multiple lines, append the next one.
955 char *continued_header;
957 continued_header = get_header_line(iob);
958 if ((continued_header == NULL) || (*continued_header == '\0'))
961 * No complete header read yet, return what we got.
962 * XXX: Should "unread" header instead.
964 log_error(LOG_LEVEL_INFO,
965 "Failed to read a multi-line header properly: '%s'",
970 if (JB_ERR_OK != string_join(&header, continued_header))
972 log_error(LOG_LEVEL_FATAL,
973 "Out of memory while appending multiple headers.");
977 /* XXX: remove before next stable release. */
978 log_error(LOG_LEVEL_HEADER,
979 "Merged multiple header lines to: '%s'",
984 normalize_lws(header);
991 /*********************************************************************
993 * Function : get_header_line
995 * Description : This (odd) routine will parse the csp->iob
996 * to get the next header line.
999 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1001 * Returns : Any one of the following:
1003 * 1) a pointer to a dynamically allocated string that contains a header line
1004 * 2) NULL indicating that the end of the header was reached
1005 * 3) "" indicating that the end of the iob was reached before finding
1006 * a complete header line.
1008 *********************************************************************/
1009 static char *get_header_line(struct iob *iob)
1013 if ((iob->cur == NULL)
1014 || ((p = strchr(iob->cur, '\n')) == NULL))
1016 return(""); /* couldn't find a complete header */
1021 ret = strdup(iob->cur);
1024 /* FIXME No way to handle error properly */
1025 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1027 assert(ret != NULL);
1031 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1033 /* is this a blank line (i.e. the end of the header) ? */
1045 /*********************************************************************
1047 * Function : get_header_value
1049 * Description : Get the value of a given header from a chained list
1050 * of header lines or return NULL if no such header is
1051 * present in the list.
1054 * 1 : header_list = pointer to list
1055 * 2 : header_name = string with name of header to look for.
1056 * Trailing colon required, capitalization
1059 * Returns : NULL if not found, else value of header
1061 *********************************************************************/
1062 char *get_header_value(const struct list *header_list, const char *header_name)
1064 struct list_entry *cur_entry;
1068 assert(header_list);
1069 assert(header_name);
1070 length = strlen(header_name);
1072 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1076 if (!strncmpic(cur_entry->str, header_name, length))
1079 * Found: return pointer to start of value
1081 ret = cur_entry->str + length;
1082 while (*ret && privoxy_isspace(*ret)) ret++;
1096 /*********************************************************************
1098 * Function : scan_headers
1100 * Description : Scans headers, applies tags and updates action bits.
1103 * 1 : csp = Current client state (buffers, headers, etc...)
1105 * Returns : JB_ERR_OK
1107 *********************************************************************/
1108 static jb_err scan_headers(struct client_state *csp)
1110 struct list_entry *h; /* Header */
1111 jb_err err = JB_ERR_OK;
1113 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1115 /* Header crunch()ed in previous run? -> ignore */
1116 if (h->str == NULL) continue;
1117 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1118 err = header_tagger(csp, h->str);
1125 /*********************************************************************
1127 * Function : enforce_header_order
1129 * Description : Enforces a given header order.
1132 * 1 : headers = List of headers to order.
1133 * 2 : ordered_headers = List of ordered header names.
1137 *********************************************************************/
1138 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1140 struct list_entry *sorted_header;
1141 struct list new_headers[1];
1142 struct list_entry *header;
1144 init_list(new_headers);
1146 /* The request line is always the first "header" */
1148 assert(NULL != headers->first->str);
1149 enlist(new_headers, headers->first->str);
1150 freez(headers->first->str)
1152 /* Enlist the specified headers in the given order */
1154 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1155 sorted_header = sorted_header->next)
1157 const size_t sorted_header_length = strlen(sorted_header->str);
1158 for (header = headers->first; header != NULL; header = header->next)
1160 /* Header enlisted in previous run? -> ignore */
1161 if (header->str == NULL) continue;
1163 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1164 && (header->str[sorted_header_length] == ':'))
1166 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1167 if (JB_ERR_OK != enlist(new_headers, header->str))
1169 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1176 /* Enlist the rest of the headers behind the ordered ones */
1177 for (header = headers->first; header != NULL; header = header->next)
1179 /* Header enlisted in previous run? -> ignore */
1180 if (header->str == NULL) continue;
1182 log_error(LOG_LEVEL_HEADER,
1183 "Enlisting left-over header %s", header->str);
1184 if (JB_ERR_OK != enlist(new_headers, header->str))
1186 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1191 list_remove_all(headers);
1192 list_duplicate(headers, new_headers);
1193 list_remove_all(new_headers);
1199 /*********************************************************************
1203 * Description : add, delete or modify lines in the HTTP header streams.
1204 * On entry, it receives a linked list of headers space
1205 * that was allocated dynamically (both the list nodes
1206 * and the header contents).
1208 * As a side effect it frees the space used by the original
1212 * 1 : csp = Current client state (buffers, headers, etc...)
1213 * 2 : filter_server_headers = Boolean to switch between
1214 * server and header filtering.
1216 * Returns : JB_ERR_OK in case off success, or
1217 * JB_ERR_MEMORY on some out-of-memory errors, or
1218 * JB_ERR_PARSE in case of fatal parse errors.
1220 *********************************************************************/
1221 jb_err sed(struct client_state *csp, int filter_server_headers)
1223 /* XXX: use more descriptive names. */
1224 struct list_entry *p;
1225 const struct parsers *v;
1226 const add_header_func_ptr *f;
1227 jb_err err = JB_ERR_OK;
1231 if (filter_server_headers)
1233 v = server_patterns;
1234 f = add_server_headers;
1235 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1239 v = client_patterns;
1240 f = add_client_headers;
1241 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1244 while (v->str != NULL)
1246 for (p = csp->headers->first; p != NULL; p = p->next)
1248 /* Header crunch()ed in previous run? -> ignore */
1249 if (p->str == NULL) continue;
1251 /* Does the current parser handle this header? */
1252 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1253 (v->len == CHECK_EVERY_HEADER_REMAINING))
1255 err = v->parser(csp, &(p->str));
1256 if (err != JB_ERR_OK)
1265 /* place additional headers on the csp->headers list */
1266 while ((err == JB_ERR_OK) && (*f))
1272 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1274 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1281 #ifdef FEATURE_HTTPS_INSPECTION
1282 /*********************************************************************
1284 * Function : sed_https
1286 * Description : add, delete or modify lines in the HTTPS client
1287 * header streams. Wrapper around sed().
1290 * 1 : csp = Current client state (buffers, headers, etc...)
1292 * Returns : JB_ERR_OK in case off success, or
1293 * JB_ERR_MEMORY on some out-of-memory errors, or
1294 * JB_ERR_PARSE in case of fatal parse errors.
1296 *********************************************************************/
1297 jb_err sed_https(struct client_state *csp)
1300 struct list headers;
1303 * Temporarily replace csp->headers with csp->https_headers
1304 * to trick sed() into filtering the https headers.
1306 headers.first = csp->headers->first;
1307 headers.last = csp->headers->last;
1308 csp->headers->first = csp->https_headers->first;
1309 csp->headers->last = csp->https_headers->last;
1312 * Start with fresh tags. Already existing tags may
1313 * be set again. This is necessary to overrule
1314 * URL-based patterns.
1316 destroy_list(csp->tags);
1319 * We want client header filters and taggers
1320 * so temporarily remove the flag.
1322 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1323 err = sed(csp, FILTER_CLIENT_HEADERS);
1324 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1327 * Update the last header which may have changed
1328 * due to header additions,
1330 csp->https_headers->last = csp->headers->last;
1332 csp->headers->first = headers.first;
1333 csp->headers->last = headers.last;
1337 #endif /* def FEATURE_HTTPS_INSPECTION */
1340 /*********************************************************************
1342 * Function : update_server_headers
1344 * Description : Updates server headers after the body has been modified.
1347 * 1 : csp = Current client state (buffers, headers, etc...)
1349 * Returns : JB_ERR_OK in case off success, or
1350 * JB_ERR_MEMORY on out-of-memory error.
1352 *********************************************************************/
1353 jb_err update_server_headers(struct client_state *csp)
1355 jb_err err = JB_ERR_OK;
1357 static const struct parsers server_patterns_light[] = {
1358 { "Content-Length:", 15, server_adjust_content_length },
1359 { "Transfer-Encoding:", 18, server_transfer_coding },
1361 { "Content-Encoding:", 17, server_adjust_content_encoding },
1362 #endif /* def FEATURE_ZLIB */
1366 if (strncmpic(csp->http->cmd, "HEAD", 4))
1368 const struct parsers *v;
1369 struct list_entry *p;
1371 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1373 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1375 /* Header crunch()ed in previous run? -> ignore */
1376 if (p->str == NULL) continue;
1378 /* Does the current parser handle this header? */
1379 if (strncmpic(p->str, v->str, v->len) == 0)
1381 err = v->parser(csp, (char **)&(p->str));
1387 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1388 if ((JB_ERR_OK == err)
1389 && (csp->flags & CSP_FLAG_MODIFIED)
1390 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1391 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1395 create_content_length_header(csp->content_length, header, sizeof(header));
1396 err = enlist(csp->headers, header);
1397 if (JB_ERR_OK == err)
1399 log_error(LOG_LEVEL_HEADER,
1400 "Content modified with no Content-Length header set. "
1401 "Created: %s.", header);
1402 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1405 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1407 #ifdef FEATURE_COMPRESSION
1408 if ((JB_ERR_OK == err)
1409 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1411 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1412 if (JB_ERR_OK == err)
1414 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1423 /*********************************************************************
1425 * Function : header_tagger
1427 * Description : Executes all text substitutions from applying
1428 * tag actions and saves the result as tag.
1430 * XXX: Shares enough code with filter_header() and
1431 * pcrs_filter_response() to warrant some helper functions.
1434 * 1 : csp = Current client state (buffers, headers, etc...)
1435 * 2 : header = Header that is used as tagger input
1437 * Returns : JB_ERR_OK on success and always succeeds
1439 *********************************************************************/
1440 static jb_err header_tagger(struct client_state *csp, char *header)
1442 enum filter_type wanted_filter_type;
1443 int multi_action_index;
1446 struct re_filterfile_spec *b;
1447 struct list_entry *tag_name;
1449 const size_t header_length = strlen(header);
1451 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1453 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1454 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1458 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1459 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1462 if (list_is_empty(csp->action->multi[multi_action_index])
1463 || filters_available(csp) == FALSE)
1465 /* Return early if no taggers apply or if none are available. */
1469 /* Execute all applying taggers */
1470 for (tag_name = csp->action->multi[multi_action_index]->first;
1471 NULL != tag_name; tag_name = tag_name->next)
1473 char *modified_tag = NULL;
1475 size_t size = header_length;
1478 b = get_filter(csp, tag_name->str, wanted_filter_type);
1484 joblist = b->joblist;
1486 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1488 if (NULL == joblist)
1490 log_error(LOG_LEVEL_RE_FILTER,
1491 "Tagger %s has empty joblist. Nothing to do.", b->name);
1495 /* execute their pcrs_joblist on the header. */
1496 for (job = joblist; NULL != job; job = job->next)
1498 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1502 /* Success, continue with the modified version. */
1511 /* Tagger doesn't match */
1514 /* Regex failure, log it but continue anyway. */
1515 assert(NULL != header);
1516 log_error(LOG_LEVEL_ERROR,
1517 "Problems with tagger \'%s\' and header \'%s\': %s",
1518 b->name, *header, pcrs_strerror(hits));
1520 freez(modified_tag);
1524 if (b->dynamic) pcrs_free_joblist(joblist);
1526 /* If this tagger matched */
1532 * There is no technical limitation which makes
1533 * it impossible to use empty tags, but I assume
1534 * no one would do it intentionally.
1537 log_error(LOG_LEVEL_INFO,
1538 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1542 if (!list_contains_item(csp->tags, tag))
1544 if (JB_ERR_OK != enlist(csp->tags, tag))
1546 log_error(LOG_LEVEL_ERROR,
1547 "Insufficient memory to add tag \'%s\', "
1548 "based on tagger \'%s\' and header \'%s\'",
1549 tag, b->name, *header);
1553 char *action_message;
1555 * update the action bits right away, to make
1556 * tagging based on tags set by earlier taggers
1557 * of the same kind possible.
1559 if (update_action_bits_for_tag(csp, tag))
1561 action_message = "Action bits updated accordingly.";
1565 action_message = "No action bits update necessary.";
1568 log_error(LOG_LEVEL_HEADER,
1569 "Tagger \'%s\' added tag \'%s\'. %s",
1570 b->name, tag, action_message);
1575 /* XXX: Is this log-worthy? */
1576 log_error(LOG_LEVEL_HEADER,
1577 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1587 /* here begins the family of parser functions that reformat header lines */
1589 /*********************************************************************
1591 * Function : filter_header
1593 * Description : Executes all text substitutions from all applying
1594 * +(server|client)-header-filter actions on the header.
1595 * Most of the code was copied from pcrs_filter_response,
1596 * including the rather short variable names
1599 * 1 : csp = Current client state (buffers, headers, etc...)
1600 * 2 : header = On input, pointer to header to modify.
1601 * On output, pointer to the modified header, or NULL
1602 * to remove the header. This function frees the
1603 * original string if necessary.
1605 * Returns : JB_ERR_OK on success and always succeeds
1607 *********************************************************************/
1608 static jb_err filter_header(struct client_state *csp, char **header)
1612 size_t size = strlen(*header);
1614 char *newheader = NULL;
1617 struct re_filterfile_spec *b;
1618 struct list_entry *filtername;
1620 enum filter_type wanted_filter_type;
1621 int multi_action_index;
1623 if (csp->flags & CSP_FLAG_NO_FILTERING)
1628 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1630 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1631 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1635 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1636 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1639 if (list_is_empty(csp->action->multi[multi_action_index])
1640 || filters_available(csp) == FALSE)
1642 /* Return early if no filters apply or if none are available. */
1646 /* Execute all applying header filters */
1647 for (filtername = csp->action->multi[multi_action_index]->first;
1648 filtername != NULL; filtername = filtername->next)
1650 int current_hits = 0;
1653 b = get_filter(csp, filtername->str, wanted_filter_type);
1659 joblist = b->joblist;
1661 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1663 if (NULL == joblist)
1665 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1669 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1670 *header, size, b->name);
1672 /* Apply all jobs from the joblist */
1673 for (job = joblist; NULL != job; job = job->next)
1675 matches = pcrs_execute(job, *header, size, &newheader, &size);
1678 current_hits += matches;
1679 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1681 *header = newheader;
1683 else if (0 == matches)
1685 /* Filter doesn't change header */
1691 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1692 *header, b->name, pcrs_strerror(matches));
1693 if (newheader != NULL)
1695 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1701 if (b->dynamic) pcrs_free_joblist(joblist);
1703 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1704 hits += current_hits;
1708 * Additionally checking for hits is important because if
1709 * the continue hack is triggered, server headers can
1710 * arrive empty to separate multiple heads from each other.
1712 if ((0 == size) && hits)
1714 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1722 /*********************************************************************
1724 * Function : server_connection
1726 * Description : Makes sure a proper "Connection:" header is
1727 * set and signals connection_header_adder to
1731 * 1 : csp = Current client state (buffers, headers, etc...)
1732 * 2 : header = On input, pointer to header to modify.
1733 * On output, pointer to the modified header, or NULL
1734 * to remove the header. This function frees the
1735 * original string if necessary.
1737 * Returns : JB_ERR_OK on success.
1739 *********************************************************************/
1740 static jb_err server_connection(struct client_state *csp, char **header)
1742 if (!strcmpic(*header, "Connection: keep-alive")
1743 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1744 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1748 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1749 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1751 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1754 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1756 log_error(LOG_LEVEL_HEADER,
1757 "Keeping the server header '%s' around.", *header);
1760 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1762 char *old_header = *header;
1764 *header = strdup_or_die("Connection: close");
1765 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1770 /* Signal server_connection_adder() to return early. */
1771 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1777 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1778 /*********************************************************************
1780 * Function : server_keep_alive
1782 * Description : Stores the server's keep alive timeout.
1785 * 1 : csp = Current client state (buffers, headers, etc...)
1786 * 2 : header = On input, pointer to header to modify.
1787 * On output, pointer to the modified header, or NULL
1788 * to remove the header. This function frees the
1789 * original string if necessary.
1791 * Returns : JB_ERR_OK.
1793 *********************************************************************/
1794 static jb_err server_keep_alive(struct client_state *csp, char **header)
1796 unsigned int keep_alive_timeout;
1797 const char *timeout_position = strstr(*header, "timeout=");
1799 if ((NULL == timeout_position)
1800 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1802 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1806 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1808 log_error(LOG_LEVEL_HEADER,
1809 "Reducing keep-alive timeout from %u to %u.",
1810 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1811 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1815 /* XXX: Is this log worthy? */
1816 log_error(LOG_LEVEL_HEADER,
1817 "Server keep-alive timeout is %u. Sticking with %u.",
1818 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1820 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1829 /*********************************************************************
1831 * Function : server_proxy_connection
1833 * Description : Figures out whether or not we should add a
1834 * Proxy-Connection header.
1837 * 1 : csp = Current client state (buffers, headers, etc...)
1838 * 2 : header = On input, pointer to header to modify.
1839 * On output, pointer to the modified header, or NULL
1840 * to remove the header. This function frees the
1841 * original string if necessary.
1843 * Returns : JB_ERR_OK.
1845 *********************************************************************/
1846 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1848 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1853 /*********************************************************************
1855 * Function : proxy_authentication
1857 * Description : Removes headers that are relevant for proxy
1858 * authentication unless forwarding them has
1859 * been explicitly requested.
1862 * 1 : csp = Current client state (buffers, headers, etc...)
1863 * 2 : header = On input, pointer to header to modify.
1864 * On output, pointer to the modified header, or NULL
1865 * to remove the header. This function frees the
1866 * original string if necessary.
1868 * Returns : JB_ERR_OK.
1870 *********************************************************************/
1871 static jb_err proxy_authentication(struct client_state *csp, char **header)
1873 if ((csp->config->feature_flags &
1874 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1875 log_error(LOG_LEVEL_HEADER,
1876 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1883 /*********************************************************************
1885 * Function : client_keep_alive
1887 * Description : Stores the client's keep alive timeout.
1890 * 1 : csp = Current client state (buffers, headers, etc...)
1891 * 2 : header = On input, pointer to header to modify.
1892 * On output, pointer to the modified header, or NULL
1893 * to remove the header. This function frees the
1894 * original string if necessary.
1896 * Returns : JB_ERR_OK.
1898 *********************************************************************/
1899 static jb_err client_keep_alive(struct client_state *csp, char **header)
1901 unsigned int keep_alive_timeout;
1902 char *timeout_position;
1904 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1906 log_error(LOG_LEVEL_HEADER,
1907 "keep-alive support is disabled. Crunching: %s.", *header);
1912 /* Check for parameter-less format "Keep-Alive: 100" */
1913 timeout_position = strstr(*header, ": ");
1914 if ((NULL == timeout_position)
1915 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1917 /* Assume parameter format "Keep-Alive: timeout=100" */
1918 timeout_position = strstr(*header, "timeout=");
1919 if ((NULL == timeout_position)
1920 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1922 log_error(LOG_LEVEL_HEADER,
1923 "Couldn't parse: '%s'. Using default timeout %u",
1924 *header, csp->config->keep_alive_timeout);
1931 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1933 log_error(LOG_LEVEL_HEADER,
1934 "Reducing keep-alive timeout from %u to %u.",
1935 csp->config->keep_alive_timeout, keep_alive_timeout);
1936 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1940 /* XXX: Is this log worthy? */
1941 log_error(LOG_LEVEL_HEADER,
1942 "Client keep-alive timeout is %u. Sticking with %u.",
1943 keep_alive_timeout, csp->config->keep_alive_timeout);
1951 /*********************************************************************
1953 * Function : get_content_length
1955 * Description : Gets the content length specified in a
1956 * Content-Length header.
1959 * 1 : header_value = The Content-Length header value.
1960 * 2 : length = Storage to return the value.
1962 * Returns : JB_ERR_OK on success, or
1963 * JB_ERR_PARSE if no value is recognized.
1965 *********************************************************************/
1966 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1969 #if SIZEOF_LONG_LONG < 8
1970 #error sizeof(unsigned long long) too small
1972 if (1 != sscanf(header_value, "%I64u", length))
1974 if (1 != sscanf(header_value, "%llu", length))
1977 return JB_ERR_PARSE;
1984 /*********************************************************************
1986 * Function : client_save_content_length
1988 * Description : Save the Content-Length sent by the client.
1991 * 1 : csp = Current client state (buffers, headers, etc...)
1992 * 2 : header = On input, pointer to header to modify.
1993 * On output, pointer to the modified header, or NULL
1994 * to remove the header. This function frees the
1995 * original string if necessary.
1997 * Returns : JB_ERR_OK on success, or
1998 * JB_ERR_MEMORY on out-of-memory error.
2000 *********************************************************************/
2001 static jb_err client_save_content_length(struct client_state *csp, char **header)
2003 unsigned long long content_length = 0;
2004 const char *header_value;
2006 assert(*(*header+14) == ':');
2008 header_value = *header + 15;
2009 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2011 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2016 csp->expected_client_content_length = content_length;
2021 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2025 /*********************************************************************
2027 * Function : client_connection
2029 * Description : Makes sure a proper "Connection:" header is
2030 * set and signals connection_header_adder
2034 * 1 : csp = Current client state (buffers, headers, etc...)
2035 * 2 : header = On input, pointer to header to modify.
2036 * On output, pointer to the modified header, or NULL
2037 * to remove the header. This function frees the
2038 * original string if necessary.
2040 * Returns : JB_ERR_OK on success.
2042 *********************************************************************/
2043 static jb_err client_connection(struct client_state *csp, char **header)
2045 static const char connection_close[] = "Connection: close";
2047 if (!strcmpic(*header, connection_close))
2049 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2050 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2051 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2053 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2055 log_error(LOG_LEVEL_HEADER,
2056 "Removing \'%s\' to imply keep-alive.", *header);
2059 * While we imply keep-alive to the server,
2060 * we have to remember that the client didn't.
2062 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2066 char *old_header = *header;
2068 *header = strdup_or_die("Connection: keep-alive");
2069 log_error(LOG_LEVEL_HEADER,
2070 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2076 log_error(LOG_LEVEL_HEADER,
2077 "Keeping the client header '%s' around. "
2078 "The connection will not be kept alive.",
2080 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2083 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2084 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2086 log_error(LOG_LEVEL_HEADER,
2087 "Keeping the client header '%s' around. "
2088 "The server connection will be kept alive if possible.",
2090 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2091 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2095 char *old_header = *header;
2097 *header = strdup_or_die(connection_close);
2098 log_error(LOG_LEVEL_HEADER,
2099 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2103 /* Signal client_connection_header_adder() to return early. */
2104 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2110 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2111 /*********************************************************************
2113 * Function : client_proxy_connection
2115 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2116 * appropriate and removes the Proxy-Connection
2120 * 1 : csp = Current client state (buffers, headers, etc...)
2121 * 2 : header = On input, pointer to header to modify.
2122 * On output, pointer to the modified header, or NULL
2123 * to remove the header. This function frees the
2124 * original string if necessary.
2126 * Returns : JB_ERR_OK
2128 *********************************************************************/
2129 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2131 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2132 && (csp->http->ssl == 0)
2133 && (NULL == strstr(*header, "close")))
2135 log_error(LOG_LEVEL_HEADER,
2136 "The client connection can be kept alive due to: %s", *header);
2137 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2139 crumble(csp, header);
2143 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2146 /*********************************************************************
2148 * Function : client_transfer_encoding
2150 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2151 * the request body is "chunked"
2153 * XXX: Currently not called through sed() as we
2154 * need the flag earlier on. Should be fixed.
2157 * 1 : csp = Current client state (buffers, headers, etc...)
2158 * 2 : header = On input, pointer to header to modify.
2159 * On output, pointer to the modified header, or NULL
2160 * to remove the header. This function frees the
2161 * original string if necessary.
2163 * Returns : JB_ERR_OK on success, or
2165 *********************************************************************/
2166 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2168 if (strstr(*header, "chunked"))
2170 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2171 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2178 /*********************************************************************
2180 * Function : client_expect
2182 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2183 * if the Expect header value is unsupported.
2185 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2186 * MAY and a RFC 2616 (obsolete) MUST.
2189 * 1 : csp = Current client state (buffers, headers, etc...)
2190 * 2 : header = On input, pointer to header to modify.
2191 * On output, pointer to the modified header, or NULL
2192 * to remove the header. This function frees the
2193 * original string if necessary.
2195 * Returns : JB_ERR_OK on success, or
2197 *********************************************************************/
2198 jb_err client_expect(struct client_state *csp, char **header)
2200 if (0 != strcmpic(*header, "Expect: 100-continue"))
2202 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2203 log_error(LOG_LEVEL_HEADER,
2204 "Unsupported client expectaction: %s", *header);
2212 /*********************************************************************
2214 * Function : crumble
2216 * Description : This is called if a header matches a pattern to "crunch"
2219 * 1 : csp = Current client state (buffers, headers, etc...)
2220 * 2 : header = On input, pointer to header to modify.
2221 * On output, pointer to the modified header, or NULL
2222 * to remove the header. This function frees the
2223 * original string if necessary.
2225 * Returns : JB_ERR_OK on success, or
2226 * JB_ERR_MEMORY on out-of-memory error.
2228 *********************************************************************/
2229 static jb_err crumble(struct client_state *csp, char **header)
2232 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2238 /*********************************************************************
2240 * Function : crunch_server_header
2242 * Description : Crunch server header if it matches a string supplied by the
2243 * user. Called from `sed'.
2246 * 1 : csp = Current client state (buffers, headers, etc...)
2247 * 2 : header = On input, pointer to header to modify.
2248 * On output, pointer to the modified header, or NULL
2249 * to remove the header. This function frees the
2250 * original string if necessary.
2252 * Returns : JB_ERR_OK on success and always succeeds
2254 *********************************************************************/
2255 static jb_err crunch_server_header(struct client_state *csp, char **header)
2257 const char *crunch_pattern;
2259 /* Do we feel like crunching? */
2260 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2262 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2264 /* Is the current header the lucky one? */
2265 if (strstr(*header, crunch_pattern))
2267 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2276 /*********************************************************************
2278 * Function : server_content_type
2280 * Description : Set the content-type for filterable types (text/.*,
2281 * .*xml.*, .*script.* and image/gif) unless filtering has been
2282 * forbidden (CT_TABOO) while parsing earlier headers.
2283 * NOTE: Since text/plain is commonly used by web servers
2284 * for files whose correct type is unknown, we don't
2285 * set CT_TEXT for it.
2288 * 1 : csp = Current client state (buffers, headers, etc...)
2289 * 2 : header = On input, pointer to header to modify.
2290 * On output, pointer to the modified header, or NULL
2291 * to remove the header. This function frees the
2292 * original string if necessary.
2294 * Returns : JB_ERR_OK on success, or
2295 * JB_ERR_MEMORY on out-of-memory error.
2297 *********************************************************************/
2298 static jb_err server_content_type(struct client_state *csp, char **header)
2300 /* Remove header if it isn't the first Content-Type header */
2301 if ((csp->content_type & CT_DECLARED))
2303 if (content_filters_enabled(csp->action))
2306 * Making sure the client interprets the content the same way
2307 * Privoxy did is only relevant if Privoxy modified it.
2309 * Checking for this is "hard" as it's not yet known when
2310 * this function is called, thus go shopping and and just
2311 * check if Privoxy could filter it.
2313 * The main thing is that we don't mess with the headers
2314 * unless the user signalled that it's acceptable.
2316 log_error(LOG_LEVEL_HEADER,
2317 "Multiple Content-Type headers detected. "
2318 "Removing and ignoring: %s",
2326 * Signal that the Content-Type has been set.
2328 csp->content_type |= CT_DECLARED;
2330 if (!(csp->content_type & CT_TABOO))
2333 * XXX: The assumption that text/plain is a sign of
2334 * binary data seems to be somewhat unreasonable nowadays
2335 * and should be dropped after 3.0.8 is out.
2337 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2338 || strstr(*header, "xml")
2339 || strstr(*header, "script"))
2341 csp->content_type |= CT_TEXT;
2343 else if (strstr(*header, "image/gif"))
2345 csp->content_type |= CT_GIF;
2350 * Are we messing with the content type?
2352 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2355 * Make sure the user doesn't accidentally
2356 * change the content type of binary documents.
2358 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2362 *header = strdup_or_die("Content-Type: ");
2364 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2365 if (JB_ERR_OK != err)
2367 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2368 return JB_ERR_MEMORY;
2370 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2374 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2375 "It doesn't look like a content type that should be filtered. "
2376 "Enable force-text-mode if you know what you're doing.", *header);
2384 /*********************************************************************
2386 * Function : server_transfer_coding
2388 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2389 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2390 * - Remove header if body was chunked but has been
2391 * de-chunked for filtering.
2394 * 1 : csp = Current client state (buffers, headers, etc...)
2395 * 2 : header = On input, pointer to header to modify.
2396 * On output, pointer to the modified header, or NULL
2397 * to remove the header. This function frees the
2398 * original string if necessary.
2400 * Returns : JB_ERR_OK on success, or
2401 * JB_ERR_MEMORY on out-of-memory error.
2403 *********************************************************************/
2404 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2407 * Turn off pcrs and gif filtering if body compressed
2409 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2413 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2415 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2416 csp->http->cmd, *header);
2417 #endif /* def FEATURE_ZLIB */
2418 csp->content_type = CT_TABOO;
2422 * Raise flag if body chunked
2424 if (strstr(*header, "chunked"))
2426 csp->flags |= CSP_FLAG_CHUNKED;
2429 * If the body was modified, it has been de-chunked first
2430 * and the header must be removed.
2432 * FIXME: If there is more than one transfer encoding,
2433 * only the "chunked" part should be removed here.
2435 if (csp->flags & CSP_FLAG_MODIFIED)
2437 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2446 /*********************************************************************
2448 * Function : server_content_encoding
2450 * Description : Used to check if the content is compressed, and if
2451 * FEATURE_ZLIB is disabled, filtering is disabled as
2454 * If FEATURE_ZLIB is enabled and the compression type
2455 * supported, the content is marked for decompression.
2457 * XXX: Doesn't properly deal with multiple or with
2458 * unsupported but unknown encodings.
2459 * Is case-sensitive but shouldn't be.
2462 * 1 : csp = Current client state (buffers, headers, etc...)
2463 * 2 : header = On input, pointer to header to modify.
2464 * On output, pointer to the modified header, or NULL
2465 * to remove the header. This function frees the
2466 * original string if necessary.
2468 * Returns : JB_ERR_OK on success, or
2469 * JB_ERR_MEMORY on out-of-memory error.
2471 *********************************************************************/
2472 static jb_err server_content_encoding(struct client_state *csp, char **header)
2475 if (strstr(*header, "sdch"))
2478 * Shared Dictionary Compression over HTTP isn't supported,
2479 * filtering it anyway is pretty much guaranteed to mess up
2482 csp->content_type |= CT_TABOO;
2485 * Log a warning if the user expects the content to be filtered.
2487 if (content_filters_enabled(csp->action))
2489 log_error(LOG_LEVEL_INFO,
2490 "SDCH-compressed content detected, content filtering disabled. "
2491 "Consider suppressing SDCH offers made by the client.");
2494 else if (strstr(*header, "gzip"))
2496 /* Mark for gzip decompression */
2497 csp->content_type |= CT_GZIP;
2499 else if (strstr(*header, "deflate"))
2501 /* Mark for zlib decompression */
2502 csp->content_type |= CT_DEFLATE;
2504 else if (strstr(*header, "br"))
2506 #ifdef FEATURE_BROTLI
2507 /* Mark for Brotli decompression */
2508 csp->content_type |= CT_BROTLI;
2510 csp->content_type |= CT_TABOO;
2513 else if (strstr(*header, "compress"))
2516 * We can't decompress this; therefore we can't filter
2519 csp->content_type |= CT_TABOO;
2521 #else /* !defined(FEATURE_ZLIB) */
2523 * XXX: Using a black list here isn't the right approach.
2525 * In case of SDCH, building with zlib support isn't
2528 if (strstr(*header, "gzip") ||
2529 strstr(*header, "compress") ||
2530 strstr(*header, "deflate") ||
2531 strstr(*header, "sdch"))
2534 * Body is compressed, turn off pcrs and gif filtering.
2536 csp->content_type |= CT_TABOO;
2539 * Log a warning if the user expects the content to be filtered.
2541 if (content_filters_enabled(csp->action))
2543 log_error(LOG_LEVEL_INFO,
2544 "Compressed content detected, content filtering disabled. "
2545 "Consider recompiling Privoxy with zlib support or "
2546 "enable the prevent-compression action.");
2549 #endif /* defined(FEATURE_ZLIB) */
2557 /*********************************************************************
2559 * Function : server_adjust_content_encoding
2561 * Description : Remove the Content-Encoding header if the
2562 * decompression was successful and the content
2563 * has been modified.
2566 * 1 : csp = Current client state (buffers, headers, etc...)
2567 * 2 : header = On input, pointer to header to modify.
2568 * On output, pointer to the modified header, or NULL
2569 * to remove the header. This function frees the
2570 * original string if necessary.
2572 * Returns : JB_ERR_OK on success, or
2573 * JB_ERR_MEMORY on out-of-memory error.
2575 *********************************************************************/
2576 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2578 if ((csp->flags & CSP_FLAG_MODIFIED)
2579 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2580 #ifdef FEATURE_BROTLI
2581 || (csp->content_type & CT_BROTLI)
2587 * We successfully decompressed the content,
2588 * and have to clean the header now, so the
2589 * client no longer expects compressed data.
2591 * XXX: There is a difference between cleaning
2592 * and removing it completely.
2594 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2601 #endif /* defined(FEATURE_ZLIB) */
2604 /*********************************************************************
2606 * Function : server_adjust_content_length
2608 * Description : Adjust Content-Length header if we modified
2612 * 1 : csp = Current client state (buffers, headers, etc...)
2613 * 2 : header = On input, pointer to header to modify.
2614 * On output, pointer to the modified header, or NULL
2615 * to remove the header. This function frees the
2616 * original string if necessary.
2618 * Returns : JB_ERR_OK on success, or
2619 * JB_ERR_MEMORY on out-of-memory error.
2621 *********************************************************************/
2622 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2624 /* Regenerate header if the content was modified. */
2625 if (csp->flags & CSP_FLAG_MODIFIED)
2627 const size_t header_length = 50;
2629 *header = malloc(header_length);
2630 if (*header == NULL)
2632 return JB_ERR_MEMORY;
2634 create_content_length_header(csp->content_length, *header, header_length);
2635 log_error(LOG_LEVEL_HEADER,
2636 "Adjusted Content-Length to %llu", csp->content_length);
2643 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2644 /*********************************************************************
2646 * Function : server_save_content_length
2648 * Description : Save the Content-Length sent by the server.
2651 * 1 : csp = Current client state (buffers, headers, etc...)
2652 * 2 : header = On input, pointer to header to modify.
2653 * On output, pointer to the modified header, or NULL
2654 * to remove the header. This function frees the
2655 * original string if necessary.
2657 * Returns : JB_ERR_OK on success, or
2658 * JB_ERR_MEMORY on out-of-memory error.
2660 *********************************************************************/
2661 static jb_err server_save_content_length(struct client_state *csp, char **header)
2663 unsigned long long content_length = 0;
2664 const char *header_value;
2666 assert(*(*header+14) == ':');
2668 header_value = *header + 15;
2669 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2671 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2676 csp->expected_content_length = content_length;
2677 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2678 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2683 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2686 /*********************************************************************
2688 * Function : server_content_md5
2690 * Description : Crumble any Content-MD5 headers if the document was
2691 * modified. FIXME: Should we re-compute instead?
2694 * 1 : csp = Current client state (buffers, headers, etc...)
2695 * 2 : header = On input, pointer to header to modify.
2696 * On output, pointer to the modified header, or NULL
2697 * to remove the header. This function frees the
2698 * original string if necessary.
2700 * Returns : JB_ERR_OK on success, or
2701 * JB_ERR_MEMORY on out-of-memory error.
2703 *********************************************************************/
2704 static jb_err server_content_md5(struct client_state *csp, char **header)
2706 if (csp->flags & CSP_FLAG_MODIFIED)
2708 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2716 /*********************************************************************
2718 * Function : server_content_disposition
2720 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2721 * Called from `sed'.
2724 * 1 : csp = Current client state (buffers, headers, etc...)
2725 * 2 : header = On input, pointer to header to modify.
2726 * On output, pointer to the modified header, or NULL
2727 * to remove the header. This function frees the
2728 * original string if necessary.
2730 * Returns : JB_ERR_OK on success, or
2731 * JB_ERR_MEMORY on out-of-memory error.
2733 *********************************************************************/
2734 static jb_err server_content_disposition(struct client_state *csp, char **header)
2739 * Are we messing with the Content-Disposition header?
2741 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2747 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2749 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2752 * Blocking content-disposition header
2754 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2761 * Replacing Content-Disposition header
2764 *header = strdup("Content-Disposition: ");
2765 string_append(header, newval);
2767 if (*header != NULL)
2769 log_error(LOG_LEVEL_HEADER,
2770 "Content-Disposition header crunched and replaced with: %s", *header);
2773 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2777 /*********************************************************************
2779 * Function : server_last_modified
2781 * Description : Changes Last-Modified header to the actual date
2782 * to help hide-if-modified-since.
2783 * Called from `sed'.
2786 * 1 : csp = Current client state (buffers, headers, etc...)
2787 * 2 : header = On input, pointer to header to modify.
2788 * On output, pointer to the modified header, or NULL
2789 * to remove the header. This function frees the
2790 * original string if necessary.
2792 * Returns : JB_ERR_OK on success, or
2793 * JB_ERR_MEMORY on out-of-memory error.
2795 *********************************************************************/
2796 static jb_err server_last_modified(struct client_state *csp, char **header)
2799 time_t last_modified;
2803 * Are we messing with the Last-Modified header?
2805 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2811 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2813 if (0 == strcmpic(newval, "block"))
2816 * Blocking Last-Modified header. Useless but why not.
2818 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2822 else if (0 == strcmpic(newval, "reset-to-request-time"))
2825 * Setting Last-Modified Header to now.
2828 get_http_time(0, buf, sizeof(buf));
2830 *header = strdup("Last-Modified: ");
2831 string_append(header, buf);
2833 if (*header == NULL)
2835 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2839 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2842 else if (0 == strcmpic(newval, "randomize"))
2844 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2846 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2848 log_error(LOG_LEVEL_HEADER,
2849 "Couldn't parse time in %s (crunching!)", *header);
2855 struct tm *timeptr = NULL;
2860 rtime = (long int)difftime(now, last_modified);
2863 long int days, hours, minutes, seconds;
2864 const int negative_delta = (rtime < 0);
2869 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2871 rtime = pick_from_range(rtime);
2876 last_modified += rtime;
2877 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2878 if ((NULL == timeptr) || !strftime(newheader,
2879 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2881 log_error(LOG_LEVEL_ERROR,
2882 "Randomizing '%s' failed. Crunching the header without replacement.",
2888 *header = strdup("Last-Modified: ");
2889 string_append(header, newheader);
2891 if (*header == NULL)
2893 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2894 return JB_ERR_MEMORY;
2897 days = rtime / (3600 * 24);
2898 hours = rtime / 3600 % 24;
2899 minutes = rtime / 60 % 60;
2900 seconds = rtime % 60;
2902 log_error(LOG_LEVEL_HEADER,
2903 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2904 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2905 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2909 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2918 /*********************************************************************
2920 * Function : client_accept_encoding
2922 * Description : Rewrite the client's Accept-Encoding header so that
2923 * if doesn't allow compression, if the action applies.
2924 * Note: For HTTP/1.0 the absence of the header is enough.
2927 * 1 : csp = Current client state (buffers, headers, etc...)
2928 * 2 : header = On input, pointer to header to modify.
2929 * On output, pointer to the modified header, or NULL
2930 * to remove the header. This function frees the
2931 * original string if necessary.
2933 * Returns : JB_ERR_OK on success, or
2934 * JB_ERR_MEMORY on out-of-memory error.
2936 *********************************************************************/
2937 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2939 #ifdef FEATURE_COMPRESSION
2940 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2941 && strstr(*header, "deflate"))
2943 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2946 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2948 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2956 /*********************************************************************
2958 * Function : client_te
2960 * Description : Rewrite the client's TE header so that
2961 * if doesn't allow compression, if the action applies.
2964 * 1 : csp = Current client state (buffers, headers, etc...)
2965 * 2 : header = On input, pointer to header to modify.
2966 * On output, pointer to the modified header, or NULL
2967 * to remove the header. This function frees the
2968 * original string if necessary.
2970 * Returns : JB_ERR_OK on success, or
2971 * JB_ERR_MEMORY on out-of-memory error.
2973 *********************************************************************/
2974 static jb_err client_te(struct client_state *csp, char **header)
2976 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2979 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2986 /*********************************************************************
2988 * Function : client_referrer
2990 * Description : Handle the "referer" config setting properly.
2991 * Called from `sed'.
2994 * 1 : csp = Current client state (buffers, headers, etc...)
2995 * 2 : header = On input, pointer to header to modify.
2996 * On output, pointer to the modified header, or NULL
2997 * to remove the header. This function frees the
2998 * original string if necessary.
3000 * Returns : JB_ERR_OK on success, or
3001 * JB_ERR_MEMORY on out-of-memory error.
3003 *********************************************************************/
3004 static jb_err client_referrer(struct client_state *csp, char **header)
3006 const char *parameter;
3007 /* booleans for parameters we have to check multiple times */
3008 int parameter_conditional_block;
3009 int parameter_conditional_forge;
3011 #ifdef FEATURE_FORCE_LOAD
3013 * Since the referrer can include the prefix even
3014 * if the request itself is non-forced, we must
3015 * clean it unconditionally.
3017 * XXX: strclean is too broad
3019 strclean(*header, FORCE_PREFIX);
3020 #endif /* def FEATURE_FORCE_LOAD */
3022 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3024 /* Nothing left to do */
3028 parameter = csp->action->string[ACTION_STRING_REFERER];
3029 assert(parameter != NULL);
3030 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3031 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3033 if (!parameter_conditional_block && !parameter_conditional_forge)
3036 * As conditional-block and conditional-forge are the only
3037 * parameters that rely on the original referrer, we can
3038 * remove it now for all the others.
3043 if (0 == strcmpic(parameter, "block"))
3045 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3048 else if (parameter_conditional_block || parameter_conditional_forge)
3050 return handle_conditional_hide_referrer_parameter(header,
3051 csp->http->hostport, parameter_conditional_block);
3053 else if (0 == strcmpic(parameter, "forge"))
3055 return create_forged_referrer(header, csp->http->hostport);
3059 /* interpret parameter as user-supplied referer to fake */
3060 return create_fake_referrer(header, parameter);
3065 /*********************************************************************
3067 * Function : client_accept_language
3069 * Description : Handle the "Accept-Language" config setting properly.
3070 * Called from `sed'.
3073 * 1 : csp = Current client state (buffers, headers, etc...)
3074 * 2 : header = On input, pointer to header to modify.
3075 * On output, pointer to the modified header, or NULL
3076 * to remove the header. This function frees the
3077 * original string if necessary.
3079 * Returns : JB_ERR_OK on success, or
3080 * JB_ERR_MEMORY on out-of-memory error.
3082 *********************************************************************/
3083 static jb_err client_accept_language(struct client_state *csp, char **header)
3088 * Are we messing with the Accept-Language?
3090 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3092 /*I don't think so*/
3096 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3098 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3101 * Blocking Accept-Language header
3103 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3110 * Replacing Accept-Language header
3113 *header = strdup("Accept-Language: ");
3114 string_append(header, newval);
3116 if (*header == NULL)
3118 log_error(LOG_LEVEL_ERROR,
3119 "Insufficient memory. Accept-Language header crunched without replacement.");
3123 log_error(LOG_LEVEL_HEADER,
3124 "Accept-Language header crunched and replaced with: %s", *header);
3127 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3131 /*********************************************************************
3133 * Function : crunch_client_header
3135 * Description : Crunch client header if it matches a string supplied by the
3136 * user. Called from `sed'.
3139 * 1 : csp = Current client state (buffers, headers, etc...)
3140 * 2 : header = On input, pointer to header to modify.
3141 * On output, pointer to the modified header, or NULL
3142 * to remove the header. This function frees the
3143 * original string if necessary.
3145 * Returns : JB_ERR_OK on success and always succeeds
3147 *********************************************************************/
3148 static jb_err crunch_client_header(struct client_state *csp, char **header)
3150 const char *crunch_pattern;
3152 /* Do we feel like crunching? */
3153 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3155 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3157 /* Is the current header the lucky one? */
3158 if (strstr(*header, crunch_pattern))
3160 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3168 /*********************************************************************
3170 * Function : client_uagent
3172 * Description : Handle the "user-agent" config setting properly
3173 * and remember its original value to enable browser
3174 * bug workarounds. Called from `sed'.
3177 * 1 : csp = Current client state (buffers, headers, etc...)
3178 * 2 : header = On input, pointer to header to modify.
3179 * On output, pointer to the modified header, or NULL
3180 * to remove the header. This function frees the
3181 * original string if necessary.
3183 * Returns : JB_ERR_OK on success, or
3184 * JB_ERR_MEMORY on out-of-memory error.
3186 *********************************************************************/
3187 static jb_err client_uagent(struct client_state *csp, char **header)
3191 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3196 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3203 *header = strdup("User-Agent: ");
3204 string_append(header, newval);
3206 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3208 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3212 /*********************************************************************
3214 * Function : client_ua
3216 * Description : Handle "ua-" headers properly. Called from `sed'.
3219 * 1 : csp = Current client state (buffers, headers, etc...)
3220 * 2 : header = On input, pointer to header to modify.
3221 * On output, pointer to the modified header, or NULL
3222 * to remove the header. This function frees the
3223 * original string if necessary.
3225 * Returns : JB_ERR_OK on success, or
3226 * JB_ERR_MEMORY on out-of-memory error.
3228 *********************************************************************/
3229 static jb_err client_ua(struct client_state *csp, char **header)
3231 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3233 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3241 /*********************************************************************
3243 * Function : client_from
3245 * Description : Handle the "from" config setting properly.
3246 * Called from `sed'.
3249 * 1 : csp = Current client state (buffers, headers, etc...)
3250 * 2 : header = On input, pointer to header to modify.
3251 * On output, pointer to the modified header, or NULL
3252 * to remove the header. This function frees the
3253 * original string if necessary.
3255 * Returns : JB_ERR_OK on success, or
3256 * JB_ERR_MEMORY on out-of-memory error.
3258 *********************************************************************/
3259 static jb_err client_from(struct client_state *csp, char **header)
3263 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3270 newval = csp->action->string[ACTION_STRING_FROM];
3273 * Are we blocking the e-mail address?
3275 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3277 log_error(LOG_LEVEL_HEADER, "crunched From!");
3281 log_error(LOG_LEVEL_HEADER, " modified");
3283 *header = strdup("From: ");
3284 string_append(header, newval);
3286 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3290 /*********************************************************************
3292 * Function : client_send_cookie
3294 * Description : Crunches the "cookie" header if necessary.
3295 * Called from `sed'.
3297 * XXX: Stupid name, doesn't send squat.
3300 * 1 : csp = Current client state (buffers, headers, etc...)
3301 * 2 : header = On input, pointer to header to modify.
3302 * On output, pointer to the modified header, or NULL
3303 * to remove the header. This function frees the
3304 * original string if necessary.
3306 * Returns : JB_ERR_OK on success, or
3307 * JB_ERR_MEMORY on out-of-memory error.
3309 *********************************************************************/
3310 static jb_err client_send_cookie(struct client_state *csp, char **header)
3312 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3314 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3322 /*********************************************************************
3324 * Function : client_x_forwarded
3326 * Description : Handle the "x-forwarded-for" config setting properly,
3327 * also used in the add_client_headers list. Called from `sed'.
3330 * 1 : csp = Current client state (buffers, headers, etc...)
3331 * 2 : header = On input, pointer to header to modify.
3332 * On output, pointer to the modified header, or NULL
3333 * to remove the header. This function frees the
3334 * original string if necessary.
3336 * Returns : JB_ERR_OK on success, or
3337 * JB_ERR_MEMORY on out-of-memory error.
3339 *********************************************************************/
3340 jb_err client_x_forwarded(struct client_state *csp, char **header)
3342 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3344 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3346 if (0 == strcmpic(parameter, "block"))
3349 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3351 else if (0 == strcmpic(parameter, "add"))
3353 string_append(header, ", ");
3354 string_append(header, csp->ip_addr_str);
3356 if (*header == NULL)
3358 return JB_ERR_MEMORY;
3360 log_error(LOG_LEVEL_HEADER,
3361 "Appended client IP address to %s", *header);
3362 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3366 log_error(LOG_LEVEL_FATAL,
3367 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3375 /*********************************************************************
3377 * Function : client_max_forwards
3379 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3380 * from the value of the Max-Forwards header field.
3383 * 1 : csp = Current client state (buffers, headers, etc...)
3384 * 2 : header = On input, pointer to header to modify.
3385 * On output, pointer to the modified header, or NULL
3386 * to remove the header. This function frees the
3387 * original string if necessary.
3389 * Returns : JB_ERR_OK on success, or
3390 * JB_ERR_MEMORY on out-of-memory error.
3392 *********************************************************************/
3393 static jb_err client_max_forwards(struct client_state *csp, char **header)
3397 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3398 (0 == strcmpic(csp->http->gpc, "options")))
3400 assert(*(*header+12) == ':');
3401 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3403 if (max_forwards > 0)
3405 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3406 log_error(LOG_LEVEL_HEADER,
3407 "Max-Forwards value for %s request reduced to %d.",
3408 csp->http->gpc, max_forwards);
3410 else if (max_forwards < 0)
3412 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3418 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3427 /*********************************************************************
3429 * Function : client_host
3431 * Description : If the request URI did not contain host and
3432 * port information, parse and evaluate the Host
3436 * 1 : csp = Current client state (buffers, headers, etc...)
3437 * 2 : header = On input, pointer to header to modify.
3438 * On output, pointer to the modified header, or NULL
3439 * to remove the header. This function frees the
3440 * original string if necessary.
3442 * Returns : JB_ERR_OK on success, or
3443 * JB_ERR_MEMORY on out-of-memory error.
3445 *********************************************************************/
3446 static jb_err client_host(struct client_state *csp, char **header)
3450 if (strlen(*header) < 7)
3452 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3457 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3458 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3461 p = strdup_or_die((*header)+6);
3463 q = strdup_or_die(p);
3465 freez(csp->http->hostport);
3466 csp->http->hostport = p;
3467 freez(csp->http->host);
3468 csp->http->host = q;
3469 q = strchr(csp->http->host, ':');
3472 /* Terminate hostname and evaluate port string */
3474 csp->http->port = atoi(q);
3478 csp->http->port = csp->http->ssl ? 443 : 80;
3481 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3482 csp->http->hostport, csp->http->host, csp->http->port);
3485 /* Signal client_host_adder() to return right away */
3486 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3492 /*********************************************************************
3494 * Function : client_if_modified_since
3496 * Description : Remove or modify the If-Modified-Since header.
3499 * 1 : csp = Current client state (buffers, headers, etc...)
3500 * 2 : header = On input, pointer to header to modify.
3501 * On output, pointer to the modified header, or NULL
3502 * to remove the header. This function frees the
3503 * original string if necessary.
3505 * Returns : JB_ERR_OK on success, or
3506 * JB_ERR_MEMORY on out-of-memory error.
3508 *********************************************************************/
3509 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3513 struct tm *timeptr = NULL;
3518 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3521 * The client got an error message because of a temporary problem,
3522 * the problem is gone and the client now tries to revalidate our
3523 * error message on the real server. The revalidation would always
3524 * end with the transmission of the whole document and there is
3525 * no need to expose the bogus If-Modified-Since header.
3527 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3530 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3532 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3534 if ((0 == strcmpic(newval, "block")))
3536 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3539 else /* add random value */
3541 if (JB_ERR_OK != parse_time_header(*header, &tm))
3543 log_error(LOG_LEVEL_HEADER,
3544 "Couldn't parse time in %s (crunching!)", *header);
3549 long int hours, minutes, seconds;
3550 long int rtime = strtol(newval, &endptr, 0);
3551 const int negative_range = (rtime < 0);
3555 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3556 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3562 rtime = pick_from_range(rtime);
3566 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3569 tm += rtime * (negative_range ? -1 : 1);
3570 timeptr = privoxy_gmtime_r(&tm, &gmt);
3571 if ((NULL == timeptr) || !strftime(newheader,
3572 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3574 log_error(LOG_LEVEL_ERROR,
3575 "Randomizing '%s' failed. Crunching the header without replacement.",
3581 *header = strdup("If-Modified-Since: ");
3582 string_append(header, newheader);
3584 if (*header == NULL)
3586 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3587 return JB_ERR_MEMORY;
3590 hours = rtime / 3600;
3591 minutes = rtime / 60 % 60;
3592 seconds = rtime % 60;
3594 log_error(LOG_LEVEL_HEADER,
3595 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3596 *header, (negative_range) ? "subtracted" : "added", hours,
3597 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3598 seconds, (seconds == 1) ? ")" : "s)");
3607 /*********************************************************************
3609 * Function : client_if_none_match
3611 * Description : Remove the If-None-Match header.
3614 * 1 : csp = Current client state (buffers, headers, etc...)
3615 * 2 : header = On input, pointer to header to modify.
3616 * On output, pointer to the modified header, or NULL
3617 * to remove the header. This function frees the
3618 * original string if necessary.
3620 * Returns : JB_ERR_OK on success, or
3621 * JB_ERR_MEMORY on out-of-memory error.
3623 *********************************************************************/
3624 static jb_err client_if_none_match(struct client_state *csp, char **header)
3626 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3628 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3636 /*********************************************************************
3638 * Function : client_x_filter
3640 * Description : Disables filtering if the client set "X-Filter: No".
3641 * Called from `sed'.
3644 * 1 : csp = Current client state (buffers, headers, etc...)
3645 * 2 : header = On input, pointer to header to modify.
3646 * On output, pointer to the modified header, or NULL
3647 * to remove the header. This function frees the
3648 * original string if necessary.
3650 * Returns : JB_ERR_OK on success
3652 *********************************************************************/
3653 jb_err client_x_filter(struct client_state *csp, char **header)
3655 if (0 == strcmpic(*header, "X-Filter: No"))
3657 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3659 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3663 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3665 log_error(LOG_LEVEL_HEADER,
3666 "force-text-mode overruled the client's request to fetch without filtering!");
3670 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3671 csp->flags |= CSP_FLAG_NO_FILTERING;
3672 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3674 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3682 /*********************************************************************
3684 * Function : client_range
3686 * Description : Removes Range, Request-Range and If-Range headers if
3687 * content filtering is enabled and the range doesn't
3690 * If the client's version of the document has been
3691 * altered by Privoxy, the server could interpret the
3692 * range differently than the client intended in which
3693 * case the user could end up with corrupted content.
3695 * If the range starts at byte 0 this isn't an issue
3696 * so the header can pass. Partial requests like this
3697 * are used to render preview images for videos without
3698 * downloading the whole video.
3700 * While HTTP doesn't require that range requests are
3701 * honoured and the client could simply abort the download
3702 * after receiving a sufficient amount of data, various
3703 * clients don't handle complete responses to range
3704 * requests gracefully and emit misleading error messages
3708 * 1 : csp = Current client state (buffers, headers, etc...)
3709 * 2 : header = On input, pointer to header to modify.
3710 * On output, pointer to the modified header, or NULL
3711 * to remove the header. This function frees the
3712 * original string if necessary.
3714 * Returns : JB_ERR_OK
3716 *********************************************************************/
3717 static jb_err client_range(struct client_state *csp, char **header)
3719 if (content_filters_enabled(csp->action)
3720 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3722 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3723 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3730 /* the following functions add headers directly to the header list */
3732 /*********************************************************************
3734 * Function : client_host_adder
3736 * Description : Adds the Host: header field if it is missing.
3737 * Called from `sed'.
3740 * 1 : csp = Current client state (buffers, headers, etc...)
3742 * Returns : JB_ERR_OK on success, or
3743 * JB_ERR_MEMORY on out-of-memory error.
3745 *********************************************************************/
3746 static jb_err client_host_adder(struct client_state *csp)
3751 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3753 /* Header already set by the client, nothing to do. */
3757 if (!csp->http->hostport || !*(csp->http->hostport))
3759 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3760 return JB_ERR_PARSE;
3764 * remove 'user:pass@' from 'proto://user:pass@host'
3766 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3772 p = csp->http->hostport;
3775 /* XXX: Just add it, we already made sure that it will be unique */
3776 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3777 err = enlist_unique_header(csp->headers, "Host", p);
3783 /*********************************************************************
3785 * Function : client_xtra_adder
3787 * Description : Used in the add_client_headers list. Called from `sed'.
3790 * 1 : csp = Current client state (buffers, headers, etc...)
3792 * Returns : JB_ERR_OK on success, or
3793 * JB_ERR_MEMORY on out-of-memory error.
3795 *********************************************************************/
3796 static jb_err client_xtra_adder(struct client_state *csp)
3798 struct list_entry *lst;
3801 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3802 lst ; lst = lst->next)
3804 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3805 err = enlist(csp->headers, lst->str);
3817 /*********************************************************************
3819 * Function : client_x_forwarded_for_adder
3821 * Description : Used in the add_client_headers list. Called from `sed'.
3824 * 1 : csp = Current client state (buffers, headers, etc...)
3826 * Returns : JB_ERR_OK on success, or
3827 * JB_ERR_MEMORY on out-of-memory error.
3829 *********************************************************************/
3830 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3832 char *header = NULL;
3835 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3836 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3837 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3840 * If we aren't adding X-Forwarded-For headers,
3841 * or we already appended an existing X-Forwarded-For
3842 * header, there's nothing left to do here.
3847 header = strdup("X-Forwarded-For: ");
3848 string_append(&header, csp->ip_addr_str);
3852 return JB_ERR_MEMORY;
3855 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3856 err = enlist(csp->headers, header);
3863 /*********************************************************************
3865 * Function : server_connection_adder
3867 * Description : Adds an appropriate "Connection:" header to csp->headers
3868 * unless the header was already present. Called from `sed'.
3871 * 1 : csp = Current client state (buffers, headers, etc...)
3873 * Returns : JB_ERR_OK on success, or
3874 * JB_ERR_MEMORY on out-of-memory error.
3876 *********************************************************************/
3877 static jb_err server_connection_adder(struct client_state *csp)
3879 const unsigned int flags = csp->flags;
3880 const char *response_status_line = csp->headers->first->str;
3881 static const char connection_close[] = "Connection: close";
3883 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3884 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3890 * XXX: if we downgraded the response, this check will fail.
3892 if ((csp->config->feature_flags &
3893 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3894 && (NULL != response_status_line)
3895 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3896 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3897 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3901 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3902 "without Connection header implies keep-alive.");
3903 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3907 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3909 return enlist(csp->headers, connection_close);
3913 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3914 /*********************************************************************
3916 * Function : server_proxy_connection_adder
3918 * Description : Adds a "Proxy-Connection: keep-alive" header to
3919 * csp->headers when appropriate.
3922 * 1 : csp = Current client state (buffers, headers, etc...)
3924 * Returns : JB_ERR_OK on success, or
3925 * JB_ERR_MEMORY on out-of-memory error.
3927 *********************************************************************/
3928 static jb_err server_proxy_connection_adder(struct client_state *csp)
3930 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3931 jb_err err = JB_ERR_OK;
3933 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3934 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3935 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3936 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3937 || (csp->flags & CSP_FLAG_CHUNKED)))
3939 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3940 err = enlist(csp->headers, proxy_connection_header);
3945 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3948 /*********************************************************************
3950 * Function : client_connection_header_adder
3952 * Description : Adds a proper "Connection:" header to csp->headers
3953 * unless the header was already present or it's a
3954 * CONNECT request. Called from `sed'.
3957 * 1 : csp = Current client state (buffers, headers, etc...)
3959 * Returns : JB_ERR_OK on success, or
3960 * JB_ERR_MEMORY on out-of-memory error.
3962 *********************************************************************/
3963 static jb_err client_connection_header_adder(struct client_state *csp)
3965 static const char connection_close[] = "Connection: close";
3967 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3968 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3974 * In case of CONNECT requests "Connection: close" is implied,
3975 * but actually setting the header has been reported to cause
3976 * problems with some forwarding proxies that close the
3977 * connection prematurely.
3979 if (csp->http->ssl != 0)
3984 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3985 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3986 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3987 && !strcmpic(csp->http->version, "HTTP/1.1"))
3989 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3992 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3994 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3996 return enlist(csp->headers, connection_close);
4000 /*********************************************************************
4002 * Function : server_http
4004 * Description : - Save the HTTP Status into csp->http->status
4005 * - Set CT_TABOO to prevent filtering if the answer
4006 * is a partial range (HTTP status 206)
4007 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4009 * - Normalize the HTTP-version.
4012 * 1 : csp = Current client state (buffers, headers, etc...)
4013 * 2 : header = On input, pointer to header to modify.
4014 * On output, pointer to the modified header, or NULL
4015 * to remove the header. This function frees the
4016 * original string if necessary.
4018 * Returns : JB_ERR_OK on success, or
4019 * JB_ERR_PARSE on fatal parse errors.
4021 *********************************************************************/
4022 static jb_err server_http(struct client_state *csp, char **header)
4024 char *reason_phrase = NULL;
4025 char *new_response_line;
4028 unsigned int major_version;
4029 unsigned int minor_version;
4031 /* Get the reason phrase which start after the second whitespace */
4032 p = strchr(*header, ' ');
4036 reason_phrase = strchr(p, ' ');
4039 if (reason_phrase != NULL)
4045 log_error(LOG_LEVEL_ERROR,
4046 "Response line lacks reason phrase: %s", *header);
4050 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4051 &minor_version, &(csp->http->status)))
4053 log_error(LOG_LEVEL_ERROR,
4054 "Failed to parse the response line: %s", *header);
4055 return JB_ERR_PARSE;
4058 if (csp->http->status == 206)
4060 csp->content_type = CT_TABOO;
4063 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4066 * According to RFC 7230 2.6 intermediaries MUST send
4067 * their own HTTP-version in forwarded messages.
4069 log_error(LOG_LEVEL_ERROR,
4070 "Unsupported HTTP version. Downgrading to 1.1.");
4075 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4077 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4081 /* Rebuild response line. */
4082 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4083 new_response_line = malloc_or_die(length);
4085 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4086 major_version, minor_version, csp->http->status, reason_phrase);
4088 if (0 != strcmp(*header, new_response_line))
4090 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4091 *header, new_response_line);
4095 *header = new_response_line;
4100 /*********************************************************************
4102 * Function : add_cooky_expiry_date
4104 * Description : Adds a cookie expiry date to a string.
4107 * 1 : cookie = On input, pointer to cookie to modify.
4108 * On output, pointer to the modified header.
4109 * The original string is freed.
4110 * 2 : lifetime = Seconds the cookie should be valid
4114 *********************************************************************/
4115 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4118 struct tm *timeptr = NULL;
4119 time_t expiry_date = time(NULL) + lifetime;
4122 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4123 if (NULL == timeptr)
4125 log_error(LOG_LEVEL_FATAL,
4126 "Failed to get the time in add_cooky_expiry_date()");
4128 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4129 if (JB_ERR_OK != string_append(cookie, tmp))
4131 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4136 /*********************************************************************
4138 * Function : server_set_cookie
4140 * Description : Handle the server "cookie" header properly.
4141 * Crunch, accept or rewrite it to a session cookie.
4142 * Called from `sed'.
4145 * 1 : csp = Current client state (buffers, headers, etc...)
4146 * 2 : header = On input, pointer to header to modify.
4147 * On output, pointer to the modified header, or NULL
4148 * to remove the header. This function frees the
4149 * original string if necessary.
4151 * Returns : JB_ERR_OK on success, or
4152 * JB_ERR_MEMORY on out-of-memory error.
4154 *********************************************************************/
4155 static jb_err server_set_cookie(struct client_state *csp, char **header)
4157 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4159 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4162 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4163 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4167 long cookie_lifetime = 0;
4170 NO_EXPIRY_DATE_SPECIFIED,
4171 EXPIRY_DATE_ACCEPTABLE,
4172 EXPIRY_DATE_UNACCEPTABLE
4173 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4175 /* A variable to store the tag we're working on */
4178 /* Skip "Set-Cookie:" (11 characters) in header */
4179 cur_tag = *header + 11;
4181 /* skip whitespace between "Set-Cookie:" and value */
4182 while (*cur_tag && privoxy_isspace(*cur_tag))
4189 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4191 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4193 cookie_lifetime = strtol(param, NULL, 0);
4194 if (cookie_lifetime < 0)
4196 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4198 cookie_lifetime *= 60;
4201 /* Loop through each tag in the cookie */
4205 char *next_tag = strchr(cur_tag, ';');
4206 if (next_tag != NULL)
4208 /* Skip the ';' character itself */
4211 /* skip whitespace ";" and start of tag */
4212 while (*next_tag && privoxy_isspace(*next_tag))
4219 /* "Next tag" is the end of the string */
4220 next_tag = cur_tag + strlen(cur_tag);
4224 * Check the expiration date to see
4225 * if the cookie is still valid, if yes,
4226 * rewrite it to a session cookie.
4228 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4230 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4232 if ((expiration_date[0] == '"')
4233 && (expiration_date[1] != '\0'))
4236 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4237 * that the expiration date isn't supposed to be quoted,
4238 * but some servers do it anyway.
4243 /* Did we detect the date properly? */
4244 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4247 * Nope, treat it as if it was still valid.
4249 * XXX: Should we remove the whole cookie instead?
4251 log_error(LOG_LEVEL_ERROR,
4252 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4253 string_move(cur_tag, next_tag);
4254 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4259 * Yes. Check if the cookie is still valid.
4261 * If the cookie is already expired it's probably
4262 * a delete cookie and even if it isn't, the browser
4263 * will discard it anyway.
4267 * XXX: timegm() isn't available on some AmigaOS
4268 * versions and our replacement doesn't work.
4270 * Our options are to either:
4272 * - disable session-cookies-only completely if timegm
4275 * - to simply remove all expired tags, like it has
4276 * been done until Privoxy 3.0.6 and to live with
4277 * the consequence that it can cause login/logout
4278 * problems on servers that don't validate their
4279 * input properly, or
4281 * - to replace it with mktime in which
4282 * case there is a slight chance of valid cookies
4283 * passing as already expired.
4285 * This is the way it's currently done and it's not
4286 * as bad as it sounds. If the missing GMT offset is
4287 * enough to change the result of the expiration check
4288 * the cookie will be only valid for a few hours
4289 * anyway, which in many cases will be shorter
4290 * than a browser session.
4292 if (cookie_time < now)
4294 log_error(LOG_LEVEL_HEADER,
4295 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4296 /* Just in case some clown sets more then one expiration date */
4298 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4300 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4302 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4303 "Its lifetime is below the limit.", *header);
4304 /* Just in case some clown sets more then one expiration date */
4306 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4311 * Still valid, delete expiration date by copying
4312 * the rest of the string over it.
4314 string_move(cur_tag, next_tag);
4316 /* That changed the header, need to issue a log message */
4317 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4320 * Note that the next tag has now been moved to *cur_tag,
4321 * so we do not need to update the cur_tag pointer.
4329 /* Move on to next cookie tag */
4334 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4336 assert(NULL != *header);
4337 if (cookie_lifetime != 0)
4339 add_cookie_expiry_date(header, cookie_lifetime);
4340 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4342 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4344 log_error(LOG_LEVEL_HEADER,
4345 "Cookie rewritten to a temporary one: %s", *header);
4354 #ifdef FEATURE_FORCE_LOAD
4355 /*********************************************************************
4357 * Function : strclean
4359 * Description : In-Situ-Eliminate all occurrences of substring in
4363 * 1 : string = string to clean
4364 * 2 : substring = substring to eliminate
4366 * Returns : Number of eliminations
4368 *********************************************************************/
4369 int strclean(char *string, const char *substring)
4375 len = strlen(substring);
4377 while((pos = strstr(string, substring)) != NULL)
4384 while (*p++ != '\0');
4391 #endif /* def FEATURE_FORCE_LOAD */
4394 /*********************************************************************
4396 * Function : parse_header_time
4398 * Description : Parses time formats used in HTTP header strings
4399 * to get the numerical respresentation.
4402 * 1 : header_time = HTTP header time as string.
4403 * 2 : result = storage for header_time in seconds
4405 * Returns : JB_ERR_OK if the time format was recognized, or
4406 * JB_ERR_PARSE otherwise.
4408 *********************************************************************/
4409 static jb_err parse_header_time(const char *header_time, time_t *result)
4413 * Checking for two-digit years first in an
4414 * attempt to work around GNU libc's strptime()
4415 * reporting negative year values when using %Y.
4417 static const char time_formats[][22] = {
4418 /* Tue, 02-Jun-37 20:00:00 */
4419 "%a, %d-%b-%y %H:%M:%S",
4420 /* Tue, 02 Jun 2037 20:00:00 */
4421 "%a, %d %b %Y %H:%M:%S",
4422 /* Tue, 02-Jun-2037 20:00:00 */
4423 "%a, %d-%b-%Y %H:%M:%S",
4424 /* Tuesday, 02-Jun-2037 20:00:00 */
4425 "%A, %d-%b-%Y %H:%M:%S",
4426 /* Tuesday Jun 02 20:00:00 2037 */
4427 "%A %b %d %H:%M:%S %Y"
4431 for (i = 0; i < SZ(time_formats); i++)
4434 * Zero out gmt to prevent time zone offsets.
4435 * Documented to be required for GNU libc.
4437 memset(&gmt, 0, sizeof(gmt));
4439 if (NULL != strptime(header_time, time_formats[i], &gmt))
4441 /* Sanity check for GNU libc. */
4442 if (gmt.tm_year < 0)
4444 log_error(LOG_LEVEL_HEADER,
4445 "Failed to parse '%s' using '%s'. Moving on.",
4446 header_time, time_formats[i]);
4449 *result = timegm(&gmt);
4451 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4453 * Verify that parsing the date recreated from the first
4454 * parse operation gets the previous result. If it doesn't,
4455 * either strptime() or strftime() are malfunctioning.
4457 * We could string-compare the recreated date with the original
4458 * header date, but this leads to false positives as strptime()
4459 * may let %a accept all day formats while strftime() will only
4463 char recreated_date[100];
4468 tm = privoxy_gmtime_r(result, &storage);
4469 if (!strftime(recreated_date, sizeof(recreated_date),
4470 time_formats[i], tm))
4472 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4473 header_time, time_formats[i]);
4476 memset(&gmt, 0, sizeof(gmt));
4477 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4479 log_error(LOG_LEVEL_ERROR,
4480 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4481 recreated_date, time_formats[i], header_time);
4484 result2 = timegm(&gmt);
4485 if (*result != result2)
4487 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4488 "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4489 time_formats[i], header_time, recreated_date, *result, result2);
4499 return JB_ERR_PARSE;
4503 /*********************************************************************
4505 * Function : parse_time_header
4507 * Description : Parses the time in an HTTP time header to get
4508 * the numerical respresentation.
4511 * 1 : header = HTTP header with a time value
4512 * 2 : result = storage for header_time in seconds
4514 * Returns : JB_ERR_OK if the time format was recognized, or
4515 * JB_ERR_PARSE otherwise.
4517 *********************************************************************/
4518 static jb_err parse_time_header(const char *header, time_t *result)
4520 const char *header_time;
4522 header_time = strchr(header, ':');
4525 * Currently this can't happen as all callers are called
4526 * through sed() which requires a header name followed by
4529 assert(header_time != NULL);
4532 if (*header_time == ' ')
4537 return parse_header_time(header_time, result);
4542 /*********************************************************************
4544 * Function : get_destination_from_headers
4546 * Description : Parse the "Host:" header to get the request's destination.
4547 * Only needed if the client's request was forcefully
4548 * redirected into Privoxy.
4550 * Code mainly copied from client_host() which is currently
4551 * run too late for this purpose.
4554 * 1 : headers = List of headers (one of them hopefully being
4555 * the "Host:" header)
4556 * 2 : http = storage for the result (host, port and hostport).
4558 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4559 * JB_ERR_PARSE if the host header couldn't be found,
4560 * JB_ERR_OK otherwise.
4562 *********************************************************************/
4563 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4569 host = get_header_value(headers, "Host:");
4573 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4574 return JB_ERR_PARSE;
4577 p = strdup_or_die(host);
4579 q = strdup_or_die(p);
4581 freez(http->hostport);
4585 q = strchr(http->host, ':');
4588 /* Terminate hostname and evaluate port string */
4590 http->port = atoi(q);
4597 /* Rebuild request URL */
4599 http->url = strdup("http://");
4600 string_append(&http->url, http->hostport);
4601 string_append(&http->url, http->path);
4602 if (http->url == NULL)
4604 return JB_ERR_MEMORY;
4607 log_error(LOG_LEVEL_HEADER,
4608 "Destination extracted from \"Host\" header. New request URL: %s",
4612 * Regenerate request line in "proxy format"
4613 * to make rewrites more convenient.
4615 assert(http->cmd != NULL);
4617 http->cmd = strdup_or_die(http->gpc);
4618 string_append(&http->cmd, " ");
4619 string_append(&http->cmd, http->url);
4620 string_append(&http->cmd, " ");
4621 string_append(&http->cmd, http->version);
4622 if (http->cmd == NULL)
4624 return JB_ERR_MEMORY;
4632 #ifdef FEATURE_HTTPS_INSPECTION
4633 /*********************************************************************
4635 * Function : get_destination_from_https_headers
4637 * Description : Parse the previously encrypted "Host:" header to
4638 * get the request's destination.
4641 * 1 : headers = List of headers (one of them hopefully being
4642 * the "Host:" header)
4643 * 2 : http = storage for the result (host, port and hostport).
4645 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4646 * JB_ERR_PARSE if the host header couldn't be found,
4647 * JB_ERR_OK otherwise.
4649 *********************************************************************/
4650 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4656 host = get_header_value(headers, "Host:");
4660 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4661 return JB_ERR_PARSE;
4664 p = strdup_or_die(host);
4666 q = strdup_or_die(p);
4668 freez(http->hostport);
4672 q = strchr(http->host, ':');
4675 /* Terminate hostname and evaluate port string */
4677 http->port = atoi(q);
4684 /* Rebuild request URL */
4686 http->url = strdup_or_die(http->path);
4688 log_error(LOG_LEVEL_HEADER,
4689 "Destination extracted from \"Host\" header. New request URL: %s",
4693 * Regenerate request line in "proxy format"
4694 * to make rewrites more convenient.
4696 assert(http->cmd != NULL);
4698 http->cmd = strdup_or_die(http->gpc);
4699 string_append(&http->cmd, " ");
4700 string_append(&http->cmd, http->url);
4701 string_append(&http->cmd, " ");
4702 string_append(&http->cmd, http->version);
4703 if (http->cmd == NULL)
4705 return JB_ERR_MEMORY;
4711 #endif /* def FEATURE_HTTPS_INSPECTION */
4714 /*********************************************************************
4716 * Function : create_forged_referrer
4718 * Description : Helper for client_referrer to forge a referer as
4719 * 'http://hostname[:port]/' to fool stupid
4720 * checks for in-site links
4723 * 1 : header = Pointer to header pointer
4724 * 2 : hostport = Host and optionally port as string
4726 * Returns : JB_ERR_OK in case of success, or
4727 * JB_ERR_MEMORY in case of memory problems.
4729 *********************************************************************/
4730 static jb_err create_forged_referrer(char **header, const char *hostport)
4732 assert(NULL == *header);
4734 *header = strdup("Referer: http://");
4735 string_append(header, hostport);
4736 string_append(header, "/");
4738 if (NULL == *header)
4740 return JB_ERR_MEMORY;
4743 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4750 /*********************************************************************
4752 * Function : create_fake_referrer
4754 * Description : Helper for client_referrer to create a fake referrer
4755 * based on a string supplied by the user.
4758 * 1 : header = Pointer to header pointer
4759 * 2 : hosthost = Referrer to fake
4761 * Returns : JB_ERR_OK in case of success, or
4762 * JB_ERR_MEMORY in case of memory problems.
4764 *********************************************************************/
4765 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4767 assert(NULL == *header);
4769 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4771 log_error(LOG_LEVEL_HEADER,
4772 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4774 *header = strdup("Referer: ");
4775 string_append(header, fake_referrer);
4777 if (NULL == *header)
4779 return JB_ERR_MEMORY;
4782 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4789 /*********************************************************************
4791 * Function : handle_conditional_hide_referrer_parameter
4793 * Description : Helper for client_referrer to crunch or forge
4794 * the referrer header if the host has changed.
4797 * 1 : header = Pointer to header pointer
4798 * 2 : host = The target host (may include the port)
4799 * 3 : parameter_conditional_block = Boolean to signal
4800 * if we're in conditional-block mode. If not set,
4801 * we're in conditional-forge mode.
4803 * Returns : JB_ERR_OK in case of success, or
4804 * JB_ERR_MEMORY in case of memory problems.
4806 *********************************************************************/
4807 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4808 const char *host, const int parameter_conditional_block)
4810 char *referer = strdup_or_die(*header);
4811 const size_t hostlength = strlen(host);
4812 const char *referer_url = NULL;
4814 /* referer begins with 'Referer: http[s]://' */
4815 if ((hostlength+17) < strlen(referer))
4818 * Shorten referer to make sure the referer is blocked
4819 * if www.example.org/www.example.com-shall-see-the-referer/
4820 * links to www.example.com/
4822 referer[hostlength+17] = '\0';
4824 referer_url = strstr(referer, "http://");
4825 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4827 /* Host has changed, Referer is invalid or a https URL. */
4828 if (parameter_conditional_block)
4830 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4837 return create_forged_referrer(header, host);
4847 /*********************************************************************
4849 * Function : create_content_length_header
4851 * Description : Creates a Content-Length header.
4854 * 1 : content_length = The content length to be used in the header.
4855 * 2 : header = Allocated space to safe the header.
4856 * 3 : buffer_length = The length of the allocated space.
4860 *********************************************************************/
4861 static void create_content_length_header(unsigned long long content_length,
4862 char *header, size_t buffer_length)
4865 #if SIZEOF_LONG_LONG < 8
4866 #error sizeof(unsigned long long) too small
4868 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4870 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4875 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4876 /*********************************************************************
4878 * Function : get_expected_content_length
4880 * Description : Figures out the content length from a list of headers.
4883 * 1 : headers = List of headers
4885 * Returns : Number of bytes to expect
4887 *********************************************************************/
4888 unsigned long long get_expected_content_length(struct list *headers)
4890 const char *content_length_header;
4891 unsigned long long content_length = 0;
4893 content_length_header = get_header_value(headers, "Content-Length:");
4894 if (content_length_header != NULL)
4896 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4898 log_error(LOG_LEVEL_ERROR,
4899 "Failed to get the Content-Length in %s", content_length_header);
4900 /* XXX: The header will be removed later on */
4905 return content_length;