1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2021 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
61 #define GZIP_FLAG_CHECKSUM 0x02
62 #define GZIP_FLAG_EXTRA_FIELDS 0x04
63 #define GZIP_FLAG_FILE_NAME 0x08
64 #define GZIP_FLAG_COMMENT 0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
68 #include <brotli/decode.h>
77 #ifdef FEATURE_PTHREAD
79 /* jcc.h is for mutex semapores only */
80 #endif /* def FEATURE_PTHREAD */
85 #include "jbsockets.h"
90 #ifdef FEATURE_HTTPS_INSPECTION
98 static char *get_header_line(struct iob *iob);
99 static jb_err scan_headers(struct client_state *csp);
100 static jb_err header_tagger(struct client_state *csp, char *header);
101 static jb_err parse_header_time(const char *header_time, time_t *result);
102 static jb_err parse_time_header(const char *header, time_t *result);
104 static jb_err crumble (struct client_state *csp, char **header);
105 static jb_err filter_header (struct client_state *csp, char **header);
106 static jb_err client_connection (struct client_state *csp, char **header);
107 static jb_err client_referrer (struct client_state *csp, char **header);
108 static jb_err client_uagent (struct client_state *csp, char **header);
109 static jb_err client_ua (struct client_state *csp, char **header);
110 static jb_err client_from (struct client_state *csp, char **header);
111 static jb_err client_send_cookie (struct client_state *csp, char **header);
112 static jb_err client_x_forwarded (struct client_state *csp, char **header);
113 static jb_err client_accept_encoding (struct client_state *csp, char **header);
114 static jb_err client_te (struct client_state *csp, char **header);
115 static jb_err client_max_forwards (struct client_state *csp, char **header);
116 static jb_err client_host (struct client_state *csp, char **header);
117 static jb_err client_if_modified_since (struct client_state *csp, char **header);
118 static jb_err client_accept_language (struct client_state *csp, char **header);
119 static jb_err client_if_none_match (struct client_state *csp, char **header);
120 static jb_err crunch_client_header (struct client_state *csp, char **header);
121 static jb_err client_x_filter (struct client_state *csp, char **header);
122 static jb_err client_range (struct client_state *csp, char **header);
123 static jb_err client_expect (struct client_state *csp, char **header);
124 static jb_err server_set_cookie (struct client_state *csp, char **header);
125 static jb_err server_connection (struct client_state *csp, char **header);
126 static jb_err server_content_type (struct client_state *csp, char **header);
127 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
128 static jb_err server_content_md5 (struct client_state *csp, char **header);
129 static jb_err server_content_encoding (struct client_state *csp, char **header);
130 static jb_err server_transfer_coding (struct client_state *csp, char **header);
131 static jb_err server_http (struct client_state *csp, char **header);
132 static jb_err crunch_server_header (struct client_state *csp, char **header);
133 static jb_err server_last_modified (struct client_state *csp, char **header);
134 static jb_err server_content_disposition(struct client_state *csp, char **header);
136 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
139 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
140 static jb_err server_save_content_length(struct client_state *csp, char **header);
141 static jb_err server_keep_alive(struct client_state *csp, char **header);
142 static jb_err server_proxy_connection(struct client_state *csp, char **header);
143 static jb_err client_keep_alive(struct client_state *csp, char **header);
144 static jb_err client_proxy_connection(struct client_state *csp, char **header);
145 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
147 static jb_err client_save_content_length(struct client_state *csp, char **header);
148 static jb_err client_host_adder (struct client_state *csp);
149 static jb_err client_xtra_adder (struct client_state *csp);
150 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
151 static jb_err client_connection_header_adder(struct client_state *csp);
152 static jb_err server_connection_adder(struct client_state *csp);
153 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
154 static jb_err server_proxy_connection_adder(struct client_state *csp);
155 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
156 static jb_err proxy_authentication(struct client_state *csp, char **header);
158 static jb_err create_forged_referrer(char **header, const char *hostport);
159 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
160 static jb_err handle_conditional_hide_referrer_parameter(char **header,
161 const char *host, const int parameter_conditional_block);
162 static void create_content_length_header(unsigned long long content_length,
163 char *header, size_t buffer_length);
166 * List of functions to run on a list of headers.
170 /** The header prefix to match */
173 /** The length of the prefix to match */
176 /** The function to apply to this line */
177 const parser_func_ptr parser;
180 static const struct parsers client_patterns[] = {
181 { "referer:", 8, client_referrer },
182 { "user-agent:", 11, client_uagent },
183 { "ua-", 3, client_ua },
184 { "from:", 5, client_from },
185 { "cookie:", 7, client_send_cookie },
186 { "x-forwarded-for:", 16, client_x_forwarded },
187 { "Accept-Encoding:", 16, client_accept_encoding },
188 { "TE:", 3, client_te },
189 { "Host:", 5, client_host },
190 { "if-modified-since:", 18, client_if_modified_since },
191 { "Content-Length:", 15, client_save_content_length },
192 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
193 { "Keep-Alive:", 11, client_keep_alive },
194 { "Proxy-Connection:", 17, client_proxy_connection },
196 { "Keep-Alive:", 11, crumble },
197 { "Proxy-Connection:", 17, crumble },
199 { "connection:", 11, client_connection },
200 { "max-forwards:", 13, client_max_forwards },
201 { "Accept-Language:", 16, client_accept_language },
202 { "if-none-match:", 14, client_if_none_match },
203 { "Range:", 6, client_range },
204 { "Request-Range:", 14, client_range },
205 { "If-Range:", 9, client_range },
206 { "X-Filter:", 9, client_x_filter },
207 { "Proxy-Authorization:", 20, proxy_authentication },
209 { "Transfer-Encoding:", 18, client_transfer_encoding },
211 { "Expect:", 7, client_expect },
212 { "*", 0, crunch_client_header },
213 { "*", 0, filter_header },
217 static const struct parsers server_patterns[] = {
218 { "HTTP/", 5, server_http },
219 { "set-cookie:", 11, server_set_cookie },
220 { "connection:", 11, server_connection },
221 { "Content-Type:", 13, server_content_type },
222 { "Content-MD5:", 12, server_content_md5 },
223 { "Content-Encoding:", 17, server_content_encoding },
224 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
225 { "Content-Length:", 15, server_save_content_length },
226 { "Keep-Alive:", 11, server_keep_alive },
227 { "Proxy-Connection:", 17, server_proxy_connection },
229 { "Keep-Alive:", 11, crumble },
230 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
231 { "Transfer-Encoding:", 18, server_transfer_coding },
232 { "content-disposition:", 20, server_content_disposition },
233 { "Last-Modified:", 14, server_last_modified },
234 { "Proxy-Authenticate:", 19, proxy_authentication },
235 { "*", 0, crunch_server_header },
236 { "*", 0, filter_header },
240 static const add_header_func_ptr add_client_headers[] = {
242 client_x_forwarded_for_adder,
244 client_connection_header_adder,
248 static const add_header_func_ptr add_server_headers[] = {
249 server_connection_adder,
250 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
251 server_proxy_connection_adder,
252 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
256 /*********************************************************************
258 * Function : flush_iob
260 * Description : Write any pending "buffered" content.
263 * 1 : fd = file descriptor of the socket to read
264 * 2 : iob = The I/O buffer to flush, usually csp->iob.
265 * 3 : delay = Number of milliseconds to delay the writes
267 * Returns : On success, the number of bytes written are returned (zero
268 * indicates nothing was written). On error, -1 is returned,
269 * and errno is set appropriately. If count is zero and the
270 * file descriptor refers to a regular file, 0 will be
271 * returned without causing any other effect. For a special
272 * file, the results are not portable.
274 *********************************************************************/
275 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
277 long len = iob->eod - iob->cur;
284 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
288 iob->eod = iob->cur = iob->buf;
294 /*********************************************************************
296 * Function : can_add_to_iob
298 * Description : Checks if the given number of bytes can be added to the given iob
299 * without exceeding the given buffer limit.
302 * 1 : iob = Destination buffer.
303 * 2 : buffer_limit = Limit to which the destination may grow
304 * 3 : n = number of bytes to be added
306 * Returns : TRUE if the given iob can handle given number of bytes
307 * FALSE buffer limit will be exceeded
309 *********************************************************************/
310 int can_add_to_iob(const struct iob *iob, const size_t buffer_limit, size_t n)
312 return ((size_t)(iob->eod - iob->buf) + n + 1) > buffer_limit ? FALSE : TRUE;
315 /*********************************************************************
317 * Function : add_to_iob
319 * Description : Add content to the buffer, expanding the
320 * buffer if necessary.
323 * 1 : iob = Destination buffer.
324 * 2 : buffer_limit = Limit to which the destination may grow
325 * 3 : src = holds the content to be added
326 * 4 : n = number of bytes to be added
328 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
329 * or buffer limit reached.
331 *********************************************************************/
332 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, const char *src, long n)
334 size_t used, offset, need;
337 if (n <= 0) return JB_ERR_OK;
339 used = (size_t)(iob->eod - iob->buf);
340 offset = (size_t)(iob->cur - iob->buf);
341 need = used + (size_t)n + 1;
344 * If the buffer can't hold the new data, extend it first.
345 * Use the next power of two if possible, else use the actual need.
347 if (need > buffer_limit)
349 log_error(LOG_LEVEL_INFO,
350 "Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
352 return JB_ERR_MEMORY;
355 if (need > iob->size)
357 size_t want = iob->size ? iob->size : 512;
364 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
368 else if (NULL != (p = (char *)realloc(iob->buf, need)))
374 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
375 return JB_ERR_MEMORY;
378 /* Update the iob pointers */
379 iob->cur = p + offset;
384 /* copy the new data into the iob buffer */
385 memcpy(iob->eod, src, (size_t)n);
387 /* point to the end of the data */
390 /* null terminate == cheap insurance */
398 /*********************************************************************
400 * Function : clear_iob
402 * Description : Frees the memory allocated for an I/O buffer and
403 * resets the structure.
406 * 1 : iob = I/O buffer to clear.
410 *********************************************************************/
411 void clear_iob(struct iob *iob)
414 memset(iob, '\0', sizeof(*iob));
419 #ifdef FEATURE_BROTLI
420 /*********************************************************************
422 * Function : decompress_iob_with_brotli
424 * Description : Decompress buffered page using Brotli.
427 * 1 : csp = Current client state (buffers, headers, etc...)
429 * Returns : JB_ERR_OK on success,
430 * JB_ERR_MEMORY if out-of-memory limit reached, and
431 * JB_ERR_COMPRESS if error decompressing buffer.
433 *********************************************************************/
434 static jb_err decompress_iob_with_brotli(struct client_state *csp)
436 BrotliDecoderResult result;
437 char *decoded_buffer;
439 size_t decoded_buffer_size;
441 enum { MAX_COMPRESSION_FACTOR = 15 };
443 encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
445 * The BrotliDecoderDecompress() api is a bit unfortunate
446 * and requires the caller to reserve enough memory for
447 * the decompressed content. Hopefully reserving
448 * MAX_COMPRESSION_FACTOR times the original size is
449 * sufficient. If not, BrotliDecoderDecompress() will fail.
451 decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
453 if (decoded_buffer_size > csp->config->buffer_limit)
455 log_error(LOG_LEVEL_ERROR,
456 "Buffer limit reached before decompressing iob with Brotli");
457 return JB_ERR_MEMORY;
460 decoded_buffer = malloc(decoded_buffer_size);
461 if (decoded_buffer == NULL)
463 log_error(LOG_LEVEL_ERROR,
464 "Failed to allocate %lu bytes for Brotli decompression",
465 decoded_buffer_size);
466 return JB_ERR_MEMORY;
469 decoded_size = decoded_buffer_size;
470 result = BrotliDecoderDecompress(encoded_size,
471 (const uint8_t *)csp->iob->cur, &decoded_size,
472 (uint8_t *)decoded_buffer);
473 if (result == BROTLI_DECODER_RESULT_SUCCESS)
476 * Update the iob, since the decompression was successful.
478 freez(csp->iob->buf);
479 csp->iob->buf = decoded_buffer;
480 csp->iob->cur = csp->iob->buf;
481 csp->iob->eod = csp->iob->cur + decoded_size;
482 csp->iob->size = decoded_buffer_size;
484 log_error(LOG_LEVEL_RE_FILTER,
485 "Decompression successful. Old size: %lu, new size: %lu.",
486 encoded_size, decoded_size);
492 log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
493 freez(decoded_buffer);
495 return JB_ERR_COMPRESS;
500 /*********************************************************************
502 * Function : decompress_iob
504 * Description : Decompress buffered page, expanding the
505 * buffer as necessary. csp->iob->cur
506 * should point to the the beginning of the
507 * compressed data block.
510 * 1 : csp = Current client state (buffers, headers, etc...)
512 * Returns : JB_ERR_OK on success,
513 * JB_ERR_MEMORY if out-of-memory limit reached, and
514 * JB_ERR_COMPRESS if error decompressing buffer.
516 *********************************************************************/
517 jb_err decompress_iob(struct client_state *csp)
519 char *buf; /* new, uncompressed buffer */
520 char *cur; /* Current iob position (to keep the original
521 * iob->cur unmodified if we return early) */
522 size_t bufsize; /* allocated size of the new buffer */
523 size_t old_size; /* Content size before decompression */
524 size_t skip_size; /* Number of bytes at the beginning of the iob
525 that we should NOT decompress. */
526 int status; /* return status of the inflate() call */
527 z_stream zstr; /* used by calls to zlib */
530 assert(csp->iob->cur - csp->iob->buf >= 0);
531 assert(csp->iob->eod - csp->iob->cur >= 0);
533 assert(csp->iob->cur - csp->iob->buf > 0);
534 assert(csp->iob->eod - csp->iob->cur > 0);
537 bufsize = csp->iob->size;
538 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
539 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
543 if (bufsize < (size_t)10)
546 * This is to protect the parsing of gzipped data,
547 * but it should(?) be valid for deflated data also.
549 log_error(LOG_LEVEL_ERROR,
550 "Insufficient data to start decompression. Bytes in buffer: %ld",
551 csp->iob->eod - csp->iob->cur);
552 return JB_ERR_COMPRESS;
555 #ifdef FEATURE_BROTLI
556 if (csp->content_type & CT_BROTLI)
558 return decompress_iob_with_brotli(csp);
562 if (csp->content_type & CT_GZIP)
565 * Our task is slightly complicated by the facts that data
566 * compressed by gzip does not include a zlib header, and
567 * that there is no easily accessible interface in zlib to
568 * handle a gzip header. We strip off the gzip header by
569 * hand, and later inform zlib not to expect a header.
573 * Strip off the gzip header. Please see RFC 1952 for more
574 * explanation of the appropriate fields.
576 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
577 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
578 || (*cur++ != Z_DEFLATED))
580 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
581 return JB_ERR_COMPRESS;
586 if (flags & GZIP_FLAG_RESERVED_BITS)
588 /* The gzip header has reserved bits set; bail out. */
589 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
590 return JB_ERR_COMPRESS;
594 * Skip mtime (4 bytes), extra flags (1 byte)
595 * and OS type (1 byte).
599 /* Skip extra fields if necessary. */
600 if (flags & GZIP_FLAG_EXTRA_FIELDS)
603 * Skip a given number of bytes, specified
604 * as a 16-bit little-endian value.
606 * XXX: this code is untested and should probably be removed.
610 skip_bytes += *cur++ << 8;
613 * The number of bytes to skip should be positive
614 * and we'd like to stay in the buffer.
616 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
618 log_error(LOG_LEVEL_ERROR,
619 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
621 return JB_ERR_COMPRESS;
623 log_error(LOG_LEVEL_INFO,
624 "Skipping %d bytes for gzip compression. Does this sound right?",
629 /* Skip the filename if necessary. */
630 if (flags & GZIP_FLAG_FILE_NAME)
632 /* A null-terminated string is supposed to follow. */
633 while (*cur++ && (cur < csp->iob->eod));
636 /* Skip the comment if necessary. */
637 if (flags & GZIP_FLAG_COMMENT)
639 /* A null-terminated string is supposed to follow. */
640 while (*cur++ && (cur < csp->iob->eod));
643 /* Skip the CRC if necessary. */
644 if (flags & GZIP_FLAG_CHECKSUM)
649 if (cur >= csp->iob->eod)
652 * If the current position pointer reached or passed
653 * the buffer end, we were obviously tricked to skip
656 log_error(LOG_LEVEL_ERROR,
657 "Malformed gzip header detected. Aborting decompression.");
658 return JB_ERR_COMPRESS;
662 else if (csp->content_type & CT_DEFLATE)
665 * In theory (that is, according to RFC 1950), deflate-compressed
666 * data should begin with a two-byte zlib header and have an
667 * adler32 checksum at the end. It seems that in practice only
668 * the raw compressed data is sent. Note that this means that
669 * we are not RFC 1950-compliant here, but the advantage is that
670 * this actually works. :)
672 * We add a dummy null byte to tell zlib where the data ends,
673 * and later inform it not to expect a header.
675 * Fortunately, add_to_iob() has thoughtfully null-terminated
676 * the buffer; we can just increment the end pointer to include
683 log_error(LOG_LEVEL_ERROR,
684 "Unable to determine compression format for decompression");
685 return JB_ERR_COMPRESS;
688 /* Set up the fields required by zlib. */
689 zstr.next_in = (Bytef *)cur;
690 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
691 zstr.zalloc = Z_NULL;
693 zstr.opaque = Z_NULL;
696 * Passing -MAX_WBITS to inflateInit2 tells the library
697 * that there is no zlib header.
699 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
701 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
702 return JB_ERR_COMPRESS;
706 * Next, we allocate new storage for the inflated data.
707 * We don't modify the existing iob yet, so in case there
708 * is error in decompression we can recover gracefully.
710 buf = zalloc(bufsize);
713 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
714 return JB_ERR_MEMORY;
717 assert(bufsize >= skip_size);
718 memcpy(buf, csp->iob->buf, skip_size);
719 zstr.avail_out = (uInt)(bufsize - skip_size);
720 zstr.next_out = (Bytef *)buf + skip_size;
722 /* Try to decompress the whole stream in one shot. */
723 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
725 /* We need to allocate more memory for the output buffer. */
727 char *tmpbuf; /* used for realloc'ing the buffer */
728 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
730 if (0 == zstr.avail_in)
733 * If zlib wants more data then there's a problem, because
734 * the complete compressed file should have been buffered.
736 log_error(LOG_LEVEL_ERROR,
737 "Unexpected end of compressed iob. Using what we got so far.");
742 * If we reached the buffer limit and still didn't have enough
743 * memory, just give up. Due to the ceiling enforced by the next
744 * if block we could actually check for equality here, but as it
745 * can be easily mistaken for a bug we don't.
747 if (bufsize >= csp->config->buffer_limit)
749 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
752 return JB_ERR_MEMORY;
755 /* Try doubling the buffer size each time. */
758 /* Don't exceed the buffer limit. */
759 if (bufsize > csp->config->buffer_limit)
761 bufsize = csp->config->buffer_limit;
764 /* Try to allocate the new buffer. */
765 tmpbuf = realloc(buf, bufsize);
768 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
771 return JB_ERR_MEMORY;
775 char *oldnext_out = (char *)zstr.next_out;
778 * Update the fields for inflate() to use the new
779 * buffer, which may be in a location different from
782 zstr.avail_out += (uInt)(bufsize - oldbufsize);
783 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
786 * Compare with an uglier method of calculating these values
787 * that doesn't require the extra oldbufsize variable.
789 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
790 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
796 if (Z_STREAM_ERROR == inflateEnd(&zstr))
798 log_error(LOG_LEVEL_ERROR,
799 "Inconsistent stream state after decompression: %s", zstr.msg);
801 * XXX: Intentionally no return.
803 * According to zlib.h, Z_STREAM_ERROR is returned
804 * "if the stream state was inconsistent".
806 * I assume in this case inflate()'s status
807 * would also be something different than Z_STREAM_END
808 * so this check should be redundant, but lets see.
812 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
815 * We failed to decompress the stream and it's
816 * not simply because of missing data.
818 log_error(LOG_LEVEL_ERROR,
819 "Unexpected error while decompressing to the buffer (iob): %s",
821 return JB_ERR_COMPRESS;
825 * Finally, we can actually update the iob, since the
826 * decompression was successful. First, free the old
829 freez(csp->iob->buf);
831 /* Now, update the iob to use the new buffer. */
833 csp->iob->cur = csp->iob->buf + skip_size;
834 csp->iob->eod = (char *)zstr.next_out;
835 csp->iob->size = bufsize;
838 * Make sure the new uncompressed iob obeys some minimal
839 * consistency conditions.
841 if ((csp->iob->buf <= csp->iob->cur)
842 && (csp->iob->cur <= csp->iob->eod)
843 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
845 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
846 if (new_size > (size_t)0)
848 log_error(LOG_LEVEL_RE_FILTER,
849 "Decompression successful. Old size: %lu, new size: %lu.",
854 /* zlib thinks this is OK, so let's do the same. */
855 log_error(LOG_LEVEL_RE_FILTER,
856 "Decompression didn't result in any content.");
861 /* It seems that zlib did something weird. */
862 log_error(LOG_LEVEL_ERROR, "Inconsistent buffer after decompression");
863 return JB_ERR_COMPRESS;
869 #endif /* defined(FEATURE_ZLIB) */
872 /*********************************************************************
874 * Function : normalize_lws
876 * Description : Reduces unquoted linear whitespace in headers to
877 * a single space in accordance with RFC 7230 3.2.4.
878 * This simplifies parsing and filtering later on.
881 * 1 : header = A header with linear whitespace to reduce.
885 *********************************************************************/
886 static void normalize_lws(char *header)
892 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
896 while (privoxy_isspace(*q))
900 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
906 log_error(LOG_LEVEL_HEADER,
907 "Converting tab to space in '%s'", header);
912 char *end_of_token = strstr(p+1, "\"");
914 if (NULL != end_of_token)
916 /* Don't mess with quoted text. */
921 log_error(LOG_LEVEL_HEADER,
922 "Ignoring single quote in '%s'", header);
928 p = strchr(header, ':');
929 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
932 * There's still space before the colon.
940 /*********************************************************************
942 * Function : get_header
944 * Description : This (odd) routine will parse the csp->iob
945 * to get the next complete header.
948 * 1 : iob = The I/O buffer to parse, usually csp->iob.
950 * Returns : Any one of the following:
952 * 1) a pointer to a dynamically allocated string that contains a header line
953 * 2) NULL indicating that the end of the header was reached
954 * 3) "" indicating that the end of the iob was reached before finding
955 * a complete header line.
957 *********************************************************************/
958 char *get_header(struct iob *iob)
962 header = get_header_line(iob);
964 if ((header == NULL) || (*header == '\0'))
967 * No complete header read yet, tell the client.
972 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
975 * Header spans multiple lines, append the next one.
977 char *continued_header;
979 continued_header = get_header_line(iob);
980 if ((continued_header == NULL) || (*continued_header == '\0'))
983 * No complete header read yet, return what we got.
984 * XXX: Should "unread" header instead.
986 log_error(LOG_LEVEL_INFO,
987 "Failed to read a multi-line header properly: '%s'",
992 if (JB_ERR_OK != string_join(&header, continued_header))
994 log_error(LOG_LEVEL_FATAL,
995 "Out of memory while appending multiple headers.");
999 /* XXX: remove before next stable release. */
1000 log_error(LOG_LEVEL_HEADER,
1001 "Merged multiple header lines to: '%s'",
1006 normalize_lws(header);
1013 /*********************************************************************
1015 * Function : get_header_line
1017 * Description : This (odd) routine will parse the csp->iob
1018 * to get the next header line.
1021 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1023 * Returns : Any one of the following:
1025 * 1) a pointer to a dynamically allocated string that contains a header line
1026 * 2) NULL indicating that the end of the header was reached
1027 * 3) "" indicating that the end of the iob was reached before finding
1028 * a complete header line.
1030 *********************************************************************/
1031 static char *get_header_line(struct iob *iob)
1035 if ((iob->cur == NULL)
1036 || ((p = strchr(iob->cur, '\n')) == NULL))
1038 return(""); /* couldn't find a complete header */
1043 ret = strdup(iob->cur);
1046 /* FIXME No way to handle error properly */
1047 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1049 assert(ret != NULL);
1053 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1055 /* is this a blank line (i.e. the end of the header) ? */
1067 /*********************************************************************
1069 * Function : get_header_value
1071 * Description : Get the value of a given header from a chained list
1072 * of header lines or return NULL if no such header is
1073 * present in the list.
1076 * 1 : header_list = pointer to list
1077 * 2 : header_name = string with name of header to look for.
1078 * Trailing colon required, capitalization
1081 * Returns : NULL if not found, else value of header
1083 *********************************************************************/
1084 char *get_header_value(const struct list *header_list, const char *header_name)
1086 struct list_entry *cur_entry;
1090 assert(header_list);
1091 assert(header_name);
1092 length = strlen(header_name);
1094 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1098 if (!strncmpic(cur_entry->str, header_name, length))
1101 * Found: return pointer to start of value
1103 ret = cur_entry->str + length;
1104 while (*ret && privoxy_isspace(*ret)) ret++;
1118 /*********************************************************************
1120 * Function : scan_headers
1122 * Description : Scans headers, applies tags and updates action bits.
1125 * 1 : csp = Current client state (buffers, headers, etc...)
1127 * Returns : JB_ERR_OK
1129 *********************************************************************/
1130 static jb_err scan_headers(struct client_state *csp)
1132 struct list_entry *h; /* Header */
1133 jb_err err = JB_ERR_OK;
1135 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1137 /* Header crunch()ed in previous run? -> ignore */
1138 if (h->str == NULL) continue;
1139 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1140 err = header_tagger(csp, h->str);
1147 /*********************************************************************
1149 * Function : enforce_header_order
1151 * Description : Enforces a given header order.
1154 * 1 : headers = List of headers to order.
1155 * 2 : ordered_headers = List of ordered header names.
1159 *********************************************************************/
1160 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1162 struct list_entry *sorted_header;
1163 struct list new_headers[1];
1164 struct list_entry *header;
1166 init_list(new_headers);
1168 /* The request line is always the first "header" */
1170 assert(NULL != headers->first->str);
1171 enlist(new_headers, headers->first->str);
1172 freez(headers->first->str)
1174 /* Enlist the specified headers in the given order */
1176 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1177 sorted_header = sorted_header->next)
1179 const size_t sorted_header_length = strlen(sorted_header->str);
1180 for (header = headers->first; header != NULL; header = header->next)
1182 /* Header enlisted in previous run? -> ignore */
1183 if (header->str == NULL) continue;
1185 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1186 && (header->str[sorted_header_length] == ':'))
1188 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1189 if (JB_ERR_OK != enlist(new_headers, header->str))
1191 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1198 /* Enlist the rest of the headers behind the ordered ones */
1199 for (header = headers->first; header != NULL; header = header->next)
1201 /* Header enlisted in previous run? -> ignore */
1202 if (header->str == NULL) continue;
1204 log_error(LOG_LEVEL_HEADER,
1205 "Enlisting left-over header %s", header->str);
1206 if (JB_ERR_OK != enlist(new_headers, header->str))
1208 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1213 list_remove_all(headers);
1214 headers->first = new_headers->first;
1215 headers->last = new_headers->last;
1221 /*********************************************************************
1225 * Description : add, delete or modify lines in the HTTP header streams.
1226 * On entry, it receives a linked list of headers space
1227 * that was allocated dynamically (both the list nodes
1228 * and the header contents).
1230 * As a side effect it frees the space used by the original
1234 * 1 : csp = Current client state (buffers, headers, etc...)
1235 * 2 : filter_server_headers = Boolean to switch between
1236 * server and header filtering.
1238 * Returns : JB_ERR_OK in case off success, or
1239 * JB_ERR_MEMORY on some out-of-memory errors, or
1240 * JB_ERR_PARSE in case of fatal parse errors.
1242 *********************************************************************/
1243 jb_err sed(struct client_state *csp, int filter_server_headers)
1245 /* XXX: use more descriptive names. */
1246 struct list_entry *p;
1247 const struct parsers *v;
1248 const add_header_func_ptr *f;
1249 jb_err err = JB_ERR_OK;
1253 if (filter_server_headers)
1255 v = server_patterns;
1256 f = add_server_headers;
1257 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1261 v = client_patterns;
1262 f = add_client_headers;
1263 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1266 while (v->str != NULL)
1268 for (p = csp->headers->first; p != NULL; p = p->next)
1270 /* Header crunch()ed in previous run? -> ignore */
1271 if (p->str == NULL) continue;
1273 /* Does the current parser handle this header? */
1274 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1275 (v->len == CHECK_EVERY_HEADER_REMAINING))
1277 err = v->parser(csp, &(p->str));
1278 if (err != JB_ERR_OK)
1287 /* place additional headers on the csp->headers list */
1288 while ((err == JB_ERR_OK) && (*f))
1294 if (!filter_server_headers &&
1295 !list_is_empty(csp->config->ordered_client_headers) &&
1296 csp->headers->first->str != NULL)
1298 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1305 #ifdef FEATURE_HTTPS_INSPECTION
1306 /*********************************************************************
1308 * Function : sed_https
1310 * Description : add, delete or modify lines in the HTTPS client
1311 * header streams. Wrapper around sed().
1314 * 1 : csp = Current client state (buffers, headers, etc...)
1316 * Returns : JB_ERR_OK in case off success, or
1317 * JB_ERR_MEMORY on some out-of-memory errors, or
1318 * JB_ERR_PARSE in case of fatal parse errors.
1320 *********************************************************************/
1321 jb_err sed_https(struct client_state *csp)
1324 struct list headers;
1327 * Temporarily replace csp->headers with csp->https_headers
1328 * to trick sed() into filtering the https headers.
1330 headers.first = csp->headers->first;
1331 headers.last = csp->headers->last;
1332 csp->headers->first = csp->https_headers->first;
1333 csp->headers->last = csp->https_headers->last;
1336 * Start with fresh tags. Already existing tags may
1337 * be set again. This is necessary to overrule
1338 * URL-based patterns.
1340 destroy_list(csp->tags);
1343 * We want client header filters and taggers
1344 * so temporarily remove the flag.
1346 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1347 err = sed(csp, FILTER_CLIENT_HEADERS);
1348 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1351 * Update the https headers list which may have
1352 * been modified due to header additions or header
1355 csp->https_headers->first = csp->headers->first;
1356 csp->https_headers->last = csp->headers->last;
1358 csp->headers->first = headers.first;
1359 csp->headers->last = headers.last;
1363 #endif /* def FEATURE_HTTPS_INSPECTION */
1366 /*********************************************************************
1368 * Function : update_server_headers
1370 * Description : Updates server headers after the body has been modified.
1373 * 1 : csp = Current client state (buffers, headers, etc...)
1375 * Returns : JB_ERR_OK in case off success, or
1376 * JB_ERR_MEMORY on out-of-memory error.
1378 *********************************************************************/
1379 jb_err update_server_headers(struct client_state *csp)
1381 jb_err err = JB_ERR_OK;
1383 static const struct parsers server_patterns_light[] = {
1384 { "Content-Length:", 15, server_adjust_content_length },
1385 { "Transfer-Encoding:", 18, server_transfer_coding },
1387 { "Content-Encoding:", 17, server_adjust_content_encoding },
1388 #endif /* def FEATURE_ZLIB */
1392 if (strncmpic(csp->http->cmd, "HEAD", 4))
1394 const struct parsers *v;
1395 struct list_entry *p;
1397 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1399 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1401 /* Header crunch()ed in previous run? -> ignore */
1402 if (p->str == NULL) continue;
1404 /* Does the current parser handle this header? */
1405 if (strncmpic(p->str, v->str, v->len) == 0)
1407 err = v->parser(csp, (char **)&(p->str));
1413 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1414 if ((JB_ERR_OK == err)
1415 && (csp->flags & CSP_FLAG_MODIFIED)
1416 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1417 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1421 create_content_length_header(csp->content_length, header, sizeof(header));
1422 err = enlist(csp->headers, header);
1423 if (JB_ERR_OK == err)
1425 log_error(LOG_LEVEL_HEADER,
1426 "Content modified with no Content-Length header set. "
1427 "Created: %s.", header);
1428 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1431 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1433 #ifdef FEATURE_COMPRESSION
1434 if ((JB_ERR_OK == err)
1435 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1437 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1438 if (JB_ERR_OK == err)
1440 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1449 /*********************************************************************
1451 * Function : header_tagger
1453 * Description : Executes all text substitutions from applying
1454 * tag actions and saves the result as tag.
1456 * XXX: Shares enough code with filter_header() and
1457 * pcrs_filter_response() to warrant some helper functions.
1460 * 1 : csp = Current client state (buffers, headers, etc...)
1461 * 2 : header = Header that is used as tagger input
1463 * Returns : JB_ERR_OK on success and always succeeds
1465 *********************************************************************/
1466 static jb_err header_tagger(struct client_state *csp, char *header)
1468 enum filter_type wanted_filter_type;
1469 int multi_action_index;
1472 struct re_filterfile_spec *b;
1473 struct list_entry *tag_name;
1475 const size_t header_length = strlen(header);
1477 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1479 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1480 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1484 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1485 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1488 if (list_is_empty(csp->action->multi[multi_action_index])
1489 || filters_available(csp) == FALSE)
1491 /* Return early if no taggers apply or if none are available. */
1495 /* Execute all applying taggers */
1496 for (tag_name = csp->action->multi[multi_action_index]->first;
1497 NULL != tag_name; tag_name = tag_name->next)
1499 char *modified_tag = NULL;
1501 size_t size = header_length;
1504 b = get_filter(csp, tag_name->str, wanted_filter_type);
1510 joblist = b->joblist;
1512 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1514 if (NULL == joblist)
1516 log_error(LOG_LEVEL_TAGGING,
1517 "Tagger %s has empty joblist. Nothing to do.", b->name);
1521 /* execute their pcrs_joblist on the header. */
1522 for (job = joblist; NULL != job; job = job->next)
1524 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1528 /* Success, continue with the modified version. */
1537 /* Tagger doesn't match */
1540 /* Regex failure, log it but continue anyway. */
1541 assert(NULL != header);
1542 log_error(LOG_LEVEL_ERROR,
1543 "Problems with tagger \'%s\' and header \'%s\': %s",
1544 b->name, header, pcrs_strerror(hits));
1546 freez(modified_tag);
1550 if (b->dynamic) pcrs_free_joblist(joblist);
1552 /* If this tagger matched */
1558 * There is no technical limitation which makes
1559 * it impossible to use empty tags, but I assume
1560 * no one would do it intentionally.
1563 log_error(LOG_LEVEL_TAGGING,
1564 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1568 if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
1570 log_error(LOG_LEVEL_TAGGING,
1571 "Tagger \'%s\' didn't add tag \'%s\': suppressed",
1577 if (!list_contains_item(csp->tags, tag))
1579 if (JB_ERR_OK != enlist(csp->tags, tag))
1581 log_error(LOG_LEVEL_ERROR,
1582 "Insufficient memory to add tag \'%s\', "
1583 "based on tagger \'%s\' and header \'%s\'",
1584 tag, b->name, header);
1588 char *action_message;
1590 * update the action bits right away, to make
1591 * tagging based on tags set by earlier taggers
1592 * of the same kind possible.
1594 if (update_action_bits_for_tag(csp, tag))
1596 action_message = "Action bits updated accordingly.";
1600 action_message = "No action bits update necessary.";
1603 log_error(LOG_LEVEL_TAGGING,
1604 "Tagger \'%s\' added tag \'%s\'. %s",
1605 b->name, tag, action_message);
1610 /* XXX: Is this log-worthy? */
1611 log_error(LOG_LEVEL_TAGGING,
1612 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1622 /* here begins the family of parser functions that reformat header lines */
1624 /*********************************************************************
1626 * Function : filter_header
1628 * Description : Executes all text substitutions from all applying
1629 * +(server|client)-header-filter actions on the header.
1630 * Most of the code was copied from pcrs_filter_response,
1631 * including the rather short variable names
1634 * 1 : csp = Current client state (buffers, headers, etc...)
1635 * 2 : header = On input, pointer to header to modify.
1636 * On output, pointer to the modified header, or NULL
1637 * to remove the header. This function frees the
1638 * original string if necessary.
1640 * Returns : JB_ERR_OK on success and always succeeds
1642 *********************************************************************/
1643 static jb_err filter_header(struct client_state *csp, char **header)
1647 size_t size = strlen(*header);
1649 char *newheader = NULL;
1652 struct re_filterfile_spec *b;
1653 struct list_entry *filtername;
1655 enum filter_type wanted_filter_type;
1656 int multi_action_index;
1658 if (csp->flags & CSP_FLAG_NO_FILTERING)
1663 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1665 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1666 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1670 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1671 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1674 if (list_is_empty(csp->action->multi[multi_action_index])
1675 || filters_available(csp) == FALSE)
1677 /* Return early if no filters apply or if none are available. */
1681 /* Execute all applying header filters */
1682 for (filtername = csp->action->multi[multi_action_index]->first;
1683 filtername != NULL; filtername = filtername->next)
1685 int current_hits = 0;
1688 b = get_filter(csp, filtername->str, wanted_filter_type);
1694 joblist = b->joblist;
1696 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1698 if (NULL == joblist)
1700 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1704 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %lu) with \'%s\' ...",
1705 *header, size, b->name);
1707 /* Apply all jobs from the joblist */
1708 for (job = joblist; NULL != job; job = job->next)
1710 matches = pcrs_execute(job, *header, size, &newheader, &size);
1713 current_hits += matches;
1714 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1716 *header = newheader;
1718 else if (0 == matches)
1720 /* Filter doesn't change header */
1726 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1727 *header, b->name, pcrs_strerror(matches));
1728 if (newheader != NULL)
1730 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1736 if (b->dynamic) pcrs_free_joblist(joblist);
1738 log_error(LOG_LEVEL_RE_FILTER,
1739 "... produced %d hits (new size %lu).", current_hits, size);
1740 hits += current_hits;
1744 * Additionally checking for hits is important because if
1745 * the continue hack is triggered, server headers can
1746 * arrive empty to separate multiple heads from each other.
1748 if ((0 == size) && hits)
1750 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1758 /*********************************************************************
1760 * Function : server_connection
1762 * Description : Makes sure a proper "Connection:" header is
1763 * set and signals connection_header_adder to
1767 * 1 : csp = Current client state (buffers, headers, etc...)
1768 * 2 : header = On input, pointer to header to modify.
1769 * On output, pointer to the modified header, or NULL
1770 * to remove the header. This function frees the
1771 * original string if necessary.
1773 * Returns : JB_ERR_OK on success.
1775 *********************************************************************/
1776 static jb_err server_connection(struct client_state *csp, char **header)
1778 if (!strcmpic(*header, "Connection: keep-alive")
1779 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1780 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1784 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1785 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1787 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1790 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1792 log_error(LOG_LEVEL_HEADER,
1793 "Keeping the server header '%s' around.", *header);
1796 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1798 char *old_header = *header;
1800 *header = strdup_or_die("Connection: close");
1801 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1806 /* Signal server_connection_adder() to return early. */
1807 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1813 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1814 /*********************************************************************
1816 * Function : server_keep_alive
1818 * Description : Stores the server's keep alive timeout.
1821 * 1 : csp = Current client state (buffers, headers, etc...)
1822 * 2 : header = On input, pointer to header to modify.
1823 * On output, pointer to the modified header, or NULL
1824 * to remove the header. This function frees the
1825 * original string if necessary.
1827 * Returns : JB_ERR_OK.
1829 *********************************************************************/
1830 static jb_err server_keep_alive(struct client_state *csp, char **header)
1832 unsigned int keep_alive_timeout;
1833 const char *timeout_position = strstr(*header, "timeout=");
1835 if ((NULL == timeout_position)
1836 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1838 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1842 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1844 log_error(LOG_LEVEL_HEADER,
1845 "Reducing keep-alive timeout from %u to %u.",
1846 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1847 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1851 /* XXX: Is this log worthy? */
1852 log_error(LOG_LEVEL_HEADER,
1853 "Server keep-alive timeout is %u. Sticking with %u.",
1854 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1856 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1865 /*********************************************************************
1867 * Function : server_proxy_connection
1869 * Description : Figures out whether or not we should add a
1870 * Proxy-Connection header.
1873 * 1 : csp = Current client state (buffers, headers, etc...)
1874 * 2 : header = On input, pointer to header to modify.
1875 * On output, pointer to the modified header, or NULL
1876 * to remove the header. This function frees the
1877 * original string if necessary.
1879 * Returns : JB_ERR_OK.
1881 *********************************************************************/
1882 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1884 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1887 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1890 /*********************************************************************
1892 * Function : proxy_authentication
1894 * Description : Removes headers that are relevant for proxy
1895 * authentication unless forwarding them has
1896 * been explicitly requested.
1899 * 1 : csp = Current client state (buffers, headers, etc...)
1900 * 2 : header = On input, pointer to header to modify.
1901 * On output, pointer to the modified header, or NULL
1902 * to remove the header. This function frees the
1903 * original string if necessary.
1905 * Returns : JB_ERR_OK.
1907 *********************************************************************/
1908 static jb_err proxy_authentication(struct client_state *csp, char **header)
1910 if ((csp->config->feature_flags &
1911 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1912 log_error(LOG_LEVEL_HEADER,
1913 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1920 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1921 /*********************************************************************
1923 * Function : client_keep_alive
1925 * Description : Stores the client's keep alive timeout.
1928 * 1 : csp = Current client state (buffers, headers, etc...)
1929 * 2 : header = On input, pointer to header to modify.
1930 * On output, pointer to the modified header, or NULL
1931 * to remove the header. This function frees the
1932 * original string if necessary.
1934 * Returns : JB_ERR_OK.
1936 *********************************************************************/
1937 static jb_err client_keep_alive(struct client_state *csp, char **header)
1939 unsigned int keep_alive_timeout;
1940 char *timeout_position;
1942 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1944 log_error(LOG_LEVEL_HEADER,
1945 "keep-alive support is disabled. Crunching: %s.", *header);
1950 /* Check for parameter-less format "Keep-Alive: 100" */
1951 timeout_position = strstr(*header, ": ");
1952 if ((NULL == timeout_position)
1953 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1955 /* Assume parameter format "Keep-Alive: timeout=100" */
1956 timeout_position = strstr(*header, "timeout=");
1957 if ((NULL == timeout_position)
1958 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1960 log_error(LOG_LEVEL_HEADER,
1961 "Couldn't parse: '%s'. Using default timeout %u",
1962 *header, csp->config->keep_alive_timeout);
1969 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1971 log_error(LOG_LEVEL_HEADER,
1972 "Reducing keep-alive timeout from %u to %u.",
1973 csp->config->keep_alive_timeout, keep_alive_timeout);
1974 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1978 /* XXX: Is this log worthy? */
1979 log_error(LOG_LEVEL_HEADER,
1980 "Client keep-alive timeout is %u. Sticking with %u.",
1981 keep_alive_timeout, csp->config->keep_alive_timeout);
1987 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1990 /*********************************************************************
1992 * Function : get_content_length
1994 * Description : Gets the content length specified in a
1995 * Content-Length header.
1998 * 1 : header_value = The Content-Length header value.
1999 * 2 : length = Storage to return the value.
2001 * Returns : JB_ERR_OK on success, or
2002 * JB_ERR_PARSE if no value is recognized.
2004 *********************************************************************/
2005 static jb_err get_content_length(const char *header_value, unsigned long long *length)
2008 #if SIZEOF_LONG_LONG < 8
2009 #error sizeof(unsigned long long) too small
2011 if (1 != sscanf(header_value, "%I64u", length))
2013 if (1 != sscanf(header_value, "%llu", length))
2016 return JB_ERR_PARSE;
2023 /*********************************************************************
2025 * Function : client_save_content_length
2027 * Description : Save the Content-Length sent by the client.
2030 * 1 : csp = Current client state (buffers, headers, etc...)
2031 * 2 : header = pointer to the Content-Length header
2033 * Returns : JB_ERR_OK on success, or
2034 * JB_ERR_MEMORY on out-of-memory error.
2036 *********************************************************************/
2037 static jb_err client_save_content_length(struct client_state *csp, char **header)
2039 unsigned long long content_length = 0;
2040 const char *header_value;
2042 assert(*(*header+14) == ':');
2044 header_value = *header + 15;
2045 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2047 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2052 csp->expected_client_content_length = content_length;
2059 /*********************************************************************
2061 * Function : client_connection
2063 * Description : Makes sure a proper "Connection:" header is
2064 * set and signals connection_header_adder
2068 * 1 : csp = Current client state (buffers, headers, etc...)
2069 * 2 : header = On input, pointer to header to modify.
2070 * On output, pointer to the modified header, or NULL
2071 * to remove the header. This function frees the
2072 * original string if necessary.
2074 * Returns : JB_ERR_OK on success.
2076 *********************************************************************/
2077 static jb_err client_connection(struct client_state *csp, char **header)
2079 static const char connection_close[] = "Connection: close";
2081 if (!strcmpic(*header, connection_close))
2083 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2084 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2085 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2086 #ifdef FEATURE_HTTPS_INSPECTION
2087 && !client_use_ssl(csp)
2091 if (!strcmpic(csp->http->version, "HTTP/1.1"))
2093 log_error(LOG_LEVEL_HEADER,
2094 "Removing \'%s\' to imply keep-alive.", *header);
2097 * While we imply keep-alive to the server,
2098 * we have to remember that the client didn't.
2100 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2104 char *old_header = *header;
2106 *header = strdup_or_die("Connection: keep-alive");
2107 log_error(LOG_LEVEL_HEADER,
2108 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2114 log_error(LOG_LEVEL_HEADER,
2115 "Keeping the client header '%s' around. "
2116 "The connection will not be kept alive.",
2118 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2121 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2122 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2124 log_error(LOG_LEVEL_HEADER,
2125 "Keeping the client header '%s' around. "
2126 "The server connection will be kept alive if possible.",
2128 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2129 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2133 char *old_header = *header;
2135 *header = strdup_or_die(connection_close);
2136 log_error(LOG_LEVEL_HEADER,
2137 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2141 /* Signal client_connection_header_adder() to return early. */
2142 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2148 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2149 /*********************************************************************
2151 * Function : client_proxy_connection
2153 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2154 * appropriate and removes the Proxy-Connection
2158 * 1 : csp = Current client state (buffers, headers, etc...)
2159 * 2 : header = On input, pointer to header to modify.
2160 * On output, pointer to the modified header, or NULL
2161 * to remove the header. This function frees the
2162 * original string if necessary.
2164 * Returns : JB_ERR_OK
2166 *********************************************************************/
2167 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2169 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2170 && (csp->http->ssl == 0)
2171 && (NULL == strstr(*header, "close")))
2173 log_error(LOG_LEVEL_HEADER,
2174 "The client connection can be kept alive due to: %s", *header);
2175 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2177 crumble(csp, header);
2181 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2184 /*********************************************************************
2186 * Function : client_transfer_encoding
2188 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2189 * the request body is "chunked"
2191 * XXX: Currently not called through sed() as we
2192 * need the flag earlier on. Should be fixed.
2195 * 1 : csp = Current client state (buffers, headers, etc...)
2196 * 2 : header = On input, pointer to header to modify.
2197 * On output, pointer to the modified header, or NULL
2198 * to remove the header. This function frees the
2199 * original string if necessary.
2201 * Returns : JB_ERR_OK on success, or
2203 *********************************************************************/
2204 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2206 if (strstr(*header, "chunked"))
2208 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2209 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2216 /*********************************************************************
2218 * Function : client_expect
2220 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2221 * if the Expect header value is unsupported.
2223 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2224 * MAY and a RFC 2616 (obsolete) MUST.
2227 * 1 : csp = Current client state (buffers, headers, etc...)
2228 * 2 : header = On input, pointer to header to modify.
2229 * On output, pointer to the modified header, or NULL
2230 * to remove the header. This function frees the
2231 * original string if necessary.
2233 * Returns : JB_ERR_OK on success, or
2235 *********************************************************************/
2236 jb_err client_expect(struct client_state *csp, char **header)
2238 if (0 != strcmpic(*header, "Expect: 100-continue"))
2240 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2241 log_error(LOG_LEVEL_HEADER,
2242 "Unsupported client expectaction: %s", *header);
2250 /*********************************************************************
2252 * Function : crumble
2254 * Description : This is called if a header matches a pattern to "crunch"
2257 * 1 : csp = Current client state (buffers, headers, etc...)
2258 * 2 : header = On input, pointer to header to modify.
2259 * On output, pointer to the modified header, or NULL
2260 * to remove the header. This function frees the
2261 * original string if necessary.
2263 * Returns : JB_ERR_OK on success, or
2264 * JB_ERR_MEMORY on out-of-memory error.
2266 *********************************************************************/
2267 static jb_err crumble(struct client_state *csp, char **header)
2270 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2276 /*********************************************************************
2278 * Function : crunch_server_header
2280 * Description : Crunch server header if it matches a string supplied by the
2281 * user. Called from `sed'.
2284 * 1 : csp = Current client state (buffers, headers, etc...)
2285 * 2 : header = On input, pointer to header to modify.
2286 * On output, pointer to the modified header, or NULL
2287 * to remove the header. This function frees the
2288 * original string if necessary.
2290 * Returns : JB_ERR_OK on success and always succeeds
2292 *********************************************************************/
2293 static jb_err crunch_server_header(struct client_state *csp, char **header)
2295 const char *crunch_pattern;
2297 /* Do we feel like crunching? */
2298 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2300 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2302 /* Is the current header the lucky one? */
2303 if (strstr(*header, crunch_pattern))
2305 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2314 /*********************************************************************
2316 * Function : server_content_type
2318 * Description : Set the content-type for filterable types (text/.*,
2319 * .*xml.*, .*script.* and image/gif) unless filtering has been
2320 * forbidden (CT_TABOO) while parsing earlier headers.
2321 * NOTE: Since text/plain is commonly used by web servers
2322 * for files whose correct type is unknown, we don't
2323 * set CT_TEXT for it.
2326 * 1 : csp = Current client state (buffers, headers, etc...)
2327 * 2 : header = On input, pointer to header to modify.
2328 * On output, pointer to the modified header, or NULL
2329 * to remove the header. This function frees the
2330 * original string if necessary.
2332 * Returns : JB_ERR_OK on success, or
2333 * JB_ERR_MEMORY on out-of-memory error.
2335 *********************************************************************/
2336 static jb_err server_content_type(struct client_state *csp, char **header)
2338 /* Remove header if it isn't the first Content-Type header */
2339 if ((csp->content_type & CT_DECLARED))
2341 if (content_filters_enabled(csp->action))
2344 * Making sure the client interprets the content the same way
2345 * Privoxy did is only relevant if Privoxy modified it.
2347 * Checking for this is "hard" as it's not yet known when
2348 * this function is called, thus go shopping and and just
2349 * check if Privoxy could filter it.
2351 * The main thing is that we don't mess with the headers
2352 * unless the user signalled that it's acceptable.
2354 log_error(LOG_LEVEL_HEADER,
2355 "Multiple Content-Type headers detected. "
2356 "Removing and ignoring: %s",
2364 * Signal that the Content-Type has been set.
2366 csp->content_type |= CT_DECLARED;
2368 if (!(csp->content_type & CT_TABOO))
2371 * XXX: The assumption that text/plain is a sign of
2372 * binary data seems to be somewhat unreasonable nowadays
2373 * and should be dropped after 3.0.8 is out.
2375 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2376 || strstr(*header, "xml")
2377 || strstr(*header, "script"))
2379 csp->content_type |= CT_TEXT;
2381 else if (strstr(*header, "image/gif"))
2383 csp->content_type |= CT_GIF;
2388 * Are we messing with the content type?
2390 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2393 * Make sure the user doesn't accidentally
2394 * change the content type of binary documents.
2396 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2400 *header = strdup_or_die("Content-Type: ");
2402 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2403 if (JB_ERR_OK != err)
2405 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2406 return JB_ERR_MEMORY;
2408 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2412 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2413 "It doesn't look like a content type that should be filtered. "
2414 "Enable force-text-mode if you know what you're doing.", *header);
2422 /*********************************************************************
2424 * Function : server_transfer_coding
2426 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2427 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2428 * - Remove header if body was chunked but has been
2429 * de-chunked for filtering.
2432 * 1 : csp = Current client state (buffers, headers, etc...)
2433 * 2 : header = On input, pointer to header to modify.
2434 * On output, pointer to the modified header, or NULL
2435 * to remove the header. This function frees the
2436 * original string if necessary.
2438 * Returns : JB_ERR_OK on success, or
2439 * JB_ERR_MEMORY on out-of-memory error.
2441 *********************************************************************/
2442 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2445 * Turn off pcrs and gif filtering if body compressed
2447 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2451 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2453 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2454 csp->http->cmd, *header);
2455 #endif /* def FEATURE_ZLIB */
2456 csp->content_type = CT_TABOO;
2460 * Raise flag if body chunked
2462 if (strstr(*header, "chunked"))
2464 csp->flags |= CSP_FLAG_CHUNKED;
2467 * If the body was modified, it has been de-chunked first
2468 * and the header must be removed.
2470 * FIXME: If there is more than one transfer encoding,
2471 * only the "chunked" part should be removed here.
2473 if (csp->flags & CSP_FLAG_MODIFIED)
2475 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2484 /*********************************************************************
2486 * Function : server_content_encoding
2488 * Description : Used to check if the content is compressed, and if
2489 * FEATURE_ZLIB is disabled, filtering is disabled as
2492 * If FEATURE_ZLIB is enabled and the compression type
2493 * supported, the content is marked for decompression.
2495 * XXX: Doesn't properly deal with multiple or with
2496 * unsupported but unknown encodings.
2497 * Is case-sensitive but shouldn't be.
2500 * 1 : csp = Current client state (buffers, headers, etc...)
2501 * 2 : header = On input, pointer to header to modify.
2502 * On output, pointer to the modified header, or NULL
2503 * to remove the header. This function frees the
2504 * original string if necessary.
2506 * Returns : JB_ERR_OK on success, or
2507 * JB_ERR_MEMORY on out-of-memory error.
2509 *********************************************************************/
2510 static jb_err server_content_encoding(struct client_state *csp, char **header)
2513 if (strstr(*header, "sdch"))
2516 * Shared Dictionary Compression over HTTP isn't supported,
2517 * filtering it anyway is pretty much guaranteed to mess up
2520 csp->content_type |= CT_TABOO;
2523 * Log a warning if the user expects the content to be filtered.
2525 if (content_filters_enabled(csp->action))
2527 log_error(LOG_LEVEL_INFO,
2528 "SDCH-compressed content detected, content filtering disabled. "
2529 "Consider suppressing SDCH offers made by the client.");
2532 else if (strstr(*header, "gzip"))
2534 /* Mark for gzip decompression */
2535 csp->content_type |= CT_GZIP;
2537 else if (strstr(*header, "deflate"))
2539 /* Mark for zlib decompression */
2540 csp->content_type |= CT_DEFLATE;
2542 else if (strstr(*header, "br"))
2544 #ifdef FEATURE_BROTLI
2545 /* Mark for Brotli decompression */
2546 csp->content_type |= CT_BROTLI;
2548 csp->content_type |= CT_TABOO;
2551 else if (strstr(*header, "compress"))
2554 * We can't decompress this; therefore we can't filter
2557 csp->content_type |= CT_TABOO;
2559 #else /* !defined(FEATURE_ZLIB) */
2561 * XXX: Using a black list here isn't the right approach.
2563 * In case of SDCH, building with zlib support isn't
2566 if (strstr(*header, "gzip") ||
2567 strstr(*header, "compress") ||
2568 strstr(*header, "deflate") ||
2569 strstr(*header, "sdch"))
2572 * Body is compressed, turn off pcrs and gif filtering.
2574 csp->content_type |= CT_TABOO;
2577 * Log a warning if the user expects the content to be filtered.
2579 if (content_filters_enabled(csp->action))
2581 log_error(LOG_LEVEL_INFO,
2582 "Compressed content detected, content filtering disabled. "
2583 "Consider recompiling Privoxy with zlib support or "
2584 "enable the prevent-compression action.");
2587 #endif /* defined(FEATURE_ZLIB) */
2595 /*********************************************************************
2597 * Function : server_adjust_content_encoding
2599 * Description : Remove the Content-Encoding header if the
2600 * decompression was successful and the content
2601 * has been modified.
2604 * 1 : csp = Current client state (buffers, headers, etc...)
2605 * 2 : header = On input, pointer to header to modify.
2606 * On output, pointer to the modified header, or NULL
2607 * to remove the header. This function frees the
2608 * original string if necessary.
2610 * Returns : JB_ERR_OK on success, or
2611 * JB_ERR_MEMORY on out-of-memory error.
2613 *********************************************************************/
2614 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2616 if ((csp->flags & CSP_FLAG_MODIFIED)
2617 && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2618 #ifdef FEATURE_BROTLI
2619 || (csp->content_type & CT_BROTLI)
2625 * We successfully decompressed the content,
2626 * and have to clean the header now, so the
2627 * client no longer expects compressed data.
2629 * XXX: There is a difference between cleaning
2630 * and removing it completely.
2632 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2639 #endif /* defined(FEATURE_ZLIB) */
2642 /*********************************************************************
2644 * Function : header_adjust_content_length
2646 * Description : Replace given header with new Content-Length header.
2649 * 1 : header = On input, pointer to header to modify.
2650 * On output, pointer to the modified header, or NULL
2651 * to remove the header. This function frees the
2652 * original string if necessary.
2653 * 2 : content_length = content length value to set
2655 * Returns : JB_ERR_OK on success, or
2656 * JB_ERR_MEMORY on out-of-memory error.
2658 *********************************************************************/
2659 jb_err header_adjust_content_length(char **header, size_t content_length)
2661 const size_t header_length = 50;
2663 *header = malloc(header_length);
2664 if (*header == NULL)
2666 return JB_ERR_MEMORY;
2668 create_content_length_header(content_length, *header, header_length);
2673 /*********************************************************************
2675 * Function : server_adjust_content_length
2677 * Description : Adjust Content-Length header if we modified
2681 * 1 : csp = Current client state (buffers, headers, etc...)
2682 * 2 : header = On input, pointer to header to modify.
2683 * On output, pointer to the modified header, or NULL
2684 * to remove the header. This function frees the
2685 * original string if necessary.
2687 * Returns : JB_ERR_OK on success, or
2688 * JB_ERR_MEMORY on out-of-memory error.
2690 *********************************************************************/
2691 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2693 /* Regenerate header if the content was modified. */
2694 if (csp->flags & CSP_FLAG_MODIFIED)
2696 if (JB_ERR_OK != header_adjust_content_length(header, csp->content_length))
2698 return JB_ERR_MEMORY;
2700 log_error(LOG_LEVEL_HEADER,
2701 "Adjusted Content-Length to %llu", csp->content_length);
2708 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2709 /*********************************************************************
2711 * Function : server_save_content_length
2713 * Description : Save the Content-Length sent by the server.
2716 * 1 : csp = Current client state (buffers, headers, etc...)
2717 * 2 : header = On input, pointer to header to modify.
2718 * On output, pointer to the modified header, or NULL
2719 * to remove the header. This function frees the
2720 * original string if necessary.
2722 * Returns : JB_ERR_OK on success, or
2723 * JB_ERR_MEMORY on out-of-memory error.
2725 *********************************************************************/
2726 static jb_err server_save_content_length(struct client_state *csp, char **header)
2728 unsigned long long content_length = 0;
2729 const char *header_value;
2731 assert(*(*header+14) == ':');
2733 header_value = *header + 15;
2734 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2736 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2741 csp->expected_content_length = content_length;
2742 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2743 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2748 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2751 /*********************************************************************
2753 * Function : server_content_md5
2755 * Description : Crumble any Content-MD5 headers if the document was
2756 * modified. FIXME: Should we re-compute instead?
2759 * 1 : csp = Current client state (buffers, headers, etc...)
2760 * 2 : header = On input, pointer to header to modify.
2761 * On output, pointer to the modified header, or NULL
2762 * to remove the header. This function frees the
2763 * original string if necessary.
2765 * Returns : JB_ERR_OK on success, or
2766 * JB_ERR_MEMORY on out-of-memory error.
2768 *********************************************************************/
2769 static jb_err server_content_md5(struct client_state *csp, char **header)
2771 if (csp->flags & CSP_FLAG_MODIFIED)
2773 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2781 /*********************************************************************
2783 * Function : server_content_disposition
2785 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2786 * Called from `sed'.
2789 * 1 : csp = Current client state (buffers, headers, etc...)
2790 * 2 : header = On input, pointer to header to modify.
2791 * On output, pointer to the modified header, or NULL
2792 * to remove the header. This function frees the
2793 * original string if necessary.
2795 * Returns : JB_ERR_OK on success, or
2796 * JB_ERR_MEMORY on out-of-memory error.
2798 *********************************************************************/
2799 static jb_err server_content_disposition(struct client_state *csp, char **header)
2804 * Are we messing with the Content-Disposition header?
2806 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2812 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2814 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2817 * Blocking content-disposition header
2819 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2826 * Replacing Content-Disposition header
2829 *header = strdup("Content-Disposition: ");
2830 string_append(header, newval);
2832 if (*header != NULL)
2834 log_error(LOG_LEVEL_HEADER,
2835 "Content-Disposition header crunched and replaced with: %s", *header);
2838 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2842 /*********************************************************************
2844 * Function : server_last_modified
2846 * Description : Changes Last-Modified header to the actual date
2847 * to help hide-if-modified-since.
2848 * Called from `sed'.
2851 * 1 : csp = Current client state (buffers, headers, etc...)
2852 * 2 : header = On input, pointer to header to modify.
2853 * On output, pointer to the modified header, or NULL
2854 * to remove the header. This function frees the
2855 * original string if necessary.
2857 * Returns : JB_ERR_OK on success, or
2858 * JB_ERR_MEMORY on out-of-memory error.
2860 *********************************************************************/
2861 static jb_err server_last_modified(struct client_state *csp, char **header)
2864 time_t last_modified;
2868 * Are we messing with the Last-Modified header?
2870 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2876 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2878 if (0 == strcmpic(newval, "block"))
2881 * Blocking Last-Modified header. Useless but why not.
2883 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2887 else if (0 == strcmpic(newval, "reset-to-request-time"))
2890 * Setting Last-Modified Header to now.
2893 get_http_time(0, buf, sizeof(buf));
2895 *header = strdup("Last-Modified: ");
2896 string_append(header, buf);
2898 if (*header == NULL)
2900 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2904 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2907 else if (0 == strcmpic(newval, "randomize"))
2909 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2911 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2913 log_error(LOG_LEVEL_HEADER,
2914 "Couldn't parse time in %s (crunching!)", *header);
2920 struct tm *timeptr = NULL;
2925 rtime = (long int)difftime(now, last_modified);
2928 long int days, hours, minutes, seconds;
2929 const int negative_delta = (rtime < 0);
2934 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2936 rtime = pick_from_range(rtime);
2941 last_modified += rtime;
2942 timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2943 if ((NULL == timeptr) || !strftime(newheader,
2944 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2946 log_error(LOG_LEVEL_ERROR,
2947 "Randomizing '%s' failed. Crunching the header without replacement.",
2953 *header = strdup("Last-Modified: ");
2954 string_append(header, newheader);
2956 if (*header == NULL)
2958 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2959 return JB_ERR_MEMORY;
2962 days = rtime / (3600 * 24);
2963 hours = rtime / 3600 % 24;
2964 minutes = rtime / 60 % 60;
2965 seconds = rtime % 60;
2967 log_error(LOG_LEVEL_HEADER,
2968 "Randomized: %s (added %ld da%s %ld hou%s %ld minut%s %ld second%s",
2969 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2970 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2974 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2983 /*********************************************************************
2985 * Function : client_accept_encoding
2987 * Description : Rewrite the client's Accept-Encoding header so that
2988 * if doesn't allow compression, if the action applies.
2989 * Note: For HTTP/1.0 the absence of the header is enough.
2992 * 1 : csp = Current client state (buffers, headers, etc...)
2993 * 2 : header = On input, pointer to header to modify.
2994 * On output, pointer to the modified header, or NULL
2995 * to remove the header. This function frees the
2996 * original string if necessary.
2998 * Returns : JB_ERR_OK on success, or
2999 * JB_ERR_MEMORY on out-of-memory error.
3001 *********************************************************************/
3002 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3004 #ifdef FEATURE_COMPRESSION
3005 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
3006 && strstr(*header, "deflate"))
3008 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
3011 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3013 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3021 /*********************************************************************
3023 * Function : client_te
3025 * Description : Rewrite the client's TE header so that
3026 * if doesn't allow compression, if the action applies.
3029 * 1 : csp = Current client state (buffers, headers, etc...)
3030 * 2 : header = On input, pointer to header to modify.
3031 * On output, pointer to the modified header, or NULL
3032 * to remove the header. This function frees the
3033 * original string if necessary.
3035 * Returns : JB_ERR_OK on success, or
3036 * JB_ERR_MEMORY on out-of-memory error.
3038 *********************************************************************/
3039 static jb_err client_te(struct client_state *csp, char **header)
3041 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3044 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3051 /*********************************************************************
3053 * Function : client_referrer
3055 * Description : Handle the "referer" config setting properly.
3056 * Called from `sed'.
3059 * 1 : csp = Current client state (buffers, headers, etc...)
3060 * 2 : header = On input, pointer to header to modify.
3061 * On output, pointer to the modified header, or NULL
3062 * to remove the header. This function frees the
3063 * original string if necessary.
3065 * Returns : JB_ERR_OK on success, or
3066 * JB_ERR_MEMORY on out-of-memory error.
3068 *********************************************************************/
3069 static jb_err client_referrer(struct client_state *csp, char **header)
3071 const char *parameter;
3072 /* booleans for parameters we have to check multiple times */
3073 int parameter_conditional_block;
3074 int parameter_conditional_forge;
3076 #ifdef FEATURE_FORCE_LOAD
3078 * Since the referrer can include the prefix even
3079 * if the request itself is non-forced, we must
3080 * clean it unconditionally.
3082 * XXX: strclean is too broad
3084 strclean(*header, FORCE_PREFIX);
3085 #endif /* def FEATURE_FORCE_LOAD */
3087 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3089 /* Nothing left to do */
3093 parameter = csp->action->string[ACTION_STRING_REFERER];
3094 assert(parameter != NULL);
3095 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3096 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3098 if (!parameter_conditional_block && !parameter_conditional_forge)
3101 * As conditional-block and conditional-forge are the only
3102 * parameters that rely on the original referrer, we can
3103 * remove it now for all the others.
3108 if (0 == strcmpic(parameter, "block"))
3110 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3113 else if (parameter_conditional_block || parameter_conditional_forge)
3115 return handle_conditional_hide_referrer_parameter(header,
3116 csp->http->hostport, parameter_conditional_block);
3118 else if (0 == strcmpic(parameter, "forge"))
3120 return create_forged_referrer(header, csp->http->hostport);
3124 /* interpret parameter as user-supplied referer to fake */
3125 return create_fake_referrer(header, parameter);
3130 /*********************************************************************
3132 * Function : client_accept_language
3134 * Description : Handle the "Accept-Language" config setting properly.
3135 * Called from `sed'.
3138 * 1 : csp = Current client state (buffers, headers, etc...)
3139 * 2 : header = On input, pointer to header to modify.
3140 * On output, pointer to the modified header, or NULL
3141 * to remove the header. This function frees the
3142 * original string if necessary.
3144 * Returns : JB_ERR_OK on success, or
3145 * JB_ERR_MEMORY on out-of-memory error.
3147 *********************************************************************/
3148 static jb_err client_accept_language(struct client_state *csp, char **header)
3153 * Are we messing with the Accept-Language?
3155 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3157 /*I don't think so*/
3161 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3163 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3166 * Blocking Accept-Language header
3168 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3175 * Replacing Accept-Language header
3178 *header = strdup("Accept-Language: ");
3179 string_append(header, newval);
3181 if (*header == NULL)
3183 log_error(LOG_LEVEL_ERROR,
3184 "Insufficient memory. Accept-Language header crunched without replacement.");
3188 log_error(LOG_LEVEL_HEADER,
3189 "Accept-Language header crunched and replaced with: %s", *header);
3192 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3196 /*********************************************************************
3198 * Function : crunch_client_header
3200 * Description : Crunch client header if it matches a string supplied by the
3201 * user. Called from `sed'.
3204 * 1 : csp = Current client state (buffers, headers, etc...)
3205 * 2 : header = On input, pointer to header to modify.
3206 * On output, pointer to the modified header, or NULL
3207 * to remove the header. This function frees the
3208 * original string if necessary.
3210 * Returns : JB_ERR_OK on success and always succeeds
3212 *********************************************************************/
3213 static jb_err crunch_client_header(struct client_state *csp, char **header)
3215 const char *crunch_pattern;
3217 /* Do we feel like crunching? */
3218 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3220 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3222 /* Is the current header the lucky one? */
3223 if (strstr(*header, crunch_pattern))
3225 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3233 /*********************************************************************
3235 * Function : client_uagent
3237 * Description : Handle the "user-agent" config setting properly
3238 * and remember its original value to enable browser
3239 * bug workarounds. Called from `sed'.
3242 * 1 : csp = Current client state (buffers, headers, etc...)
3243 * 2 : header = On input, pointer to header to modify.
3244 * On output, pointer to the modified header, or NULL
3245 * to remove the header. This function frees the
3246 * original string if necessary.
3248 * Returns : JB_ERR_OK on success, or
3249 * JB_ERR_MEMORY on out-of-memory error.
3251 *********************************************************************/
3252 static jb_err client_uagent(struct client_state *csp, char **header)
3256 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3261 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3268 *header = strdup("User-Agent: ");
3269 string_append(header, newval);
3271 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3273 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3277 /*********************************************************************
3279 * Function : client_ua
3281 * Description : Handle "ua-" headers properly. Called from `sed'.
3284 * 1 : csp = Current client state (buffers, headers, etc...)
3285 * 2 : header = On input, pointer to header to modify.
3286 * On output, pointer to the modified header, or NULL
3287 * to remove the header. This function frees the
3288 * original string if necessary.
3290 * Returns : JB_ERR_OK on success, or
3291 * JB_ERR_MEMORY on out-of-memory error.
3293 *********************************************************************/
3294 static jb_err client_ua(struct client_state *csp, char **header)
3296 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3298 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3306 /*********************************************************************
3308 * Function : client_from
3310 * Description : Handle the "from" config setting properly.
3311 * Called from `sed'.
3314 * 1 : csp = Current client state (buffers, headers, etc...)
3315 * 2 : header = On input, pointer to header to modify.
3316 * On output, pointer to the modified header, or NULL
3317 * to remove the header. This function frees the
3318 * original string if necessary.
3320 * Returns : JB_ERR_OK on success, or
3321 * JB_ERR_MEMORY on out-of-memory error.
3323 *********************************************************************/
3324 static jb_err client_from(struct client_state *csp, char **header)
3328 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3335 newval = csp->action->string[ACTION_STRING_FROM];
3338 * Are we blocking the e-mail address?
3340 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3342 log_error(LOG_LEVEL_HEADER, "crunched From!");
3346 log_error(LOG_LEVEL_HEADER, " modified");
3348 *header = strdup("From: ");
3349 string_append(header, newval);
3351 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3355 /*********************************************************************
3357 * Function : client_send_cookie
3359 * Description : Crunches the "cookie" header if necessary.
3360 * Called from `sed'.
3362 * XXX: Stupid name, doesn't send squat.
3365 * 1 : csp = Current client state (buffers, headers, etc...)
3366 * 2 : header = On input, pointer to header to modify.
3367 * On output, pointer to the modified header, or NULL
3368 * to remove the header. This function frees the
3369 * original string if necessary.
3371 * Returns : JB_ERR_OK on success, or
3372 * JB_ERR_MEMORY on out-of-memory error.
3374 *********************************************************************/
3375 static jb_err client_send_cookie(struct client_state *csp, char **header)
3377 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3379 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3387 /*********************************************************************
3389 * Function : client_x_forwarded
3391 * Description : Handle the "x-forwarded-for" config setting properly,
3392 * also used in the add_client_headers list. Called from `sed'.
3395 * 1 : csp = Current client state (buffers, headers, etc...)
3396 * 2 : header = On input, pointer to header to modify.
3397 * On output, pointer to the modified header, or NULL
3398 * to remove the header. This function frees the
3399 * original string if necessary.
3401 * Returns : JB_ERR_OK on success, or
3402 * JB_ERR_MEMORY on out-of-memory error.
3404 *********************************************************************/
3405 jb_err client_x_forwarded(struct client_state *csp, char **header)
3407 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3409 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3411 if (0 == strcmpic(parameter, "block"))
3414 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3416 else if (0 == strcmpic(parameter, "add"))
3418 string_append(header, ", ");
3419 string_append(header, csp->ip_addr_str);
3421 if (*header == NULL)
3423 return JB_ERR_MEMORY;
3425 log_error(LOG_LEVEL_HEADER,
3426 "Appended client IP address to %s", *header);
3427 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3431 log_error(LOG_LEVEL_FATAL,
3432 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3440 /*********************************************************************
3442 * Function : client_max_forwards
3444 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3445 * from the value of the Max-Forwards header field.
3448 * 1 : csp = Current client state (buffers, headers, etc...)
3449 * 2 : header = On input, pointer to header to modify.
3450 * On output, pointer to the modified header, or NULL
3451 * to remove the header. This function frees the
3452 * original string if necessary.
3454 * Returns : JB_ERR_OK on success, or
3455 * JB_ERR_MEMORY on out-of-memory error.
3457 *********************************************************************/
3458 static jb_err client_max_forwards(struct client_state *csp, char **header)
3462 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3463 (0 == strcmpic(csp->http->gpc, "options")))
3465 assert(*(*header+12) == ':');
3466 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3468 if (max_forwards > 0)
3470 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3471 log_error(LOG_LEVEL_HEADER,
3472 "Max-Forwards value for %s request reduced to %d.",
3473 csp->http->gpc, max_forwards);
3475 else if (max_forwards < 0)
3477 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3483 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3492 /*********************************************************************
3494 * Function : client_host
3496 * Description : If the request URI did not contain host and
3497 * port information, parse and evaluate the Host
3501 * 1 : csp = Current client state (buffers, headers, etc...)
3502 * 2 : header = On input, pointer to header to modify.
3503 * On output, pointer to the modified header, or NULL
3504 * to remove the header. This function frees the
3505 * original string if necessary.
3507 * Returns : JB_ERR_OK on success, or
3508 * JB_ERR_MEMORY on out-of-memory error.
3510 *********************************************************************/
3511 static jb_err client_host(struct client_state *csp, char **header)
3515 if (strlen(*header) < 7)
3517 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3522 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3523 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3526 p = strdup_or_die((*header)+6);
3528 q = strdup_or_die(p);
3530 freez(csp->http->hostport);
3531 csp->http->hostport = p;
3532 freez(csp->http->host);
3533 csp->http->host = q;
3534 q = strchr(csp->http->host, ':');
3537 /* Terminate hostname and evaluate port string */
3539 csp->http->port = atoi(q);
3543 csp->http->port = csp->http->ssl ? 443 : 80;
3546 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3547 csp->http->hostport, csp->http->host, csp->http->port);
3550 /* Signal client_host_adder() to return right away */
3551 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3557 /*********************************************************************
3559 * Function : client_if_modified_since
3561 * Description : Remove or modify the If-Modified-Since header.
3564 * 1 : csp = Current client state (buffers, headers, etc...)
3565 * 2 : header = On input, pointer to header to modify.
3566 * On output, pointer to the modified header, or NULL
3567 * to remove the header. This function frees the
3568 * original string if necessary.
3570 * Returns : JB_ERR_OK on success, or
3571 * JB_ERR_MEMORY on out-of-memory error.
3573 *********************************************************************/
3574 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3578 struct tm *timeptr = NULL;
3583 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3586 * The client got an error message because of a temporary problem,
3587 * the problem is gone and the client now tries to revalidate our
3588 * error message on the real server. The revalidation would always
3589 * end with the transmission of the whole document and there is
3590 * no need to expose the bogus If-Modified-Since header.
3592 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3595 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3597 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3599 if ((0 == strcmpic(newval, "block")))
3601 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3604 else /* add random value */
3606 if (JB_ERR_OK != parse_time_header(*header, &tm))
3608 log_error(LOG_LEVEL_HEADER,
3609 "Couldn't parse time in %s (crunching!)", *header);
3614 long int hours, minutes, seconds;
3615 long int rtime = strtol(newval, &endptr, 0);
3616 const int negative_range = (rtime < 0);
3620 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %ld minut%s)",
3621 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3627 rtime = pick_from_range(rtime);
3631 log_error(LOG_LEVEL_ERROR,
3632 "Random range is 0. Assuming time transformation test.");
3634 tm += rtime * (negative_range ? -1 : 1);
3635 timeptr = privoxy_gmtime_r(&tm, &gmt);
3636 if ((NULL == timeptr) || !strftime(newheader,
3637 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3639 log_error(LOG_LEVEL_ERROR,
3640 "Randomizing '%s' failed. Crunching the header without replacement.",
3646 *header = strdup("If-Modified-Since: ");
3647 string_append(header, newheader);
3649 if (*header == NULL)
3651 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3652 return JB_ERR_MEMORY;
3655 hours = rtime / 3600;
3656 minutes = rtime / 60 % 60;
3657 seconds = rtime % 60;
3659 log_error(LOG_LEVEL_HEADER,
3660 "Randomized: %s (%s %ld hou%s %ld minut%s %ld second%s",
3661 *header, (negative_range) ? "subtracted" : "added", hours,
3662 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3663 seconds, (seconds == 1) ? ")" : "s)");
3672 /*********************************************************************
3674 * Function : client_if_none_match
3676 * Description : Remove the If-None-Match header.
3679 * 1 : csp = Current client state (buffers, headers, etc...)
3680 * 2 : header = On input, pointer to header to modify.
3681 * On output, pointer to the modified header, or NULL
3682 * to remove the header. This function frees the
3683 * original string if necessary.
3685 * Returns : JB_ERR_OK on success, or
3686 * JB_ERR_MEMORY on out-of-memory error.
3688 *********************************************************************/
3689 static jb_err client_if_none_match(struct client_state *csp, char **header)
3691 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3693 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3701 /*********************************************************************
3703 * Function : client_x_filter
3705 * Description : Disables filtering if the client set "X-Filter: No".
3706 * Called from `sed'.
3709 * 1 : csp = Current client state (buffers, headers, etc...)
3710 * 2 : header = On input, pointer to header to modify.
3711 * On output, pointer to the modified header, or NULL
3712 * to remove the header. This function frees the
3713 * original string if necessary.
3715 * Returns : JB_ERR_OK on success
3717 *********************************************************************/
3718 jb_err client_x_filter(struct client_state *csp, char **header)
3720 if (0 == strcmpic(*header, "X-Filter: No"))
3722 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3724 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3728 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3730 log_error(LOG_LEVEL_HEADER,
3731 "force-text-mode overruled the client's request to fetch without filtering!");
3735 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3736 csp->flags |= CSP_FLAG_NO_FILTERING;
3737 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3739 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3747 /*********************************************************************
3749 * Function : client_range
3751 * Description : Removes Range, Request-Range and If-Range headers if
3752 * content filtering is enabled and the range doesn't
3755 * If the client's version of the document has been
3756 * altered by Privoxy, the server could interpret the
3757 * range differently than the client intended in which
3758 * case the user could end up with corrupted content.
3760 * If the range starts at byte 0 this isn't an issue
3761 * so the header can pass. Partial requests like this
3762 * are used to render preview images for videos without
3763 * downloading the whole video.
3765 * While HTTP doesn't require that range requests are
3766 * honoured and the client could simply abort the download
3767 * after receiving a sufficient amount of data, various
3768 * clients don't handle complete responses to range
3769 * requests gracefully and emit misleading error messages
3773 * 1 : csp = Current client state (buffers, headers, etc...)
3774 * 2 : header = On input, pointer to header to modify.
3775 * On output, pointer to the modified header, or NULL
3776 * to remove the header. This function frees the
3777 * original string if necessary.
3779 * Returns : JB_ERR_OK
3781 *********************************************************************/
3782 static jb_err client_range(struct client_state *csp, char **header)
3784 if (content_filters_enabled(csp->action)
3785 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3787 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3788 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3795 /* the following functions add headers directly to the header list */
3797 /*********************************************************************
3799 * Function : client_host_adder
3801 * Description : Adds the Host: header field if it is missing.
3802 * Called from `sed'.
3805 * 1 : csp = Current client state (buffers, headers, etc...)
3807 * Returns : JB_ERR_OK on success, or
3808 * JB_ERR_MEMORY on out-of-memory error.
3810 *********************************************************************/
3811 static jb_err client_host_adder(struct client_state *csp)
3816 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3818 /* Header already set by the client, nothing to do. */
3822 if (!csp->http->hostport || !*(csp->http->hostport))
3824 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3825 return JB_ERR_PARSE;
3829 * remove 'user:pass@' from 'proto://user:pass@host'
3831 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3837 p = csp->http->hostport;
3840 /* XXX: Just add it, we already made sure that it will be unique */
3841 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3842 err = enlist_unique_header(csp->headers, "Host", p);
3848 /*********************************************************************
3850 * Function : client_xtra_adder
3852 * Description : Used in the add_client_headers list. Called from `sed'.
3855 * 1 : csp = Current client state (buffers, headers, etc...)
3857 * Returns : JB_ERR_OK on success, or
3858 * JB_ERR_MEMORY on out-of-memory error.
3860 *********************************************************************/
3861 static jb_err client_xtra_adder(struct client_state *csp)
3863 struct list_entry *lst;
3866 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3867 lst ; lst = lst->next)
3869 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3870 err = enlist(csp->headers, lst->str);
3882 /*********************************************************************
3884 * Function : client_x_forwarded_for_adder
3886 * Description : Used in the add_client_headers list. Called from `sed'.
3889 * 1 : csp = Current client state (buffers, headers, etc...)
3891 * Returns : JB_ERR_OK on success, or
3892 * JB_ERR_MEMORY on out-of-memory error.
3894 *********************************************************************/
3895 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3897 char *header = NULL;
3900 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3901 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3902 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3905 * If we aren't adding X-Forwarded-For headers,
3906 * or we already appended an existing X-Forwarded-For
3907 * header, there's nothing left to do here.
3912 header = strdup("X-Forwarded-For: ");
3913 string_append(&header, csp->ip_addr_str);
3917 return JB_ERR_MEMORY;
3920 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3921 err = enlist(csp->headers, header);
3928 /*********************************************************************
3930 * Function : server_connection_adder
3932 * Description : Adds an appropriate "Connection:" header to csp->headers
3933 * unless the header was already present. Called from `sed'.
3936 * 1 : csp = Current client state (buffers, headers, etc...)
3938 * Returns : JB_ERR_OK on success, or
3939 * JB_ERR_MEMORY on out-of-memory error.
3941 *********************************************************************/
3942 static jb_err server_connection_adder(struct client_state *csp)
3944 const unsigned int flags = csp->flags;
3945 const char *response_status_line = csp->headers->first->str;
3946 static const char connection_close[] = "Connection: close";
3948 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3949 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3955 * XXX: if we downgraded the response, this check will fail.
3957 if ((csp->config->feature_flags &
3958 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3959 && (NULL != response_status_line)
3960 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3961 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3962 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3966 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3967 "without Connection header implies keep-alive.");
3968 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3972 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3974 return enlist(csp->headers, connection_close);
3978 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3979 /*********************************************************************
3981 * Function : server_proxy_connection_adder
3983 * Description : Adds a "Proxy-Connection: keep-alive" header to
3984 * csp->headers when appropriate.
3987 * 1 : csp = Current client state (buffers, headers, etc...)
3989 * Returns : JB_ERR_OK on success, or
3990 * JB_ERR_MEMORY on out-of-memory error.
3992 *********************************************************************/
3993 static jb_err server_proxy_connection_adder(struct client_state *csp)
3995 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3996 jb_err err = JB_ERR_OK;
3998 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3999 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4000 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
4001 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4002 || (csp->flags & CSP_FLAG_CHUNKED))
4003 #ifdef FEATURE_HTTPS_INSPECTION
4004 && !client_use_ssl(csp)
4009 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
4010 err = enlist(csp->headers, proxy_connection_header);
4015 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4018 /*********************************************************************
4020 * Function : client_connection_header_adder
4022 * Description : Adds a proper "Connection:" header to csp->headers
4023 * unless the header was already present or it's a
4024 * CONNECT request. Called from `sed'.
4027 * 1 : csp = Current client state (buffers, headers, etc...)
4029 * Returns : JB_ERR_OK on success, or
4030 * JB_ERR_MEMORY on out-of-memory error.
4032 *********************************************************************/
4033 static jb_err client_connection_header_adder(struct client_state *csp)
4035 static const char connection_close[] = "Connection: close";
4037 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4038 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4044 * In case of CONNECT requests "Connection: close" is implied,
4045 * but actually setting the header has been reported to cause
4046 * problems with some forwarding proxies that close the
4047 * connection prematurely.
4049 if (csp->http->ssl != 0)
4054 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4055 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4056 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4057 && !strcmpic(csp->http->version, "HTTP/1.1"))
4059 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4062 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4064 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4066 return enlist(csp->headers, connection_close);
4070 /*********************************************************************
4072 * Function : server_http
4074 * Description : - Save the HTTP Status into csp->http->status
4075 * - Set CT_TABOO to prevent filtering if the answer
4076 * is a partial range (HTTP status 206)
4077 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4079 * - Normalize the HTTP-version.
4082 * 1 : csp = Current client state (buffers, headers, etc...)
4083 * 2 : header = On input, pointer to header to modify.
4084 * On output, pointer to the modified header, or NULL
4085 * to remove the header. This function frees the
4086 * original string if necessary.
4088 * Returns : JB_ERR_OK on success, or
4089 * JB_ERR_PARSE on fatal parse errors.
4091 *********************************************************************/
4092 static jb_err server_http(struct client_state *csp, char **header)
4094 char *reason_phrase = NULL;
4095 char *new_response_line;
4098 unsigned int major_version;
4099 unsigned int minor_version;
4101 /* Get the reason phrase which start after the second whitespace */
4102 p = strchr(*header, ' ');
4106 reason_phrase = strchr(p, ' ');
4109 if (reason_phrase != NULL)
4115 log_error(LOG_LEVEL_ERROR,
4116 "Response line lacks reason phrase: %s", *header);
4120 if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4121 &minor_version, &(csp->http->status)))
4123 log_error(LOG_LEVEL_ERROR,
4124 "Failed to parse the response line: %s", *header);
4125 return JB_ERR_PARSE;
4128 if (csp->http->status == 101 ||
4129 csp->http->status == 206)
4131 csp->content_type = CT_TABOO;
4134 if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4137 * According to RFC 7230 2.6 intermediaries MUST send
4138 * their own HTTP-version in forwarded messages.
4140 log_error(LOG_LEVEL_ERROR,
4141 "Unsupported HTTP version. Downgrading to 1.1.");
4146 if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4148 log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4152 /* Rebuild response line. */
4153 length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4154 new_response_line = malloc_or_die(length);
4156 snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4157 major_version, minor_version, csp->http->status, reason_phrase);
4159 if (0 != strcmp(*header, new_response_line))
4161 log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4162 *header, new_response_line);
4166 *header = new_response_line;
4171 /*********************************************************************
4173 * Function : add_cooky_expiry_date
4175 * Description : Adds a cookie expiry date to a string.
4178 * 1 : cookie = On input, pointer to cookie to modify.
4179 * On output, pointer to the modified header.
4180 * The original string is freed.
4181 * 2 : lifetime = Seconds the cookie should be valid
4185 *********************************************************************/
4186 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4189 struct tm *timeptr = NULL;
4190 time_t expiry_date = time(NULL) + lifetime;
4193 timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4194 if (NULL == timeptr)
4196 log_error(LOG_LEVEL_FATAL,
4197 "Failed to get the time in add_cooky_expiry_date()");
4199 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4200 if (JB_ERR_OK != string_append(cookie, tmp))
4202 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4207 /*********************************************************************
4209 * Function : server_set_cookie
4211 * Description : Handle the server "cookie" header properly.
4212 * Crunch, accept or rewrite it to a session cookie.
4213 * Called from `sed'.
4216 * 1 : csp = Current client state (buffers, headers, etc...)
4217 * 2 : header = On input, pointer to header to modify.
4218 * On output, pointer to the modified header, or NULL
4219 * to remove the header. This function frees the
4220 * original string if necessary.
4222 * Returns : JB_ERR_OK on success, or
4223 * JB_ERR_MEMORY on out-of-memory error.
4225 *********************************************************************/
4226 static jb_err server_set_cookie(struct client_state *csp, char **header)
4228 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4230 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4233 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4234 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4238 long cookie_lifetime = 0;
4241 NO_EXPIRY_DATE_SPECIFIED,
4242 EXPIRY_DATE_ACCEPTABLE,
4243 EXPIRY_DATE_UNACCEPTABLE
4244 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4246 /* A variable to store the tag we're working on */
4249 /* Skip "Set-Cookie:" (11 characters) in header */
4250 cur_tag = *header + 11;
4252 /* skip whitespace between "Set-Cookie:" and value */
4253 while (*cur_tag && privoxy_isspace(*cur_tag))
4260 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4262 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4264 cookie_lifetime = strtol(param, NULL, 0);
4265 if (cookie_lifetime < 0)
4267 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4269 cookie_lifetime *= 60;
4272 /* Loop through each tag in the cookie */
4276 char *next_tag = strchr(cur_tag, ';');
4277 if (next_tag != NULL)
4279 /* Skip the ';' character itself */
4282 /* skip whitespace ";" and start of tag */
4283 while (*next_tag && privoxy_isspace(*next_tag))
4290 /* "Next tag" is the end of the string */
4291 next_tag = cur_tag + strlen(cur_tag);
4295 * Check the expiration date to see
4296 * if the cookie is still valid, if yes,
4297 * rewrite it to a session cookie.
4299 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4301 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4303 if ((expiration_date[0] == '"')
4304 && (expiration_date[1] != '\0'))
4307 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4308 * that the expiration date isn't supposed to be quoted,
4309 * but some servers do it anyway.
4314 /* Did we detect the date properly? */
4315 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4318 * Nope, treat it as if it was still valid.
4320 * XXX: Should we remove the whole cookie instead?
4322 log_error(LOG_LEVEL_ERROR,
4323 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4324 string_move(cur_tag, next_tag);
4325 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4330 * Yes. Check if the cookie is still valid.
4332 * If the cookie is already expired it's probably
4333 * a delete cookie and even if it isn't, the browser
4334 * will discard it anyway.
4338 * XXX: timegm() isn't available on some AmigaOS
4339 * versions and our replacement doesn't work.
4341 * Our options are to either:
4343 * - disable session-cookies-only completely if timegm
4346 * - to simply remove all expired tags, like it has
4347 * been done until Privoxy 3.0.6 and to live with
4348 * the consequence that it can cause login/logout
4349 * problems on servers that don't validate their
4350 * input properly, or
4352 * - to replace it with mktime in which
4353 * case there is a slight chance of valid cookies
4354 * passing as already expired.
4356 * This is the way it's currently done and it's not
4357 * as bad as it sounds. If the missing GMT offset is
4358 * enough to change the result of the expiration check
4359 * the cookie will be only valid for a few hours
4360 * anyway, which in many cases will be shorter
4361 * than a browser session.
4363 if (cookie_time < now)
4365 log_error(LOG_LEVEL_HEADER,
4366 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4367 /* Just in case some clown sets more then one expiration date */
4369 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4371 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4373 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4374 "Its lifetime is below the limit.", *header);
4375 /* Just in case some clown sets more then one expiration date */
4377 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4382 * Still valid, delete expiration date by copying
4383 * the rest of the string over it.
4385 string_move(cur_tag, next_tag);
4387 /* That changed the header, need to issue a log message */
4388 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4391 * Note that the next tag has now been moved to *cur_tag,
4392 * so we do not need to update the cur_tag pointer.
4400 /* Move on to next cookie tag */
4405 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4407 assert(NULL != *header);
4408 if (cookie_lifetime != 0)
4410 add_cookie_expiry_date(header, cookie_lifetime);
4411 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4413 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4415 log_error(LOG_LEVEL_HEADER,
4416 "Cookie rewritten to a temporary one: %s", *header);
4425 #ifdef FEATURE_FORCE_LOAD
4426 /*********************************************************************
4428 * Function : strclean
4430 * Description : In-Situ-Eliminate all occurrences of substring in
4434 * 1 : string = string to clean
4435 * 2 : substring = substring to eliminate
4437 * Returns : Number of eliminations
4439 *********************************************************************/
4440 int strclean(char *string, const char *substring)
4446 len = strlen(substring);
4448 while((pos = strstr(string, substring)) != NULL)
4455 while (*p++ != '\0');
4462 #endif /* def FEATURE_FORCE_LOAD */
4465 /*********************************************************************
4467 * Function : parse_header_time
4469 * Description : Parses time formats used in HTTP header strings
4470 * to get the numerical respresentation.
4473 * 1 : header_time = HTTP header time as string.
4474 * 2 : result = storage for header_time in seconds
4476 * Returns : JB_ERR_OK if the time format was recognized, or
4477 * JB_ERR_PARSE otherwise.
4479 *********************************************************************/
4480 static jb_err parse_header_time(const char *header_time, time_t *result)
4484 * Checking for two-digit years first in an
4485 * attempt to work around GNU libc's strptime()
4486 * reporting negative year values when using %Y.
4488 static const char time_formats[][22] = {
4489 /* Tue, 02-Jun-37 20:00:00 */
4490 "%a, %d-%b-%y %H:%M:%S",
4491 /* Tue, 02 Jun 2037 20:00:00 */
4492 "%a, %d %b %Y %H:%M:%S",
4493 /* Tue, 02-Jun-2037 20:00:00 */
4494 "%a, %d-%b-%Y %H:%M:%S",
4495 /* Tuesday, 02-Jun-2037 20:00:00 */
4496 "%A, %d-%b-%Y %H:%M:%S",
4497 /* Tuesday Jun 02 20:00:00 2037 */
4498 "%A %b %d %H:%M:%S %Y"
4502 for (i = 0; i < SZ(time_formats); i++)
4505 * Zero out gmt to prevent time zone offsets.
4506 * Documented to be required for GNU libc.
4508 memset(&gmt, 0, sizeof(gmt));
4510 if (NULL != strptime(header_time, time_formats[i], &gmt))
4512 /* Sanity check for GNU libc. */
4513 if (gmt.tm_year < 0)
4515 log_error(LOG_LEVEL_HEADER,
4516 "Failed to parse '%s' using '%s'. Moving on.",
4517 header_time, time_formats[i]);
4520 *result = timegm(&gmt);
4522 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4524 * Verify that parsing the date recreated from the first
4525 * parse operation gets the previous result. If it doesn't,
4526 * either strptime() or strftime() are malfunctioning.
4528 * We could string-compare the recreated date with the original
4529 * header date, but this leads to false positives as strptime()
4530 * may let %a accept all day formats while strftime() will only
4534 char recreated_date[100];
4539 tm = privoxy_gmtime_r(result, &storage);
4540 if (!strftime(recreated_date, sizeof(recreated_date),
4541 time_formats[i], tm))
4543 log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4544 header_time, time_formats[i]);
4547 memset(&gmt, 0, sizeof(gmt));
4548 if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4550 log_error(LOG_LEVEL_ERROR,
4551 "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4552 recreated_date, time_formats[i], header_time);
4555 result2 = timegm(&gmt);
4556 if (*result != result2)
4558 log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4559 "Format: '%s'. In: '%s', out: '%s'. %ld != %ld. Rejecting.",
4560 time_formats[i], header_time, recreated_date, *result, result2);
4570 return JB_ERR_PARSE;
4574 /*********************************************************************
4576 * Function : parse_time_header
4578 * Description : Parses the time in an HTTP time header to get
4579 * the numerical respresentation.
4582 * 1 : header = HTTP header with a time value
4583 * 2 : result = storage for header_time in seconds
4585 * Returns : JB_ERR_OK if the time format was recognized, or
4586 * JB_ERR_PARSE otherwise.
4588 *********************************************************************/
4589 static jb_err parse_time_header(const char *header, time_t *result)
4591 const char *header_time;
4593 header_time = strchr(header, ':');
4596 * Currently this can't happen as all callers are called
4597 * through sed() which requires a header name followed by
4600 assert(header_time != NULL);
4603 if (*header_time == ' ')
4608 return parse_header_time(header_time, result);
4613 /*********************************************************************
4615 * Function : get_destination_from_headers
4617 * Description : Parse the "Host:" header to get the request's destination.
4618 * Only needed if the client's request was forcefully
4619 * redirected into Privoxy.
4621 * Code mainly copied from client_host() which is currently
4622 * run too late for this purpose.
4625 * 1 : headers = List of headers (one of them hopefully being
4626 * the "Host:" header)
4627 * 2 : http = storage for the result (host, port and hostport).
4629 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4630 * JB_ERR_PARSE if the host header couldn't be found,
4631 * JB_ERR_OK otherwise.
4633 *********************************************************************/
4634 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4640 host = get_header_value(headers, "Host:");
4644 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4645 return JB_ERR_PARSE;
4648 p = string_tolower(host);
4651 return JB_ERR_MEMORY;
4654 q = strdup_or_die(p);
4656 freez(http->hostport);
4660 q = strchr(http->host, ':');
4663 /* Terminate hostname and evaluate port string */
4665 http->port = atoi(q);
4672 /* Rebuild request URL */
4674 http->url = strdup("http://");
4675 string_append(&http->url, http->hostport);
4676 string_append(&http->url, http->path);
4677 if (http->url == NULL)
4679 return JB_ERR_MEMORY;
4682 log_error(LOG_LEVEL_HEADER,
4683 "Destination extracted from \"Host\" header. New request URL: %s",
4687 * Regenerate request line in "proxy format"
4688 * to make rewrites more convenient.
4690 assert(http->cmd != NULL);
4692 http->cmd = strdup_or_die(http->gpc);
4693 string_append(&http->cmd, " ");
4694 string_append(&http->cmd, http->url);
4695 string_append(&http->cmd, " ");
4696 string_append(&http->cmd, http->version);
4697 if (http->cmd == NULL)
4699 return JB_ERR_MEMORY;
4707 #ifdef FEATURE_HTTPS_INSPECTION
4708 /*********************************************************************
4710 * Function : get_destination_from_https_headers
4712 * Description : Parse the previously encrypted "Host:" header to
4713 * get the request's destination.
4716 * 1 : headers = List of headers (one of them hopefully being
4717 * the "Host:" header)
4718 * 2 : http = storage for the result (host, port and hostport).
4720 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4721 * JB_ERR_PARSE if the host header couldn't be found,
4722 * JB_ERR_OK otherwise.
4724 *********************************************************************/
4725 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4731 host = get_header_value(headers, "Host:");
4735 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4736 return JB_ERR_PARSE;
4739 p = string_tolower(host);
4742 return JB_ERR_MEMORY;
4745 q = strdup_or_die(p);
4747 freez(http->hostport);
4751 q = strchr(http->host, ':');
4754 /* Terminate hostname and evaluate port string */
4756 http->port = atoi(q);
4763 /* Rebuild request URL */
4765 http->url = strdup_or_die(http->path);
4767 log_error(LOG_LEVEL_HEADER,
4768 "Destination extracted from \"Host\" header. New request URL: %s",
4772 * Regenerate request line in "proxy format"
4773 * to make rewrites more convenient.
4775 assert(http->cmd != NULL);
4777 http->cmd = strdup_or_die(http->gpc);
4778 string_append(&http->cmd, " ");
4779 string_append(&http->cmd, http->url);
4780 string_append(&http->cmd, " ");
4781 string_append(&http->cmd, http->version);
4782 if (http->cmd == NULL)
4784 return JB_ERR_MEMORY;
4790 #endif /* def FEATURE_HTTPS_INSPECTION */
4793 /*********************************************************************
4795 * Function : create_forged_referrer
4797 * Description : Helper for client_referrer to forge a referer as
4798 * 'http://hostname[:port]/' to fool stupid
4799 * checks for in-site links
4802 * 1 : header = Pointer to header pointer
4803 * 2 : hostport = Host and optionally port as string
4805 * Returns : JB_ERR_OK in case of success, or
4806 * JB_ERR_MEMORY in case of memory problems.
4808 *********************************************************************/
4809 static jb_err create_forged_referrer(char **header, const char *hostport)
4811 assert(NULL == *header);
4813 *header = strdup("Referer: http://");
4814 string_append(header, hostport);
4815 string_append(header, "/");
4817 if (NULL == *header)
4819 return JB_ERR_MEMORY;
4822 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4829 /*********************************************************************
4831 * Function : create_fake_referrer
4833 * Description : Helper for client_referrer to create a fake referrer
4834 * based on a string supplied by the user.
4837 * 1 : header = Pointer to header pointer
4838 * 2 : hosthost = Referrer to fake
4840 * Returns : JB_ERR_OK in case of success, or
4841 * JB_ERR_MEMORY in case of memory problems.
4843 *********************************************************************/
4844 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4846 assert(NULL == *header);
4848 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4850 log_error(LOG_LEVEL_HEADER,
4851 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4853 *header = strdup("Referer: ");
4854 string_append(header, fake_referrer);
4856 if (NULL == *header)
4858 return JB_ERR_MEMORY;
4861 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4868 /*********************************************************************
4870 * Function : handle_conditional_hide_referrer_parameter
4872 * Description : Helper for client_referrer to crunch or forge
4873 * the referrer header if the host has changed.
4876 * 1 : header = Pointer to header pointer
4877 * 2 : host = The target host (may include the port)
4878 * 3 : parameter_conditional_block = Boolean to signal
4879 * if we're in conditional-block mode. If not set,
4880 * we're in conditional-forge mode.
4882 * Returns : JB_ERR_OK in case of success, or
4883 * JB_ERR_MEMORY in case of memory problems.
4885 *********************************************************************/
4886 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4887 const char *host, const int parameter_conditional_block)
4889 char *referer = strdup_or_die(*header);
4890 const size_t hostlength = strlen(host);
4891 const char *referer_url = NULL;
4893 /* referer begins with 'Referer: http[s]://' */
4894 if ((hostlength+17) < strlen(referer))
4897 * Shorten referer to make sure the referer is blocked
4898 * if www.example.org/www.example.com-shall-see-the-referer/
4899 * links to www.example.com/
4901 referer[hostlength+17] = '\0';
4903 referer_url = strstr(referer, "http://");
4904 if (NULL == referer_url)
4906 referer_url = strstr(referer, "https://");
4908 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4910 /* Host has changed, Referer is invalid or a https URL. */
4911 if (parameter_conditional_block)
4913 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4920 return create_forged_referrer(header, host);
4930 /*********************************************************************
4932 * Function : create_content_length_header
4934 * Description : Creates a Content-Length header.
4937 * 1 : content_length = The content length to be used in the header.
4938 * 2 : header = Allocated space to safe the header.
4939 * 3 : buffer_length = The length of the allocated space.
4943 *********************************************************************/
4944 static void create_content_length_header(unsigned long long content_length,
4945 char *header, size_t buffer_length)
4948 #if SIZEOF_LONG_LONG < 8
4949 #error sizeof(unsigned long long) too small
4951 snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4953 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4958 /*********************************************************************
4960 * Function : get_expected_content_length
4962 * Description : Figures out the content length from a list of headers.
4965 * 1 : headers = List of headers
4967 * Returns : Number of bytes to expect
4969 *********************************************************************/
4970 unsigned long long get_expected_content_length(struct list *headers)
4972 const char *content_length_header;
4973 unsigned long long content_length = 0;
4975 content_length_header = get_header_value(headers, "Content-Length:");
4976 if (content_length_header != NULL)
4978 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4980 log_error(LOG_LEVEL_ERROR,
4981 "Failed to get the Content-Length in %s", content_length_header);
4982 /* XXX: The header will be removed later on */
4987 return content_length;